b'{"filepath": "/home/enrico/ghc/compiler/GHC/Rename/Names.hs", "line_num": 1, "column_num": 1, "working_dir": "/home/enrico/ghc", "file_data": {"/home/enrico/ghc/compiler/GHC/Rename/Names.hs": {"contents": "{-\\n(c) The GRASP/AQUA Project, Glasgow University, 1992-1998\\n\\nExtracting imported and top-level names in scope\\n-}\\n\\n{-# LANGUAGE NondecreasingIndentation #-}\\n{-# LANGUAGE TypeFamilies #-}\\n\\nmodule GHC.Rename.Names (\\n rnImports, getLocalNonValBinders, newRecordFieldLabel,\\n importsFromIface,\\n ImportUserSpec(..),\\n extendGlobalRdrEnvRn,\\n gresFromAvails,\\n calculateAvails,\\n reportUnusedNames,\\n checkConName,\\n mkChildEnv,\\n findChildren,\\n mkBadExportSubordinate,\\n findImportUsage,\\n getMinimalImports,\\n printMinimalImports,\\n renamePkgQual, renameRawPkgQual,\\n classifyGREs,\\n ImportDeclUsage,\\n rnNamespaceSpecifier\\n ) where\\n\\nimport GHC.Prelude hiding ( head, init, last, tail )\\n\\nimport GHC.Driver.Env\\nimport GHC.Driver.Session\\nimport GHC.Driver.Ppr\\n\\nimport GHC.Rename.Env\\nimport GHC.Rename.Fixity\\nimport GHC.Rename.Utils ( warnUnusedTopBinds )\\nimport GHC.Rename.Unbound\\nimport qualified GHC.Rename.Unbound as Unbound\\n\\nimport GHC.Tc.Errors.Types\\nimport GHC.Tc.Utils.Env\\nimport GHC.Tc.Utils.Monad\\nimport GHC.Tc.Types.LclEnv\\nimport GHC.Tc.Zonk.TcType ( tcInitTidyEnv )\\n\\nimport GHC.Hs\\nimport GHC.Iface.Load ( loadSrcInterface, loadSrcInterface_maybe )\\nimport GHC.Iface.Errors.Types\\n ( IfaceMessage(..), MissingInterfaceError, InterfaceLookingFor(..)\\n , LoadEssentialsReason(..) )\\nimport GHC.Iface.Syntax ( fromIfaceWarnings )\\nimport GHC.Builtin.Modules( pRELUDE_NAME, rEBINDABLE_MOD_NAME )\\nimport GHC.Parser.PostProcess ( setRdrNameSpace )\\nimport GHC.Core.TyCo.Tidy\\nimport GHC.Core.PatSyn\\nimport GHC.Core.TyCon ( TyCon, tyConName )\\nimport qualified GHC.LanguageExtensions as LangExt\\n\\nimport GHC.Utils.Outputable as Outputable\\nimport GHC.Utils.Misc as Utils\\nimport GHC.Utils.Panic\\n\\nimport GHC.Types.Fixity.Env\\nimport GHC.Types.SafeHaskell\\nimport GHC.Types.Name\\nimport GHC.Types.Name.Env\\nimport GHC.Types.Name.Set\\nimport GHC.Types.Name.Reader\\nimport GHC.Types.Avail\\nimport GHC.Types.FieldLabel\\nimport GHC.Types.Hint\\nimport GHC.Types.SourceFile\\nimport GHC.Types.SrcLoc as SrcLoc\\nimport GHC.Types.Basic (TyConFlavour (..), convImportLevel, VisArity)\\nimport GHC.Types.UnresolvedImport\\nimport GHC.Types.Id\\nimport GHC.Types.PkgQual\\nimport GHC.Types.GREInfo (ConInfo(..), ConFieldInfo (..), ConLikeInfo (ConIsData))\\n\\nimport GHC.Unit\\nimport GHC.Unit.Module.Warnings\\nimport GHC.Unit.Module.ModIface\\nimport GHC.Unit.Module.Imported\\nimport GHC.Unit.Module.Deps\\nimport GHC.Unit.Env\\n\\nimport GHC.Data.Bag\\nimport GHC.Data.FastString\\nimport GHC.Data.FastString.Env\\nimport GHC.Data.Maybe\\nimport GHC.Data.List.SetOps ( removeDups )\\n\\nimport Control.Arrow ( second )\\nimport Control.Monad\\nimport Data.Foldable ( for_ )\\nimport Data.IntMap ( IntMap )\\nimport qualified Data.IntMap as IntMap\\nimport Data.Map ( Map )\\nimport qualified Data.Map as Map\\nimport Data.Ord ( comparing )\\nimport Data.Semigroup ( Any(..) )\\nimport qualified Data.Semigroup as S\\nimport Data.List ( partition, find, sortBy )\\nimport Data.List.NonEmpty (NonEmpty(..))\\nimport qualified Data.List.NonEmpty as NE\\nimport Data.Function ( on )\\nimport qualified Data.Set as S\\nimport System.FilePath (())\\nimport System.IO\\n\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{rnImports}\\n* *\\n************************************************************************\\n\\nNote [Tracking Trust Transitively]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen we import a package as well as checking that the direct imports are safe\\naccording to the rules outlined in the Note [Safe Haskell Trust Check] in GHC.Driver.Main\\nwe must also check that these rules hold transitively for all dependent modules\\nand packages. Doing this without caching any trust information would be very\\nslow as we would need to touch all packages and interface files a module depends\\non. To avoid this we make use of the property that if a modules Safe Haskell\\nmode changes, this triggers a recompilation from that module in the dependency\\ngraph. So we can just worry mostly about direct imports.\\n\\nThere is one trust property that can change for a package though without\\nrecompilation being triggered: package trust. So we must check that all\\npackages a module transitively depends on to be trusted are still trusted when\\nwe are compiling this module (as due to recompilation avoidance some modules\\nbelow may not be considered trusted any more without recompilation being\\ntriggered).\\n\\nWe handle this by augmenting the existing transitive list of packages a module M\\ndepends on with a bool for each package that says if it must be trusted when the\\nmodule M is being checked for trust. This list of trust required packages for a\\nsingle import is gathered in the rnImportDecl function and stored in an\\nImportAvails data structure. The union of these trust required packages for all\\nimports is done by the rnImports function using the combine function which calls\\nthe plusImportAvails function that is a union operation for the ImportAvails\\ntype. This gives us in an ImportAvails structure all packages required to be\\ntrusted for the module we are currently compiling. Checking that these packages\\nare still trusted (and that direct imports are trusted) is done in\\nGHC.Driver.Main.checkSafeImports.\\n\\nSee the note below, [Trust Own Package] for a corner case in this method and\\nhow its handled.\\n\\n\\nNote [Trust Own Package]\\n~~~~~~~~~~~~~~~~~~~~~~~~\\nThere is a corner case of package trust checking that the usual transitive check\\ndoesn\'t cover. (For how the usual check operates see the Note [Tracking Trust\\nTransitively] below). The case is when you import a -XSafe module M and M\\nimports a -XTrustworthy module N. If N resides in a different package than M,\\nthen the usual check works as M will record a package dependency on N\'s package\\nand mark it as required to be trusted. If N resides in the same package as M\\nthough, then importing M should require its own package be trusted due to N\\n(since M is -XSafe so doesn\'t create this requirement by itself). The usual\\ncheck fails as a module doesn\'t record a package dependency of its own package.\\nSo instead we now have a bool field in a modules interface file that simply\\nstates if the module requires its own package to be trusted. This field avoids\\nus having to load all interface files that the module depends on to see if one\\nis trustworthy.\\n\\n\\nNote [Trust Transitive Property]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSo there is an interesting design question in regards to transitive trust\\nchecking. Say I have a module B compiled with -XSafe. B is dependent on a bunch\\nof modules and packages, some packages it requires to be trusted as its using\\n-XTrustworthy modules from them. Now if I have a module A that doesn\'t use safe\\nhaskell at all and simply imports B, should A inherit all the trust\\nrequirements from B? Should A now also require that a package p is trusted since\\nB required it?\\n\\nWe currently say no but saying yes also makes sense. The difference is, if a\\nmodule M that doesn\'t use Safe Haskell imports a module N that does, should all\\nthe trusted package requirements be dropped since M didn\'t declare that it cares\\nabout Safe Haskell (so -XSafe is more strongly associated with the module doing\\nthe importing) or should it be done still since the author of the module N that\\nuses Safe Haskell said they cared (so -XSafe is more strongly associated with\\nthe module that was compiled that used it).\\n\\nGoing with yes is a simpler semantics we think and harder for the user to stuff\\nup but it does mean that Safe Haskell will affect users who don\'t care about\\nSafe Haskell as they might grab a package from Cabal which uses safe haskell (say\\nnetwork) and that packages imports -XTrustworthy modules from another package\\n(say bytestring), so requires that package is trusted. The user may now get\\ncompilation errors in code that doesn\'t do anything with Safe Haskell simply\\nbecause they are using the network package. They will have to call \'ghc-pkg\\ntrust network\' to get everything working. Due to this invasive nature of going\\nwith yes we have gone with no for now.\\n-}\\n\\n-- | Process Import Decls. See \'rnImportDecl\' for a description of what\\n-- the return types represent.\\n-- Note: Do the non SOURCE ones first, so that we get a helpful warning\\n-- for SOURCE ones that are unnecessary\\nrnImports :: [(LImportDecl GhcPs, SDoc)]\\n -> RnM ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\nrnImports imports = do\\n tcg_env <- getGblEnv\\n -- NB: want an identity module here, because it\'s OK for a signature\\n -- module to import from its implementor\\n let this_mod = tcg_mod tcg_env\\n let (source, ordinary) = partition (is_source_import . fst) imports\\n is_source_import (d::LImportDecl GhcPs) = ideclSource (unLoc d) == IsBoot\\n stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary\\n stuff2 <- mapAndReportM (rnImportDecl this_mod) source\\n -- Safe Haskell: See Note [Tracking Trust Transitively]\\n let (decls, imp_user_spec, rdr_env, imp_avails) = combine (stuff1 ++ stuff2)\\n -- Update imp_boot_mods if imp_direct_mods mentions any of them\\n let merged_import_avail = clobberSourceImports imp_avails\\n return (decls, imp_user_spec, rdr_env, merged_import_avail)\\n\\n where\\n clobberSourceImports imp_avails =\\n imp_avails { imp_boot_mods = imp_boot_mods\' }\\n where\\n imp_boot_mods\' = mergeInstalledModuleEnv combJ id (const emptyInstalledModuleEnv)\\n (imp_boot_mods imp_avails)\\n (imp_direct_dep_mods imp_avails)\\n\\n combJ (GWIB _ IsBoot) (_, x) = Just x\\n combJ r _ = Just r\\n -- See Note [Combining ImportAvails]\\n combine :: [(LImportDecl GhcRn, ImportUserSpec, GlobalRdrEnv, ImportAvails)]\\n -> ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\n combine ss =\\n let (decls, imp_user_spec, rdr_env, imp_avails, finsts) = foldr\\n plus\\n ([], [], emptyGlobalRdrEnv, emptyImportAvails, emptyModuleSet)\\n ss\\n in (decls, imp_user_spec, rdr_env, imp_avails { imp_finsts = moduleSetElts finsts })\\n\\n plus (decl, us, gbl_env1, imp_avails1)\\n (decls, uss, gbl_env2, imp_avails2, finsts_set)\\n = ( decl:decls,\\n us:uss,\\n gbl_env1 `plusGlobalRdrEnv` gbl_env2,\\n imp_avails1\' `plusImportAvails` imp_avails2,\\n extendModuleSetList finsts_set new_finsts )\\n where\\n imp_avails1\' = imp_avails1 { imp_finsts = [] }\\n new_finsts = imp_finsts imp_avails1\\n\\n{-\\nNote [Combining ImportAvails]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nimp_finsts in ImportAvails is a list of family instance modules\\ntransitively depended on by an import. imp_finsts for a currently\\ncompiled module is a union of all the imp_finsts of imports.\\nComputing the union of two lists of size N is O(N^2) and if we\\ndo it to M imports we end up with O(M*N^2). That can get very\\nexpensive for bigger module hierarchies.\\n\\nUnion can be optimized to O(N log N) if we use a Set.\\nimp_finsts is converted back and forth between dep_finsts, so\\nchanging a type of imp_finsts means either paying for the conversions\\nor changing the type of dep_finsts as well.\\n\\nI\'ve measured that the conversions would cost 20% of allocations on my\\ntest case, so that can be ruled out.\\n\\nChanging the type of dep_finsts forces checkFamInsts to\\nget the module lists in non-deterministic order. If we wanted to restore\\nthe deterministic order, we\'d have to sort there, which is an additional\\ncost. As far as I can tell, using a non-deterministic order is fine there,\\nbut that\'s a brittle nonlocal property which I\'d like to avoid.\\n\\nAdditionally, dep_finsts is read from an interface file, so its \\"natural\\"\\ntype is a list. Which makes it a natural type for imp_finsts.\\n\\nSince rnImports.combine is really the only place that would benefit from\\nit being a Set, it makes sense to optimize the hot loop in rnImports.combine\\nwithout changing the representation.\\n\\nSo here\'s what we do: instead of naively merging ImportAvails with\\nplusImportAvails in a loop, we make plusImportAvails merge empty imp_finsts\\nand compute the union on the side using Sets. When we\'re done, we can\\nconvert it back to a list. One nice side effect of this approach is that\\nif there\'s a lot of overlap in the imp_finsts of imports, the\\nSet doesn\'t really need to grow and we don\'t need to allocate.\\n\\nRunning generateModules from #14693 with DEPTH=16, WIDTH=30 finishes in\\n23s before, and 11s after.\\n-}\\n\\n-- | Given a located import declaration @decl@ from @this_mod@,\\n-- calculate the following pieces of information:\\n--\\n-- 1. An updated \'LImportDecl\', where all unresolved \'RdrName\' in\\n-- the entity lists have been resolved into \'Name\'s,\\n--\\n-- 2. A \'GlobalRdrEnv\' representing the new identifiers that were\\n-- brought into scope (taking into account module qualification\\n-- and hiding),\\n--\\n-- 3. \'ImportAvails\' summarizing the identifiers that were imported\\n-- by this declaration, and\\n--\\n-- 4. A boolean \'AnyHpcUsage\' which is true if the imported module\\n-- used HPC.\\nrnImportDecl :: Module -> (LImportDecl GhcPs, SDoc)\\n -> RnM (LImportDecl GhcRn, ImportUserSpec , GlobalRdrEnv, ImportAvails)\\nrnImportDecl this_mod\\n (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name\\n , ideclPkgQual = raw_pkg_qual\\n , ideclSource = want_boot\\n , ideclSafe = mod_safe\\n , ideclLevelSpec = import_level\\n , ideclQualified = qual_style\\n , ideclExt = XImportDeclPass { ideclOrigin = origin }\\n , ideclAs = as_mod, ideclImportList = imp_details }), import_reason)\\n = setSrcSpanA loc $ do\\n\\n case raw_pkg_qual of\\n NoRawPkgQual -> pure ()\\n RawPkgQual {} -> do\\n pkg_imports <- xoptM LangExt.PackageImports\\n when (not pkg_imports) $ addErr TcRnPackageImportsDisabled\\n\\n let qual_only = isImportDeclQualified qual_style\\n generated = isGeneratedImport origin\\n\\n lookup_scope = importDeclLookupScope origin\\n\\n -- If there\'s an error in loadInterface, (e.g. interface\\n -- file not found) we get lots of spurious errors from \'filterImports\'\\n let imp_mod_name = unLoc loc_imp_mod_name\\n doc = ppr imp_mod_name <+> import_reason\\n\\n hsc_env <- getTopEnv\\n unit_env <- hsc_unit_env <$> getTopEnv\\n let pkg_qual = renameRawPkgQual unit_env imp_mod_name raw_pkg_qual\\n\\n -- Check for self-import, which confuses the typechecker (#9032)\\n -- ghc --make rejects self-import cycles already, but batch-mode may not\\n -- at least not until GHC.IfaceToCore.tcHiBootIface, which is too late to avoid\\n -- typechecker crashes. (Indirect self imports are not caught until\\n -- GHC.IfaceToCore, see #10337 tracking how to make this error better.)\\n --\\n -- Originally, we also allowed \'import {-# SOURCE #-} M\', but this\\n -- caused bug #10182: in one-shot mode, we should never load an hs-boot\\n -- file for the module we are compiling into the EPS. In principle,\\n -- it should be possible to support this mode of use, but we would have to\\n -- extend Provenance to support a local definition in a qualified location.\\n -- For now, we don\'t support it, but see #10336\\n when (imp_mod_name == moduleName this_mod &&\\n (case pkg_qual of -- If we have import \\"\\" M, then we should\\n -- check that \\"\\" is \\"this\\" (which is magic)\\n -- or the name of this_mod\'s package. Yurgh!\\n -- c.f. GHC.findModule, and #9997\\n NoPkgQual -> True\\n ThisPkg uid -> uid == homeUnitId_ (hsc_dflags hsc_env)\\n OtherPkg _ -> False))\\n (addErr (TcRnSelfImport imp_mod_name))\\n\\n -- Check for a missing import list (Opt_WarnMissingImportList also\\n -- checks for T(..) items but that is done in checkDodgyImport below)\\n case imp_details of\\n Just (Exactly, _) -> return () -- Explicit import list\\n _ | generated -> return () -- Do not bleat for generated imports\\n | qual_only -> return ()\\n | otherwise -> addDiagnostic (TcRnNoExplicitImportList imp_mod_name)\\n\\n\\n mb_iface <- loadSrcInterface_maybe doc lookup_scope imp_mod_name want_boot pkg_qual\\n iface <- case mb_iface of\\n Succeeded iface -> return iface\\n Failed err -> failWithTc $\\n importDeclLoadFailure origin imp_mod_name want_boot err\\n\\n -- Compiler sanity check: if the import didn\'t say\\n -- {-# SOURCE #-} we should not get a hi-boot file\\n warnPprTrace ((want_boot == NotBoot) && (mi_boot iface == IsBoot)) \\"rnImportDecl\\" (ppr imp_mod_name) $ do\\n\\n -- Issue a user warning for a redundant {- SOURCE -} import\\n -- NB that we arrange to read all the ordinary imports before\\n -- any of the {- SOURCE -} imports.\\n --\\n -- in --make and GHCi, the compilation manager checks for this,\\n -- and indeed we shouldn\'t do it here because the existence of\\n -- the non-boot module depends on the compilation order, which\\n -- is not deterministic. The hs-boot test can show this up.\\n dflags <- getDynFlags\\n warnIf ((want_boot == IsBoot) && (mi_boot iface == NotBoot) && isOneShot (ghcMode dflags))\\n (TcRnRedundantSourceImport imp_mod_name)\\n when (mod_safe && not (safeImportsOn dflags)) $\\n addErr (TcRnSafeImportsDisabled imp_mod_name)\\n\\n let imp_mod = mi_module iface\\n qual_mod_name = fmap unLoc as_mod `orElse` imp_mod_name\\n imp_spec = ImpDeclSpec { is_mod = imp_mod, is_qual = qual_only,\\n is_dloc = locA loc, is_as = qual_mod_name,\\n is_pkg_qual = pkg_qual, is_isboot = want_boot,\\n is_level = convImportLevel import_level }\\n\\n let filter_imports = do\\n -- filter the imports according to the import declaration\\n (new_imp_details, imp_user_list, gbl_env)\\n <- filterImports hsc_env iface imp_spec imp_details\\n -- for certain error messages, we\\u2019d like to know what could be\\n -- imported here, if everything were imported\\n potential_gres <- (\\\\(_,_,x) -> x) <$> filterImports hsc_env iface imp_spec Nothing\\n return (new_imp_details, imp_user_list, gbl_env, potential_gres)\\n\\n (new_imp_details, imp_user_list, gbl_env, potential_gres) <-\\n case origin of\\n ImplicitEssentialsImport ->\\n -- The implicit GHC.Essentials import does not bring anything into scope.\\n -- See Note [Finding GHC.Essentials] in GHC.Builtin.\\n return (Nothing, ImpUserDependOnly, emptyGlobalRdrEnv, emptyGlobalRdrEnv)\\n UserWrittenImport -> filter_imports\\n ImplicitPreludeImport -> filter_imports\\n PluginImport -> filter_imports\\n\\n let is_hiding | Just (EverythingBut,_) <- imp_details = True\\n | otherwise = False\\n\\n -- should the import be safe?\\n mod_safe\' = mod_safe\\n || (not generated && safeDirectImpsReq dflags)\\n || (generated && safeImplicitImpsReq dflags)\\n\\n hsc_env <- getTopEnv\\n let home_unit = hsc_home_unit hsc_env\\n other_home_units = hsc_all_home_unit_ids hsc_env\\n\\n imported_by\\n | isDependOnlyImport imp_user_list\\n = ImportedBySystem\\n | otherwise\\n = ImportedByUser $ ImportedModsVal\\n { imv_name = is_as imp_spec\\n , imv_span = locA loc\\n , imv_is_safe = mod_safe\'\\n , imv_is_hiding = is_hiding\\n , imv_all_exports = potential_gres\\n , imv_qualified = qual_only\\n , imv_is_level = convImportLevel import_level\\n }\\n imports = calculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by\\n\\n -- Complain if we import a deprecated module\\n case fromIfaceWarnings (mi_warns iface) of\\n WarnAll txt -> addDiagnostic (TcRnDeprecatedModule imp_mod_name txt)\\n _ -> return ()\\n\\n let new_imp_decl = ImportDecl\\n { ideclExt = ideclExt decl\\n , ideclName = ideclName decl\\n , ideclPkgQual = pkg_qual\\n , ideclSource = ideclSource decl\\n , ideclSafe = mod_safe\'\\n , ideclQualified = ideclQualified decl\\n , ideclAs = ideclAs decl\\n , ideclImportList = new_imp_details\\n , ideclLevelSpec = ideclLevelSpec decl\\n }\\n\\n return (L loc new_imp_decl, ImpUserSpec imp_spec imp_user_list, gbl_env, imports)\\n\\n-- | The error message to emit when we failed to load an interface.\\nimportDeclLoadFailure :: ImportDeclOrigin -> ModuleName -> IsBootInterface\\n -> MissingInterfaceError -> TcRnMessage\\nimportDeclLoadFailure ImplicitEssentialsImport _ _ err\\n = TcRnInterfaceError $ CantFindEssentials err LookingForEssentialsModule\\nimportDeclLoadFailure _ mod_name want_boot err\\n = TcRnInterfaceError $ Can\'tFindInterface err $ LookingForModule mod_name want_boot\\n\\n-- | Rename raw package imports\\nrenameRawPkgQual :: UnitEnv -> ModuleName -> RawPkgQual -> PkgQual\\nrenameRawPkgQual unit_env mn = \\\\case\\n NoRawPkgQual -> NoPkgQual\\n RawPkgQual _ fs -> renamePkgQual unit_env mn $ Just fs\\n\\n-- | Rename raw package imports\\nrenamePkgQual :: UnitEnv -> ModuleName -> Maybe FastString -> PkgQual\\nrenamePkgQual unit_env mn mb_pkg = case mb_pkg of\\n Nothing -> NoPkgQual\\n Just pkg_fs\\n | Just uid <- homeUnitId <$> ue_homeUnit unit_env\\n , pkg_fs == fsLit \\"this\\"\\n -> ThisPkg uid\\n\\n | Just (uid, _) <- find (fromMaybe False . fmap (== pkg_fs) . snd) home_names\\n -> ThisPkg uid\\n\\n | Just uid <- resolvePackageImport unit_state mn (PackageName pkg_fs)\\n -> OtherPkg uid\\n\\n | otherwise\\n -> OtherPkg (UnitId pkg_fs)\\n -- not really correct as pkg_fs is unlikely to be a valid unit-id but\\n -- we will report the failure later...\\n where\\n home_names =\\n [ (uid, mkFastString <$> thisPackageName (homeUnitEnv_dflags (ue_findHomeUnitEnv uid unit_env)))\\n | uid <- S.toList hpt_deps\\n ]\\n\\n unit_state = ue_homeUnitState unit_env\\n\\n hpt_deps :: S.Set UnitId\\n hpt_deps = homeUnitDepends unit_state\\n\\n\\n-- | Calculate the \'ImportAvails\' induced by an import of a particular\\n-- interface, but without \'imp_mods\'.\\ncalculateAvails :: HomeUnit\\n -> S.Set UnitId\\n -> ModIface\\n -> IsSafeImport\\n -> IsBootInterface\\n -> ImportedBy\\n -> ImportAvails\\ncalculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by =\\n let imp_mod = mi_module iface\\n imp_sem_mod= mi_semantic_module iface\\n orph_iface = mi_orphan iface\\n has_finsts = mi_finsts iface\\n deps = mi_deps iface\\n trust = getSafeMode $ mi_trust iface\\n trust_pkg = mi_trust_pkg iface\\n is_sig = mi_hsc_src iface == HsigFile\\n\\n -- If the module exports anything defined in this module, just\\n -- ignore it. Reason: otherwise it looks as if there are two\\n -- local definition sites for the thing, and an error gets\\n -- reported. Easiest thing is just to filter them out up\\n -- front. This situation only arises if a module imports\\n -- itself, or another module that imported it. (Necessarily,\\n -- this involves a loop.)\\n --\\n -- We do this *after* filterImports, so that if you say\\n -- module A where\\n -- import B( AType )\\n -- type AType = ...\\n --\\n -- module B( AType ) where\\n -- import {-# SOURCE #-} A( AType )\\n --\\n -- then you won\'t get a \'B does not export AType\' message.\\n\\n\\n -- Compute new transitive dependencies\\n --\\n -- \'dep_orphs\' and \'dep_finsts\' do NOT include the imported module\\n -- itself, but we DO need to include this module in \'imp_orphs\' and\\n -- \'imp_finsts\' if it defines an orphan or instance family; thus the\\n -- orph_iface/has_iface tests.\\n\\n deporphs = dep_orphs deps\\n depfinsts = dep_finsts deps\\n\\n orphans | orph_iface = assertPpr (not (imp_sem_mod `elem` deporphs)) (ppr imp_sem_mod <+> ppr deporphs) $\\n imp_sem_mod : deporphs\\n | otherwise = deporphs\\n\\n finsts | has_finsts = assertPpr (not (imp_sem_mod `elem` depfinsts)) (ppr imp_sem_mod <+> ppr depfinsts) $\\n imp_sem_mod : depfinsts\\n | otherwise = depfinsts\\n\\n -- Trusted packages are a lot like orphans.\\n trusted_pkgs | mod_safe\' = dep_trusted_pkgs deps\\n | otherwise = S.empty\\n\\n\\n pkg = moduleUnit (mi_module iface)\\n ipkg = toUnitId pkg\\n\\n -- Does this import mean we now require our own pkg\\n -- to be trusted? See Note [Trust Own Package]\\n ptrust = trust == Sf_Trustworthy || trust_pkg\\n pkg_trust_req\\n | isHomeUnit home_unit pkg = ptrust\\n | otherwise = False\\n\\n dependent_pkgs = if toUnitId pkg `S.member` other_home_units\\n then S.empty\\n else S.singleton (lvl, ipkg)\\n\\n lvl = case imported_by of\\n ImportedByUser imv -> imv_is_level imv\\n ImportedBySystem -> NormalLevel\\n\\n\\n direct_mods = if toUnitId pkg `S.member` other_home_units\\n then mkPlusModDeps (moduleUnitId imp_mod) lvl (GWIB (moduleName imp_mod) want_boot)\\n else emptyInstalledModuleEnv\\n\\n dep_boot_mods_map = mkModDeps (dep_boot_mods deps)\\n\\n\\n boot_mods\\n -- If we are looking for a boot module, it must be HPT\\n | IsBoot <- want_boot = extendInstalledModuleEnv dep_boot_mods_map (toUnitId <$> imp_mod) (GWIB (moduleName imp_mod) IsBoot)\\n -- Now we are importing A properly, so don\'t go looking for\\n -- A.hs-boot\\n | isHomeUnit home_unit pkg = dep_boot_mods_map\\n -- There\'s no boot files to find in external imports\\n | otherwise = emptyInstalledModuleEnv\\n\\n sig_mods =\\n if is_sig\\n then moduleName imp_mod : dep_sig_mods deps\\n else dep_sig_mods deps\\n\\n\\n in ImportAvails {\\n imp_mods = Map.singleton (mi_module iface) [imported_by],\\n imp_orphs = orphans,\\n imp_finsts = finsts,\\n imp_sig_mods = sig_mods,\\n imp_direct_dep_mods = direct_mods,\\n imp_dep_direct_pkgs = dependent_pkgs,\\n imp_boot_mods = boot_mods,\\n\\n -- Add in the imported modules trusted package\\n -- requirements. ONLY do this though if we import the\\n -- module as a safe import.\\n -- See Note [Tracking Trust Transitively]\\n -- and Note [Trust Transitive Property]\\n imp_trust_pkgs = trusted_pkgs,\\n -- Do we require our own pkg to be trusted?\\n -- See Note [Trust Own Package]\\n imp_trust_own_pkg = pkg_trust_req\\n }\\n\\nmkPlusModDeps :: UnitId -> ImportLevel -> ModuleNameWithIsBoot\\n -> InstalledModuleEnv (S.Set ImportLevel, ModuleNameWithIsBoot)\\nmkPlusModDeps uid st elt = extendInstalledModuleEnv emptyInstalledModuleEnv (mkModule uid (gwib_mod elt)) (S.singleton st, elt)\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{importsFromLocalDecls}\\n* *\\n************************************************************************\\n\\nFrom the top-level declarations of this module produce\\n * the lexical environment\\n * the ImportAvails\\ncreated by its bindings.\\n\\nNote [Top-level Names in Template Haskell decl quotes]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSee also: Note [Interactively-bound Ids in GHCi] in GHC.Driver.Env\\n Note [Looking up Exact RdrNames] in GHC.Rename.Env\\n\\nConsider a Template Haskell declaration quotation like this:\\n module M where\\n f x = h [d| f = 3 |]\\nWhen renaming the declarations inside [d| ...|], we treat the\\ntop level binders specially in two ways\\n\\n1. We give them an Internal Name, not (as usual) an External one.\\n This is done by GHC.Rename.Env.newTopSrcBinder.\\n\\n2. We make them *shadow* the outer bindings.\\n See Note [GlobalRdrEnv shadowing]\\n\\n3. We find out whether we are inside a [d| ... |] by testing the TH\\n level. This is a slight hack, because the level field was really\\n meant for the type checker, and here we are not interested in the\\n fields of Brack, hence the error thunks in thRnBrack.\\n-}\\n\\nextendGlobalRdrEnvRn :: [GlobalRdrElt]\\n -> MiniFixityEnv\\n -> RnM (TcGblEnv, TcLclEnv)\\n-- Updates both the GlobalRdrEnv and the FixityEnv\\n-- We return a new TcLclEnv only because we might have to\\n-- delete some bindings from it;\\n-- see Note [Top-level Names in Template Haskell decl quotes]\\n\\nextendGlobalRdrEnvRn new_gres new_fixities\\n = checkNoErrs $ -- See Note [Fail fast on duplicate definitions]\\n do { (gbl_env, lcl_env) <- getEnvs\\n ; level <- getThLevel\\n ; isGHCi <- getIsGHCi\\n ; let rdr_env = tcg_rdr_env gbl_env\\n fix_env = tcg_fix_env gbl_env\\n th_bndrs = getLclEnvThBndrs lcl_env\\n th_lvl = thLevelIndex level\\n\\n -- Delete new_occs from global and local envs\\n -- If we are in a TemplateHaskell decl bracket,\\n -- we are going to shadow them\\n -- See Note [GlobalRdrEnv shadowing]\\n inBracket = isBrackLevel level\\n\\n lcl_env_TH = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_rdr = minusLocalRdrEnv (tcl_rdr lcl_env) new_gres_env }) lcl_env\\n -- See Note [GlobalRdrEnv shadowing]\\n\\n lcl_env2 | inBracket = lcl_env_TH\\n | otherwise = lcl_env\\n\\n -- Deal with shadowing: see Note [GlobalRdrEnv shadowing]\\n want_shadowing = isGHCi || inBracket\\n rdr_env1 | want_shadowing = shadowNames False rdr_env new_gres_env\\n | otherwise = rdr_env\\n\\n lcl_env3 = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_th_bndrs = extendNameEnvList th_bndrs\\n [ ( n, (TopLevel, th_lvl) )\\n | n <- new_names ] }) lcl_env2\\n\\n ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres\\n\\n ; let fix_env\' = foldl\' extend_fix_env fix_env new_gres\\n gbl_env\' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env\' }\\n\\n ; traceRn \\"extendGlobalRdrEnvRn 2\\" (pprGlobalRdrEnv True rdr_env2)\\n ; return (gbl_env\', lcl_env3) }\\n where\\n new_names = map greName new_gres\\n new_gres_env = mkGlobalRdrEnv new_gres\\n\\n -- If there is a fixity decl for the gre, add it to the fixity env\\n extend_fix_env fix_env gre\\n | Just (L _ fi) <- lookupMiniFixityEnv new_fixities name\\n = extendNameEnv fix_env name (FixItem occ fi)\\n | otherwise\\n = fix_env\\n where\\n name = greName gre\\n occ = greOccName gre\\n\\n add_gre :: GlobalRdrEnv -> GlobalRdrElt -> RnM GlobalRdrEnv\\n -- Extend the GlobalRdrEnv with a LocalDef GRE\\n -- If there is already a LocalDef GRE with the same OccName,\\n -- report an error and discard the new GRE\\n -- This establishes INVARIANT 1 of GlobalRdrEnvs\\n add_gre env gre\\n | not (null dups) -- Same OccName defined twice\\n = do { addDupDeclErr (gre :| dups); return env }\\n\\n | otherwise\\n = return (extendGlobalRdrEnv env gre)\\n where\\n -- See Note [Reporting duplicate local declarations]\\n dups = filter isBadDupGRE\\n $ lookupGRE env (LookupOccName (greOccName gre) (RelevantGREsFOS WantBoth))\\n isBadDupGRE old_gre = isLocalGRE old_gre && greClashesWith gre old_gre\\n\\n{- Note [Fail fast on duplicate definitions]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIf there are duplicate bindings for the same thing, we want to fail\\nfast. Having two bindings for the same thing can cause follow-on errors.\\nExample (test T9975a):\\n data Test = Test { x :: Int }\\n pattern Test wat = Test { x = wat }\\nThis defines \'Test\' twice. The second defn has no field-names; and then\\nwe get an error from Test { x=wat }, saying \\"Test has no field \'x\'\\".\\n\\nEasiest thing is to bale out fast on duplicate definitions, which\\nwe do via `checkNoErrs` on `extendGlobalRdrEnvRn`.\\n\\nNote [Reporting duplicate local declarations]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn general, a single module may not define the same OccName multiple times. This\\nis checked in extendGlobalRdrEnvRn: when adding a new locally-defined GRE to the\\nGlobalRdrEnv we report an error if there are already duplicates in the\\nenvironment. This establishes INVARIANT 1 (see comments on GlobalRdrEnv in\\nGHC.Types.Name.Reader), which says that for a given OccName, all the\\nGlobalRdrElts to which it maps must have distinct \'greName\'s.\\n\\nFor example, the following will be rejected:\\n\\n f x = x\\n g x = x\\n f x = x -- Duplicate!\\n\\nUsers are allowed to introduce new GREs with the same OccName as an imported GRE,\\nas disambiguation is possible through the module system, e.g.:\\n\\n module M where\\n import N (f)\\n f x = x\\n g x = M.f x + N.f x\\n\\nIf both GREs are local, the general rule is that two GREs clash if they have\\nthe same OccName, i.e. they share a textual name and live in the same namespace.\\nHowever, there are additional clashes due to record fields:\\n\\n - a new variable clashes with previously defined record fields\\n which define field selectors,\\n\\n - a new record field shadows:\\n\\n - previously defined variables, if it defines a field selector,\\n - previously defined record fields, unless it is a duplicate record field.\\n\\nThis logic is implemented in the function \'GHC.Types.Name.Reader.greClashesWith\'.\\n\\nSee also Note [Skipping ambiguity errors at use sites of local declarations] in\\nGHC.Rename.Utils.\\n-}\\n\\n\\n{- *********************************************************************\\n* *\\n getLocalDeclBindersd@ returns the names for an HsDecl\\n It\'s used for source code.\\n\\n *** See Note [The Naming story] in GHC.Hs.Decls ****\\n* *\\n********************************************************************* -}\\n\\ngetLocalNonValBinders :: MiniFixityEnv -> HsGroup GhcPs\\n -> RnM ((TcGblEnv, TcLclEnv), NameSet)\\n-- Get all the top-level binders bound the group *except*\\n-- for value bindings, which are treated separately\\n-- Specifically we return AvailInfo for\\n-- * type decls (incl constructors and record selectors)\\n-- * class decls (including class ops)\\n-- * associated types\\n-- * foreign imports\\n-- * value signatures (in hs-boot files only)\\n\\ngetLocalNonValBinders fixity_env\\n (HsGroup { hs_valds = binds,\\n hs_tyclds = tycl_decls,\\n hs_fords = foreign_decls })\\n = do { -- Process all type/class decls *except* family instances\\n ; let inst_decls = tycl_decls >>= group_instds\\n ; dup_fields_ok <- xopt_DuplicateRecordFields <$> getDynFlags\\n ; has_sel <- xopt_FieldSelectors <$> getDynFlags\\n ; tc_gres\\n <- concatMapM\\n (new_tc dup_fields_ok has_sel)\\n (tyClGroupTyClDecls tycl_decls)\\n ; traceRn \\"getLocalNonValBinders 1\\" (ppr tc_gres)\\n ; envs <- extendGlobalRdrEnvRn tc_gres fixity_env\\n ; restoreEnvs envs $ do {\\n -- Bring these things into scope first\\n -- See Note [Looking up family names in family instances]\\n\\n -- Process all family instances\\n -- to bring new data constructors into scope\\n ; nti_gress <- mapM (new_assoc dup_fields_ok has_sel) inst_decls\\n\\n -- Finish off with value binders:\\n -- foreign decls and pattern synonyms for an ordinary module\\n -- type sigs in case of a hs-boot file only\\n ; is_boot <- tcIsHsBootOrSig\\n ; let val_bndrs\\n | is_boot = case binds of\\n ValBinds _ val_binds ->\\n -- In a hs-boot file, the value binders come from the\\n -- *signatures*, and there should be no foreign binders\\n [ L (l2l decl_loc) (unLoc n)\\n | L decl_loc (TypeSig _ _ ns _) <- (val_sigs val_binds), n <- ns]\\n _ -> panic \\"Non-ValBinds in hs-boot group\\"\\n | otherwise = for_hs_bndrs\\n ; val_gres <- mapM new_simple val_bndrs\\n\\n ; let avails = concat nti_gress ++ val_gres\\n new_bndrs = gresToNameSet avails `unionNameSet`\\n gresToNameSet tc_gres\\n ; traceRn \\"getLocalNonValBinders 2\\" (ppr avails)\\n ; envs <- extendGlobalRdrEnvRn avails fixity_env\\n ; return (envs, new_bndrs) } }\\n where\\n for_hs_bndrs :: [LocatedN RdrName]\\n for_hs_bndrs = hsForeignDeclsBinders foreign_decls\\n\\n -- the SrcSpan attached to the input should be the span of the\\n -- declaration, not just the name\\n new_simple :: LocatedN RdrName -> RnM GlobalRdrElt\\n new_simple rdr_name = do { nm <- newTopSrcBinder rdr_name\\n ; return (mkLocalVanillaGRE NoParent nm) }\\n\\n new_tc :: DuplicateRecordFields -> FieldSelectors -> LTyClDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_tc dup_fields_ok has_sel tc_decl -- NOT for type/data instances\\n = do { let TyDeclBinders (main_bndr, tc_flav) at_bndrs sig_bndrs\\n (LConsWithFields cons_with_flds flds) = hsLTyClDeclBinders tc_decl\\n ; tycon_name <- newTopSrcBinder $ la2la main_bndr\\n ; at_names <- mapM (newTopSrcBinder . la2la . fst) at_bndrs\\n ; sig_names <- mapM (newTopSrcBinder . la2la) sig_bndrs\\n ; con_names_with_flds <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst con_names_with_flds) flds\\n ; mapM_ (add_dup_fld_errs flds\') con_names_with_flds\\n ; let tc_gre = mkLocalTyConGRE (fmap (const tycon_name) tc_flav) tycon_name\\n fld_env = mk_fld_env con_names_with_flds flds\'\\n at_gres = zipWith (\\\\ (_, at_flav) at_nm -> mkLocalTyConGRE (fmap (const tycon_name) at_flav) at_nm)\\n at_bndrs at_names\\n sig_gres = map (mkLocalVanillaGRE (ParentIs tycon_name)) sig_names\\n con_gres = map (mkLocalConLikeGRE (ParentIs tycon_name)) fld_env\\n fld_gres = mkLocalFieldGREs (ParentIs tycon_name) fld_env\\n sub_gres = at_gres ++ sig_gres ++ con_gres ++ fld_gres\\n ; traceRn \\"getLocalNonValBinders new_tc\\" $\\n vcat [ text \\"tycon:\\" <+> ppr tycon_name\\n , text \\"tc_gre:\\" <+> ppr tc_gre\\n , text \\"sub_gres:\\" <+> ppr sub_gres ]\\n ; return $ tc_gre : sub_gres }\\n\\n -- Calculate the record field information, which feeds into the GlobalRdrElts\\n -- for DataCons and their fields. It\'s convenient to do this here where\\n -- we are working with a single datatype definition.\\n --\\n -- The information we needed was all set up for us:\\n -- see Note [Collecting record fields in data declarations] in GHC.Hs.Utils.\\n mk_fld_env :: [(Name, Either VisArity [Located Int])] -> IntMap FieldLabel\\n -> [(ConLikeName, ConInfo)]\\n mk_fld_env names flds =\\n [ (DataConName con, ConInfo (ConIsData (map fst names)) fld_info)\\n | (con, con_fl_indxs) <- names\\n , let fld_info = case fmap (map ((flds IntMap.!) . unLoc)) con_fl_indxs of\\n Left 0 -> ConIsNullary\\n Left arity -> ConHasPositionalArgs arity\\n Right [] -> ConIsNullary\\n Right (fld:flds) -> ConHasRecordFields $ fld NE.:| flds ]\\n\\n new_assoc :: DuplicateRecordFields -> FieldSelectors -> LInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_assoc _ _ (L _ (TyFamInstD {})) = return []\\n -- type instances don\'t bind new names\\n\\n new_assoc dup_fields_ok has_sel (L _ (DataFamInstD _ d))\\n = new_di dup_fields_ok has_sel Nothing d\\n new_assoc dup_fields_ok has_sel\\n (L _ (ClsInstD _ (ClsInstDecl { cid_poly_ty = inst_ty\\n , cid_decls = decls })))\\n = do -- First, attempt to grab the name of the class from the instance.\\n -- This step could fail if the instance is not headed by a class,\\n -- such as in the following examples:\\n --\\n -- (1) The class is headed by a bang pattern, such as in\\n -- `instance !Show Int` (#3811c)\\n -- (2) The class is headed by a type variable, such as in\\n -- `instance c` (#16385)\\n --\\n -- If looking up the class name fails, then mb_cls_gre will\\n -- be Nothing.\\n mb_cls_gre <- runMaybeT $ do\\n -- See (1) above\\n L loc cls_rdr <- MaybeT $ pure $ getLHsInstDeclClass_maybe inst_ty\\n -- See (2) above\\n MaybeT $ setSrcSpan (locA loc) $ lookupGlobalOccRn_maybe SameNameSpace cls_rdr\\n -- Assuming the previous step succeeded, process any associated data\\n -- family instances. If the previous step failed, bail out.\\n case mb_cls_gre of\\n Nothing\\n -> pure []\\n Just cls_gre\\n -> let cls_nm = greName cls_gre\\n in concatMapM (new_di dup_fields_ok has_sel (Just cls_nm) . unLoc) (data_fam_insts decls)\\n\\n data_fam_insts decls = concatMap get decls\\n where\\n get (L l (InstD _ (DataFamInstD { dfid_inst = d}))) = [L l d]\\n get _ = []\\n\\n new_di :: DuplicateRecordFields -> FieldSelectors\\n -> Maybe Name -- class name\\n -> DataFamInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_di dup_fields_ok has_sel mb_cls dfid@(DataFamInstDecl { dfid_eqn = ti_decl })\\n = do { main_name <- unLoc <$> lookupFamInstName mb_cls (feqn_tycon ti_decl)\\n ; let LConsWithFields cons_with_flds flds = hsDataFamInstBinders dfid\\n ; sub_names <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst sub_names) flds\\n ; mapM_ (add_dup_fld_errs flds\') sub_names\\n ; let fld_env = mk_fld_env sub_names flds\'\\n con_gres = map (mkLocalConLikeGRE (ParentIs main_name)) fld_env\\n field_gres = mkLocalFieldGREs (ParentIs main_name) fld_env\\n -- NB: the data family name is not bound here,\\n -- so we don\'t return a GlobalRdrElt for it here!\\n ; return $ con_gres ++ field_gres }\\n\\n -- Add errors if a constructor has a duplicate record field.\\n add_dup_fld_errs :: IntMap FieldLabel\\n -> (Name, Either VisArity [Located Int])\\n -> IOEnv (Env TcGblEnv TcLclEnv) ()\\n add_dup_fld_errs all_flds (con, con_flds_or_arity)\\n | Right con_flds <- con_flds_or_arity\\n , let (_, dups) = removeDups (comparing unLoc) con_flds\\n = for_ dups $ \\\\ dup_flds ->\\n -- Report the error at the location of the second occurrence\\n -- of the duplicate field.\\n let loc =\\n case dup_flds of\\n _ :| ( L loc _ : _) -> loc\\n L loc _ :| _ -> loc\\n dup_rdrs = fmap (nameRdrName . flSelector . (all_flds IntMap.!) . unLoc) dup_flds\\n in addErrAt loc $ TcRnDuplicateFieldName (RecordFieldDecl con) dup_rdrs\\n | otherwise\\n = return ()\\n\\nnewRecordFieldLabel :: DuplicateRecordFields -> FieldSelectors -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel\\nnewRecordFieldLabel _ _ [] _ = error \\"newRecordFieldLabel: datatype has no constructors!\\"\\nnewRecordFieldLabel dup_fields_ok has_sel (dc:_) (L loc (FieldOcc _ (L _ fld)))\\n = do { selName <- newTopSrcBinder $ L (l2l loc) $ field\\n ; return $ FieldLabel { flHasDuplicateRecordFields = dup_fields_ok\\n , flHasFieldSelector = has_sel\\n , flSelector = selName } }\\n where\\n fld_occ = rdrNameOcc fld\\n dc_fs = occNameFS $ nameOccName dc\\n field\\n -- Use an Exact RdrName as-is, to preserve the bindings\\n -- of an already renamer-resolved field and its use\\n -- sites. This is needed to correctly support record\\n -- selectors in Template Haskell. See Note [Binders in\\n -- Template Haskell] in \\"GHC.ThToHs\\" and Note [Looking up\\n -- Exact RdrNames] in \\"GHC.Rename.Env\\".\\n | isExact fld\\n = assertPpr (fieldOcc_maybe fld_occ == Just dc_fs)\\n (vcat [ text \\"newRecordFieldLabel: incorrect namespace for exact Name\\" <+> quotes (ppr fld)\\n , text \\"expected namespace:\\" <+> pprNameSpace (fieldName dc_fs)\\n , text \\" actual namespace:\\" <+> pprNameSpace (occNameSpace fld_occ) ])\\n fld\\n\\n -- Field names produced by the parser are namespaced with VarName.\\n -- Here we namespace them according to the first constructor.\\n -- See Note [Record field namespacing] in GHC.Types.Name.Occurrence.\\n | otherwise\\n = mkRdrUnqual $ varToRecFieldOcc dc_fs fld_occ\\n\\n{-\\nNote [Looking up family names in family instances]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider\\n\\n module M where\\n type family T a :: *\\n type instance M.T Int = Bool\\n\\nWe might think that we can simply use \'lookupOccRn\' when processing the type\\ninstance to look up \'M.T\'. Alas, we can\'t! The type family declaration is in\\nthe *same* HsGroup as the type instance declaration. Hence, as we are\\ncurrently collecting the binders declared in that HsGroup, these binders will\\nnot have been added to the global environment yet.\\n\\nSolution is simple: process the type family declarations first, extend\\nthe environment, and then process the type instances.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Filtering imports}\\n* *\\n************************************************************************\\n\\n@filterImports@ takes the @ExportEnv@ telling what the imported module makes\\navailable, and filters it through the import spec (if any).\\n\\nNote [Dealing with imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nFor import M( ies ), we take each AvailInfo from the mi_exports of M, and make\\n\\n imp_occ_env :: OccEnv (NameEnv ImpOccItem)\\n\\nThis map contains one entry for each OccName that M exports, mapping each OccName\\nto the following information:\\n\\n 1. the GlobalRdrElt corresponding to the OccName,\\n 2. whether this GlobalRdrElt was the parent in the AvailInfo we found\\n the OccName in.\\n 3. the GlobalRdrElts that were bundled together in the AvailInfo we found\\n this OccName in (not including the parent),\\n\\nWe need (2) and (3) during the construction of the OccEnv because of associated\\ntypes and bundled pattern synonyms, respectively.\\n(3) is explained in Note [Importing PatternSynonyms].\\n\\nTo explain (2), consider for example:\\n\\n module M where\\n class C a where { data T a }\\n instance C Int where { data T Int = T1 | T2 }\\n instance C Bool where { data T Int = T3 }\\n\\nHere, M\'s exports avails are (recalling the AvailTC invariant from GHC.Types.Avail)\\n\\n C(C,T), T(T,T1,T2,T3)\\n\\nNotice that T appears *twice*, once as a child and once as a parent. From\\nthese two exports, respectively, during construction of the imp_occ_env, we begin\\nby associating the following two elements with the key T:\\n\\n T -> ImpOccItem { imp_item = gre1, imp_bundled = [C,T] , imp_is_parent = False }\\n T -> ImpOccItem { imp_item = gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nwhere `gre1`, `gre2` are two GlobalRdrElts with greName T.\\nWe combine these (in function \'combine\' in \'mkImportOccEnv\') by discarding the\\nnon-parent item, thusly:\\n\\n T -> IE_ITem { imp_item = gre1 `plusGRE` gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nNote the `plusGRE`: this ensures we don\'t drop parent information;\\nsee Note [Preserve parent information when combining import OccEnvs].\\n\\nSo the overall imp_occ_env is:\\n\\n C -> ImpOccItem { imp_item = C, imp_bundled = [T ], imp_is_parent = True }\\n T -> ImpOccItem { imp_item = T , imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n T1 -> ImpOccItem { imp_item = T1, imp_bundled = [T1,T2,T3], imp_is_parent = False }\\n -- similarly for T2, T3\\n\\nNote that the imp_occ_env will have entries for data constructors too,\\nalthough we never look up data constructors.\\n\\nNote [Importing PatternSynonyms]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nAs described in Note [Dealing with imports], associated types can lead to the\\nsame Name appearing twice, both as a child and once as a parent, when\\nconstructing the imp_occ_env. The same thing can happen with pattern synonyms\\nif they are exported bundled with a type.\\n\\nA simplified example, based on #11959:\\n\\n {-# LANGUAGE PatternSynonyms #-}\\n module M (T(P), pattern P) where -- Duplicate export warning, but allowed\\n data T = MkT\\n pattern P = MkT\\n\\nHere we have T(P) and P in export_avails, and respectively construct both\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n P -> ImpOccItem { imp_item = P, imp_bundled = [] , imp_is_parent = False }\\n\\nWe combine these by dropping the one with no siblings, leaving us with:\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n\\nThat is, we simply discard the non-bundled Avail.\\n\\nNote [Importing DuplicateRecordFields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn filterImports, another complicating factor is DuplicateRecordFields.\\nSuppose we have:\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (S(foo), T(foo)) where\\n data S = MkS { foo :: Int }\\n data T = MkT { foo :: Int }\\n\\n module N where\\n import M (foo) -- this is allowed (A)\\n import M (S(foo)) -- this is allowed (B)\\n\\nHere M exports \'foo\' at two different OccNames, with different namespaces for\\nthe two construtors MkS and MkT. Then, when we look up \'foo\' in lookup_names\\nfor case (A), we have a variable foo but must look in all the record field\\nnamespaces to find the two fields (and hence two different Avails).\\nWhereas in case (B) we reach the lookup_ie case for IEThingWith,\\nwhich looks up \'S\' and then finds the unique \'foo\' amongst its children.\\n\\nSee T16745 for a test of this.\\n\\nNote [Preserve parent information when combining import OccEnvs]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen discarding one ImpOccItem in favour of another, as described in\\nNote [Dealing with imports], we must make sure to combine the GREs so that\\nwe don\'t lose information.\\n\\nConsider for example #24084:\\n\\n module M1 where { class C a where { type T a } }\\n module M2 ( module M1 ) where { import M1 }\\n module M3 where { import M2 ( C, T ); instance C () where T () = () }\\n\\nWhen processing the import list of `M3`, we will have two `Avail`s attached\\nto `T`, namely `C(C, T)` and `T(T)`. We combine them in the `combine` function\\nof `mkImportOccEnv`; as described in Note [Dealing with imports] we discard\\n`C(C, T)` in favour of `T(T)`. However, in doing so, we **must not**\\ndiscard the information want that `C` is the parent of `T`. Indeed,\\nlosing track of this information can cause errors when importing,\\nas we could get an error of the form\\n\\n \\u2018T\\u2019 is not a (visible) associated type of class \\u2018C\\u2019\\n\\nThis explains why we use `plusGRE` when combining the two ImpOccItems, even\\nthough we are discarding one in favour of the other.\\n-}\\n\\n-- | All the \'GlobalRdrElt\'s associated with an \'AvailInfo\'.\\ngresFromAvail :: HasDebugCallStack\\n => HscEnv -> Maybe ImportSpec -> AvailInfo -> [GlobalRdrElt]\\ngresFromAvail hsc_env prov avail =\\n [ mk_gre nm info\\n | nm <- availNames avail\\n , let info = lookupGREInfo hsc_env nm ]\\n where\\n\\n mk_gre n info\\n = case prov of\\n -- Nothing => bound locally\\n -- Just is => imported from \'is\'\\n Nothing -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = True, gre_imp = emptyBag\\n , gre_info = info }\\n Just is -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = False, gre_imp = unitBag is\\n , gre_info = info }\\n\\n-- | All the \'GlobalRdrElt\'s associated with a collection of \'AvailInfo\'s.\\ngresFromAvails :: HscEnv -> Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]\\ngresFromAvails hsc_env prov = concatMap (gresFromAvail hsc_env prov)\\n\\nimportsFromIface :: HscEnv -> ModIface -> ImpDeclSpec -> Maybe NameSet -> GlobalRdrEnv\\nimportsFromIface hsc_env iface decl_spec hidden = mkGlobalRdrEnv $ case hidden of\\n Nothing -> all_gres\\n Just hidden_names -> filter (not . (`elemNameSet` hidden_names) . greName) all_gres\\n where\\n all_gres = gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\nrnNamespaceSpecifier :: NamespaceSpecifier GhcPs -> NamespaceSpecifier GhcRn\\nrnNamespaceSpecifier (NoNamespaceSpecifier _) = NoNamespaceSpecifier noExtField\\nrnNamespaceSpecifier (TypeNamespaceSpecifier x) = TypeNamespaceSpecifier x\\nrnNamespaceSpecifier (DataNamespaceSpecifier x) = DataNamespaceSpecifier x\\n\\nfilterImports\\n :: HasDebugCallStack\\n => HscEnv\\n -> ModIface\\n -> ImpDeclSpec\\n -- ^ Import spec\\n -> Maybe (ImportListInterpretation, [LIE GhcPs])\\n -- ^ Whether this is a \\"hiding\\" import list\\n -> RnM (Maybe (ImportListInterpretation, [LIE GhcRn]), -- Import spec w/ Names\\n ImpUserList, -- same, but designed for storage in interfaces\\n GlobalRdrEnv) -- Same again, but in GRE form\\nfilterImports hsc_env iface decl_spec Nothing\\n = return (Nothing, ImpUserAll, importsFromIface hsc_env iface decl_spec Nothing)\\nfilterImports hsc_env iface decl_spec (Just (want_hiding, import_items))\\n = do -- check for errors, convert RdrNames to Names\\n items1 <- mapM lookup_lie import_items\\n\\n let items2 :: [(LIE GhcRn, [GlobalRdrElt])]\\n items2 = concat items1\\n -- NB we may have duplicates, and several items\\n -- for the same parent; e.g N(x) and N(y)\\n\\n (gres, imp_user_list) = case want_hiding of\\n Exactly ->\\n let gres = concatMap (gresFromIE decl_spec) items2\\n gre_env = mkGlobalRdrEnv gres\\n implicit_parents = mkNameSet $ mapMaybe parentOfImplicitlyImportedGRE gres\\n in (gre_env, ImpUserExplicit (gresToAvailInfo $ globalRdrEnvElts $ gre_env) implicit_parents)\\n EverythingBut ->\\n let hidden_names = mkNameSet $ concatMap (map greName . snd) items2\\n in (importsFromIface hsc_env iface decl_spec (Just hidden_names), ImpUserEverythingBut hidden_names)\\n\\n return (Just (want_hiding, map fst items2), imp_user_list, gres)\\n where\\n import_mod = mi_module iface\\n all_avails = mi_exports iface\\n imp_occ_env = mkImportOccEnv hsc_env decl_spec all_avails\\n\\n -- Look up a parent (type constructor, class or data constructor)\\n -- in an import.\\n lookup_parent :: IE GhcPs -> RdrName -> IELookupM ImpOccItem\\n lookup_parent ie rdr =\\n assertPpr (not $ isVarNameSpace ns)\\n (vcat [ text \\"filterImports lookup_parent: unexpected variable\\"\\n , text \\"rdr:\\" <+> ppr rdr\\n , text \\"namespace:\\" <+> pprNameSpace ns ]) $\\n do { xs <- lookup_names ie rdr\\n ; case xs of\\n cax :| [] -> return cax\\n _ -> pprPanic \\"filter_imports lookup_parent ambiguous\\" $\\n vcat [ text \\"rdr:\\" <+> ppr rdr\\n , text \\"lookups:\\" <+> ppr (fmap imp_item xs) ] }\\n -- Looking up non-variables is always unambiguous,\\n -- as there can be at most one corresponding item\\n -- in the imp_occ_env.\\n -- See item (1) of Note [Exporting duplicate declarations]\\n -- in GHC.Tc.Gen.Export.\\n where\\n occ = rdrNameOcc rdr\\n ns = occNameSpace occ\\n\\n -- Look up a RdrName used in an import, returning multiple values if there\\n -- are several fields with the same name exposed by the module\\n lookup_names :: IE GhcPs -> RdrName -> IELookupM (NonEmpty ImpOccItem)\\n lookup_names ie rdr\\n | isQual rdr\\n = failLookupWith (QualImportError rdr)\\n | otherwise\\n = case lookups of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n item:items -> return $ item :| items\\n where\\n lookups = concatMap nonDetNameEnvElts\\n $ lookupImpOccEnv (RelevantGREsFOS WantNormal) imp_occ_env (rdrNameOcc rdr)\\n\\n lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, [GlobalRdrElt])]\\n lookup_lie (L loc ieRdr)\\n = setSrcSpanA loc $\\n do (stuff, warns) <- run_lookup ([],[]) (lookup_ie ieRdr)\\n mapM_ (addTcRnDiagnostic <=< warning_msg) warns\\n return [ (L loc ie, gres) | (ie,gres) <- stuff ]\\n where\\n\\n -- Warn when importing T(..) and no children are brought in scope\\n warning_msg (DodgyImport reason) =\\n pure (TcRnDodgyImports reason)\\n warning_msg MissingImportList =\\n pure (TcRnMissingImportList ieRdr)\\n warning_msg (BadImportW ie sub) = do\\n -- \'BadImportW\' is only constructed below in \'bad_import_w\', in\\n -- the \'EverythingBut\' case, so here we assume a \'hiding\' clause.\\n (reason :| _) <- badImportItemErr iface decl_spec ie sub all_avails\\n pure (TcRnDodgyImports (DodgyImportsHiding reason))\\n warning_msg (DeprecatedExport n w) =\\n pure $ TcRnPragmaWarning\\n PragmaWarningExport\\n { pwarn_occname = occName n\\n , pwarn_impmod = moduleName import_mod }\\n w\\n\\n run_lookup :: a -> IELookupM a -> TcRn a\\n run_lookup def m = case m of\\n Failed err -> do\\n msgs <- lookup_err_msgs err\\n forM_ msgs $ \\\\msg -> addErr (TcRnImportLookup msg)\\n return def\\n Succeeded a -> return a\\n\\n lookup_err_msgs err = case err of\\n BadImport ie sub -> badImportItemErr iface decl_spec ie sub all_avails\\n IllegalImport -> pure $ NE.singleton ImportLookupIllegal\\n QualImportError rdr -> pure $ NE.singleton (ImportLookupQualified rdr)\\n\\n -- For each import item, we convert its RdrNames to Names,\\n -- and at the same time compute all the GlobalRdrElt corresponding\\n -- to what is actually imported by this item.\\n -- Returns Nothing on error.\\n --\\n -- Returns a list because, with DuplicateRecordFields, a naked\\n -- import/export of a record field can correspond to multiple\\n -- different GlobalRdrElts. See Note [Importing DuplicateRecordFields].\\n lookup_ie :: IE GhcPs\\n -> IELookupM ([(IE GhcRn, [GlobalRdrElt])], [IELookupWarning])\\n lookup_ie ie = handle_bad_import $\\n case ie of\\n IEVar _ (L l n) _ -> do\\n -- See Note [Importing DuplicateRecordFields]\\n xs <- lookup_names ie (ieWrappedName n)\\n let gres = map imp_item $ NE.toList xs\\n export_depr_warns\\n | want_hiding == Exactly\\n = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ( [ (IEVar Nothing (L l (replaceWrappedName n name)) noDocstring, [gre])\\n | gre <- gres\\n , let name = greName gre ]\\n , export_depr_warns )\\n\\n IEThingAll x ns_spec (L l tc) _ -> do\\n ImpOccItem { imp_item = gre\\n , imp_bundled = bundled_gres\\n , imp_is_parent = is_par\\n }\\n <- lookup_parent ie $ ieWrappedName tc\\n let name = greName gre\\n\\n child_gres :: [GlobalRdrElt]\\n child_gres\\n | is_par = filterByNamespaceSpecifierGREs ns_spec bundled_gres\\n | otherwise = []\\n\\n imp_list_warn\\n\\n | null child_gres\\n -- e.g. f(..) or T(..) where T is a type synonym\\n = [DodgyImport (DodgyImportsEmptyParent ie ns_spec gre)]\\n\\n -- e.g. import M( T(..) )\\n | not (is_qual decl_spec)\\n = [MissingImportList]\\n\\n | otherwise\\n = []\\n\\n renamed_ie = IEThingAll (x { ieta_warning = Nothing })\\n (rnNamespaceSpecifier ns_spec)\\n (L l (replaceWrappedName tc name))\\n noDocstring\\n export_depr_warn\\n | want_hiding == Exactly\\n = maybeToList $ mk_depr_export_warning gre\\n -- We don\'t want to warn about the children as they\\n -- are not explicitly mentioned; the warning will\\n -- be emitted later on if they are used\\n | otherwise = []\\n\\n return ( [(renamed_ie, gre:child_gres)]\\n , imp_list_warn ++ export_depr_warn)\\n\\n\\n IEThingAbs _ (L l tc\') _\\n | want_hiding == EverythingBut -- hiding ( C )\\n -- Here the \'C\' can be a data constructor\\n -- *or* a type/class, or even both\\n -> let tc = ieWrappedName tc\'\\n tc_name = lookup_parent ie tc\\n dc_name = lookup_parent ie (setRdrNameSpace tc srcDataName)\\n in\\n case catIELookupM [ tc_name, dc_name ] of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n names -> return ( [mkIEThingAbs tc\' l (imp_item name) | name <- names], [])\\n | otherwise\\n -> do ImpOccItem { imp_item = gre } <- lookup_parent ie (ieWrappedName tc\')\\n return ( [mkIEThingAbs tc\' l gre]\\n , maybeToList $ mk_depr_export_warning gre)\\n\\n IEThingWith (deprecation, ann) ltc@(L l rdr_tc) wc rdr_ns _ -> do\\n ImpOccItem { imp_item = gre, imp_bundled = subnames }\\n <- lookup_parent (IEThingAbs Nothing ltc noDocstring) (ieWrappedName rdr_tc)\\n let name = greName gre\\n\\n -- Look up the children in the sub-names of the parent\\n -- See Note [Importing DuplicateRecordFields]\\n let (children_errs, childnames) = lookupChildren subnames rdr_ns\\n\\n bad_import_warns <-\\n if null children_errs then return [] else\\n let items = map lce_wrapped_name children_errs\\n ie = IEThingWith (deprecation, ann) ltc wc items noDocstring\\n -- We are trying to import T( a,b,c,d ), and failed\\n -- to find \'b\' and \'d\'. So we make up an import item\\n -- to report as failing, namely T( b, d ).\\n -- c.f. #15413\\n subordinate_err = mkSubordinateError gre children_errs\\n in bad_import_w ie subordinate_err\\n\\n let name\' = replaceWrappedName rdr_tc name\\n childnames\' = map (to_ie_post_rn . fmap greName) childnames\\n gres = gre : map unLoc childnames\\n export_depr_warns\\n | want_hiding == Exactly = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ([ (IEThingWith (Nothing, ann) (L l name\') wc childnames\' noDocstring\\n ,gres)]\\n , bad_import_warns ++ export_depr_warns)\\n\\n IEWholeNamespace x ns_spec -> do\\n let mod_name = moduleName import_mod\\n names = map greName gres\\n renamed_ie = IEWholeNamespace x { iewn_warning = Nothing\\n , iewn_names = names }\\n (rnNamespaceSpecifier ns_spec)\\n gres = filterByNamespaceSpecifierGREs ns_spec $\\n gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n dodgy_warn\\n | null gres = [DodgyImport (DodgyImportsWildcard mod_name ns_spec)]\\n | otherwise = []\\n return ([(renamed_ie, gres)],\\n dodgy_warn)\\n\\n _other -> failLookupWith IllegalImport\\n -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed...\\n -- all of those constitute errors.\\n\\n where\\n mkIEThingAbs tc l gre\\n = (IEThingAbs Nothing (L l (replaceWrappedName tc n)) noDocstring, [gre])\\n where n = greName gre\\n\\n -- N.B. imports never have docstrings\\n noDocstring = Nothing\\n\\n handle_bad_import m = catchIELookup m $ \\\\case\\n BadImport ie sub -> do\\n ws <- bad_import_w ie sub\\n return ([], ws)\\n err -> failLookupWith err\\n\\n bad_import_w :: IE GhcPs -> IsSubordinateError -> IELookupM [IELookupWarning]\\n bad_import_w ie sub\\n | want_hiding == EverythingBut = return [BadImportW ie sub]\\n | otherwise = failLookupWith (BadImport ie sub)\\n\\n mk_depr_export_warning gre\\n = DeprecatedExport name <$> mi_export_warn_fn iface name\\n where\\n name = greName gre\\n\\n-- | Assuming a subordinate item could not be found, do another lookup for a\\n-- more specific error message.\\nmkBadExportSubordinate :: [GlobalRdrElt] -> LIEWrappedName GhcPs -> BadExportSubordinate\\nmkBadExportSubordinate child_gres n =\\n case lookupChildren child_gres [n] of\\n (LookupChildNonType {lce_nontype_item = g} : _, _) -> BadExportSubordinateNonType g\\n (LookupChildNonData {lce_nondata_item = g} : _, _) -> BadExportSubordinateNonData g\\n _ -> BadExportSubordinateNotFound n\\n\\ntype IELookupM = MaybeErr IELookupError\\n\\ndata IELookupWarning\\n = BadImportW (IE GhcPs) IsSubordinateError\\n | MissingImportList\\n | DodgyImport DodgyImportsReason\\n | DeprecatedExport Name (WarningTxt GhcRn)\\n\\n-- | Is this import/export item a subordinate or not?\\ndata IsSubordinateError\\n = IsSubordinateError { subordinate_err_parent :: !GlobalRdrElt\\n , subordinate_err_unavailable :: [FastString]\\n , subordinate_err_nontype :: [GlobalRdrElt]\\n , subordinate_err_nondata :: [GlobalRdrElt] }\\n | IsNotSubordinate\\n\\nmkSubordinateError :: GlobalRdrElt -> [LookupChildError] -> IsSubordinateError\\nmkSubordinateError gre children_errs = foldr add init_acc children_errs\\n where\\n init_acc :: IsSubordinateError\\n init_acc = IsSubordinateError gre [] [] []\\n\\n add :: LookupChildError -> IsSubordinateError -> IsSubordinateError\\n add children_err sub@IsSubordinateError{} =\\n case children_err of\\n LookupChildNonType{lce_nontype_item = g} ->\\n sub { subordinate_err_nontype = g : subordinate_err_nontype sub }\\n LookupChildNonData{lce_nondata_item = g} ->\\n sub { subordinate_err_nondata = g : subordinate_err_nondata sub }\\n LookupChildNotFound (L _ wname) ->\\n let fs = (occNameFS . rdrNameOcc . ieWrappedName) wname\\n in sub { subordinate_err_unavailable = fs : subordinate_err_unavailable sub }\\n add _ IsNotSubordinate = panic \\"mkSubordinateError: IsNotSubordinate\\"\\n\\ndata IELookupError\\n = QualImportError RdrName\\n | BadImport (IE GhcPs) IsSubordinateError\\n | IllegalImport\\n\\nfailLookupWith :: IELookupError -> IELookupM a\\nfailLookupWith err = Failed err\\n\\ncatchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a\\ncatchIELookup m h = case m of\\n Succeeded r -> return r\\n Failed err -> h err\\n\\ncatIELookupM :: [IELookupM a] -> [a]\\ncatIELookupM ms = [ a | Succeeded a <- ms ]\\n\\n-- | Information associated to an \'AvailInfo\' used in constructing\\n-- an \'OccEnv\' corresponding to imports.\\n--\\n-- See Note [Dealing with imports].\\ndata ImpOccItem\\n = ImpOccItem\\n { imp_item :: GlobalRdrElt\\n -- ^ The import item\\n , imp_bundled :: [GlobalRdrElt]\\n -- ^ Items bundled in the Avail this import item came from,\\n -- not including the import item itself if it is a parent.\\n , imp_is_parent :: Bool\\n -- ^ Is the import item a parent? See Note [Dealing with imports].\\n }\\n\\ninstance Outputable ImpOccItem where\\n ppr (ImpOccItem { imp_item = item, imp_bundled = bundled, imp_is_parent = is_par })\\n = braces $ hsep\\n [ text \\"ImpOccItem\\"\\n , if is_par then text \\"[is_par]\\" else empty\\n , ppr (greName item) <+> ppr (greParent item)\\n , braces $ text \\"bundled:\\" <+> ppr (map greName bundled) ]\\n\\n-- | Make an \'OccEnv\' of all the imports.\\n--\\n-- Complicated by the fact that associated data types and pattern synonyms\\n-- can appear twice. See Note [Dealing with imports].\\nmkImportOccEnv :: HscEnv -> ImpDeclSpec -> [IfaceExport] -> OccEnv (NameEnv ImpOccItem)\\nmkImportOccEnv hsc_env decl_spec all_avails =\\n mkOccEnv_C (plusNameEnv_C combine)\\n [ (occ, mkNameEnv [(nm, item)])\\n | avail <- all_avails\\n , let gres = gresFromAvail hsc_env (Just hiding_spec) avail\\n , gre <- gres\\n , let nm = greName gre\\n occ = greOccName gre\\n (is_parent, bundled) = case avail of\\n AvailTC c _\\n | c == nm -- (Recall the AvailTC invariant from GHC.Types.AvailInfo)\\n -> ( True, drop 1 gres ) -- \\"drop 1\\": don\'t include the parent itself.\\n | otherwise\\n -> ( False, gres )\\n _ -> ( False, [] )\\n item = ImpOccItem\\n { imp_item = gre\\n , imp_bundled = bundled\\n , imp_is_parent = is_parent }\\n ]\\n where\\n\\n hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\n -- See Note [Dealing with imports]\\n -- \'combine\' may be called for associated data types which appear\\n -- twice in the all_avails. In the example, we have two Avails for T,\\n -- namely T(T,T1,T2,T3) and C(C,T), and we combine them by dropping the\\n -- latter, in which T is not the parent.\\n combine :: ImpOccItem -> ImpOccItem -> ImpOccItem\\n combine item1@(ImpOccItem { imp_item = gre1, imp_is_parent = is_parent1 })\\n item2@(ImpOccItem { imp_item = gre2, imp_is_parent = is_parent2 })\\n | is_parent1 || is_parent2\\n , not (isRecFldGRE gre1 || isRecFldGRE gre2) -- NB: does not force GREInfo.\\n , let name1 = greName gre1\\n name2 = greName gre2\\n gre = gre1 `plusGRE` gre2\\n -- See Note [Preserve parent information when combining import OccEnvs]\\n = assertPpr (name1 == name2)\\n (ppr name1 <+> ppr name2) $\\n if is_parent1\\n then item1 { imp_item = gre }\\n else item2 { imp_item = gre }\\n -- Discard C(C,T) in favour of T(T, T1, T2, T3).\\n\\n -- \'combine\' may also be called for pattern synonyms which appear both\\n -- unassociated and associated (see Note [Importing PatternSynonyms]).\\n combine item1@(ImpOccItem { imp_item = c1, imp_bundled = kids1 })\\n item2@(ImpOccItem { imp_item = c2, imp_bundled = kids2 })\\n = assertPpr (greName c1 == greName c2\\n && (not (null kids1 && null kids2)))\\n (ppr c1 <+> ppr c2 <+> ppr kids1 <+> ppr kids2) $\\n if null kids1\\n then item2\\n else item1\\n -- Discard standalone pattern P in favour of T(P).\\n\\n-- | Essentially like @lookupGRE env (LookupOccName occ which_gres)@,\\n-- but working with \'ImpOccItem\'s instead of \'GlobalRdrElt\'s.\\nlookupImpOccEnv :: WhichGREs GREInfo\\n -> OccEnv (NameEnv ImpOccItem) -> OccName -> [NameEnv ImpOccItem]\\nlookupImpOccEnv which_gres env occ =\\n mapMaybe relevant_items $ lookupOccEnv_AllNameSpaces env occ\\n where\\n is_relevant :: ImpOccItem -> Bool\\n is_relevant (ImpOccItem { imp_item = gre }) =\\n greIsRelevant which_gres (occNameSpace occ) gre\\n relevant_items :: NameEnv ImpOccItem -> Maybe (NameEnv ImpOccItem)\\n relevant_items nms\\n | let nms\' = filterNameEnv is_relevant nms\\n = if isEmptyNameEnv nms\'\\n then Nothing\\n else Just nms\'\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{Import/Export Utils}\\n* *\\n************************************************************************\\n-}\\n\\n-- | Given an import\\\\/export spec, appropriately set the @gre_imp@ field\\n-- for the \'GlobalRdrElt\'s.\\ngresFromIE :: ImpDeclSpec -> (LIE GhcRn, [GlobalRdrElt]) -> [GlobalRdrElt]\\ngresFromIE decl_spec (L loc ie, gres)\\n = map set_gre_imp gres\\n where\\n is_explicit = case ie of\\n IEThingAll _ _ name _ -> \\\\n -> n == lieWrappedName name\\n IEWholeNamespace _ _ -> \\\\_ -> False\\n _ -> \\\\_ -> True\\n prov_fn name\\n = ImpSpec { is_decl = decl_spec, is_item = item_spec }\\n where\\n item_spec = ImpSome { is_explicit = is_explicit name\\n , is_iloc = locA loc }\\n set_gre_imp gre@( GRE { gre_name = nm } )\\n = gre { gre_imp = unitBag $ prov_fn nm }\\n\\nparentOfImplicitlyImportedGRE :: Outputable info => GlobalRdrEltX info -> Maybe Name\\nparentOfImplicitlyImportedGRE gre =\\n if any (explicit_import . is_item) $ gre_imp gre\\n then Nothing\\n else greParent_maybe gre\\n where\\n explicit_import :: ImpItemSpec -> Bool\\n explicit_import (ImpAll {}) =\\n pprPanic \\"parentOfImplicitlyImportedGRE: ImpAll\\" (ppr gre)\\n explicit_import (ImpSome { is_explicit }) = is_explicit\\n\\n{- Note [Children for duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider the module\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (F(foo, MkFInt, MkFBool)) where\\n data family F a\\n data instance F Int = MkFInt { foo :: Int }\\n data instance F Bool = MkFBool { foo :: Bool }\\n\\nThe `foo` in the export list refers to *both* selectors! For this\\nreason, lookupChildren builds an environment that maps the FastString\\nto a list of items, rather than a single item.\\n-}\\n\\nmkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]\\nmkChildEnv gres = foldr add emptyNameEnv gres\\n where\\n add gre env = case greParent gre of\\n ParentIs p -> extendNameEnv_Acc (:) Utils.singleton env p gre\\n NoParent -> env\\n\\nfindChildren :: NameEnv [a] -> Name -> [a]\\nfindChildren env n = lookupNameEnv env n `orElse` []\\n\\ndata LookupChildError\\n = LookupChildNotFound { lce_wrapped_name :: !(LIEWrappedName GhcPs) }\\n | LookupChildNonType { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nontype_item :: !GlobalRdrElt }\\n | LookupChildNonData { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nondata_item :: !GlobalRdrElt }\\n\\nlookupChildren :: [GlobalRdrElt]\\n -> [LIEWrappedName GhcPs]\\n -> ( [LookupChildError] -- The ones for which the lookup failed\\n , [LocatedA GlobalRdrElt] )\\n-- (lookupChildren all_kids rdr_items) maps each rdr_item to its\\n-- corresponding Name in all_kids, if the former exists\\n-- The matching is done by FastString, not OccName, so that\\n-- Cls( meth, AssocTy )\\n-- will correctly find AssocTy among the all_kids of Cls, even though\\n-- the RdrName for AssocTy may have a (bogus) DataName namespace\\n-- (Really the rdr_items should be FastStrings in the first place.)\\nlookupChildren all_kids rdr_items = (fails, successes)\\n where\\n mb_xs = map do_one rdr_items\\n fails = [ err | Failed err <- mb_xs ]\\n successes = [ ok | Succeeded oks <- mb_xs, ok <- NE.toList oks ]\\n\\n do_one :: LIEWrappedName GhcPs -> MaybeErr LookupChildError (NonEmpty (LocatedA GlobalRdrElt))\\n do_one item@(L l r) =\\n case r of\\n IEName{}\\n -- IEName (unadorned name) places no restriction on the namespace of\\n -- the imported entity, so we look in both `val_gres` and `typ_gres`.\\n -- In case of conflict (punning), the value namespace takes priority.\\n -- See Note [Prioritise the value namespace in subordinate import lists]\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEType{}\\n -- IEType (\'type\' namespace specifier) restricts the lookup to the\\n -- type namespace, i.e. to `typ_gres`. In case of failure, we check\\n -- `val_gres` to produce a more helpful error message.\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- val_gres -> Failed $ LookupChildNonType item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEData{}\\n -- IEData (\'data\' namespace specifier) restricts the lookup to the\\n -- data namespace, i.e. to `val_gres`. In case of failure, we check\\n -- `typ_gres` to produce a more helpful error message.\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- typ_gres -> Failed $ LookupChildNonData item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEPattern{} -> panic \\"lookupChildren: IEPattern\\" -- Never happens (invalid syntax)\\n IEDefault{} -> panic \\"lookupChildren: IEDefault\\" -- Never happens (invalid syntax)\\n where\\n fs = (occNameFS . rdrNameOcc . ieWrappedName) r\\n gres = fromMaybe [] (lookupFsEnv kid_env fs)\\n (val_gres, typ_gres) = partition (isValNameSpace . greNameSpace) gres\\n\\n -- See Note [Children for duplicate record fields]\\n kid_env :: FastStringEnv [GlobalRdrElt]\\n kid_env = extendFsEnvList_C (++) emptyFsEnv\\n [(occNameFS (occName x), [x]) | x <- all_kids]\\n\\n\\n{- Note [Prioritise the value namespace in subordinate import lists]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider this program that defines a class that has both an associated type\\nnamed (#) and a method named (#)\\n\\n module M_assoc where\\n class C a b where\\n type a # b\\n (#) :: a -> b -> ()\\n module N_assoc where\\n import M_assoc( C((#)) )\\n\\nIn the import declaration, when we see the unadorned name (#) in the subordinate\\nimport list of C, which children should we bring into scope? Our options are:\\n\\n a) only the method (#)\\n b) only the associated type (#)\\n c) both the method and the associated type\\n\\nTo follow the precedent established by top-level items, we go with option (a).\\nIndeed, consider a slightly different program\\n\\n module M_top where\\n type family a # b\\n a # b = ()\\n module N_top where\\n import M_top( (#) )\\n\\nHere the import brings only the function (#) into scope, and one has to say\\n`type (#)` to get the type family.\\n-}\\n\\n-------------------------------\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused names}\\n* *\\n*********************************************************\\n-}\\n\\nreportUnusedNames :: TcGblEnv -> HscSource -> RnM ()\\nreportUnusedNames gbl_env hsc_src\\n = do { keep <- readTcRef (tcg_keep gbl_env)\\n ; traceRn \\"RUN\\" (ppr (tcg_dus gbl_env))\\n ; warnUnusedImportDecls gbl_env hsc_src\\n ; warnUnusedTopBinds $ unused_locals keep\\n ; warnMissingSignatures gbl_env\\n ; warnMissingKindSignatures gbl_env }\\n where\\n used_names :: NameSet -> NameSet\\n used_names keep = findUses (tcg_dus gbl_env) emptyNameSet `unionNameSet` keep\\n -- NB: currently, if f x = g, we only treat \'g\' as used if \'f\' is used\\n -- Hence findUses\\n\\n -- Collect the defined names from the in-scope environment\\n defined_names :: [GlobalRdrElt]\\n defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)\\n\\n kids_env = mkChildEnv defined_names\\n -- This is done in mkExports too; duplicated work\\n\\n gre_is_used :: NameSet -> GlobalRdrElt -> Bool\\n gre_is_used used_names gre0\\n = name `elemNameSet` used_names\\n || any (\\\\ gre -> greName gre `elemNameSet` used_names) (findChildren kids_env name)\\n -- A use of C implies a use of T,\\n -- if C was brought into scope by T(..) or T(C)\\n where\\n name = greName gre0\\n\\n -- Filter out the ones that are\\n -- (a) defined in this module, and\\n -- (b) not defined by a \'deriving\' clause\\n -- The latter have an Internal Name, so we can filter them out easily\\n unused_locals :: NameSet -> [GlobalRdrElt]\\n unused_locals keep =\\n let -- Note that defined_and_used, defined_but_not_used\\n -- are both [GRE]; that\'s why we need defined_and_used\\n -- rather than just used_names\\n _defined_and_used, defined_but_not_used :: [GlobalRdrElt]\\n (_defined_and_used, defined_but_not_used)\\n = partition (gre_is_used (used_names keep)) defined_names\\n\\n in filter is_unused_local defined_but_not_used\\n is_unused_local :: GlobalRdrElt -> Bool\\n is_unused_local gre = isLocalGRE gre\\n && isExternalName (greName gre)\\n\\n{- *********************************************************************\\n* *\\n Missing signatures\\n* *\\n********************************************************************* -}\\n\\n{-\\nNote [Missing signatures]\\n~~~~~~~~~~~~~~~~~~~~~~~~~\\nThere are four warning flags in play:\\n\\n * -Wmissing-exported-signatures\\n Warn about any exported top-level function/value without a type signature.\\n Does not include pattern synonyms.\\n\\n * -Wmissing-signatures\\n Warn about any top-level function/value without a type signature. Does not\\n include pattern synonyms. Takes priority over -Wmissing-exported-signatures.\\n\\n * -Wmissing-exported-pattern-synonym-signatures\\n Warn about any exported pattern synonym without a type signature.\\n\\n * -Wmissing-pattern-synonym-signatures\\n Warn about any pattern synonym without a type signature. Takes priority over\\n -Wmissing-exported-pattern-synonym-signatures.\\n\\n-}\\n\\n-- | Warn the user about top level binders that lack type signatures.\\n-- Called /after/ type inference, so that we can report the\\n-- inferred type of the function\\nwarnMissingSignatures :: TcGblEnv -> RnM ()\\nwarnMissingSignatures gbl_env\\n = do { let exports = availsToNameSet (tcg_exports gbl_env)\\n sig_ns = tcg_sigs gbl_env\\n -- We use sig_ns to exclude top-level bindings that are generated by GHC\\n binds = collectHsBindsBinders CollNoDictBinders $ tcg_binds gbl_env\\n pat_syns = tcg_patsyns gbl_env\\n\\n not_ghc_generated :: Name -> Bool\\n not_ghc_generated name = name `elemNameSet` sig_ns\\n\\n add_binding_warn :: Id -> RnM ()\\n add_binding_warn id =\\n when (not_ghc_generated name) $\\n do { env <- liftZonkM $ tcInitTidyEnv -- Why not use emptyTidyEnv?\\n ; let ty = tidyOpenType env (idType id)\\n missing = MissingTopLevelBindingSig name ty\\n diag = TcRnMissingSignature missing exported\\n ; addDiagnosticAt (getSrcSpan name) diag }\\n where\\n name = idName id\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n add_patsyn_warn :: PatSyn -> RnM ()\\n add_patsyn_warn ps =\\n when (not_ghc_generated name) $\\n addDiagnosticAt (getSrcSpan name)\\n (TcRnMissingSignature missing exported)\\n where\\n name = patSynName ps\\n missing = MissingPatSynSig ps\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n -- Warn about missing signatures\\n -- Do this only when we have a type to offer\\n -- See Note [Missing signatures]\\n ; mapM_ add_binding_warn binds\\n ; mapM_ add_patsyn_warn pat_syns\\n }\\n\\n-- | Warn the user about tycons that lack kind signatures.\\n-- Called /after/ type (and kind) inference, so that we can report the\\n-- inferred kinds.\\nwarnMissingKindSignatures :: TcGblEnv -> RnM ()\\nwarnMissingKindSignatures gbl_env\\n = do { cusks_enabled <- xoptM LangExt.CUSKs\\n ; mapM_ (add_ty_warn cusks_enabled) tcs\\n }\\n where\\n tcs = tcg_tcs gbl_env\\n ksig_ns = tcg_ksigs gbl_env\\n exports = availsToNameSet (tcg_exports gbl_env)\\n\\n has_kind_signature :: Name -> Bool\\n has_kind_signature name = name `elemNameSet` ksig_ns\\n\\n add_ty_warn :: Bool -> TyCon -> RnM ()\\n add_ty_warn cusks_enabled tyCon =\\n when (has_kind_signature name) $\\n addDiagnosticAt (getSrcSpan name) diag\\n where\\n name = tyConName tyCon\\n diag = TcRnMissingSignature missing exported\\n missing = MissingTyConKindSig tyCon cusks_enabled\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused imports}\\n* *\\n*********************************************************\\n\\nThis code finds which import declarations are unused. The\\nspecification and implementation notes are here:\\n https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/unused-imports\\n\\nSee also Note [Choosing the best import declaration] in GHC.Types.Name.Reader\\n-}\\n\\ntype ImportDeclUsage\\n = ( LImportDecl GhcRn -- The import declaration\\n , [GlobalRdrElt] -- What *is* used (normalised)\\n , [Name] -- What is imported but *not* used\\n , [NamespaceSpecifier GhcRn] ) -- Unused wildcards\\n\\nwarnUnusedImportDecls :: TcGblEnv -> HscSource -> RnM ()\\nwarnUnusedImportDecls gbl_env hsc_src\\n = do { uses <- readMutVar (tcg_used_gres gbl_env)\\n ; let imports = tcg_rn_imports gbl_env\\n rdr_env = tcg_rdr_env gbl_env\\n\\n -- We should only warn for unnecessary *user* imports, but deciding\\n -- minimal imports should take generated imports into account\\n ; let usageUserImports = findImportUsage (excludeGenerated imports) uses\\n usageAllImports = findImportUsage imports uses\\n\\n ; traceRn \\"warnUnusedImportDecls\\" $\\n (vcat [ text \\"Uses:\\" <+> ppr uses\\n , text \\"Usage all user imports: \\" <+> ppr usageUserImports\\n , text \\"Usage all imports: \\" <+> ppr usageAllImports])\\n\\n ; mapM_ (warnUnusedImport rdr_env) usageUserImports\\n\\n ; whenGOptM Opt_D_dump_minimal_imports $\\n printMinimalImports hsc_src usageAllImports }\\n\\n-- | Exclude generated imports\\nexcludeGenerated :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\nexcludeGenerated = filterOut (isGeneratedImport . ideclOrigin . ideclExt . unLoc)\\n\\nfindImportUsage :: [LImportDecl GhcRn]\\n -> [GlobalRdrElt]\\n -> [ImportDeclUsage]\\n\\nfindImportUsage imports used_gres\\n = map unused_decl imports\\n where\\n import_usage :: ImportMap\\n import_usage = mkImportMap used_gres\\n\\n unused_decl :: LImportDecl GhcRn -> ImportDeclUsage\\n unused_decl decl@(L _ (ImportDecl { ideclImportList = imps }))\\n = -- pprTrace \\"unused_decl\\" (vcat [ ppr decl\\n -- , text \\"used\\" <+> ppr used_gres\\n -- , text \\"unused\\" <+> ppr unused_names ]) $\\n (decl, used_gres, unused_names, unused_wcs)\\n where\\n used_gres = lookupImportMap decl import_usage\\n\\n used_gre_env = mkGlobalRdrEnv used_gres\\n used_parents = mkNameSet (mapMaybe greParent_maybe used_gres)\\n\\n (unused_names, unused_wcs) -- Not trivial; see eg #7454\\n = case imps of\\n Just (Exactly, imp_ies) ->\\n let unused = foldr (add_unused . unLoc) emptyUnusedNames imp_ies\\n nms = nameSetElemsStable (collectUnusedNames unused)\\n wcs = collectUnusedWildcards unused\\n in (nms, wcs)\\n _other -> ([], []) -- No explicit import list => no unused-name list\\n\\n add_unused :: IE GhcRn -> UnusedNames -> UnusedNames\\n add_unused (IEVar _ n _) acc = add_unused_name (lieWrappedName n) True acc\\n add_unused (IEThingAbs _ n _) acc = add_unused_name (lieWrappedName n) False acc\\n add_unused (IEThingAll _ _ n _) acc = add_unused_all (lieWrappedName n) acc\\n add_unused (IEThingWith _ p wc ns _) acc = add_wc_all (add_unused_with pn xs acc)\\n where pn = lieWrappedName p\\n xs = map lieWrappedName ns\\n add_wc_all = case wc of\\n NoIEWildcard -> id\\n IEWildcard _ -> add_unused_all pn\\n add_unused (IEWholeNamespace x ns_spec) acc = add_unused_wildcard ns_spec (iewn_names x) acc\\n add_unused _ acc = acc\\n\\n add_unused_name :: Name -> Bool -> UnusedNames -> UnusedNames\\n add_unused_name n is_ie_var acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | is_ie_var\\n , isFieldName n\\n -- See Note [Reporting unused imported duplicate record fields]\\n = let\\n fs = getOccFS n\\n (flds, flds_used) = lookupFsEnv acc_fs fs `orElse` (emptyNameSet, Any False)\\n acc_fs\' = extendFsEnv acc_fs fs (extendNameSet flds n, Any used S.<> flds_used)\\n in UnusedNames acc_ns acc_wcs acc_fs\'\\n\\n | used\\n = acc\\n\\n | otherwise\\n = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n where\\n used = isJust $ lookupGRE_Name used_gre_env n\\n\\n add_unused_all :: Name -> UnusedNames -> UnusedNames\\n add_unused_all n acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | Just {} <- lookupGRE_Name used_gre_env n = acc\\n | n `elemNameSet` used_parents = acc\\n | otherwise = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n\\n add_unused_with :: Name -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_with p ns acc\\n | all (`elemNameSet` acc1_ns) ns = add_unused_name p False acc1\\n | otherwise = acc1\\n where\\n acc1@(UnusedNames acc1_ns _ _) = foldr (\\\\n acc\' -> add_unused_name n False acc\') acc ns\\n -- If you use \'signum\' from Num, then the user may well have\\n -- imported Num(signum). We don\'t want to complain that\\n -- Num is not itself mentioned. Hence the two cases in add_unused_with.\\n\\n add_unused_wildcard :: NamespaceSpecifier GhcRn -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_wildcard ns_spec names acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | any_used = acc\\n | otherwise = UnusedNames acc_ns (ns_spec : acc_wcs) acc_fs\\n where\\n -- A wildcard `type ..` or `data ..` is used if at least one of\\n -- the names it expands to is used\\n any_used = any (isJust . lookupGRE_Name used_gre_env) names\\n\\n\\n-- | An accumulator for unused names in an import list.\\n--\\n-- See Note [Reporting unused imported duplicate record fields].\\ndata UnusedNames =\\n UnusedNames\\n { unused_names :: NameSet\\n -- ^ Unused \'Name\'s in an import list, not including record fields\\n -- that are plain \'IEVar\' imports (tracked by \'rec_fld_uses\')\\n -- or wildcard imports (tracked by \'unused_wildcards\').\\n , unused_wildcards :: [NamespaceSpecifier GhcRn]\\n -- ^ Unused wildcards @type ..@ or @data ..@ in an import list.\\n , rec_fld_uses :: FastStringEnv (NameSet, Any)\\n -- ^ Record fields imported without a parent (i.e. an \'IEVar\' import).\\n --\\n -- The \'Any\' value records whether any of the record fields\\n -- sharing the same underlying \'FastString\' have been used.\\n }\\n\\nemptyUnusedNames :: UnusedNames\\nemptyUnusedNames = UnusedNames emptyNameSet [] emptyFsEnv\\n\\ninstance Outputable UnusedNames where\\n ppr (UnusedNames nms wcs flds) =\\n text \\"UnusedNames\\" <+>\\n braces (ppr nms <+> ppr wcs <+> ppr (fmap (second getAny) flds))\\n\\n-- | Collect all unused names from a \'UnusedNames\' value.\\ncollectUnusedNames :: UnusedNames -> NameSet\\ncollectUnusedNames (UnusedNames { unused_names = nms, rec_fld_uses = flds })\\n = nms S.<> unused_flds\\n where\\n unused_flds = nonDetFoldFsEnv collect_unused emptyNameSet flds\\n collect_unused :: (NameSet, Any) -> NameSet -> NameSet\\n collect_unused (nms, Any at_least_one_name_is_used) acc\\n | at_least_one_name_is_used = acc\\n | otherwise = unionNameSet nms acc\\n\\ncollectUnusedWildcards :: UnusedNames -> [NamespaceSpecifier GhcRn]\\ncollectUnusedWildcards = unused_wildcards\\n\\n{- Note [Reporting unused imported duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have (#24035):\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M1 (R1(..), R2(..)) where\\n data R1 = MkR1 { fld :: Int }\\n data R2 = MkR2 { fld :: Int }\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M2 where\\n import M1 (R1(MkR1), R2, fld)\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nIn the import of \'M1\' in \'M2\', the \'fld\' import resolves to two separate GREs,\\nnamely R1(fld) and R2(fld). From the perspective of the renamer, and in particular\\nthe \'findImportUsage\' function, it\'s as if the user had imported the two names\\nseparately (even though no source syntax allows that).\\n\\nThis means that we need to be careful when reporting unused imports: the R2(fld)\\nimport is indeed unused, but because R1(fld) is used, we should not report\\nfld as unused altogether.\\n\\nTo achieve this, we keep track of record field imports without a parent (i.e.\\nusing the IEVar constructor) separately from other import items, using the\\nUnusedNames datatype.\\nOnce we have accumulated usages, we emit warnings for unused record fields\\nwithout parents one whole group (of record fields sharing the same textual name)\\nat a time, and only if *all* of the record fields in the group are unused;\\nsee \'collectUnusedNames\'.\\n\\nNote that this only applies to record fields imported without a parent. If we\\nhad:\\n\\n import M1 (R1(MkR1, fld), R2(fld))\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nthen of course we should report the second \'fld\' as unused.\\n-}\\n\\n\\n{- Note [The ImportMap]\\n~~~~~~~~~~~~~~~~~~~~~~~\\nThe ImportMap is a short-lived intermediate data structure records, for\\neach import declaration, what stuff brought into scope by that\\ndeclaration is actually used in the module.\\n\\nThe [GlobalRdrElt] are the things imported from that decl.\\n-}\\n\\ndata ImportMap = ImportMap\\n { im_imports :: Map RealSrcSpan [GlobalRdrElt]\\n -- ^ See [The ImportMap]\\n -- If loc :-> gres, then\\n -- \'loc\' = the end loc of the bestImport of each GRE in \'gres\'\\n , im_generatedImports :: Map ModuleName [GlobalRdrElt]\\n }\\n\\nmkImportMap :: [GlobalRdrElt] -> ImportMap\\n-- For each of a list of used GREs, find all the import decls that brought\\n-- it into scope; choose one of them (bestImport), and record\\n-- the RdrName in that import decl\'s entry in the ImportMap\\nmkImportMap = foldr insertImportMap $ ImportMap Map.empty Map.empty\\n\\ninsertImportMap :: GlobalRdrElt -> ImportMap -> ImportMap\\ninsertImportMap gre@(GRE { gre_imp = imp_specs }) importMap\\n | RealSrcSpan importSpan _ <- is_dloc best_imp_spec =\\n importMap{im_imports = insertElem importSpan gre $ im_imports importMap}\\n | GeneratedSrcSpan{} <- is_dloc best_imp_spec =\\n importMap{im_generatedImports = insertElem (moduleName $ is_mod best_imp_spec) gre $ im_generatedImports importMap}\\n | otherwise = importMap\\n where\\n best_imp_spec =\\n case bagToList imp_specs of\\n [] -> pprPanic \\"mkImportMap: GRE with no ImportSpecs\\" (ppr gre)\\n is:iss -> is_decl $ bestImport (is NE.:| iss)\\n\\n -- https://github.com/haskell/containers/issues/784\\n insertElem :: Ord k => k -> v -> Map k [v] -> Map k [v]\\n insertElem k v = flip Map.alter k $ \\\\case\\n Just vs -> Just (v : vs)\\n Nothing -> Just [v]\\n\\nlookupImportMap :: LImportDecl GhcRn -> ImportMap -> [GlobalRdrElt]\\nlookupImportMap (L srcSpan ImportDecl{ideclName = L _ modName}) importMap =\\n fromMaybe [] $\\n -- should match logic in insertImportMap\\n case locA srcSpan of\\n RealSrcSpan realSrcSpan _ -> realSrcSpan `Map.lookup` im_imports importMap\\n GeneratedSrcSpan{} -> modName `Map.lookup` im_generatedImports importMap\\n _ -> Nothing\\n\\nlieNames :: LIE (GhcPass p) -> [Located (IdP (GhcPass p))]\\nlieNames = _\\n\\nwarnUnusedImport :: GlobalRdrEnv -> ImportDeclUsage -> RnM ()\\nwarnUnusedImport rdr_env (L loc decl, used, unused, unused_wcs)\\n\\n -- Do not warn for \'import M()\'\\n -- See (UI1) in Note [Unused imports]\\n | Just (Exactly, _) <- ideclImportList decl\\n , null unused && null unused_wcs\\n = return ()\\n\\n -- Note [Do not warn about Prelude hiding]\\n | Just (EverythingBut, hides) <- ideclImportList decl\\n , not (null hides)\\n , pRELUDE_NAME == unLoc (ideclName decl)\\n = return ()\\n\\n -- Do not warn about import X as Rebindable\\n -- See (UI2) in Note [Unused imports]\\n | Just (L _ mod) <- ideclAs decl\\n , mod == rEBINDABLE_MOD_NAME\\n = return ()\\n\\n -- Nothing used; drop entire declaration\\n | null used\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl UnusedImportNone)\\n\\n -- Everything imported is used; nop\\n | null unused && null unused_wcs\\n = return ()\\n\\n -- Some imports are unused: make the `SrcSpan` cover only the unused\\n -- items instead of the whole import statement\\n | Just (_, imports) <- ideclImportList decl\\n , let unused_locs = [ locA loc | L loc ie <- imports\\n , name <- ieNames ie\\n , name `elem` unused ]\\n , loc1 : locs <- unused_locs\\n , let span = foldr1 combineSrcSpans ( loc1 NE.:| locs )\\n = addDiagnosticAt span (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n -- Some imports are unused\\n | otherwise\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n where\\n -- In warning message, pretty-print identifiers unqualified unconditionally\\n -- to improve the consistent for ambiguous/unambiguous identifiers.\\n -- See #14881.\\n possible_field n =\\n case lookupGRE_Name rdr_env n of\\n Just (GRE { gre_par = par, gre_info = IAmRecField info }) ->\\n let fld_occ :: OccName\\n fld_occ = nameOccName $ flSelector $ recFieldLabel info\\n in UnusedImportNameRecField par fld_occ\\n _ -> UnusedImportNameRegular n\\n\\n -- Print unused names in a deterministic (lexicographic) order\\n sort_unused :: [UnusedImportName]\\n sort_unused =\\n [ UnusedImportWildcard wc | wc <- unused_wcs ] ++\\n [ possible_field nm | nm <- sortBy (comparing nameOccName) unused ]\\n\\ngetMinimalImports :: [ImportDeclUsage] -> RnM [LImportDecl GhcRn]\\ngetMinimalImports ie_decls\\n = do { rdr_env <- getGlobalRdrEnv\\n ; fmap combine $ mapM (mk_minimal rdr_env) ie_decls }\\n where\\n mk_minimal rdr_env (L l decl, used_gres, unused, unused_wcs)\\n | null unused && null unused_wcs\\n , Just (Exactly, _) <- ideclImportList decl\\n = return (L l decl)\\n | otherwise\\n = do { let ImportDecl { ideclName = L _ mod_name\\n , ideclSource = is_boot\\n , ideclPkgQual = pkg_qual\\n , ideclExt = XImportDeclPass { ideclOrigin = origin } } = decl\\n ; iface <- loadSrcInterface doc (importDeclLookupScope origin)\\n mod_name is_boot pkg_qual\\n ; let used_avails = gresToAvailInfo used_gres\\n ; lies <- map (L l) <$> concatMapM (to_ie rdr_env iface) used_avails\\n ; return (L l (decl { ideclImportList = Just (Exactly, lies) })) }\\n where\\n doc = text \\"Compute minimal imports for\\" <+> ppr decl\\n\\n to_ie :: GlobalRdrEnv -> ModIface -> AvailInfo -> RnM [IE GhcRn]\\n -- The main trick here is that if we\'re importing all the constructors\\n -- we want to say \\"T(..)\\", but if we\'re importing only a subset we want\\n -- to say \\"T(A,B,C)\\". So we have to find out what the module exports.\\n to_ie rdr_env _ (Avail c) -- Note [Overloaded field import]\\n = do { let\\n gre = expectJust $ lookupGRE_Name rdr_env c\\n ; return $ [IEVar Nothing (to_ie_post_rn $ noLocA $ greName gre) Nothing] }\\n to_ie _ _ avail@(AvailTC n [_]) -- Exporting the main decl and nothing else\\n | availExportsDecl avail\\n = return [IEThingAbs Nothing (to_ie_post_rn $ noLocA n) Nothing]\\n to_ie rdr_env iface (AvailTC n cs) =\\n case [ xs | avail@(AvailTC x xs) <- mi_exports iface\\n , x == n\\n , availExportsDecl avail -- Note [Partial export]\\n ] of\\n [xs]\\n | all_used xs\\n -> return [IEThingAll (IEThingAllExt Nothing noAnn noAnn noAnn)\\n (NoNamespaceSpecifier noExtField)\\n (to_ie_post_rn $ noLocA n)\\n Nothing]\\n | otherwise\\n -> do { let ns_gres = map (expectJust . lookupGRE_Name rdr_env) cs\\n ns = map greName ns_gres\\n ; return [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n -- Note [Overloaded field import]\\n _other\\n -> do { let infos = map (expectJust . lookupGRE_Name rdr_env) cs\\n (ns_gres,fs_gres) = classifyGREs infos\\n ns = map greName (ns_gres ++ fs_gres)\\n fs = map fieldGREInfo fs_gres\\n ; return $\\n if all_non_overloaded fs\\n then map (\\\\nm -> IEVar Nothing (to_ie_post_rn_var $ noLocA nm) Nothing) ns\\n else [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n where\\n\\n all_used avail_cs = all (`elem` cs) avail_cs\\n\\n all_non_overloaded = all (not . flIsOverloaded . recFieldLabel)\\n\\n combine :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\n combine = map merge . NE.groupAllWith getKey\\n\\n getKey :: LImportDecl GhcRn -> (Bool, Maybe ModuleName, ModuleName)\\n getKey decl =\\n ( isImportDeclQualified . ideclQualified $ idecl -- is this qualified? (important that this be first)\\n , unLoc <$> ideclAs idecl -- what is the qualifier (inside Maybe monad)\\n , unLoc . ideclName $ idecl -- Module Name\\n )\\n where\\n idecl :: ImportDecl GhcRn\\n idecl = unLoc decl\\n\\n merge :: NonEmpty (LImportDecl GhcRn) -> LImportDecl GhcRn\\n merge decls@((L l decl) :| _) = L l (decl { ideclImportList = Just (Exactly, lies) })\\n where lies = concatMap snd $ mapMaybe (ideclImportList . unLoc) $ NE.toList decls\\n\\nclassifyGREs :: [GlobalRdrElt] -> ([GlobalRdrElt], [FieldGlobalRdrElt])\\nclassifyGREs = partition (not . isRecFldGRE)\\n\\nprintMinimalImports :: HscSource -> [ImportDeclUsage] -> RnM ()\\n-- See Note [Printing minimal imports]\\nprintMinimalImports hsc_src imports_w_usage\\n = do { imports\' <- excludeGenerated <$> getMinimalImports imports_w_usage\\n ; this_mod <- getModule\\n ; dflags <- getDynFlags\\n ; liftIO $ withFile (mkFilename dflags this_mod) WriteMode $ \\\\h ->\\n printForUser dflags h neverQualify AllTheWay (vcat (map ppr imports\'))\\n -- The neverQualify is important. We are printing Names\\n -- but they are in the context of an \'import\' decl, and\\n -- we never qualify things inside there\\n -- E.g. import Blag( f, b )\\n -- not import Blag( Blag.f, Blag.g )!\\n }\\n where\\n mkFilename dflags this_mod\\n | Just d <- dumpDir dflags = d basefn\\n | otherwise = basefn\\n where\\n suffix = case hsc_src of\\n HsBootFile -> \\".imports-boot\\"\\n HsSrcFile -> \\".imports\\"\\n HsigFile -> \\".imports\\"\\n basefn = moduleNameString (moduleName this_mod) ++ suffix\\n\\n\\nto_ie_post_rn_var :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn_var (L l n)\\n | isDataOcc $ occName n = L l (IEPattern noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n\\n\\nto_ie_post_rn :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn (L l n)\\n | isTcOcc occ && isSymOcc occ = L l (IEType noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n where occ = occName n\\n\\n{- Note [Do not warn about Prelude hiding]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWe do not warn about\\n import Prelude hiding( x, y )\\nbecause even if nothing else from Prelude is used, it may be essential to hide\\nx,y to avoid name-shadowing warnings. Example (#9061)\\n import Prelude hiding( log )\\n f x = log where log = ()\\n\\nNote [Unused imports]\\n~~~~~~~~~~~~~~~~~~~~~\\nIn `warnUnusedImport`, if we see an import with an explicit list imports, thus\\n import M( a, b )\\nand neither `a` nor `b` is used, we report the entire import decl as unused. We\\ncheck this by looking at the names that it brings into scope scope; if there are\\nno ununused names, don\'t report.\\n\\n(UI1) We don\'t want to complain about `import M()`, because that is often used to bring\\n M\'s /instances/ into scope. That is neatly dealt with by the \\"no unused\\n names\\" (nor unused wildcard imports) criterion.\\n\\n(UI2) We don\'t report a decl as unused if it has an `as Rebindable` qualifier.\\n See (KN1) in Note [Overview of known entities] in GHC.Builtin\\n\\n\\nNote [Printing minimal imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nTo print the minimal imports we walk over all import decls (both user-supplied\\nand generated), trim their import lists, then filter out generated decls.\\n\\nNB that\\n\\n * We do *not* change the \'qualified\' or \'as\' parts!\\n\\n * We do not discard a decl altogether; we might need instances\\n from it. Instead we just trim to an empty import list\\n\\nNote [Partial export]\\n~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have\\n\\n module A( op ) where\\n class C a where\\n op :: a -> a\\n\\n module B where\\n import A\\n f = ..op...\\n\\nThen the minimal import for module B is\\n import A( op )\\nnot\\n import A( C( op ) )\\nwhich we would usually generate if C was exported from B. Hence\\nthe availExportsDecl test when deciding what to generate.\\n\\n\\nNote [Overloaded field import]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nOn the other hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n data T = MkT { foo :: Int }\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( T(foo) )\\nbecause when DuplicateRecordFields is enabled, field selectors are\\nnot in scope without their enclosing datatype.\\n\\nOn the third hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n pattern MkT { foo } = Just foo\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( foo )\\nbecause foo doesn\'t have a parent. This might actually be ambiguous if A\\nexports another field called foo, but there is no good answer to return and this\\nis a very obscure corner, so it seems to be the best we can do. See\\nDRFPatSynExport for a test of this.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Errors}\\n* *\\n************************************************************************\\n-}\\n\\nbadImportItemErr\\n :: ModIface -> ImpDeclSpec -> IE GhcPs\\n -> IsSubordinateError\\n -> [AvailInfo]\\n -> TcRn (NonEmpty ImportLookupReason)\\nbadImportItemErr iface decl_spec ie sub avails = do\\n exts <- importLookupExtensions\\n let import_lookup_bad :: BadImportKind -> ImportLookupReason\\n import_lookup_bad k = ImportLookupBad k iface decl_spec ie exts\\n dflags <- getDynFlags\\n hsc_env <- getTopEnv\\n let rdr_env = mkGlobalRdrEnv\\n $ gresFromAvails hsc_env (Just imp_spec) all_avails\\n pure $ fmap import_lookup_bad (importErrorKind dflags rdr_env)\\n where\\n importErrorKind :: DynFlags -> GlobalRdrEnv -> NonEmpty BadImportKind\\n importErrorKind dflags rdr_env\\n | any checkIfTyCon avails = case sub of\\n IsNotSubordinate -> NE.singleton BadImportAvailTyCon\\n IsSubordinateError { subordinate_err_parent = gre\\n , subordinate_err_unavailable = unavailable\\n , subordinate_err_nontype = nontype\\n , subordinate_err_nondata = nondata }\\n -> NE.fromList $ catMaybes $\\n [ fmap (BadImportNotExportedSubordinates gre) (NE.nonEmpty unavailable)\\n , fmap (BadImportNonTypeSubordinates gre) (NE.nonEmpty nontype)\\n , fmap (BadImportNonDataSubordinates gre) (NE.nonEmpty nondata) ]\\n | any checkIfVarName avails = NE.singleton BadImportAvailVar\\n | Just con <- find checkIfDataCon avails = NE.singleton (BadImportAvailDataCon (availOccName con))\\n | otherwise = NE.singleton (BadImportNotExported suggs)\\n where\\n suggs = similar_suggs ++ fieldSelectorSuggestions rdr_env rdr\\n what_look = case sub of\\n IsNotSubordinate -> WL_TyCon_or_TermVar\\n IsSubordinateError { subordinate_err_parent = gre } ->\\n case greInfo gre of\\n IAmTyCon ClassFlavour\\n -> WL_TyCon_or_TermVar\\n _ -> WL_Term\\n similar_names =\\n similarNameSuggestions (Unbound.LF what_look WL_Global)\\n dflags rdr_env emptyLocalRdrEnv rdr\\n similar_suggs =\\n case NE.nonEmpty $ mapMaybe imported_item $ similar_names of\\n Just similar -> [ SuggestSimilarNames rdr similar ]\\n Nothing -> [ ]\\n\\n -- Only keep imported items, and set the \\"HowInScope\\" to\\n -- \\"Nothing\\" to avoid printing \\"imported from...\\" in the suggestion\\n -- error message.\\n imported_item (SimilarRdrName rdr_name gre (Just (ImportedBy {})))\\n = Just (SimilarRdrName rdr_name gre Nothing)\\n imported_item _ = Nothing\\n\\n checkIfDataCon = checkIfAvailMatches isDataConName\\n checkIfTyCon = checkIfAvailMatches isTyConName\\n checkIfVarName =\\n \\\\case\\n AvailTC{} -> False\\n Avail n -> importedFS == occNameFS (occName n)\\n && (isVarOcc <||> isFieldOcc) (occName n)\\n checkIfAvailMatches namePred =\\n \\\\case\\n AvailTC _ ns ->\\n case find (\\\\n -> importedFS == occNameFS (occName n)) ns of\\n Just n -> namePred n\\n Nothing -> False\\n Avail{} -> False\\n availOccName = occName . availName\\n rdr = ieName ie\\n importedFS = occNameFS $ rdrNameOcc rdr\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n all_avails = mi_exports iface\\n\\nimportLookupExtensions :: TcRn ImportLookupExtensions\\nimportLookupExtensions = do\\n ile_pattern_synonyms <- xoptM LangExt.PatternSynonyms\\n ile_explicit_namespaces <- xoptM LangExt.ExplicitNamespaces\\n return ImportLookupExtensions{ile_pattern_synonyms, ile_explicit_namespaces}\\n\\naddDupDeclErr :: NonEmpty GlobalRdrElt -> TcRn ()\\naddDupDeclErr gres@(gre :| _)\\n -- Report the error at the later location\\n = addErrAt (getSrcSpan (NE.last sorted_names)) $ (TcRnDuplicateDecls (greOccName gre) sorted_names)\\n where\\n sorted_names =\\n NE.sortBy (SrcLoc.leftmost_smallest `on` nameSrcSpan)\\n (fmap greName gres)\\n\\n-- This data decl will parse OK\\n-- data T = a Int\\n-- treating \\"a\\" as the constructor.\\n-- It is really hard to make the parser spot this malformation.\\n-- So the renamer has to check that the constructor is legal\\n--\\n-- We can get an operator as the constructor, even in the prefix form:\\n-- data T = :% Int Int\\n-- from interface files, which always print in prefix form\\n--\\n-- We also allow type constructor names, which are defined by \\"type data\\"\\n-- declarations. See Note [Type data declarations] in GHC.Rename.Module.\\n\\ncheckConName :: RdrName -> TcRn ()\\ncheckConName name\\n = checkErr (isRdrDataCon name || isRdrTc name) (TcRnIllegalDataCon name)\\n", "filetypes": ["haskell"]}}, "event_name": "FileReadyToParse"}' 2026-10-16 14:45:30,319 - DEBUG - POST b'http://127.0.0.1:37093/receive_messages' {'content-type': 'application/json', 'x-ycm-hmac': b'Rga7Yd4l4fgfufwYw+0sxzurvznImlBO0MPmgAlS4EY='} b'{"filepath": "/home/enrico/ghc/compiler/GHC/Rename/Names.hs", "line_num": 1, "column_num": 1, "working_dir": "/home/enrico/ghc", "file_data": {"/home/enrico/ghc/compiler/GHC/Rename/Names.hs": {"contents": "{-\\n(c) The GRASP/AQUA Project, Glasgow University, 1992-1998\\n\\nExtracting imported and top-level names in scope\\n-}\\n\\n{-# LANGUAGE NondecreasingIndentation #-}\\n{-# LANGUAGE TypeFamilies #-}\\n\\nmodule GHC.Rename.Names (\\n rnImports, getLocalNonValBinders, newRecordFieldLabel,\\n importsFromIface,\\n ImportUserSpec(..),\\n extendGlobalRdrEnvRn,\\n gresFromAvails,\\n calculateAvails,\\n reportUnusedNames,\\n checkConName,\\n mkChildEnv,\\n findChildren,\\n mkBadExportSubordinate,\\n findImportUsage,\\n getMinimalImports,\\n printMinimalImports,\\n renamePkgQual, renameRawPkgQual,\\n classifyGREs,\\n ImportDeclUsage,\\n rnNamespaceSpecifier\\n ) where\\n\\nimport GHC.Prelude hiding ( head, init, last, tail )\\n\\nimport GHC.Driver.Env\\nimport GHC.Driver.Session\\nimport GHC.Driver.Ppr\\n\\nimport GHC.Rename.Env\\nimport GHC.Rename.Fixity\\nimport GHC.Rename.Utils ( warnUnusedTopBinds )\\nimport GHC.Rename.Unbound\\nimport qualified GHC.Rename.Unbound as Unbound\\n\\nimport GHC.Tc.Errors.Types\\nimport GHC.Tc.Utils.Env\\nimport GHC.Tc.Utils.Monad\\nimport GHC.Tc.Types.LclEnv\\nimport GHC.Tc.Zonk.TcType ( tcInitTidyEnv )\\n\\nimport GHC.Hs\\nimport GHC.Iface.Load ( loadSrcInterface, loadSrcInterface_maybe )\\nimport GHC.Iface.Errors.Types\\n ( IfaceMessage(..), MissingInterfaceError, InterfaceLookingFor(..)\\n , LoadEssentialsReason(..) )\\nimport GHC.Iface.Syntax ( fromIfaceWarnings )\\nimport GHC.Builtin.Modules( pRELUDE_NAME, rEBINDABLE_MOD_NAME )\\nimport GHC.Parser.PostProcess ( setRdrNameSpace )\\nimport GHC.Core.TyCo.Tidy\\nimport GHC.Core.PatSyn\\nimport GHC.Core.TyCon ( TyCon, tyConName )\\nimport qualified GHC.LanguageExtensions as LangExt\\n\\nimport GHC.Utils.Outputable as Outputable\\nimport GHC.Utils.Misc as Utils\\nimport GHC.Utils.Panic\\n\\nimport GHC.Types.Fixity.Env\\nimport GHC.Types.SafeHaskell\\nimport GHC.Types.Name\\nimport GHC.Types.Name.Env\\nimport GHC.Types.Name.Set\\nimport GHC.Types.Name.Reader\\nimport GHC.Types.Avail\\nimport GHC.Types.FieldLabel\\nimport GHC.Types.Hint\\nimport GHC.Types.SourceFile\\nimport GHC.Types.SrcLoc as SrcLoc\\nimport GHC.Types.Basic (TyConFlavour (..), convImportLevel, VisArity)\\nimport GHC.Types.UnresolvedImport\\nimport GHC.Types.Id\\nimport GHC.Types.PkgQual\\nimport GHC.Types.GREInfo (ConInfo(..), ConFieldInfo (..), ConLikeInfo (ConIsData))\\n\\nimport GHC.Unit\\nimport GHC.Unit.Module.Warnings\\nimport GHC.Unit.Module.ModIface\\nimport GHC.Unit.Module.Imported\\nimport GHC.Unit.Module.Deps\\nimport GHC.Unit.Env\\n\\nimport GHC.Data.Bag\\nimport GHC.Data.FastString\\nimport GHC.Data.FastString.Env\\nimport GHC.Data.Maybe\\nimport GHC.Data.List.SetOps ( removeDups )\\n\\nimport Control.Arrow ( second )\\nimport Control.Monad\\nimport Data.Foldable ( for_ )\\nimport Data.IntMap ( IntMap )\\nimport qualified Data.IntMap as IntMap\\nimport Data.Map ( Map )\\nimport qualified Data.Map as Map\\nimport Data.Ord ( comparing )\\nimport Data.Semigroup ( Any(..) )\\nimport qualified Data.Semigroup as S\\nimport Data.List ( partition, find, sortBy )\\nimport Data.List.NonEmpty (NonEmpty(..))\\nimport qualified Data.List.NonEmpty as NE\\nimport Data.Function ( on )\\nimport qualified Data.Set as S\\nimport System.FilePath (())\\nimport System.IO\\n\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{rnImports}\\n* *\\n************************************************************************\\n\\nNote [Tracking Trust Transitively]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen we import a package as well as checking that the direct imports are safe\\naccording to the rules outlined in the Note [Safe Haskell Trust Check] in GHC.Driver.Main\\nwe must also check that these rules hold transitively for all dependent modules\\nand packages. Doing this without caching any trust information would be very\\nslow as we would need to touch all packages and interface files a module depends\\non. To avoid this we make use of the property that if a modules Safe Haskell\\nmode changes, this triggers a recompilation from that module in the dependency\\ngraph. So we can just worry mostly about direct imports.\\n\\nThere is one trust property that can change for a package though without\\nrecompilation being triggered: package trust. So we must check that all\\npackages a module transitively depends on to be trusted are still trusted when\\nwe are compiling this module (as due to recompilation avoidance some modules\\nbelow may not be considered trusted any more without recompilation being\\ntriggered).\\n\\nWe handle this by augmenting the existing transitive list of packages a module M\\ndepends on with a bool for each package that says if it must be trusted when the\\nmodule M is being checked for trust. This list of trust required packages for a\\nsingle import is gathered in the rnImportDecl function and stored in an\\nImportAvails data structure. The union of these trust required packages for all\\nimports is done by the rnImports function using the combine function which calls\\nthe plusImportAvails function that is a union operation for the ImportAvails\\ntype. This gives us in an ImportAvails structure all packages required to be\\ntrusted for the module we are currently compiling. Checking that these packages\\nare still trusted (and that direct imports are trusted) is done in\\nGHC.Driver.Main.checkSafeImports.\\n\\nSee the note below, [Trust Own Package] for a corner case in this method and\\nhow its handled.\\n\\n\\nNote [Trust Own Package]\\n~~~~~~~~~~~~~~~~~~~~~~~~\\nThere is a corner case of package trust checking that the usual transitive check\\ndoesn\'t cover. (For how the usual check operates see the Note [Tracking Trust\\nTransitively] below). The case is when you import a -XSafe module M and M\\nimports a -XTrustworthy module N. If N resides in a different package than M,\\nthen the usual check works as M will record a package dependency on N\'s package\\nand mark it as required to be trusted. If N resides in the same package as M\\nthough, then importing M should require its own package be trusted due to N\\n(since M is -XSafe so doesn\'t create this requirement by itself). The usual\\ncheck fails as a module doesn\'t record a package dependency of its own package.\\nSo instead we now have a bool field in a modules interface file that simply\\nstates if the module requires its own package to be trusted. This field avoids\\nus having to load all interface files that the module depends on to see if one\\nis trustworthy.\\n\\n\\nNote [Trust Transitive Property]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSo there is an interesting design question in regards to transitive trust\\nchecking. Say I have a module B compiled with -XSafe. B is dependent on a bunch\\nof modules and packages, some packages it requires to be trusted as its using\\n-XTrustworthy modules from them. Now if I have a module A that doesn\'t use safe\\nhaskell at all and simply imports B, should A inherit all the trust\\nrequirements from B? Should A now also require that a package p is trusted since\\nB required it?\\n\\nWe currently say no but saying yes also makes sense. The difference is, if a\\nmodule M that doesn\'t use Safe Haskell imports a module N that does, should all\\nthe trusted package requirements be dropped since M didn\'t declare that it cares\\nabout Safe Haskell (so -XSafe is more strongly associated with the module doing\\nthe importing) or should it be done still since the author of the module N that\\nuses Safe Haskell said they cared (so -XSafe is more strongly associated with\\nthe module that was compiled that used it).\\n\\nGoing with yes is a simpler semantics we think and harder for the user to stuff\\nup but it does mean that Safe Haskell will affect users who don\'t care about\\nSafe Haskell as they might grab a package from Cabal which uses safe haskell (say\\nnetwork) and that packages imports -XTrustworthy modules from another package\\n(say bytestring), so requires that package is trusted. The user may now get\\ncompilation errors in code that doesn\'t do anything with Safe Haskell simply\\nbecause they are using the network package. They will have to call \'ghc-pkg\\ntrust network\' to get everything working. Due to this invasive nature of going\\nwith yes we have gone with no for now.\\n-}\\n\\n-- | Process Import Decls. See \'rnImportDecl\' for a description of what\\n-- the return types represent.\\n-- Note: Do the non SOURCE ones first, so that we get a helpful warning\\n-- for SOURCE ones that are unnecessary\\nrnImports :: [(LImportDecl GhcPs, SDoc)]\\n -> RnM ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\nrnImports imports = do\\n tcg_env <- getGblEnv\\n -- NB: want an identity module here, because it\'s OK for a signature\\n -- module to import from its implementor\\n let this_mod = tcg_mod tcg_env\\n let (source, ordinary) = partition (is_source_import . fst) imports\\n is_source_import (d::LImportDecl GhcPs) = ideclSource (unLoc d) == IsBoot\\n stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary\\n stuff2 <- mapAndReportM (rnImportDecl this_mod) source\\n -- Safe Haskell: See Note [Tracking Trust Transitively]\\n let (decls, imp_user_spec, rdr_env, imp_avails) = combine (stuff1 ++ stuff2)\\n -- Update imp_boot_mods if imp_direct_mods mentions any of them\\n let merged_import_avail = clobberSourceImports imp_avails\\n return (decls, imp_user_spec, rdr_env, merged_import_avail)\\n\\n where\\n clobberSourceImports imp_avails =\\n imp_avails { imp_boot_mods = imp_boot_mods\' }\\n where\\n imp_boot_mods\' = mergeInstalledModuleEnv combJ id (const emptyInstalledModuleEnv)\\n (imp_boot_mods imp_avails)\\n (imp_direct_dep_mods imp_avails)\\n\\n combJ (GWIB _ IsBoot) (_, x) = Just x\\n combJ r _ = Just r\\n -- See Note [Combining ImportAvails]\\n combine :: [(LImportDecl GhcRn, ImportUserSpec, GlobalRdrEnv, ImportAvails)]\\n -> ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\n combine ss =\\n let (decls, imp_user_spec, rdr_env, imp_avails, finsts) = foldr\\n plus\\n ([], [], emptyGlobalRdrEnv, emptyImportAvails, emptyModuleSet)\\n ss\\n in (decls, imp_user_spec, rdr_env, imp_avails { imp_finsts = moduleSetElts finsts })\\n\\n plus (decl, us, gbl_env1, imp_avails1)\\n (decls, uss, gbl_env2, imp_avails2, finsts_set)\\n = ( decl:decls,\\n us:uss,\\n gbl_env1 `plusGlobalRdrEnv` gbl_env2,\\n imp_avails1\' `plusImportAvails` imp_avails2,\\n extendModuleSetList finsts_set new_finsts )\\n where\\n imp_avails1\' = imp_avails1 { imp_finsts = [] }\\n new_finsts = imp_finsts imp_avails1\\n\\n{-\\nNote [Combining ImportAvails]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nimp_finsts in ImportAvails is a list of family instance modules\\ntransitively depended on by an import. imp_finsts for a currently\\ncompiled module is a union of all the imp_finsts of imports.\\nComputing the union of two lists of size N is O(N^2) and if we\\ndo it to M imports we end up with O(M*N^2). That can get very\\nexpensive for bigger module hierarchies.\\n\\nUnion can be optimized to O(N log N) if we use a Set.\\nimp_finsts is converted back and forth between dep_finsts, so\\nchanging a type of imp_finsts means either paying for the conversions\\nor changing the type of dep_finsts as well.\\n\\nI\'ve measured that the conversions would cost 20% of allocations on my\\ntest case, so that can be ruled out.\\n\\nChanging the type of dep_finsts forces checkFamInsts to\\nget the module lists in non-deterministic order. If we wanted to restore\\nthe deterministic order, we\'d have to sort there, which is an additional\\ncost. As far as I can tell, using a non-deterministic order is fine there,\\nbut that\'s a brittle nonlocal property which I\'d like to avoid.\\n\\nAdditionally, dep_finsts is read from an interface file, so its \\"natural\\"\\ntype is a list. Which makes it a natural type for imp_finsts.\\n\\nSince rnImports.combine is really the only place that would benefit from\\nit being a Set, it makes sense to optimize the hot loop in rnImports.combine\\nwithout changing the representation.\\n\\nSo here\'s what we do: instead of naively merging ImportAvails with\\nplusImportAvails in a loop, we make plusImportAvails merge empty imp_finsts\\nand compute the union on the side using Sets. When we\'re done, we can\\nconvert it back to a list. One nice side effect of this approach is that\\nif there\'s a lot of overlap in the imp_finsts of imports, the\\nSet doesn\'t really need to grow and we don\'t need to allocate.\\n\\nRunning generateModules from #14693 with DEPTH=16, WIDTH=30 finishes in\\n23s before, and 11s after.\\n-}\\n\\n-- | Given a located import declaration @decl@ from @this_mod@,\\n-- calculate the following pieces of information:\\n--\\n-- 1. An updated \'LImportDecl\', where all unresolved \'RdrName\' in\\n-- the entity lists have been resolved into \'Name\'s,\\n--\\n-- 2. A \'GlobalRdrEnv\' representing the new identifiers that were\\n-- brought into scope (taking into account module qualification\\n-- and hiding),\\n--\\n-- 3. \'ImportAvails\' summarizing the identifiers that were imported\\n-- by this declaration, and\\n--\\n-- 4. A boolean \'AnyHpcUsage\' which is true if the imported module\\n-- used HPC.\\nrnImportDecl :: Module -> (LImportDecl GhcPs, SDoc)\\n -> RnM (LImportDecl GhcRn, ImportUserSpec , GlobalRdrEnv, ImportAvails)\\nrnImportDecl this_mod\\n (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name\\n , ideclPkgQual = raw_pkg_qual\\n , ideclSource = want_boot\\n , ideclSafe = mod_safe\\n , ideclLevelSpec = import_level\\n , ideclQualified = qual_style\\n , ideclExt = XImportDeclPass { ideclOrigin = origin }\\n , ideclAs = as_mod, ideclImportList = imp_details }), import_reason)\\n = setSrcSpanA loc $ do\\n\\n case raw_pkg_qual of\\n NoRawPkgQual -> pure ()\\n RawPkgQual {} -> do\\n pkg_imports <- xoptM LangExt.PackageImports\\n when (not pkg_imports) $ addErr TcRnPackageImportsDisabled\\n\\n let qual_only = isImportDeclQualified qual_style\\n generated = isGeneratedImport origin\\n\\n lookup_scope = importDeclLookupScope origin\\n\\n -- If there\'s an error in loadInterface, (e.g. interface\\n -- file not found) we get lots of spurious errors from \'filterImports\'\\n let imp_mod_name = unLoc loc_imp_mod_name\\n doc = ppr imp_mod_name <+> import_reason\\n\\n hsc_env <- getTopEnv\\n unit_env <- hsc_unit_env <$> getTopEnv\\n let pkg_qual = renameRawPkgQual unit_env imp_mod_name raw_pkg_qual\\n\\n -- Check for self-import, which confuses the typechecker (#9032)\\n -- ghc --make rejects self-import cycles already, but batch-mode may not\\n -- at least not until GHC.IfaceToCore.tcHiBootIface, which is too late to avoid\\n -- typechecker crashes. (Indirect self imports are not caught until\\n -- GHC.IfaceToCore, see #10337 tracking how to make this error better.)\\n --\\n -- Originally, we also allowed \'import {-# SOURCE #-} M\', but this\\n -- caused bug #10182: in one-shot mode, we should never load an hs-boot\\n -- file for the module we are compiling into the EPS. In principle,\\n -- it should be possible to support this mode of use, but we would have to\\n -- extend Provenance to support a local definition in a qualified location.\\n -- For now, we don\'t support it, but see #10336\\n when (imp_mod_name == moduleName this_mod &&\\n (case pkg_qual of -- If we have import \\"\\" M, then we should\\n -- check that \\"\\" is \\"this\\" (which is magic)\\n -- or the name of this_mod\'s package. Yurgh!\\n -- c.f. GHC.findModule, and #9997\\n NoPkgQual -> True\\n ThisPkg uid -> uid == homeUnitId_ (hsc_dflags hsc_env)\\n OtherPkg _ -> False))\\n (addErr (TcRnSelfImport imp_mod_name))\\n\\n -- Check for a missing import list (Opt_WarnMissingImportList also\\n -- checks for T(..) items but that is done in checkDodgyImport below)\\n case imp_details of\\n Just (Exactly, _) -> return () -- Explicit import list\\n _ | generated -> return () -- Do not bleat for generated imports\\n | qual_only -> return ()\\n | otherwise -> addDiagnostic (TcRnNoExplicitImportList imp_mod_name)\\n\\n\\n mb_iface <- loadSrcInterface_maybe doc lookup_scope imp_mod_name want_boot pkg_qual\\n iface <- case mb_iface of\\n Succeeded iface -> return iface\\n Failed err -> failWithTc $\\n importDeclLoadFailure origin imp_mod_name want_boot err\\n\\n -- Compiler sanity check: if the import didn\'t say\\n -- {-# SOURCE #-} we should not get a hi-boot file\\n warnPprTrace ((want_boot == NotBoot) && (mi_boot iface == IsBoot)) \\"rnImportDecl\\" (ppr imp_mod_name) $ do\\n\\n -- Issue a user warning for a redundant {- SOURCE -} import\\n -- NB that we arrange to read all the ordinary imports before\\n -- any of the {- SOURCE -} imports.\\n --\\n -- in --make and GHCi, the compilation manager checks for this,\\n -- and indeed we shouldn\'t do it here because the existence of\\n -- the non-boot module depends on the compilation order, which\\n -- is not deterministic. The hs-boot test can show this up.\\n dflags <- getDynFlags\\n warnIf ((want_boot == IsBoot) && (mi_boot iface == NotBoot) && isOneShot (ghcMode dflags))\\n (TcRnRedundantSourceImport imp_mod_name)\\n when (mod_safe && not (safeImportsOn dflags)) $\\n addErr (TcRnSafeImportsDisabled imp_mod_name)\\n\\n let imp_mod = mi_module iface\\n qual_mod_name = fmap unLoc as_mod `orElse` imp_mod_name\\n imp_spec = ImpDeclSpec { is_mod = imp_mod, is_qual = qual_only,\\n is_dloc = locA loc, is_as = qual_mod_name,\\n is_pkg_qual = pkg_qual, is_isboot = want_boot,\\n is_level = convImportLevel import_level }\\n\\n let filter_imports = do\\n -- filter the imports according to the import declaration\\n (new_imp_details, imp_user_list, gbl_env)\\n <- filterImports hsc_env iface imp_spec imp_details\\n -- for certain error messages, we\\u2019d like to know what could be\\n -- imported here, if everything were imported\\n potential_gres <- (\\\\(_,_,x) -> x) <$> filterImports hsc_env iface imp_spec Nothing\\n return (new_imp_details, imp_user_list, gbl_env, potential_gres)\\n\\n (new_imp_details, imp_user_list, gbl_env, potential_gres) <-\\n case origin of\\n ImplicitEssentialsImport ->\\n -- The implicit GHC.Essentials import does not bring anything into scope.\\n -- See Note [Finding GHC.Essentials] in GHC.Builtin.\\n return (Nothing, ImpUserDependOnly, emptyGlobalRdrEnv, emptyGlobalRdrEnv)\\n UserWrittenImport -> filter_imports\\n ImplicitPreludeImport -> filter_imports\\n PluginImport -> filter_imports\\n\\n let is_hiding | Just (EverythingBut,_) <- imp_details = True\\n | otherwise = False\\n\\n -- should the import be safe?\\n mod_safe\' = mod_safe\\n || (not generated && safeDirectImpsReq dflags)\\n || (generated && safeImplicitImpsReq dflags)\\n\\n hsc_env <- getTopEnv\\n let home_unit = hsc_home_unit hsc_env\\n other_home_units = hsc_all_home_unit_ids hsc_env\\n\\n imported_by\\n | isDependOnlyImport imp_user_list\\n = ImportedBySystem\\n | otherwise\\n = ImportedByUser $ ImportedModsVal\\n { imv_name = is_as imp_spec\\n , imv_span = locA loc\\n , imv_is_safe = mod_safe\'\\n , imv_is_hiding = is_hiding\\n , imv_all_exports = potential_gres\\n , imv_qualified = qual_only\\n , imv_is_level = convImportLevel import_level\\n }\\n imports = calculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by\\n\\n -- Complain if we import a deprecated module\\n case fromIfaceWarnings (mi_warns iface) of\\n WarnAll txt -> addDiagnostic (TcRnDeprecatedModule imp_mod_name txt)\\n _ -> return ()\\n\\n let new_imp_decl = ImportDecl\\n { ideclExt = ideclExt decl\\n , ideclName = ideclName decl\\n , ideclPkgQual = pkg_qual\\n , ideclSource = ideclSource decl\\n , ideclSafe = mod_safe\'\\n , ideclQualified = ideclQualified decl\\n , ideclAs = ideclAs decl\\n , ideclImportList = new_imp_details\\n , ideclLevelSpec = ideclLevelSpec decl\\n }\\n\\n return (L loc new_imp_decl, ImpUserSpec imp_spec imp_user_list, gbl_env, imports)\\n\\n-- | The error message to emit when we failed to load an interface.\\nimportDeclLoadFailure :: ImportDeclOrigin -> ModuleName -> IsBootInterface\\n -> MissingInterfaceError -> TcRnMessage\\nimportDeclLoadFailure ImplicitEssentialsImport _ _ err\\n = TcRnInterfaceError $ CantFindEssentials err LookingForEssentialsModule\\nimportDeclLoadFailure _ mod_name want_boot err\\n = TcRnInterfaceError $ Can\'tFindInterface err $ LookingForModule mod_name want_boot\\n\\n-- | Rename raw package imports\\nrenameRawPkgQual :: UnitEnv -> ModuleName -> RawPkgQual -> PkgQual\\nrenameRawPkgQual unit_env mn = \\\\case\\n NoRawPkgQual -> NoPkgQual\\n RawPkgQual _ fs -> renamePkgQual unit_env mn $ Just fs\\n\\n-- | Rename raw package imports\\nrenamePkgQual :: UnitEnv -> ModuleName -> Maybe FastString -> PkgQual\\nrenamePkgQual unit_env mn mb_pkg = case mb_pkg of\\n Nothing -> NoPkgQual\\n Just pkg_fs\\n | Just uid <- homeUnitId <$> ue_homeUnit unit_env\\n , pkg_fs == fsLit \\"this\\"\\n -> ThisPkg uid\\n\\n | Just (uid, _) <- find (fromMaybe False . fmap (== pkg_fs) . snd) home_names\\n -> ThisPkg uid\\n\\n | Just uid <- resolvePackageImport unit_state mn (PackageName pkg_fs)\\n -> OtherPkg uid\\n\\n | otherwise\\n -> OtherPkg (UnitId pkg_fs)\\n -- not really correct as pkg_fs is unlikely to be a valid unit-id but\\n -- we will report the failure later...\\n where\\n home_names =\\n [ (uid, mkFastString <$> thisPackageName (homeUnitEnv_dflags (ue_findHomeUnitEnv uid unit_env)))\\n | uid <- S.toList hpt_deps\\n ]\\n\\n unit_state = ue_homeUnitState unit_env\\n\\n hpt_deps :: S.Set UnitId\\n hpt_deps = homeUnitDepends unit_state\\n\\n\\n-- | Calculate the \'ImportAvails\' induced by an import of a particular\\n-- interface, but without \'imp_mods\'.\\ncalculateAvails :: HomeUnit\\n -> S.Set UnitId\\n -> ModIface\\n -> IsSafeImport\\n -> IsBootInterface\\n -> ImportedBy\\n -> ImportAvails\\ncalculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by =\\n let imp_mod = mi_module iface\\n imp_sem_mod= mi_semantic_module iface\\n orph_iface = mi_orphan iface\\n has_finsts = mi_finsts iface\\n deps = mi_deps iface\\n trust = getSafeMode $ mi_trust iface\\n trust_pkg = mi_trust_pkg iface\\n is_sig = mi_hsc_src iface == HsigFile\\n\\n -- If the module exports anything defined in this module, just\\n -- ignore it. Reason: otherwise it looks as if there are two\\n -- local definition sites for the thing, and an error gets\\n -- reported. Easiest thing is just to filter them out up\\n -- front. This situation only arises if a module imports\\n -- itself, or another module that imported it. (Necessarily,\\n -- this involves a loop.)\\n --\\n -- We do this *after* filterImports, so that if you say\\n -- module A where\\n -- import B( AType )\\n -- type AType = ...\\n --\\n -- module B( AType ) where\\n -- import {-# SOURCE #-} A( AType )\\n --\\n -- then you won\'t get a \'B does not export AType\' message.\\n\\n\\n -- Compute new transitive dependencies\\n --\\n -- \'dep_orphs\' and \'dep_finsts\' do NOT include the imported module\\n -- itself, but we DO need to include this module in \'imp_orphs\' and\\n -- \'imp_finsts\' if it defines an orphan or instance family; thus the\\n -- orph_iface/has_iface tests.\\n\\n deporphs = dep_orphs deps\\n depfinsts = dep_finsts deps\\n\\n orphans | orph_iface = assertPpr (not (imp_sem_mod `elem` deporphs)) (ppr imp_sem_mod <+> ppr deporphs) $\\n imp_sem_mod : deporphs\\n | otherwise = deporphs\\n\\n finsts | has_finsts = assertPpr (not (imp_sem_mod `elem` depfinsts)) (ppr imp_sem_mod <+> ppr depfinsts) $\\n imp_sem_mod : depfinsts\\n | otherwise = depfinsts\\n\\n -- Trusted packages are a lot like orphans.\\n trusted_pkgs | mod_safe\' = dep_trusted_pkgs deps\\n | otherwise = S.empty\\n\\n\\n pkg = moduleUnit (mi_module iface)\\n ipkg = toUnitId pkg\\n\\n -- Does this import mean we now require our own pkg\\n -- to be trusted? See Note [Trust Own Package]\\n ptrust = trust == Sf_Trustworthy || trust_pkg\\n pkg_trust_req\\n | isHomeUnit home_unit pkg = ptrust\\n | otherwise = False\\n\\n dependent_pkgs = if toUnitId pkg `S.member` other_home_units\\n then S.empty\\n else S.singleton (lvl, ipkg)\\n\\n lvl = case imported_by of\\n ImportedByUser imv -> imv_is_level imv\\n ImportedBySystem -> NormalLevel\\n\\n\\n direct_mods = if toUnitId pkg `S.member` other_home_units\\n then mkPlusModDeps (moduleUnitId imp_mod) lvl (GWIB (moduleName imp_mod) want_boot)\\n else emptyInstalledModuleEnv\\n\\n dep_boot_mods_map = mkModDeps (dep_boot_mods deps)\\n\\n\\n boot_mods\\n -- If we are looking for a boot module, it must be HPT\\n | IsBoot <- want_boot = extendInstalledModuleEnv dep_boot_mods_map (toUnitId <$> imp_mod) (GWIB (moduleName imp_mod) IsBoot)\\n -- Now we are importing A properly, so don\'t go looking for\\n -- A.hs-boot\\n | isHomeUnit home_unit pkg = dep_boot_mods_map\\n -- There\'s no boot files to find in external imports\\n | otherwise = emptyInstalledModuleEnv\\n\\n sig_mods =\\n if is_sig\\n then moduleName imp_mod : dep_sig_mods deps\\n else dep_sig_mods deps\\n\\n\\n in ImportAvails {\\n imp_mods = Map.singleton (mi_module iface) [imported_by],\\n imp_orphs = orphans,\\n imp_finsts = finsts,\\n imp_sig_mods = sig_mods,\\n imp_direct_dep_mods = direct_mods,\\n imp_dep_direct_pkgs = dependent_pkgs,\\n imp_boot_mods = boot_mods,\\n\\n -- Add in the imported modules trusted package\\n -- requirements. ONLY do this though if we import the\\n -- module as a safe import.\\n -- See Note [Tracking Trust Transitively]\\n -- and Note [Trust Transitive Property]\\n imp_trust_pkgs = trusted_pkgs,\\n -- Do we require our own pkg to be trusted?\\n -- See Note [Trust Own Package]\\n imp_trust_own_pkg = pkg_trust_req\\n }\\n\\nmkPlusModDeps :: UnitId -> ImportLevel -> ModuleNameWithIsBoot\\n -> InstalledModuleEnv (S.Set ImportLevel, ModuleNameWithIsBoot)\\nmkPlusModDeps uid st elt = extendInstalledModuleEnv emptyInstalledModuleEnv (mkModule uid (gwib_mod elt)) (S.singleton st, elt)\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{importsFromLocalDecls}\\n* *\\n************************************************************************\\n\\nFrom the top-level declarations of this module produce\\n * the lexical environment\\n * the ImportAvails\\ncreated by its bindings.\\n\\nNote [Top-level Names in Template Haskell decl quotes]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSee also: Note [Interactively-bound Ids in GHCi] in GHC.Driver.Env\\n Note [Looking up Exact RdrNames] in GHC.Rename.Env\\n\\nConsider a Template Haskell declaration quotation like this:\\n module M where\\n f x = h [d| f = 3 |]\\nWhen renaming the declarations inside [d| ...|], we treat the\\ntop level binders specially in two ways\\n\\n1. We give them an Internal Name, not (as usual) an External one.\\n This is done by GHC.Rename.Env.newTopSrcBinder.\\n\\n2. We make them *shadow* the outer bindings.\\n See Note [GlobalRdrEnv shadowing]\\n\\n3. We find out whether we are inside a [d| ... |] by testing the TH\\n level. This is a slight hack, because the level field was really\\n meant for the type checker, and here we are not interested in the\\n fields of Brack, hence the error thunks in thRnBrack.\\n-}\\n\\nextendGlobalRdrEnvRn :: [GlobalRdrElt]\\n -> MiniFixityEnv\\n -> RnM (TcGblEnv, TcLclEnv)\\n-- Updates both the GlobalRdrEnv and the FixityEnv\\n-- We return a new TcLclEnv only because we might have to\\n-- delete some bindings from it;\\n-- see Note [Top-level Names in Template Haskell decl quotes]\\n\\nextendGlobalRdrEnvRn new_gres new_fixities\\n = checkNoErrs $ -- See Note [Fail fast on duplicate definitions]\\n do { (gbl_env, lcl_env) <- getEnvs\\n ; level <- getThLevel\\n ; isGHCi <- getIsGHCi\\n ; let rdr_env = tcg_rdr_env gbl_env\\n fix_env = tcg_fix_env gbl_env\\n th_bndrs = getLclEnvThBndrs lcl_env\\n th_lvl = thLevelIndex level\\n\\n -- Delete new_occs from global and local envs\\n -- If we are in a TemplateHaskell decl bracket,\\n -- we are going to shadow them\\n -- See Note [GlobalRdrEnv shadowing]\\n inBracket = isBrackLevel level\\n\\n lcl_env_TH = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_rdr = minusLocalRdrEnv (tcl_rdr lcl_env) new_gres_env }) lcl_env\\n -- See Note [GlobalRdrEnv shadowing]\\n\\n lcl_env2 | inBracket = lcl_env_TH\\n | otherwise = lcl_env\\n\\n -- Deal with shadowing: see Note [GlobalRdrEnv shadowing]\\n want_shadowing = isGHCi || inBracket\\n rdr_env1 | want_shadowing = shadowNames False rdr_env new_gres_env\\n | otherwise = rdr_env\\n\\n lcl_env3 = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_th_bndrs = extendNameEnvList th_bndrs\\n [ ( n, (TopLevel, th_lvl) )\\n | n <- new_names ] }) lcl_env2\\n\\n ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres\\n\\n ; let fix_env\' = foldl\' extend_fix_env fix_env new_gres\\n gbl_env\' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env\' }\\n\\n ; traceRn \\"extendGlobalRdrEnvRn 2\\" (pprGlobalRdrEnv True rdr_env2)\\n ; return (gbl_env\', lcl_env3) }\\n where\\n new_names = map greName new_gres\\n new_gres_env = mkGlobalRdrEnv new_gres\\n\\n -- If there is a fixity decl for the gre, add it to the fixity env\\n extend_fix_env fix_env gre\\n | Just (L _ fi) <- lookupMiniFixityEnv new_fixities name\\n = extendNameEnv fix_env name (FixItem occ fi)\\n | otherwise\\n = fix_env\\n where\\n name = greName gre\\n occ = greOccName gre\\n\\n add_gre :: GlobalRdrEnv -> GlobalRdrElt -> RnM GlobalRdrEnv\\n -- Extend the GlobalRdrEnv with a LocalDef GRE\\n -- If there is already a LocalDef GRE with the same OccName,\\n -- report an error and discard the new GRE\\n -- This establishes INVARIANT 1 of GlobalRdrEnvs\\n add_gre env gre\\n | not (null dups) -- Same OccName defined twice\\n = do { addDupDeclErr (gre :| dups); return env }\\n\\n | otherwise\\n = return (extendGlobalRdrEnv env gre)\\n where\\n -- See Note [Reporting duplicate local declarations]\\n dups = filter isBadDupGRE\\n $ lookupGRE env (LookupOccName (greOccName gre) (RelevantGREsFOS WantBoth))\\n isBadDupGRE old_gre = isLocalGRE old_gre && greClashesWith gre old_gre\\n\\n{- Note [Fail fast on duplicate definitions]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIf there are duplicate bindings for the same thing, we want to fail\\nfast. Having two bindings for the same thing can cause follow-on errors.\\nExample (test T9975a):\\n data Test = Test { x :: Int }\\n pattern Test wat = Test { x = wat }\\nThis defines \'Test\' twice. The second defn has no field-names; and then\\nwe get an error from Test { x=wat }, saying \\"Test has no field \'x\'\\".\\n\\nEasiest thing is to bale out fast on duplicate definitions, which\\nwe do via `checkNoErrs` on `extendGlobalRdrEnvRn`.\\n\\nNote [Reporting duplicate local declarations]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn general, a single module may not define the same OccName multiple times. This\\nis checked in extendGlobalRdrEnvRn: when adding a new locally-defined GRE to the\\nGlobalRdrEnv we report an error if there are already duplicates in the\\nenvironment. This establishes INVARIANT 1 (see comments on GlobalRdrEnv in\\nGHC.Types.Name.Reader), which says that for a given OccName, all the\\nGlobalRdrElts to which it maps must have distinct \'greName\'s.\\n\\nFor example, the following will be rejected:\\n\\n f x = x\\n g x = x\\n f x = x -- Duplicate!\\n\\nUsers are allowed to introduce new GREs with the same OccName as an imported GRE,\\nas disambiguation is possible through the module system, e.g.:\\n\\n module M where\\n import N (f)\\n f x = x\\n g x = M.f x + N.f x\\n\\nIf both GREs are local, the general rule is that two GREs clash if they have\\nthe same OccName, i.e. they share a textual name and live in the same namespace.\\nHowever, there are additional clashes due to record fields:\\n\\n - a new variable clashes with previously defined record fields\\n which define field selectors,\\n\\n - a new record field shadows:\\n\\n - previously defined variables, if it defines a field selector,\\n - previously defined record fields, unless it is a duplicate record field.\\n\\nThis logic is implemented in the function \'GHC.Types.Name.Reader.greClashesWith\'.\\n\\nSee also Note [Skipping ambiguity errors at use sites of local declarations] in\\nGHC.Rename.Utils.\\n-}\\n\\n\\n{- *********************************************************************\\n* *\\n getLocalDeclBindersd@ returns the names for an HsDecl\\n It\'s used for source code.\\n\\n *** See Note [The Naming story] in GHC.Hs.Decls ****\\n* *\\n********************************************************************* -}\\n\\ngetLocalNonValBinders :: MiniFixityEnv -> HsGroup GhcPs\\n -> RnM ((TcGblEnv, TcLclEnv), NameSet)\\n-- Get all the top-level binders bound the group *except*\\n-- for value bindings, which are treated separately\\n-- Specifically we return AvailInfo for\\n-- * type decls (incl constructors and record selectors)\\n-- * class decls (including class ops)\\n-- * associated types\\n-- * foreign imports\\n-- * value signatures (in hs-boot files only)\\n\\ngetLocalNonValBinders fixity_env\\n (HsGroup { hs_valds = binds,\\n hs_tyclds = tycl_decls,\\n hs_fords = foreign_decls })\\n = do { -- Process all type/class decls *except* family instances\\n ; let inst_decls = tycl_decls >>= group_instds\\n ; dup_fields_ok <- xopt_DuplicateRecordFields <$> getDynFlags\\n ; has_sel <- xopt_FieldSelectors <$> getDynFlags\\n ; tc_gres\\n <- concatMapM\\n (new_tc dup_fields_ok has_sel)\\n (tyClGroupTyClDecls tycl_decls)\\n ; traceRn \\"getLocalNonValBinders 1\\" (ppr tc_gres)\\n ; envs <- extendGlobalRdrEnvRn tc_gres fixity_env\\n ; restoreEnvs envs $ do {\\n -- Bring these things into scope first\\n -- See Note [Looking up family names in family instances]\\n\\n -- Process all family instances\\n -- to bring new data constructors into scope\\n ; nti_gress <- mapM (new_assoc dup_fields_ok has_sel) inst_decls\\n\\n -- Finish off with value binders:\\n -- foreign decls and pattern synonyms for an ordinary module\\n -- type sigs in case of a hs-boot file only\\n ; is_boot <- tcIsHsBootOrSig\\n ; let val_bndrs\\n | is_boot = case binds of\\n ValBinds _ val_binds ->\\n -- In a hs-boot file, the value binders come from the\\n -- *signatures*, and there should be no foreign binders\\n [ L (l2l decl_loc) (unLoc n)\\n | L decl_loc (TypeSig _ _ ns _) <- (val_sigs val_binds), n <- ns]\\n _ -> panic \\"Non-ValBinds in hs-boot group\\"\\n | otherwise = for_hs_bndrs\\n ; val_gres <- mapM new_simple val_bndrs\\n\\n ; let avails = concat nti_gress ++ val_gres\\n new_bndrs = gresToNameSet avails `unionNameSet`\\n gresToNameSet tc_gres\\n ; traceRn \\"getLocalNonValBinders 2\\" (ppr avails)\\n ; envs <- extendGlobalRdrEnvRn avails fixity_env\\n ; return (envs, new_bndrs) } }\\n where\\n for_hs_bndrs :: [LocatedN RdrName]\\n for_hs_bndrs = hsForeignDeclsBinders foreign_decls\\n\\n -- the SrcSpan attached to the input should be the span of the\\n -- declaration, not just the name\\n new_simple :: LocatedN RdrName -> RnM GlobalRdrElt\\n new_simple rdr_name = do { nm <- newTopSrcBinder rdr_name\\n ; return (mkLocalVanillaGRE NoParent nm) }\\n\\n new_tc :: DuplicateRecordFields -> FieldSelectors -> LTyClDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_tc dup_fields_ok has_sel tc_decl -- NOT for type/data instances\\n = do { let TyDeclBinders (main_bndr, tc_flav) at_bndrs sig_bndrs\\n (LConsWithFields cons_with_flds flds) = hsLTyClDeclBinders tc_decl\\n ; tycon_name <- newTopSrcBinder $ la2la main_bndr\\n ; at_names <- mapM (newTopSrcBinder . la2la . fst) at_bndrs\\n ; sig_names <- mapM (newTopSrcBinder . la2la) sig_bndrs\\n ; con_names_with_flds <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst con_names_with_flds) flds\\n ; mapM_ (add_dup_fld_errs flds\') con_names_with_flds\\n ; let tc_gre = mkLocalTyConGRE (fmap (const tycon_name) tc_flav) tycon_name\\n fld_env = mk_fld_env con_names_with_flds flds\'\\n at_gres = zipWith (\\\\ (_, at_flav) at_nm -> mkLocalTyConGRE (fmap (const tycon_name) at_flav) at_nm)\\n at_bndrs at_names\\n sig_gres = map (mkLocalVanillaGRE (ParentIs tycon_name)) sig_names\\n con_gres = map (mkLocalConLikeGRE (ParentIs tycon_name)) fld_env\\n fld_gres = mkLocalFieldGREs (ParentIs tycon_name) fld_env\\n sub_gres = at_gres ++ sig_gres ++ con_gres ++ fld_gres\\n ; traceRn \\"getLocalNonValBinders new_tc\\" $\\n vcat [ text \\"tycon:\\" <+> ppr tycon_name\\n , text \\"tc_gre:\\" <+> ppr tc_gre\\n , text \\"sub_gres:\\" <+> ppr sub_gres ]\\n ; return $ tc_gre : sub_gres }\\n\\n -- Calculate the record field information, which feeds into the GlobalRdrElts\\n -- for DataCons and their fields. It\'s convenient to do this here where\\n -- we are working with a single datatype definition.\\n --\\n -- The information we needed was all set up for us:\\n -- see Note [Collecting record fields in data declarations] in GHC.Hs.Utils.\\n mk_fld_env :: [(Name, Either VisArity [Located Int])] -> IntMap FieldLabel\\n -> [(ConLikeName, ConInfo)]\\n mk_fld_env names flds =\\n [ (DataConName con, ConInfo (ConIsData (map fst names)) fld_info)\\n | (con, con_fl_indxs) <- names\\n , let fld_info = case fmap (map ((flds IntMap.!) . unLoc)) con_fl_indxs of\\n Left 0 -> ConIsNullary\\n Left arity -> ConHasPositionalArgs arity\\n Right [] -> ConIsNullary\\n Right (fld:flds) -> ConHasRecordFields $ fld NE.:| flds ]\\n\\n new_assoc :: DuplicateRecordFields -> FieldSelectors -> LInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_assoc _ _ (L _ (TyFamInstD {})) = return []\\n -- type instances don\'t bind new names\\n\\n new_assoc dup_fields_ok has_sel (L _ (DataFamInstD _ d))\\n = new_di dup_fields_ok has_sel Nothing d\\n new_assoc dup_fields_ok has_sel\\n (L _ (ClsInstD _ (ClsInstDecl { cid_poly_ty = inst_ty\\n , cid_decls = decls })))\\n = do -- First, attempt to grab the name of the class from the instance.\\n -- This step could fail if the instance is not headed by a class,\\n -- such as in the following examples:\\n --\\n -- (1) The class is headed by a bang pattern, such as in\\n -- `instance !Show Int` (#3811c)\\n -- (2) The class is headed by a type variable, such as in\\n -- `instance c` (#16385)\\n --\\n -- If looking up the class name fails, then mb_cls_gre will\\n -- be Nothing.\\n mb_cls_gre <- runMaybeT $ do\\n -- See (1) above\\n L loc cls_rdr <- MaybeT $ pure $ getLHsInstDeclClass_maybe inst_ty\\n -- See (2) above\\n MaybeT $ setSrcSpan (locA loc) $ lookupGlobalOccRn_maybe SameNameSpace cls_rdr\\n -- Assuming the previous step succeeded, process any associated data\\n -- family instances. If the previous step failed, bail out.\\n case mb_cls_gre of\\n Nothing\\n -> pure []\\n Just cls_gre\\n -> let cls_nm = greName cls_gre\\n in concatMapM (new_di dup_fields_ok has_sel (Just cls_nm) . unLoc) (data_fam_insts decls)\\n\\n data_fam_insts decls = concatMap get decls\\n where\\n get (L l (InstD _ (DataFamInstD { dfid_inst = d}))) = [L l d]\\n get _ = []\\n\\n new_di :: DuplicateRecordFields -> FieldSelectors\\n -> Maybe Name -- class name\\n -> DataFamInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_di dup_fields_ok has_sel mb_cls dfid@(DataFamInstDecl { dfid_eqn = ti_decl })\\n = do { main_name <- unLoc <$> lookupFamInstName mb_cls (feqn_tycon ti_decl)\\n ; let LConsWithFields cons_with_flds flds = hsDataFamInstBinders dfid\\n ; sub_names <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst sub_names) flds\\n ; mapM_ (add_dup_fld_errs flds\') sub_names\\n ; let fld_env = mk_fld_env sub_names flds\'\\n con_gres = map (mkLocalConLikeGRE (ParentIs main_name)) fld_env\\n field_gres = mkLocalFieldGREs (ParentIs main_name) fld_env\\n -- NB: the data family name is not bound here,\\n -- so we don\'t return a GlobalRdrElt for it here!\\n ; return $ con_gres ++ field_gres }\\n\\n -- Add errors if a constructor has a duplicate record field.\\n add_dup_fld_errs :: IntMap FieldLabel\\n -> (Name, Either VisArity [Located Int])\\n -> IOEnv (Env TcGblEnv TcLclEnv) ()\\n add_dup_fld_errs all_flds (con, con_flds_or_arity)\\n | Right con_flds <- con_flds_or_arity\\n , let (_, dups) = removeDups (comparing unLoc) con_flds\\n = for_ dups $ \\\\ dup_flds ->\\n -- Report the error at the location of the second occurrence\\n -- of the duplicate field.\\n let loc =\\n case dup_flds of\\n _ :| ( L loc _ : _) -> loc\\n L loc _ :| _ -> loc\\n dup_rdrs = fmap (nameRdrName . flSelector . (all_flds IntMap.!) . unLoc) dup_flds\\n in addErrAt loc $ TcRnDuplicateFieldName (RecordFieldDecl con) dup_rdrs\\n | otherwise\\n = return ()\\n\\nnewRecordFieldLabel :: DuplicateRecordFields -> FieldSelectors -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel\\nnewRecordFieldLabel _ _ [] _ = error \\"newRecordFieldLabel: datatype has no constructors!\\"\\nnewRecordFieldLabel dup_fields_ok has_sel (dc:_) (L loc (FieldOcc _ (L _ fld)))\\n = do { selName <- newTopSrcBinder $ L (l2l loc) $ field\\n ; return $ FieldLabel { flHasDuplicateRecordFields = dup_fields_ok\\n , flHasFieldSelector = has_sel\\n , flSelector = selName } }\\n where\\n fld_occ = rdrNameOcc fld\\n dc_fs = occNameFS $ nameOccName dc\\n field\\n -- Use an Exact RdrName as-is, to preserve the bindings\\n -- of an already renamer-resolved field and its use\\n -- sites. This is needed to correctly support record\\n -- selectors in Template Haskell. See Note [Binders in\\n -- Template Haskell] in \\"GHC.ThToHs\\" and Note [Looking up\\n -- Exact RdrNames] in \\"GHC.Rename.Env\\".\\n | isExact fld\\n = assertPpr (fieldOcc_maybe fld_occ == Just dc_fs)\\n (vcat [ text \\"newRecordFieldLabel: incorrect namespace for exact Name\\" <+> quotes (ppr fld)\\n , text \\"expected namespace:\\" <+> pprNameSpace (fieldName dc_fs)\\n , text \\" actual namespace:\\" <+> pprNameSpace (occNameSpace fld_occ) ])\\n fld\\n\\n -- Field names produced by the parser are namespaced with VarName.\\n -- Here we namespace them according to the first constructor.\\n -- See Note [Record field namespacing] in GHC.Types.Name.Occurrence.\\n | otherwise\\n = mkRdrUnqual $ varToRecFieldOcc dc_fs fld_occ\\n\\n{-\\nNote [Looking up family names in family instances]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider\\n\\n module M where\\n type family T a :: *\\n type instance M.T Int = Bool\\n\\nWe might think that we can simply use \'lookupOccRn\' when processing the type\\ninstance to look up \'M.T\'. Alas, we can\'t! The type family declaration is in\\nthe *same* HsGroup as the type instance declaration. Hence, as we are\\ncurrently collecting the binders declared in that HsGroup, these binders will\\nnot have been added to the global environment yet.\\n\\nSolution is simple: process the type family declarations first, extend\\nthe environment, and then process the type instances.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Filtering imports}\\n* *\\n************************************************************************\\n\\n@filterImports@ takes the @ExportEnv@ telling what the imported module makes\\navailable, and filters it through the import spec (if any).\\n\\nNote [Dealing with imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nFor import M( ies ), we take each AvailInfo from the mi_exports of M, and make\\n\\n imp_occ_env :: OccEnv (NameEnv ImpOccItem)\\n\\nThis map contains one entry for each OccName that M exports, mapping each OccName\\nto the following information:\\n\\n 1. the GlobalRdrElt corresponding to the OccName,\\n 2. whether this GlobalRdrElt was the parent in the AvailInfo we found\\n the OccName in.\\n 3. the GlobalRdrElts that were bundled together in the AvailInfo we found\\n this OccName in (not including the parent),\\n\\nWe need (2) and (3) during the construction of the OccEnv because of associated\\ntypes and bundled pattern synonyms, respectively.\\n(3) is explained in Note [Importing PatternSynonyms].\\n\\nTo explain (2), consider for example:\\n\\n module M where\\n class C a where { data T a }\\n instance C Int where { data T Int = T1 | T2 }\\n instance C Bool where { data T Int = T3 }\\n\\nHere, M\'s exports avails are (recalling the AvailTC invariant from GHC.Types.Avail)\\n\\n C(C,T), T(T,T1,T2,T3)\\n\\nNotice that T appears *twice*, once as a child and once as a parent. From\\nthese two exports, respectively, during construction of the imp_occ_env, we begin\\nby associating the following two elements with the key T:\\n\\n T -> ImpOccItem { imp_item = gre1, imp_bundled = [C,T] , imp_is_parent = False }\\n T -> ImpOccItem { imp_item = gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nwhere `gre1`, `gre2` are two GlobalRdrElts with greName T.\\nWe combine these (in function \'combine\' in \'mkImportOccEnv\') by discarding the\\nnon-parent item, thusly:\\n\\n T -> IE_ITem { imp_item = gre1 `plusGRE` gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nNote the `plusGRE`: this ensures we don\'t drop parent information;\\nsee Note [Preserve parent information when combining import OccEnvs].\\n\\nSo the overall imp_occ_env is:\\n\\n C -> ImpOccItem { imp_item = C, imp_bundled = [T ], imp_is_parent = True }\\n T -> ImpOccItem { imp_item = T , imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n T1 -> ImpOccItem { imp_item = T1, imp_bundled = [T1,T2,T3], imp_is_parent = False }\\n -- similarly for T2, T3\\n\\nNote that the imp_occ_env will have entries for data constructors too,\\nalthough we never look up data constructors.\\n\\nNote [Importing PatternSynonyms]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nAs described in Note [Dealing with imports], associated types can lead to the\\nsame Name appearing twice, both as a child and once as a parent, when\\nconstructing the imp_occ_env. The same thing can happen with pattern synonyms\\nif they are exported bundled with a type.\\n\\nA simplified example, based on #11959:\\n\\n {-# LANGUAGE PatternSynonyms #-}\\n module M (T(P), pattern P) where -- Duplicate export warning, but allowed\\n data T = MkT\\n pattern P = MkT\\n\\nHere we have T(P) and P in export_avails, and respectively construct both\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n P -> ImpOccItem { imp_item = P, imp_bundled = [] , imp_is_parent = False }\\n\\nWe combine these by dropping the one with no siblings, leaving us with:\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n\\nThat is, we simply discard the non-bundled Avail.\\n\\nNote [Importing DuplicateRecordFields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn filterImports, another complicating factor is DuplicateRecordFields.\\nSuppose we have:\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (S(foo), T(foo)) where\\n data S = MkS { foo :: Int }\\n data T = MkT { foo :: Int }\\n\\n module N where\\n import M (foo) -- this is allowed (A)\\n import M (S(foo)) -- this is allowed (B)\\n\\nHere M exports \'foo\' at two different OccNames, with different namespaces for\\nthe two construtors MkS and MkT. Then, when we look up \'foo\' in lookup_names\\nfor case (A), we have a variable foo but must look in all the record field\\nnamespaces to find the two fields (and hence two different Avails).\\nWhereas in case (B) we reach the lookup_ie case for IEThingWith,\\nwhich looks up \'S\' and then finds the unique \'foo\' amongst its children.\\n\\nSee T16745 for a test of this.\\n\\nNote [Preserve parent information when combining import OccEnvs]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen discarding one ImpOccItem in favour of another, as described in\\nNote [Dealing with imports], we must make sure to combine the GREs so that\\nwe don\'t lose information.\\n\\nConsider for example #24084:\\n\\n module M1 where { class C a where { type T a } }\\n module M2 ( module M1 ) where { import M1 }\\n module M3 where { import M2 ( C, T ); instance C () where T () = () }\\n\\nWhen processing the import list of `M3`, we will have two `Avail`s attached\\nto `T`, namely `C(C, T)` and `T(T)`. We combine them in the `combine` function\\nof `mkImportOccEnv`; as described in Note [Dealing with imports] we discard\\n`C(C, T)` in favour of `T(T)`. However, in doing so, we **must not**\\ndiscard the information want that `C` is the parent of `T`. Indeed,\\nlosing track of this information can cause errors when importing,\\nas we could get an error of the form\\n\\n \\u2018T\\u2019 is not a (visible) associated type of class \\u2018C\\u2019\\n\\nThis explains why we use `plusGRE` when combining the two ImpOccItems, even\\nthough we are discarding one in favour of the other.\\n-}\\n\\n-- | All the \'GlobalRdrElt\'s associated with an \'AvailInfo\'.\\ngresFromAvail :: HasDebugCallStack\\n => HscEnv -> Maybe ImportSpec -> AvailInfo -> [GlobalRdrElt]\\ngresFromAvail hsc_env prov avail =\\n [ mk_gre nm info\\n | nm <- availNames avail\\n , let info = lookupGREInfo hsc_env nm ]\\n where\\n\\n mk_gre n info\\n = case prov of\\n -- Nothing => bound locally\\n -- Just is => imported from \'is\'\\n Nothing -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = True, gre_imp = emptyBag\\n , gre_info = info }\\n Just is -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = False, gre_imp = unitBag is\\n , gre_info = info }\\n\\n-- | All the \'GlobalRdrElt\'s associated with a collection of \'AvailInfo\'s.\\ngresFromAvails :: HscEnv -> Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]\\ngresFromAvails hsc_env prov = concatMap (gresFromAvail hsc_env prov)\\n\\nimportsFromIface :: HscEnv -> ModIface -> ImpDeclSpec -> Maybe NameSet -> GlobalRdrEnv\\nimportsFromIface hsc_env iface decl_spec hidden = mkGlobalRdrEnv $ case hidden of\\n Nothing -> all_gres\\n Just hidden_names -> filter (not . (`elemNameSet` hidden_names) . greName) all_gres\\n where\\n all_gres = gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\nrnNamespaceSpecifier :: NamespaceSpecifier GhcPs -> NamespaceSpecifier GhcRn\\nrnNamespaceSpecifier (NoNamespaceSpecifier _) = NoNamespaceSpecifier noExtField\\nrnNamespaceSpecifier (TypeNamespaceSpecifier x) = TypeNamespaceSpecifier x\\nrnNamespaceSpecifier (DataNamespaceSpecifier x) = DataNamespaceSpecifier x\\n\\nfilterImports\\n :: HasDebugCallStack\\n => HscEnv\\n -> ModIface\\n -> ImpDeclSpec\\n -- ^ Import spec\\n -> Maybe (ImportListInterpretation, [LIE GhcPs])\\n -- ^ Whether this is a \\"hiding\\" import list\\n -> RnM (Maybe (ImportListInterpretation, [LIE GhcRn]), -- Import spec w/ Names\\n ImpUserList, -- same, but designed for storage in interfaces\\n GlobalRdrEnv) -- Same again, but in GRE form\\nfilterImports hsc_env iface decl_spec Nothing\\n = return (Nothing, ImpUserAll, importsFromIface hsc_env iface decl_spec Nothing)\\nfilterImports hsc_env iface decl_spec (Just (want_hiding, import_items))\\n = do -- check for errors, convert RdrNames to Names\\n items1 <- mapM lookup_lie import_items\\n\\n let items2 :: [(LIE GhcRn, [GlobalRdrElt])]\\n items2 = concat items1\\n -- NB we may have duplicates, and several items\\n -- for the same parent; e.g N(x) and N(y)\\n\\n (gres, imp_user_list) = case want_hiding of\\n Exactly ->\\n let gres = concatMap (gresFromIE decl_spec) items2\\n gre_env = mkGlobalRdrEnv gres\\n implicit_parents = mkNameSet $ mapMaybe parentOfImplicitlyImportedGRE gres\\n in (gre_env, ImpUserExplicit (gresToAvailInfo $ globalRdrEnvElts $ gre_env) implicit_parents)\\n EverythingBut ->\\n let hidden_names = mkNameSet $ concatMap (map greName . snd) items2\\n in (importsFromIface hsc_env iface decl_spec (Just hidden_names), ImpUserEverythingBut hidden_names)\\n\\n return (Just (want_hiding, map fst items2), imp_user_list, gres)\\n where\\n import_mod = mi_module iface\\n all_avails = mi_exports iface\\n imp_occ_env = mkImportOccEnv hsc_env decl_spec all_avails\\n\\n -- Look up a parent (type constructor, class or data constructor)\\n -- in an import.\\n lookup_parent :: IE GhcPs -> RdrName -> IELookupM ImpOccItem\\n lookup_parent ie rdr =\\n assertPpr (not $ isVarNameSpace ns)\\n (vcat [ text \\"filterImports lookup_parent: unexpected variable\\"\\n , text \\"rdr:\\" <+> ppr rdr\\n , text \\"namespace:\\" <+> pprNameSpace ns ]) $\\n do { xs <- lookup_names ie rdr\\n ; case xs of\\n cax :| [] -> return cax\\n _ -> pprPanic \\"filter_imports lookup_parent ambiguous\\" $\\n vcat [ text \\"rdr:\\" <+> ppr rdr\\n , text \\"lookups:\\" <+> ppr (fmap imp_item xs) ] }\\n -- Looking up non-variables is always unambiguous,\\n -- as there can be at most one corresponding item\\n -- in the imp_occ_env.\\n -- See item (1) of Note [Exporting duplicate declarations]\\n -- in GHC.Tc.Gen.Export.\\n where\\n occ = rdrNameOcc rdr\\n ns = occNameSpace occ\\n\\n -- Look up a RdrName used in an import, returning multiple values if there\\n -- are several fields with the same name exposed by the module\\n lookup_names :: IE GhcPs -> RdrName -> IELookupM (NonEmpty ImpOccItem)\\n lookup_names ie rdr\\n | isQual rdr\\n = failLookupWith (QualImportError rdr)\\n | otherwise\\n = case lookups of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n item:items -> return $ item :| items\\n where\\n lookups = concatMap nonDetNameEnvElts\\n $ lookupImpOccEnv (RelevantGREsFOS WantNormal) imp_occ_env (rdrNameOcc rdr)\\n\\n lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, [GlobalRdrElt])]\\n lookup_lie (L loc ieRdr)\\n = setSrcSpanA loc $\\n do (stuff, warns) <- run_lookup ([],[]) (lookup_ie ieRdr)\\n mapM_ (addTcRnDiagnostic <=< warning_msg) warns\\n return [ (L loc ie, gres) | (ie,gres) <- stuff ]\\n where\\n\\n -- Warn when importing T(..) and no children are brought in scope\\n warning_msg (DodgyImport reason) =\\n pure (TcRnDodgyImports reason)\\n warning_msg MissingImportList =\\n pure (TcRnMissingImportList ieRdr)\\n warning_msg (BadImportW ie sub) = do\\n -- \'BadImportW\' is only constructed below in \'bad_import_w\', in\\n -- the \'EverythingBut\' case, so here we assume a \'hiding\' clause.\\n (reason :| _) <- badImportItemErr iface decl_spec ie sub all_avails\\n pure (TcRnDodgyImports (DodgyImportsHiding reason))\\n warning_msg (DeprecatedExport n w) =\\n pure $ TcRnPragmaWarning\\n PragmaWarningExport\\n { pwarn_occname = occName n\\n , pwarn_impmod = moduleName import_mod }\\n w\\n\\n run_lookup :: a -> IELookupM a -> TcRn a\\n run_lookup def m = case m of\\n Failed err -> do\\n msgs <- lookup_err_msgs err\\n forM_ msgs $ \\\\msg -> addErr (TcRnImportLookup msg)\\n return def\\n Succeeded a -> return a\\n\\n lookup_err_msgs err = case err of\\n BadImport ie sub -> badImportItemErr iface decl_spec ie sub all_avails\\n IllegalImport -> pure $ NE.singleton ImportLookupIllegal\\n QualImportError rdr -> pure $ NE.singleton (ImportLookupQualified rdr)\\n\\n -- For each import item, we convert its RdrNames to Names,\\n -- and at the same time compute all the GlobalRdrElt corresponding\\n -- to what is actually imported by this item.\\n -- Returns Nothing on error.\\n --\\n -- Returns a list because, with DuplicateRecordFields, a naked\\n -- import/export of a record field can correspond to multiple\\n -- different GlobalRdrElts. See Note [Importing DuplicateRecordFields].\\n lookup_ie :: IE GhcPs\\n -> IELookupM ([(IE GhcRn, [GlobalRdrElt])], [IELookupWarning])\\n lookup_ie ie = handle_bad_import $\\n case ie of\\n IEVar _ (L l n) _ -> do\\n -- See Note [Importing DuplicateRecordFields]\\n xs <- lookup_names ie (ieWrappedName n)\\n let gres = map imp_item $ NE.toList xs\\n export_depr_warns\\n | want_hiding == Exactly\\n = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ( [ (IEVar Nothing (L l (replaceWrappedName n name)) noDocstring, [gre])\\n | gre <- gres\\n , let name = greName gre ]\\n , export_depr_warns )\\n\\n IEThingAll x ns_spec (L l tc) _ -> do\\n ImpOccItem { imp_item = gre\\n , imp_bundled = bundled_gres\\n , imp_is_parent = is_par\\n }\\n <- lookup_parent ie $ ieWrappedName tc\\n let name = greName gre\\n\\n child_gres :: [GlobalRdrElt]\\n child_gres\\n | is_par = filterByNamespaceSpecifierGREs ns_spec bundled_gres\\n | otherwise = []\\n\\n imp_list_warn\\n\\n | null child_gres\\n -- e.g. f(..) or T(..) where T is a type synonym\\n = [DodgyImport (DodgyImportsEmptyParent ie ns_spec gre)]\\n\\n -- e.g. import M( T(..) )\\n | not (is_qual decl_spec)\\n = [MissingImportList]\\n\\n | otherwise\\n = []\\n\\n renamed_ie = IEThingAll (x { ieta_warning = Nothing })\\n (rnNamespaceSpecifier ns_spec)\\n (L l (replaceWrappedName tc name))\\n noDocstring\\n export_depr_warn\\n | want_hiding == Exactly\\n = maybeToList $ mk_depr_export_warning gre\\n -- We don\'t want to warn about the children as they\\n -- are not explicitly mentioned; the warning will\\n -- be emitted later on if they are used\\n | otherwise = []\\n\\n return ( [(renamed_ie, gre:child_gres)]\\n , imp_list_warn ++ export_depr_warn)\\n\\n\\n IEThingAbs _ (L l tc\') _\\n | want_hiding == EverythingBut -- hiding ( C )\\n -- Here the \'C\' can be a data constructor\\n -- *or* a type/class, or even both\\n -> let tc = ieWrappedName tc\'\\n tc_name = lookup_parent ie tc\\n dc_name = lookup_parent ie (setRdrNameSpace tc srcDataName)\\n in\\n case catIELookupM [ tc_name, dc_name ] of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n names -> return ( [mkIEThingAbs tc\' l (imp_item name) | name <- names], [])\\n | otherwise\\n -> do ImpOccItem { imp_item = gre } <- lookup_parent ie (ieWrappedName tc\')\\n return ( [mkIEThingAbs tc\' l gre]\\n , maybeToList $ mk_depr_export_warning gre)\\n\\n IEThingWith (deprecation, ann) ltc@(L l rdr_tc) wc rdr_ns _ -> do\\n ImpOccItem { imp_item = gre, imp_bundled = subnames }\\n <- lookup_parent (IEThingAbs Nothing ltc noDocstring) (ieWrappedName rdr_tc)\\n let name = greName gre\\n\\n -- Look up the children in the sub-names of the parent\\n -- See Note [Importing DuplicateRecordFields]\\n let (children_errs, childnames) = lookupChildren subnames rdr_ns\\n\\n bad_import_warns <-\\n if null children_errs then return [] else\\n let items = map lce_wrapped_name children_errs\\n ie = IEThingWith (deprecation, ann) ltc wc items noDocstring\\n -- We are trying to import T( a,b,c,d ), and failed\\n -- to find \'b\' and \'d\'. So we make up an import item\\n -- to report as failing, namely T( b, d ).\\n -- c.f. #15413\\n subordinate_err = mkSubordinateError gre children_errs\\n in bad_import_w ie subordinate_err\\n\\n let name\' = replaceWrappedName rdr_tc name\\n childnames\' = map (to_ie_post_rn . fmap greName) childnames\\n gres = gre : map unLoc childnames\\n export_depr_warns\\n | want_hiding == Exactly = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ([ (IEThingWith (Nothing, ann) (L l name\') wc childnames\' noDocstring\\n ,gres)]\\n , bad_import_warns ++ export_depr_warns)\\n\\n IEWholeNamespace x ns_spec -> do\\n let mod_name = moduleName import_mod\\n names = map greName gres\\n renamed_ie = IEWholeNamespace x { iewn_warning = Nothing\\n , iewn_names = names }\\n (rnNamespaceSpecifier ns_spec)\\n gres = filterByNamespaceSpecifierGREs ns_spec $\\n gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n dodgy_warn\\n | null gres = [DodgyImport (DodgyImportsWildcard mod_name ns_spec)]\\n | otherwise = []\\n return ([(renamed_ie, gres)],\\n dodgy_warn)\\n\\n _other -> failLookupWith IllegalImport\\n -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed...\\n -- all of those constitute errors.\\n\\n where\\n mkIEThingAbs tc l gre\\n = (IEThingAbs Nothing (L l (replaceWrappedName tc n)) noDocstring, [gre])\\n where n = greName gre\\n\\n -- N.B. imports never have docstrings\\n noDocstring = Nothing\\n\\n handle_bad_import m = catchIELookup m $ \\\\case\\n BadImport ie sub -> do\\n ws <- bad_import_w ie sub\\n return ([], ws)\\n err -> failLookupWith err\\n\\n bad_import_w :: IE GhcPs -> IsSubordinateError -> IELookupM [IELookupWarning]\\n bad_import_w ie sub\\n | want_hiding == EverythingBut = return [BadImportW ie sub]\\n | otherwise = failLookupWith (BadImport ie sub)\\n\\n mk_depr_export_warning gre\\n = DeprecatedExport name <$> mi_export_warn_fn iface name\\n where\\n name = greName gre\\n\\n-- | Assuming a subordinate item could not be found, do another lookup for a\\n-- more specific error message.\\nmkBadExportSubordinate :: [GlobalRdrElt] -> LIEWrappedName GhcPs -> BadExportSubordinate\\nmkBadExportSubordinate child_gres n =\\n case lookupChildren child_gres [n] of\\n (LookupChildNonType {lce_nontype_item = g} : _, _) -> BadExportSubordinateNonType g\\n (LookupChildNonData {lce_nondata_item = g} : _, _) -> BadExportSubordinateNonData g\\n _ -> BadExportSubordinateNotFound n\\n\\ntype IELookupM = MaybeErr IELookupError\\n\\ndata IELookupWarning\\n = BadImportW (IE GhcPs) IsSubordinateError\\n | MissingImportList\\n | DodgyImport DodgyImportsReason\\n | DeprecatedExport Name (WarningTxt GhcRn)\\n\\n-- | Is this import/export item a subordinate or not?\\ndata IsSubordinateError\\n = IsSubordinateError { subordinate_err_parent :: !GlobalRdrElt\\n , subordinate_err_unavailable :: [FastString]\\n , subordinate_err_nontype :: [GlobalRdrElt]\\n , subordinate_err_nondata :: [GlobalRdrElt] }\\n | IsNotSubordinate\\n\\nmkSubordinateError :: GlobalRdrElt -> [LookupChildError] -> IsSubordinateError\\nmkSubordinateError gre children_errs = foldr add init_acc children_errs\\n where\\n init_acc :: IsSubordinateError\\n init_acc = IsSubordinateError gre [] [] []\\n\\n add :: LookupChildError -> IsSubordinateError -> IsSubordinateError\\n add children_err sub@IsSubordinateError{} =\\n case children_err of\\n LookupChildNonType{lce_nontype_item = g} ->\\n sub { subordinate_err_nontype = g : subordinate_err_nontype sub }\\n LookupChildNonData{lce_nondata_item = g} ->\\n sub { subordinate_err_nondata = g : subordinate_err_nondata sub }\\n LookupChildNotFound (L _ wname) ->\\n let fs = (occNameFS . rdrNameOcc . ieWrappedName) wname\\n in sub { subordinate_err_unavailable = fs : subordinate_err_unavailable sub }\\n add _ IsNotSubordinate = panic \\"mkSubordinateError: IsNotSubordinate\\"\\n\\ndata IELookupError\\n = QualImportError RdrName\\n | BadImport (IE GhcPs) IsSubordinateError\\n | IllegalImport\\n\\nfailLookupWith :: IELookupError -> IELookupM a\\nfailLookupWith err = Failed err\\n\\ncatchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a\\ncatchIELookup m h = case m of\\n Succeeded r -> return r\\n Failed err -> h err\\n\\ncatIELookupM :: [IELookupM a] -> [a]\\ncatIELookupM ms = [ a | Succeeded a <- ms ]\\n\\n-- | Information associated to an \'AvailInfo\' used in constructing\\n-- an \'OccEnv\' corresponding to imports.\\n--\\n-- See Note [Dealing with imports].\\ndata ImpOccItem\\n = ImpOccItem\\n { imp_item :: GlobalRdrElt\\n -- ^ The import item\\n , imp_bundled :: [GlobalRdrElt]\\n -- ^ Items bundled in the Avail this import item came from,\\n -- not including the import item itself if it is a parent.\\n , imp_is_parent :: Bool\\n -- ^ Is the import item a parent? See Note [Dealing with imports].\\n }\\n\\ninstance Outputable ImpOccItem where\\n ppr (ImpOccItem { imp_item = item, imp_bundled = bundled, imp_is_parent = is_par })\\n = braces $ hsep\\n [ text \\"ImpOccItem\\"\\n , if is_par then text \\"[is_par]\\" else empty\\n , ppr (greName item) <+> ppr (greParent item)\\n , braces $ text \\"bundled:\\" <+> ppr (map greName bundled) ]\\n\\n-- | Make an \'OccEnv\' of all the imports.\\n--\\n-- Complicated by the fact that associated data types and pattern synonyms\\n-- can appear twice. See Note [Dealing with imports].\\nmkImportOccEnv :: HscEnv -> ImpDeclSpec -> [IfaceExport] -> OccEnv (NameEnv ImpOccItem)\\nmkImportOccEnv hsc_env decl_spec all_avails =\\n mkOccEnv_C (plusNameEnv_C combine)\\n [ (occ, mkNameEnv [(nm, item)])\\n | avail <- all_avails\\n , let gres = gresFromAvail hsc_env (Just hiding_spec) avail\\n , gre <- gres\\n , let nm = greName gre\\n occ = greOccName gre\\n (is_parent, bundled) = case avail of\\n AvailTC c _\\n | c == nm -- (Recall the AvailTC invariant from GHC.Types.AvailInfo)\\n -> ( True, drop 1 gres ) -- \\"drop 1\\": don\'t include the parent itself.\\n | otherwise\\n -> ( False, gres )\\n _ -> ( False, [] )\\n item = ImpOccItem\\n { imp_item = gre\\n , imp_bundled = bundled\\n , imp_is_parent = is_parent }\\n ]\\n where\\n\\n hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\n -- See Note [Dealing with imports]\\n -- \'combine\' may be called for associated data types which appear\\n -- twice in the all_avails. In the example, we have two Avails for T,\\n -- namely T(T,T1,T2,T3) and C(C,T), and we combine them by dropping the\\n -- latter, in which T is not the parent.\\n combine :: ImpOccItem -> ImpOccItem -> ImpOccItem\\n combine item1@(ImpOccItem { imp_item = gre1, imp_is_parent = is_parent1 })\\n item2@(ImpOccItem { imp_item = gre2, imp_is_parent = is_parent2 })\\n | is_parent1 || is_parent2\\n , not (isRecFldGRE gre1 || isRecFldGRE gre2) -- NB: does not force GREInfo.\\n , let name1 = greName gre1\\n name2 = greName gre2\\n gre = gre1 `plusGRE` gre2\\n -- See Note [Preserve parent information when combining import OccEnvs]\\n = assertPpr (name1 == name2)\\n (ppr name1 <+> ppr name2) $\\n if is_parent1\\n then item1 { imp_item = gre }\\n else item2 { imp_item = gre }\\n -- Discard C(C,T) in favour of T(T, T1, T2, T3).\\n\\n -- \'combine\' may also be called for pattern synonyms which appear both\\n -- unassociated and associated (see Note [Importing PatternSynonyms]).\\n combine item1@(ImpOccItem { imp_item = c1, imp_bundled = kids1 })\\n item2@(ImpOccItem { imp_item = c2, imp_bundled = kids2 })\\n = assertPpr (greName c1 == greName c2\\n && (not (null kids1 && null kids2)))\\n (ppr c1 <+> ppr c2 <+> ppr kids1 <+> ppr kids2) $\\n if null kids1\\n then item2\\n else item1\\n -- Discard standalone pattern P in favour of T(P).\\n\\n-- | Essentially like @lookupGRE env (LookupOccName occ which_gres)@,\\n-- but working with \'ImpOccItem\'s instead of \'GlobalRdrElt\'s.\\nlookupImpOccEnv :: WhichGREs GREInfo\\n -> OccEnv (NameEnv ImpOccItem) -> OccName -> [NameEnv ImpOccItem]\\nlookupImpOccEnv which_gres env occ =\\n mapMaybe relevant_items $ lookupOccEnv_AllNameSpaces env occ\\n where\\n is_relevant :: ImpOccItem -> Bool\\n is_relevant (ImpOccItem { imp_item = gre }) =\\n greIsRelevant which_gres (occNameSpace occ) gre\\n relevant_items :: NameEnv ImpOccItem -> Maybe (NameEnv ImpOccItem)\\n relevant_items nms\\n | let nms\' = filterNameEnv is_relevant nms\\n = if isEmptyNameEnv nms\'\\n then Nothing\\n else Just nms\'\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{Import/Export Utils}\\n* *\\n************************************************************************\\n-}\\n\\n-- | Given an import\\\\/export spec, appropriately set the @gre_imp@ field\\n-- for the \'GlobalRdrElt\'s.\\ngresFromIE :: ImpDeclSpec -> (LIE GhcRn, [GlobalRdrElt]) -> [GlobalRdrElt]\\ngresFromIE decl_spec (L loc ie, gres)\\n = map set_gre_imp gres\\n where\\n is_explicit = case ie of\\n IEThingAll _ _ name _ -> \\\\n -> n == lieWrappedName name\\n IEWholeNamespace _ _ -> \\\\_ -> False\\n _ -> \\\\_ -> True\\n prov_fn name\\n = ImpSpec { is_decl = decl_spec, is_item = item_spec }\\n where\\n item_spec = ImpSome { is_explicit = is_explicit name\\n , is_iloc = locA loc }\\n set_gre_imp gre@( GRE { gre_name = nm } )\\n = gre { gre_imp = unitBag $ prov_fn nm }\\n\\nparentOfImplicitlyImportedGRE :: Outputable info => GlobalRdrEltX info -> Maybe Name\\nparentOfImplicitlyImportedGRE gre =\\n if any (explicit_import . is_item) $ gre_imp gre\\n then Nothing\\n else greParent_maybe gre\\n where\\n explicit_import :: ImpItemSpec -> Bool\\n explicit_import (ImpAll {}) =\\n pprPanic \\"parentOfImplicitlyImportedGRE: ImpAll\\" (ppr gre)\\n explicit_import (ImpSome { is_explicit }) = is_explicit\\n\\n{- Note [Children for duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider the module\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (F(foo, MkFInt, MkFBool)) where\\n data family F a\\n data instance F Int = MkFInt { foo :: Int }\\n data instance F Bool = MkFBool { foo :: Bool }\\n\\nThe `foo` in the export list refers to *both* selectors! For this\\nreason, lookupChildren builds an environment that maps the FastString\\nto a list of items, rather than a single item.\\n-}\\n\\nmkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]\\nmkChildEnv gres = foldr add emptyNameEnv gres\\n where\\n add gre env = case greParent gre of\\n ParentIs p -> extendNameEnv_Acc (:) Utils.singleton env p gre\\n NoParent -> env\\n\\nfindChildren :: NameEnv [a] -> Name -> [a]\\nfindChildren env n = lookupNameEnv env n `orElse` []\\n\\ndata LookupChildError\\n = LookupChildNotFound { lce_wrapped_name :: !(LIEWrappedName GhcPs) }\\n | LookupChildNonType { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nontype_item :: !GlobalRdrElt }\\n | LookupChildNonData { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nondata_item :: !GlobalRdrElt }\\n\\nlookupChildren :: [GlobalRdrElt]\\n -> [LIEWrappedName GhcPs]\\n -> ( [LookupChildError] -- The ones for which the lookup failed\\n , [LocatedA GlobalRdrElt] )\\n-- (lookupChildren all_kids rdr_items) maps each rdr_item to its\\n-- corresponding Name in all_kids, if the former exists\\n-- The matching is done by FastString, not OccName, so that\\n-- Cls( meth, AssocTy )\\n-- will correctly find AssocTy among the all_kids of Cls, even though\\n-- the RdrName for AssocTy may have a (bogus) DataName namespace\\n-- (Really the rdr_items should be FastStrings in the first place.)\\nlookupChildren all_kids rdr_items = (fails, successes)\\n where\\n mb_xs = map do_one rdr_items\\n fails = [ err | Failed err <- mb_xs ]\\n successes = [ ok | Succeeded oks <- mb_xs, ok <- NE.toList oks ]\\n\\n do_one :: LIEWrappedName GhcPs -> MaybeErr LookupChildError (NonEmpty (LocatedA GlobalRdrElt))\\n do_one item@(L l r) =\\n case r of\\n IEName{}\\n -- IEName (unadorned name) places no restriction on the namespace of\\n -- the imported entity, so we look in both `val_gres` and `typ_gres`.\\n -- In case of conflict (punning), the value namespace takes priority.\\n -- See Note [Prioritise the value namespace in subordinate import lists]\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEType{}\\n -- IEType (\'type\' namespace specifier) restricts the lookup to the\\n -- type namespace, i.e. to `typ_gres`. In case of failure, we check\\n -- `val_gres` to produce a more helpful error message.\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- val_gres -> Failed $ LookupChildNonType item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEData{}\\n -- IEData (\'data\' namespace specifier) restricts the lookup to the\\n -- data namespace, i.e. to `val_gres`. In case of failure, we check\\n -- `typ_gres` to produce a more helpful error message.\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- typ_gres -> Failed $ LookupChildNonData item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEPattern{} -> panic \\"lookupChildren: IEPattern\\" -- Never happens (invalid syntax)\\n IEDefault{} -> panic \\"lookupChildren: IEDefault\\" -- Never happens (invalid syntax)\\n where\\n fs = (occNameFS . rdrNameOcc . ieWrappedName) r\\n gres = fromMaybe [] (lookupFsEnv kid_env fs)\\n (val_gres, typ_gres) = partition (isValNameSpace . greNameSpace) gres\\n\\n -- See Note [Children for duplicate record fields]\\n kid_env :: FastStringEnv [GlobalRdrElt]\\n kid_env = extendFsEnvList_C (++) emptyFsEnv\\n [(occNameFS (occName x), [x]) | x <- all_kids]\\n\\n\\n{- Note [Prioritise the value namespace in subordinate import lists]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider this program that defines a class that has both an associated type\\nnamed (#) and a method named (#)\\n\\n module M_assoc where\\n class C a b where\\n type a # b\\n (#) :: a -> b -> ()\\n module N_assoc where\\n import M_assoc( C((#)) )\\n\\nIn the import declaration, when we see the unadorned name (#) in the subordinate\\nimport list of C, which children should we bring into scope? Our options are:\\n\\n a) only the method (#)\\n b) only the associated type (#)\\n c) both the method and the associated type\\n\\nTo follow the precedent established by top-level items, we go with option (a).\\nIndeed, consider a slightly different program\\n\\n module M_top where\\n type family a # b\\n a # b = ()\\n module N_top where\\n import M_top( (#) )\\n\\nHere the import brings only the function (#) into scope, and one has to say\\n`type (#)` to get the type family.\\n-}\\n\\n-------------------------------\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused names}\\n* *\\n*********************************************************\\n-}\\n\\nreportUnusedNames :: TcGblEnv -> HscSource -> RnM ()\\nreportUnusedNames gbl_env hsc_src\\n = do { keep <- readTcRef (tcg_keep gbl_env)\\n ; traceRn \\"RUN\\" (ppr (tcg_dus gbl_env))\\n ; warnUnusedImportDecls gbl_env hsc_src\\n ; warnUnusedTopBinds $ unused_locals keep\\n ; warnMissingSignatures gbl_env\\n ; warnMissingKindSignatures gbl_env }\\n where\\n used_names :: NameSet -> NameSet\\n used_names keep = findUses (tcg_dus gbl_env) emptyNameSet `unionNameSet` keep\\n -- NB: currently, if f x = g, we only treat \'g\' as used if \'f\' is used\\n -- Hence findUses\\n\\n -- Collect the defined names from the in-scope environment\\n defined_names :: [GlobalRdrElt]\\n defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)\\n\\n kids_env = mkChildEnv defined_names\\n -- This is done in mkExports too; duplicated work\\n\\n gre_is_used :: NameSet -> GlobalRdrElt -> Bool\\n gre_is_used used_names gre0\\n = name `elemNameSet` used_names\\n || any (\\\\ gre -> greName gre `elemNameSet` used_names) (findChildren kids_env name)\\n -- A use of C implies a use of T,\\n -- if C was brought into scope by T(..) or T(C)\\n where\\n name = greName gre0\\n\\n -- Filter out the ones that are\\n -- (a) defined in this module, and\\n -- (b) not defined by a \'deriving\' clause\\n -- The latter have an Internal Name, so we can filter them out easily\\n unused_locals :: NameSet -> [GlobalRdrElt]\\n unused_locals keep =\\n let -- Note that defined_and_used, defined_but_not_used\\n -- are both [GRE]; that\'s why we need defined_and_used\\n -- rather than just used_names\\n _defined_and_used, defined_but_not_used :: [GlobalRdrElt]\\n (_defined_and_used, defined_but_not_used)\\n = partition (gre_is_used (used_names keep)) defined_names\\n\\n in filter is_unused_local defined_but_not_used\\n is_unused_local :: GlobalRdrElt -> Bool\\n is_unused_local gre = isLocalGRE gre\\n && isExternalName (greName gre)\\n\\n{- *********************************************************************\\n* *\\n Missing signatures\\n* *\\n********************************************************************* -}\\n\\n{-\\nNote [Missing signatures]\\n~~~~~~~~~~~~~~~~~~~~~~~~~\\nThere are four warning flags in play:\\n\\n * -Wmissing-exported-signatures\\n Warn about any exported top-level function/value without a type signature.\\n Does not include pattern synonyms.\\n\\n * -Wmissing-signatures\\n Warn about any top-level function/value without a type signature. Does not\\n include pattern synonyms. Takes priority over -Wmissing-exported-signatures.\\n\\n * -Wmissing-exported-pattern-synonym-signatures\\n Warn about any exported pattern synonym without a type signature.\\n\\n * -Wmissing-pattern-synonym-signatures\\n Warn about any pattern synonym without a type signature. Takes priority over\\n -Wmissing-exported-pattern-synonym-signatures.\\n\\n-}\\n\\n-- | Warn the user about top level binders that lack type signatures.\\n-- Called /after/ type inference, so that we can report the\\n-- inferred type of the function\\nwarnMissingSignatures :: TcGblEnv -> RnM ()\\nwarnMissingSignatures gbl_env\\n = do { let exports = availsToNameSet (tcg_exports gbl_env)\\n sig_ns = tcg_sigs gbl_env\\n -- We use sig_ns to exclude top-level bindings that are generated by GHC\\n binds = collectHsBindsBinders CollNoDictBinders $ tcg_binds gbl_env\\n pat_syns = tcg_patsyns gbl_env\\n\\n not_ghc_generated :: Name -> Bool\\n not_ghc_generated name = name `elemNameSet` sig_ns\\n\\n add_binding_warn :: Id -> RnM ()\\n add_binding_warn id =\\n when (not_ghc_generated name) $\\n do { env <- liftZonkM $ tcInitTidyEnv -- Why not use emptyTidyEnv?\\n ; let ty = tidyOpenType env (idType id)\\n missing = MissingTopLevelBindingSig name ty\\n diag = TcRnMissingSignature missing exported\\n ; addDiagnosticAt (getSrcSpan name) diag }\\n where\\n name = idName id\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n add_patsyn_warn :: PatSyn -> RnM ()\\n add_patsyn_warn ps =\\n when (not_ghc_generated name) $\\n addDiagnosticAt (getSrcSpan name)\\n (TcRnMissingSignature missing exported)\\n where\\n name = patSynName ps\\n missing = MissingPatSynSig ps\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n -- Warn about missing signatures\\n -- Do this only when we have a type to offer\\n -- See Note [Missing signatures]\\n ; mapM_ add_binding_warn binds\\n ; mapM_ add_patsyn_warn pat_syns\\n }\\n\\n-- | Warn the user about tycons that lack kind signatures.\\n-- Called /after/ type (and kind) inference, so that we can report the\\n-- inferred kinds.\\nwarnMissingKindSignatures :: TcGblEnv -> RnM ()\\nwarnMissingKindSignatures gbl_env\\n = do { cusks_enabled <- xoptM LangExt.CUSKs\\n ; mapM_ (add_ty_warn cusks_enabled) tcs\\n }\\n where\\n tcs = tcg_tcs gbl_env\\n ksig_ns = tcg_ksigs gbl_env\\n exports = availsToNameSet (tcg_exports gbl_env)\\n\\n has_kind_signature :: Name -> Bool\\n has_kind_signature name = name `elemNameSet` ksig_ns\\n\\n add_ty_warn :: Bool -> TyCon -> RnM ()\\n add_ty_warn cusks_enabled tyCon =\\n when (has_kind_signature name) $\\n addDiagnosticAt (getSrcSpan name) diag\\n where\\n name = tyConName tyCon\\n diag = TcRnMissingSignature missing exported\\n missing = MissingTyConKindSig tyCon cusks_enabled\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused imports}\\n* *\\n*********************************************************\\n\\nThis code finds which import declarations are unused. The\\nspecification and implementation notes are here:\\n https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/unused-imports\\n\\nSee also Note [Choosing the best import declaration] in GHC.Types.Name.Reader\\n-}\\n\\ntype ImportDeclUsage\\n = ( LImportDecl GhcRn -- The import declaration\\n , [GlobalRdrElt] -- What *is* used (normalised)\\n , [Name] -- What is imported but *not* used\\n , [NamespaceSpecifier GhcRn] ) -- Unused wildcards\\n\\nwarnUnusedImportDecls :: TcGblEnv -> HscSource -> RnM ()\\nwarnUnusedImportDecls gbl_env hsc_src\\n = do { uses <- readMutVar (tcg_used_gres gbl_env)\\n ; let imports = tcg_rn_imports gbl_env\\n rdr_env = tcg_rdr_env gbl_env\\n\\n -- We should only warn for unnecessary *user* imports, but deciding\\n -- minimal imports should take generated imports into account\\n ; let usageUserImports = findImportUsage (excludeGenerated imports) uses\\n usageAllImports = findImportUsage imports uses\\n\\n ; traceRn \\"warnUnusedImportDecls\\" $\\n (vcat [ text \\"Uses:\\" <+> ppr uses\\n , text \\"Usage all user imports: \\" <+> ppr usageUserImports\\n , text \\"Usage all imports: \\" <+> ppr usageAllImports])\\n\\n ; mapM_ (warnUnusedImport rdr_env) usageUserImports\\n\\n ; whenGOptM Opt_D_dump_minimal_imports $\\n printMinimalImports hsc_src usageAllImports }\\n\\n-- | Exclude generated imports\\nexcludeGenerated :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\nexcludeGenerated = filterOut (isGeneratedImport . ideclOrigin . ideclExt . unLoc)\\n\\nfindImportUsage :: [LImportDecl GhcRn]\\n -> [GlobalRdrElt]\\n -> [ImportDeclUsage]\\n\\nfindImportUsage imports used_gres\\n = map unused_decl imports\\n where\\n import_usage :: ImportMap\\n import_usage = mkImportMap used_gres\\n\\n unused_decl :: LImportDecl GhcRn -> ImportDeclUsage\\n unused_decl decl@(L _ (ImportDecl { ideclImportList = imps }))\\n = -- pprTrace \\"unused_decl\\" (vcat [ ppr decl\\n -- , text \\"used\\" <+> ppr used_gres\\n -- , text \\"unused\\" <+> ppr unused_names ]) $\\n (decl, used_gres, unused_names, unused_wcs)\\n where\\n used_gres = lookupImportMap decl import_usage\\n\\n used_gre_env = mkGlobalRdrEnv used_gres\\n used_parents = mkNameSet (mapMaybe greParent_maybe used_gres)\\n\\n (unused_names, unused_wcs) -- Not trivial; see eg #7454\\n = case imps of\\n Just (Exactly, imp_ies) ->\\n let unused = foldr (add_unused . unLoc) emptyUnusedNames imp_ies\\n nms = nameSetElemsStable (collectUnusedNames unused)\\n wcs = collectUnusedWildcards unused\\n in (nms, wcs)\\n _other -> ([], []) -- No explicit import list => no unused-name list\\n\\n add_unused :: IE GhcRn -> UnusedNames -> UnusedNames\\n add_unused (IEVar _ n _) acc = add_unused_name (lieWrappedName n) True acc\\n add_unused (IEThingAbs _ n _) acc = add_unused_name (lieWrappedName n) False acc\\n add_unused (IEThingAll _ _ n _) acc = add_unused_all (lieWrappedName n) acc\\n add_unused (IEThingWith _ p wc ns _) acc = add_wc_all (add_unused_with pn xs acc)\\n where pn = lieWrappedName p\\n xs = map lieWrappedName ns\\n add_wc_all = case wc of\\n NoIEWildcard -> id\\n IEWildcard _ -> add_unused_all pn\\n add_unused (IEWholeNamespace x ns_spec) acc = add_unused_wildcard ns_spec (iewn_names x) acc\\n add_unused _ acc = acc\\n\\n add_unused_name :: Name -> Bool -> UnusedNames -> UnusedNames\\n add_unused_name n is_ie_var acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | is_ie_var\\n , isFieldName n\\n -- See Note [Reporting unused imported duplicate record fields]\\n = let\\n fs = getOccFS n\\n (flds, flds_used) = lookupFsEnv acc_fs fs `orElse` (emptyNameSet, Any False)\\n acc_fs\' = extendFsEnv acc_fs fs (extendNameSet flds n, Any used S.<> flds_used)\\n in UnusedNames acc_ns acc_wcs acc_fs\'\\n\\n | used\\n = acc\\n\\n | otherwise\\n = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n where\\n used = isJust $ lookupGRE_Name used_gre_env n\\n\\n add_unused_all :: Name -> UnusedNames -> UnusedNames\\n add_unused_all n acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | Just {} <- lookupGRE_Name used_gre_env n = acc\\n | n `elemNameSet` used_parents = acc\\n | otherwise = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n\\n add_unused_with :: Name -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_with p ns acc\\n | all (`elemNameSet` acc1_ns) ns = add_unused_name p False acc1\\n | otherwise = acc1\\n where\\n acc1@(UnusedNames acc1_ns _ _) = foldr (\\\\n acc\' -> add_unused_name n False acc\') acc ns\\n -- If you use \'signum\' from Num, then the user may well have\\n -- imported Num(signum). We don\'t want to complain that\\n -- Num is not itself mentioned. Hence the two cases in add_unused_with.\\n\\n add_unused_wildcard :: NamespaceSpecifier GhcRn -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_wildcard ns_spec names acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | any_used = acc\\n | otherwise = UnusedNames acc_ns (ns_spec : acc_wcs) acc_fs\\n where\\n -- A wildcard `type ..` or `data ..` is used if at least one of\\n -- the names it expands to is used\\n any_used = any (isJust . lookupGRE_Name used_gre_env) names\\n\\n\\n-- | An accumulator for unused names in an import list.\\n--\\n-- See Note [Reporting unused imported duplicate record fields].\\ndata UnusedNames =\\n UnusedNames\\n { unused_names :: NameSet\\n -- ^ Unused \'Name\'s in an import list, not including record fields\\n -- that are plain \'IEVar\' imports (tracked by \'rec_fld_uses\')\\n -- or wildcard imports (tracked by \'unused_wildcards\').\\n , unused_wildcards :: [NamespaceSpecifier GhcRn]\\n -- ^ Unused wildcards @type ..@ or @data ..@ in an import list.\\n , rec_fld_uses :: FastStringEnv (NameSet, Any)\\n -- ^ Record fields imported without a parent (i.e. an \'IEVar\' import).\\n --\\n -- The \'Any\' value records whether any of the record fields\\n -- sharing the same underlying \'FastString\' have been used.\\n }\\n\\nemptyUnusedNames :: UnusedNames\\nemptyUnusedNames = UnusedNames emptyNameSet [] emptyFsEnv\\n\\ninstance Outputable UnusedNames where\\n ppr (UnusedNames nms wcs flds) =\\n text \\"UnusedNames\\" <+>\\n braces (ppr nms <+> ppr wcs <+> ppr (fmap (second getAny) flds))\\n\\n-- | Collect all unused names from a \'UnusedNames\' value.\\ncollectUnusedNames :: UnusedNames -> NameSet\\ncollectUnusedNames (UnusedNames { unused_names = nms, rec_fld_uses = flds })\\n = nms S.<> unused_flds\\n where\\n unused_flds = nonDetFoldFsEnv collect_unused emptyNameSet flds\\n collect_unused :: (NameSet, Any) -> NameSet -> NameSet\\n collect_unused (nms, Any at_least_one_name_is_used) acc\\n | at_least_one_name_is_used = acc\\n | otherwise = unionNameSet nms acc\\n\\ncollectUnusedWildcards :: UnusedNames -> [NamespaceSpecifier GhcRn]\\ncollectUnusedWildcards = unused_wildcards\\n\\n{- Note [Reporting unused imported duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have (#24035):\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M1 (R1(..), R2(..)) where\\n data R1 = MkR1 { fld :: Int }\\n data R2 = MkR2 { fld :: Int }\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M2 where\\n import M1 (R1(MkR1), R2, fld)\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nIn the import of \'M1\' in \'M2\', the \'fld\' import resolves to two separate GREs,\\nnamely R1(fld) and R2(fld). From the perspective of the renamer, and in particular\\nthe \'findImportUsage\' function, it\'s as if the user had imported the two names\\nseparately (even though no source syntax allows that).\\n\\nThis means that we need to be careful when reporting unused imports: the R2(fld)\\nimport is indeed unused, but because R1(fld) is used, we should not report\\nfld as unused altogether.\\n\\nTo achieve this, we keep track of record field imports without a parent (i.e.\\nusing the IEVar constructor) separately from other import items, using the\\nUnusedNames datatype.\\nOnce we have accumulated usages, we emit warnings for unused record fields\\nwithout parents one whole group (of record fields sharing the same textual name)\\nat a time, and only if *all* of the record fields in the group are unused;\\nsee \'collectUnusedNames\'.\\n\\nNote that this only applies to record fields imported without a parent. If we\\nhad:\\n\\n import M1 (R1(MkR1, fld), R2(fld))\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nthen of course we should report the second \'fld\' as unused.\\n-}\\n\\n\\n{- Note [The ImportMap]\\n~~~~~~~~~~~~~~~~~~~~~~~\\nThe ImportMap is a short-lived intermediate data structure records, for\\neach import declaration, what stuff brought into scope by that\\ndeclaration is actually used in the module.\\n\\nThe [GlobalRdrElt] are the things imported from that decl.\\n-}\\n\\ndata ImportMap = ImportMap\\n { im_imports :: Map RealSrcSpan [GlobalRdrElt]\\n -- ^ See [The ImportMap]\\n -- If loc :-> gres, then\\n -- \'loc\' = the end loc of the bestImport of each GRE in \'gres\'\\n , im_generatedImports :: Map ModuleName [GlobalRdrElt]\\n }\\n\\nmkImportMap :: [GlobalRdrElt] -> ImportMap\\n-- For each of a list of used GREs, find all the import decls that brought\\n-- it into scope; choose one of them (bestImport), and record\\n-- the RdrName in that import decl\'s entry in the ImportMap\\nmkImportMap = foldr insertImportMap $ ImportMap Map.empty Map.empty\\n\\ninsertImportMap :: GlobalRdrElt -> ImportMap -> ImportMap\\ninsertImportMap gre@(GRE { gre_imp = imp_specs }) importMap\\n | RealSrcSpan importSpan _ <- is_dloc best_imp_spec =\\n importMap{im_imports = insertElem importSpan gre $ im_imports importMap}\\n | GeneratedSrcSpan{} <- is_dloc best_imp_spec =\\n importMap{im_generatedImports = insertElem (moduleName $ is_mod best_imp_spec) gre $ im_generatedImports importMap}\\n | otherwise = importMap\\n where\\n best_imp_spec =\\n case bagToList imp_specs of\\n [] -> pprPanic \\"mkImportMap: GRE with no ImportSpecs\\" (ppr gre)\\n is:iss -> is_decl $ bestImport (is NE.:| iss)\\n\\n -- https://github.com/haskell/containers/issues/784\\n insertElem :: Ord k => k -> v -> Map k [v] -> Map k [v]\\n insertElem k v = flip Map.alter k $ \\\\case\\n Just vs -> Just (v : vs)\\n Nothing -> Just [v]\\n\\nlookupImportMap :: LImportDecl GhcRn -> ImportMap -> [GlobalRdrElt]\\nlookupImportMap (L srcSpan ImportDecl{ideclName = L _ modName}) importMap =\\n fromMaybe [] $\\n -- should match logic in insertImportMap\\n case locA srcSpan of\\n RealSrcSpan realSrcSpan _ -> realSrcSpan `Map.lookup` im_imports importMap\\n GeneratedSrcSpan{} -> modName `Map.lookup` im_generatedImports importMap\\n _ -> Nothing\\n\\nlieNames :: LIE (GhcPass p) -> [Located (IdP (GhcPass p))]\\nlieNames = _\\n\\nwarnUnusedImport :: GlobalRdrEnv -> ImportDeclUsage -> RnM ()\\nwarnUnusedImport rdr_env (L loc decl, used, unused, unused_wcs)\\n\\n -- Do not warn for \'import M()\'\\n -- See (UI1) in Note [Unused imports]\\n | Just (Exactly, _) <- ideclImportList decl\\n , null unused && null unused_wcs\\n = return ()\\n\\n -- Note [Do not warn about Prelude hiding]\\n | Just (EverythingBut, hides) <- ideclImportList decl\\n , not (null hides)\\n , pRELUDE_NAME == unLoc (ideclName decl)\\n = return ()\\n\\n -- Do not warn about import X as Rebindable\\n -- See (UI2) in Note [Unused imports]\\n | Just (L _ mod) <- ideclAs decl\\n , mod == rEBINDABLE_MOD_NAME\\n = return ()\\n\\n -- Nothing used; drop entire declaration\\n | null used\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl UnusedImportNone)\\n\\n -- Everything imported is used; nop\\n | null unused && null unused_wcs\\n = return ()\\n\\n -- Some imports are unused: make the `SrcSpan` cover only the unused\\n -- items instead of the whole import statement\\n | Just (_, imports) <- ideclImportList decl\\n , let unused_locs = [ locA loc | L loc ie <- imports\\n , name <- ieNames ie\\n , name `elem` unused ]\\n , loc1 : locs <- unused_locs\\n , let span = foldr1 combineSrcSpans ( loc1 NE.:| locs )\\n = addDiagnosticAt span (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n -- Some imports are unused\\n | otherwise\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n where\\n -- In warning message, pretty-print identifiers unqualified unconditionally\\n -- to improve the consistent for ambiguous/unambiguous identifiers.\\n -- See #14881.\\n possible_field n =\\n case lookupGRE_Name rdr_env n of\\n Just (GRE { gre_par = par, gre_info = IAmRecField info }) ->\\n let fld_occ :: OccName\\n fld_occ = nameOccName $ flSelector $ recFieldLabel info\\n in UnusedImportNameRecField par fld_occ\\n _ -> UnusedImportNameRegular n\\n\\n -- Print unused names in a deterministic (lexicographic) order\\n sort_unused :: [UnusedImportName]\\n sort_unused =\\n [ UnusedImportWildcard wc | wc <- unused_wcs ] ++\\n [ possible_field nm | nm <- sortBy (comparing nameOccName) unused ]\\n\\ngetMinimalImports :: [ImportDeclUsage] -> RnM [LImportDecl GhcRn]\\ngetMinimalImports ie_decls\\n = do { rdr_env <- getGlobalRdrEnv\\n ; fmap combine $ mapM (mk_minimal rdr_env) ie_decls }\\n where\\n mk_minimal rdr_env (L l decl, used_gres, unused, unused_wcs)\\n | null unused && null unused_wcs\\n , Just (Exactly, _) <- ideclImportList decl\\n = return (L l decl)\\n | otherwise\\n = do { let ImportDecl { ideclName = L _ mod_name\\n , ideclSource = is_boot\\n , ideclPkgQual = pkg_qual\\n , ideclExt = XImportDeclPass { ideclOrigin = origin } } = decl\\n ; iface <- loadSrcInterface doc (importDeclLookupScope origin)\\n mod_name is_boot pkg_qual\\n ; let used_avails = gresToAvailInfo used_gres\\n ; lies <- map (L l) <$> concatMapM (to_ie rdr_env iface) used_avails\\n ; return (L l (decl { ideclImportList = Just (Exactly, lies) })) }\\n where\\n doc = text \\"Compute minimal imports for\\" <+> ppr decl\\n\\n to_ie :: GlobalRdrEnv -> ModIface -> AvailInfo -> RnM [IE GhcRn]\\n -- The main trick here is that if we\'re importing all the constructors\\n -- we want to say \\"T(..)\\", but if we\'re importing only a subset we want\\n -- to say \\"T(A,B,C)\\". So we have to find out what the module exports.\\n to_ie rdr_env _ (Avail c) -- Note [Overloaded field import]\\n = do { let\\n gre = expectJust $ lookupGRE_Name rdr_env c\\n ; return $ [IEVar Nothing (to_ie_post_rn $ noLocA $ greName gre) Nothing] }\\n to_ie _ _ avail@(AvailTC n [_]) -- Exporting the main decl and nothing else\\n | availExportsDecl avail\\n = return [IEThingAbs Nothing (to_ie_post_rn $ noLocA n) Nothing]\\n to_ie rdr_env iface (AvailTC n cs) =\\n case [ xs | avail@(AvailTC x xs) <- mi_exports iface\\n , x == n\\n , availExportsDecl avail -- Note [Partial export]\\n ] of\\n [xs]\\n | all_used xs\\n -> return [IEThingAll (IEThingAllExt Nothing noAnn noAnn noAnn)\\n (NoNamespaceSpecifier noExtField)\\n (to_ie_post_rn $ noLocA n)\\n Nothing]\\n | otherwise\\n -> do { let ns_gres = map (expectJust . lookupGRE_Name rdr_env) cs\\n ns = map greName ns_gres\\n ; return [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n -- Note [Overloaded field import]\\n _other\\n -> do { let infos = map (expectJust . lookupGRE_Name rdr_env) cs\\n (ns_gres,fs_gres) = classifyGREs infos\\n ns = map greName (ns_gres ++ fs_gres)\\n fs = map fieldGREInfo fs_gres\\n ; return $\\n if all_non_overloaded fs\\n then map (\\\\nm -> IEVar Nothing (to_ie_post_rn_var $ noLocA nm) Nothing) ns\\n else [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n where\\n\\n all_used avail_cs = all (`elem` cs) avail_cs\\n\\n all_non_overloaded = all (not . flIsOverloaded . recFieldLabel)\\n\\n combine :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\n combine = map merge . NE.groupAllWith getKey\\n\\n getKey :: LImportDecl GhcRn -> (Bool, Maybe ModuleName, ModuleName)\\n getKey decl =\\n ( isImportDeclQualified . ideclQualified $ idecl -- is this qualified? (important that this be first)\\n , unLoc <$> ideclAs idecl -- what is the qualifier (inside Maybe monad)\\n , unLoc . ideclName $ idecl -- Module Name\\n )\\n where\\n idecl :: ImportDecl GhcRn\\n idecl = unLoc decl\\n\\n merge :: NonEmpty (LImportDecl GhcRn) -> LImportDecl GhcRn\\n merge decls@((L l decl) :| _) = L l (decl { ideclImportList = Just (Exactly, lies) })\\n where lies = concatMap snd $ mapMaybe (ideclImportList . unLoc) $ NE.toList decls\\n\\nclassifyGREs :: [GlobalRdrElt] -> ([GlobalRdrElt], [FieldGlobalRdrElt])\\nclassifyGREs = partition (not . isRecFldGRE)\\n\\nprintMinimalImports :: HscSource -> [ImportDeclUsage] -> RnM ()\\n-- See Note [Printing minimal imports]\\nprintMinimalImports hsc_src imports_w_usage\\n = do { imports\' <- excludeGenerated <$> getMinimalImports imports_w_usage\\n ; this_mod <- getModule\\n ; dflags <- getDynFlags\\n ; liftIO $ withFile (mkFilename dflags this_mod) WriteMode $ \\\\h ->\\n printForUser dflags h neverQualify AllTheWay (vcat (map ppr imports\'))\\n -- The neverQualify is important. We are printing Names\\n -- but they are in the context of an \'import\' decl, and\\n -- we never qualify things inside there\\n -- E.g. import Blag( f, b )\\n -- not import Blag( Blag.f, Blag.g )!\\n }\\n where\\n mkFilename dflags this_mod\\n | Just d <- dumpDir dflags = d basefn\\n | otherwise = basefn\\n where\\n suffix = case hsc_src of\\n HsBootFile -> \\".imports-boot\\"\\n HsSrcFile -> \\".imports\\"\\n HsigFile -> \\".imports\\"\\n basefn = moduleNameString (moduleName this_mod) ++ suffix\\n\\n\\nto_ie_post_rn_var :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn_var (L l n)\\n | isDataOcc $ occName n = L l (IEPattern noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n\\n\\nto_ie_post_rn :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn (L l n)\\n | isTcOcc occ && isSymOcc occ = L l (IEType noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n where occ = occName n\\n\\n{- Note [Do not warn about Prelude hiding]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWe do not warn about\\n import Prelude hiding( x, y )\\nbecause even if nothing else from Prelude is used, it may be essential to hide\\nx,y to avoid name-shadowing warnings. Example (#9061)\\n import Prelude hiding( log )\\n f x = log where log = ()\\n\\nNote [Unused imports]\\n~~~~~~~~~~~~~~~~~~~~~\\nIn `warnUnusedImport`, if we see an import with an explicit list imports, thus\\n import M( a, b )\\nand neither `a` nor `b` is used, we report the entire import decl as unused. We\\ncheck this by looking at the names that it brings into scope scope; if there are\\nno ununused names, don\'t report.\\n\\n(UI1) We don\'t want to complain about `import M()`, because that is often used to bring\\n M\'s /instances/ into scope. That is neatly dealt with by the \\"no unused\\n names\\" (nor unused wildcard imports) criterion.\\n\\n(UI2) We don\'t report a decl as unused if it has an `as Rebindable` qualifier.\\n See (KN1) in Note [Overview of known entities] in GHC.Builtin\\n\\n\\nNote [Printing minimal imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nTo print the minimal imports we walk over all import decls (both user-supplied\\nand generated), trim their import lists, then filter out generated decls.\\n\\nNB that\\n\\n * We do *not* change the \'qualified\' or \'as\' parts!\\n\\n * We do not discard a decl altogether; we might need instances\\n from it. Instead we just trim to an empty import list\\n\\nNote [Partial export]\\n~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have\\n\\n module A( op ) where\\n class C a where\\n op :: a -> a\\n\\n module B where\\n import A\\n f = ..op...\\n\\nThen the minimal import for module B is\\n import A( op )\\nnot\\n import A( C( op ) )\\nwhich we would usually generate if C was exported from B. Hence\\nthe availExportsDecl test when deciding what to generate.\\n\\n\\nNote [Overloaded field import]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nOn the other hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n data T = MkT { foo :: Int }\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( T(foo) )\\nbecause when DuplicateRecordFields is enabled, field selectors are\\nnot in scope without their enclosing datatype.\\n\\nOn the third hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n pattern MkT { foo } = Just foo\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( foo )\\nbecause foo doesn\'t have a parent. This might actually be ambiguous if A\\nexports another field called foo, but there is no good answer to return and this\\nis a very obscure corner, so it seems to be the best we can do. See\\nDRFPatSynExport for a test of this.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Errors}\\n* *\\n************************************************************************\\n-}\\n\\nbadImportItemErr\\n :: ModIface -> ImpDeclSpec -> IE GhcPs\\n -> IsSubordinateError\\n -> [AvailInfo]\\n -> TcRn (NonEmpty ImportLookupReason)\\nbadImportItemErr iface decl_spec ie sub avails = do\\n exts <- importLookupExtensions\\n let import_lookup_bad :: BadImportKind -> ImportLookupReason\\n import_lookup_bad k = ImportLookupBad k iface decl_spec ie exts\\n dflags <- getDynFlags\\n hsc_env <- getTopEnv\\n let rdr_env = mkGlobalRdrEnv\\n $ gresFromAvails hsc_env (Just imp_spec) all_avails\\n pure $ fmap import_lookup_bad (importErrorKind dflags rdr_env)\\n where\\n importErrorKind :: DynFlags -> GlobalRdrEnv -> NonEmpty BadImportKind\\n importErrorKind dflags rdr_env\\n | any checkIfTyCon avails = case sub of\\n IsNotSubordinate -> NE.singleton BadImportAvailTyCon\\n IsSubordinateError { subordinate_err_parent = gre\\n , subordinate_err_unavailable = unavailable\\n , subordinate_err_nontype = nontype\\n , subordinate_err_nondata = nondata }\\n -> NE.fromList $ catMaybes $\\n [ fmap (BadImportNotExportedSubordinates gre) (NE.nonEmpty unavailable)\\n , fmap (BadImportNonTypeSubordinates gre) (NE.nonEmpty nontype)\\n , fmap (BadImportNonDataSubordinates gre) (NE.nonEmpty nondata) ]\\n | any checkIfVarName avails = NE.singleton BadImportAvailVar\\n | Just con <- find checkIfDataCon avails = NE.singleton (BadImportAvailDataCon (availOccName con))\\n | otherwise = NE.singleton (BadImportNotExported suggs)\\n where\\n suggs = similar_suggs ++ fieldSelectorSuggestions rdr_env rdr\\n what_look = case sub of\\n IsNotSubordinate -> WL_TyCon_or_TermVar\\n IsSubordinateError { subordinate_err_parent = gre } ->\\n case greInfo gre of\\n IAmTyCon ClassFlavour\\n -> WL_TyCon_or_TermVar\\n _ -> WL_Term\\n similar_names =\\n similarNameSuggestions (Unbound.LF what_look WL_Global)\\n dflags rdr_env emptyLocalRdrEnv rdr\\n similar_suggs =\\n case NE.nonEmpty $ mapMaybe imported_item $ similar_names of\\n Just similar -> [ SuggestSimilarNames rdr similar ]\\n Nothing -> [ ]\\n\\n -- Only keep imported items, and set the \\"HowInScope\\" to\\n -- \\"Nothing\\" to avoid printing \\"imported from...\\" in the suggestion\\n -- error message.\\n imported_item (SimilarRdrName rdr_name gre (Just (ImportedBy {})))\\n = Just (SimilarRdrName rdr_name gre Nothing)\\n imported_item _ = Nothing\\n\\n checkIfDataCon = checkIfAvailMatches isDataConName\\n checkIfTyCon = checkIfAvailMatches isTyConName\\n checkIfVarName =\\n \\\\case\\n AvailTC{} -> False\\n Avail n -> importedFS == occNameFS (occName n)\\n && (isVarOcc <||> isFieldOcc) (occName n)\\n checkIfAvailMatches namePred =\\n \\\\case\\n AvailTC _ ns ->\\n case find (\\\\n -> importedFS == occNameFS (occName n)) ns of\\n Just n -> namePred n\\n Nothing -> False\\n Avail{} -> False\\n availOccName = occName . availName\\n rdr = ieName ie\\n importedFS = occNameFS $ rdrNameOcc rdr\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n all_avails = mi_exports iface\\n\\nimportLookupExtensions :: TcRn ImportLookupExtensions\\nimportLookupExtensions = do\\n ile_pattern_synonyms <- xoptM LangExt.PatternSynonyms\\n ile_explicit_namespaces <- xoptM LangExt.ExplicitNamespaces\\n return ImportLookupExtensions{ile_pattern_synonyms, ile_explicit_namespaces}\\n\\naddDupDeclErr :: NonEmpty GlobalRdrElt -> TcRn ()\\naddDupDeclErr gres@(gre :| _)\\n -- Report the error at the later location\\n = addErrAt (getSrcSpan (NE.last sorted_names)) $ (TcRnDuplicateDecls (greOccName gre) sorted_names)\\n where\\n sorted_names =\\n NE.sortBy (SrcLoc.leftmost_smallest `on` nameSrcSpan)\\n (fmap greName gres)\\n\\n-- This data decl will parse OK\\n-- data T = a Int\\n-- treating \\"a\\" as the constructor.\\n-- It is really hard to make the parser spot this malformation.\\n-- So the renamer has to check that the constructor is legal\\n--\\n-- We can get an operator as the constructor, even in the prefix form:\\n-- data T = :% Int Int\\n-- from interface files, which always print in prefix form\\n--\\n-- We also allow type constructor names, which are defined by \\"type data\\"\\n-- declarations. See Note [Type data declarations] in GHC.Rename.Module.\\n\\ncheckConName :: RdrName -> TcRn ()\\ncheckConName name\\n = checkErr (isRdrDataCon name || isRdrTc name) (TcRnIllegalDataCon name)\\n", "filetypes": ["haskell"]}}}' 2026-10-16 14:45:33,560 - DEBUG - POST b'http://127.0.0.1:37093/defined_subcommands' {'content-type': 'application/json', 'x-ycm-hmac': b'fpOVEVs8xgo9/z+swWds2rBM6q4KX47S2fptA9DkOLA='} b'{"filepath": "/home/enrico/ghc/compiler/GHC/Rename/Names.hs", "line_num": 2248, "column_num": 10, "working_dir": "/home/enrico/ghc", "file_data": {"/home/enrico/ghc/compiler/GHC/Rename/Names.hs": {"contents": "{-\\n(c) The GRASP/AQUA Project, Glasgow University, 1992-1998\\n\\nExtracting imported and top-level names in scope\\n-}\\n\\n{-# LANGUAGE NondecreasingIndentation #-}\\n{-# LANGUAGE TypeFamilies #-}\\n\\nmodule GHC.Rename.Names (\\n rnImports, getLocalNonValBinders, newRecordFieldLabel,\\n importsFromIface,\\n ImportUserSpec(..),\\n extendGlobalRdrEnvRn,\\n gresFromAvails,\\n calculateAvails,\\n reportUnusedNames,\\n checkConName,\\n mkChildEnv,\\n findChildren,\\n mkBadExportSubordinate,\\n findImportUsage,\\n getMinimalImports,\\n printMinimalImports,\\n renamePkgQual, renameRawPkgQual,\\n classifyGREs,\\n ImportDeclUsage,\\n rnNamespaceSpecifier\\n ) where\\n\\nimport GHC.Prelude hiding ( head, init, last, tail )\\n\\nimport GHC.Driver.Env\\nimport GHC.Driver.Session\\nimport GHC.Driver.Ppr\\n\\nimport GHC.Rename.Env\\nimport GHC.Rename.Fixity\\nimport GHC.Rename.Utils ( warnUnusedTopBinds )\\nimport GHC.Rename.Unbound\\nimport qualified GHC.Rename.Unbound as Unbound\\n\\nimport GHC.Tc.Errors.Types\\nimport GHC.Tc.Utils.Env\\nimport GHC.Tc.Utils.Monad\\nimport GHC.Tc.Types.LclEnv\\nimport GHC.Tc.Zonk.TcType ( tcInitTidyEnv )\\n\\nimport GHC.Hs\\nimport GHC.Iface.Load ( loadSrcInterface, loadSrcInterface_maybe )\\nimport GHC.Iface.Errors.Types\\n ( IfaceMessage(..), MissingInterfaceError, InterfaceLookingFor(..)\\n , LoadEssentialsReason(..) )\\nimport GHC.Iface.Syntax ( fromIfaceWarnings )\\nimport GHC.Builtin.Modules( pRELUDE_NAME, rEBINDABLE_MOD_NAME )\\nimport GHC.Parser.PostProcess ( setRdrNameSpace )\\nimport GHC.Core.TyCo.Tidy\\nimport GHC.Core.PatSyn\\nimport GHC.Core.TyCon ( TyCon, tyConName )\\nimport qualified GHC.LanguageExtensions as LangExt\\n\\nimport GHC.Utils.Outputable as Outputable\\nimport GHC.Utils.Misc as Utils\\nimport GHC.Utils.Panic\\n\\nimport GHC.Types.Fixity.Env\\nimport GHC.Types.SafeHaskell\\nimport GHC.Types.Name\\nimport GHC.Types.Name.Env\\nimport GHC.Types.Name.Set\\nimport GHC.Types.Name.Reader\\nimport GHC.Types.Avail\\nimport GHC.Types.FieldLabel\\nimport GHC.Types.Hint\\nimport GHC.Types.SourceFile\\nimport GHC.Types.SrcLoc as SrcLoc\\nimport GHC.Types.Basic (TyConFlavour (..), convImportLevel, VisArity)\\nimport GHC.Types.UnresolvedImport\\nimport GHC.Types.Id\\nimport GHC.Types.PkgQual\\nimport GHC.Types.GREInfo (ConInfo(..), ConFieldInfo (..), ConLikeInfo (ConIsData))\\n\\nimport GHC.Unit\\nimport GHC.Unit.Module.Warnings\\nimport GHC.Unit.Module.ModIface\\nimport GHC.Unit.Module.Imported\\nimport GHC.Unit.Module.Deps\\nimport GHC.Unit.Env\\n\\nimport GHC.Data.Bag\\nimport GHC.Data.FastString\\nimport GHC.Data.FastString.Env\\nimport GHC.Data.Maybe\\nimport GHC.Data.List.SetOps ( removeDups )\\n\\nimport Control.Arrow ( second )\\nimport Control.Monad\\nimport Data.Foldable ( for_ )\\nimport Data.IntMap ( IntMap )\\nimport qualified Data.IntMap as IntMap\\nimport Data.Map ( Map )\\nimport qualified Data.Map as Map\\nimport Data.Ord ( comparing )\\nimport Data.Semigroup ( Any(..) )\\nimport qualified Data.Semigroup as S\\nimport Data.List ( partition, find, sortBy )\\nimport Data.List.NonEmpty (NonEmpty(..))\\nimport qualified Data.List.NonEmpty as NE\\nimport Data.Function ( on )\\nimport qualified Data.Set as S\\nimport System.FilePath (())\\nimport System.IO\\n\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{rnImports}\\n* *\\n************************************************************************\\n\\nNote [Tracking Trust Transitively]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen we import a package as well as checking that the direct imports are safe\\naccording to the rules outlined in the Note [Safe Haskell Trust Check] in GHC.Driver.Main\\nwe must also check that these rules hold transitively for all dependent modules\\nand packages. Doing this without caching any trust information would be very\\nslow as we would need to touch all packages and interface files a module depends\\non. To avoid this we make use of the property that if a modules Safe Haskell\\nmode changes, this triggers a recompilation from that module in the dependency\\ngraph. So we can just worry mostly about direct imports.\\n\\nThere is one trust property that can change for a package though without\\nrecompilation being triggered: package trust. So we must check that all\\npackages a module transitively depends on to be trusted are still trusted when\\nwe are compiling this module (as due to recompilation avoidance some modules\\nbelow may not be considered trusted any more without recompilation being\\ntriggered).\\n\\nWe handle this by augmenting the existing transitive list of packages a module M\\ndepends on with a bool for each package that says if it must be trusted when the\\nmodule M is being checked for trust. This list of trust required packages for a\\nsingle import is gathered in the rnImportDecl function and stored in an\\nImportAvails data structure. The union of these trust required packages for all\\nimports is done by the rnImports function using the combine function which calls\\nthe plusImportAvails function that is a union operation for the ImportAvails\\ntype. This gives us in an ImportAvails structure all packages required to be\\ntrusted for the module we are currently compiling. Checking that these packages\\nare still trusted (and that direct imports are trusted) is done in\\nGHC.Driver.Main.checkSafeImports.\\n\\nSee the note below, [Trust Own Package] for a corner case in this method and\\nhow its handled.\\n\\n\\nNote [Trust Own Package]\\n~~~~~~~~~~~~~~~~~~~~~~~~\\nThere is a corner case of package trust checking that the usual transitive check\\ndoesn\'t cover. (For how the usual check operates see the Note [Tracking Trust\\nTransitively] below). The case is when you import a -XSafe module M and M\\nimports a -XTrustworthy module N. If N resides in a different package than M,\\nthen the usual check works as M will record a package dependency on N\'s package\\nand mark it as required to be trusted. If N resides in the same package as M\\nthough, then importing M should require its own package be trusted due to N\\n(since M is -XSafe so doesn\'t create this requirement by itself). The usual\\ncheck fails as a module doesn\'t record a package dependency of its own package.\\nSo instead we now have a bool field in a modules interface file that simply\\nstates if the module requires its own package to be trusted. This field avoids\\nus having to load all interface files that the module depends on to see if one\\nis trustworthy.\\n\\n\\nNote [Trust Transitive Property]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSo there is an interesting design question in regards to transitive trust\\nchecking. Say I have a module B compiled with -XSafe. B is dependent on a bunch\\nof modules and packages, some packages it requires to be trusted as its using\\n-XTrustworthy modules from them. Now if I have a module A that doesn\'t use safe\\nhaskell at all and simply imports B, should A inherit all the trust\\nrequirements from B? Should A now also require that a package p is trusted since\\nB required it?\\n\\nWe currently say no but saying yes also makes sense. The difference is, if a\\nmodule M that doesn\'t use Safe Haskell imports a module N that does, should all\\nthe trusted package requirements be dropped since M didn\'t declare that it cares\\nabout Safe Haskell (so -XSafe is more strongly associated with the module doing\\nthe importing) or should it be done still since the author of the module N that\\nuses Safe Haskell said they cared (so -XSafe is more strongly associated with\\nthe module that was compiled that used it).\\n\\nGoing with yes is a simpler semantics we think and harder for the user to stuff\\nup but it does mean that Safe Haskell will affect users who don\'t care about\\nSafe Haskell as they might grab a package from Cabal which uses safe haskell (say\\nnetwork) and that packages imports -XTrustworthy modules from another package\\n(say bytestring), so requires that package is trusted. The user may now get\\ncompilation errors in code that doesn\'t do anything with Safe Haskell simply\\nbecause they are using the network package. They will have to call \'ghc-pkg\\ntrust network\' to get everything working. Due to this invasive nature of going\\nwith yes we have gone with no for now.\\n-}\\n\\n-- | Process Import Decls. See \'rnImportDecl\' for a description of what\\n-- the return types represent.\\n-- Note: Do the non SOURCE ones first, so that we get a helpful warning\\n-- for SOURCE ones that are unnecessary\\nrnImports :: [(LImportDecl GhcPs, SDoc)]\\n -> RnM ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\nrnImports imports = do\\n tcg_env <- getGblEnv\\n -- NB: want an identity module here, because it\'s OK for a signature\\n -- module to import from its implementor\\n let this_mod = tcg_mod tcg_env\\n let (source, ordinary) = partition (is_source_import . fst) imports\\n is_source_import (d::LImportDecl GhcPs) = ideclSource (unLoc d) == IsBoot\\n stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary\\n stuff2 <- mapAndReportM (rnImportDecl this_mod) source\\n -- Safe Haskell: See Note [Tracking Trust Transitively]\\n let (decls, imp_user_spec, rdr_env, imp_avails) = combine (stuff1 ++ stuff2)\\n -- Update imp_boot_mods if imp_direct_mods mentions any of them\\n let merged_import_avail = clobberSourceImports imp_avails\\n return (decls, imp_user_spec, rdr_env, merged_import_avail)\\n\\n where\\n clobberSourceImports imp_avails =\\n imp_avails { imp_boot_mods = imp_boot_mods\' }\\n where\\n imp_boot_mods\' = mergeInstalledModuleEnv combJ id (const emptyInstalledModuleEnv)\\n (imp_boot_mods imp_avails)\\n (imp_direct_dep_mods imp_avails)\\n\\n combJ (GWIB _ IsBoot) (_, x) = Just x\\n combJ r _ = Just r\\n -- See Note [Combining ImportAvails]\\n combine :: [(LImportDecl GhcRn, ImportUserSpec, GlobalRdrEnv, ImportAvails)]\\n -> ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\n combine ss =\\n let (decls, imp_user_spec, rdr_env, imp_avails, finsts) = foldr\\n plus\\n ([], [], emptyGlobalRdrEnv, emptyImportAvails, emptyModuleSet)\\n ss\\n in (decls, imp_user_spec, rdr_env, imp_avails { imp_finsts = moduleSetElts finsts })\\n\\n plus (decl, us, gbl_env1, imp_avails1)\\n (decls, uss, gbl_env2, imp_avails2, finsts_set)\\n = ( decl:decls,\\n us:uss,\\n gbl_env1 `plusGlobalRdrEnv` gbl_env2,\\n imp_avails1\' `plusImportAvails` imp_avails2,\\n extendModuleSetList finsts_set new_finsts )\\n where\\n imp_avails1\' = imp_avails1 { imp_finsts = [] }\\n new_finsts = imp_finsts imp_avails1\\n\\n{-\\nNote [Combining ImportAvails]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nimp_finsts in ImportAvails is a list of family instance modules\\ntransitively depended on by an import. imp_finsts for a currently\\ncompiled module is a union of all the imp_finsts of imports.\\nComputing the union of two lists of size N is O(N^2) and if we\\ndo it to M imports we end up with O(M*N^2). That can get very\\nexpensive for bigger module hierarchies.\\n\\nUnion can be optimized to O(N log N) if we use a Set.\\nimp_finsts is converted back and forth between dep_finsts, so\\nchanging a type of imp_finsts means either paying for the conversions\\nor changing the type of dep_finsts as well.\\n\\nI\'ve measured that the conversions would cost 20% of allocations on my\\ntest case, so that can be ruled out.\\n\\nChanging the type of dep_finsts forces checkFamInsts to\\nget the module lists in non-deterministic order. If we wanted to restore\\nthe deterministic order, we\'d have to sort there, which is an additional\\ncost. As far as I can tell, using a non-deterministic order is fine there,\\nbut that\'s a brittle nonlocal property which I\'d like to avoid.\\n\\nAdditionally, dep_finsts is read from an interface file, so its \\"natural\\"\\ntype is a list. Which makes it a natural type for imp_finsts.\\n\\nSince rnImports.combine is really the only place that would benefit from\\nit being a Set, it makes sense to optimize the hot loop in rnImports.combine\\nwithout changing the representation.\\n\\nSo here\'s what we do: instead of naively merging ImportAvails with\\nplusImportAvails in a loop, we make plusImportAvails merge empty imp_finsts\\nand compute the union on the side using Sets. When we\'re done, we can\\nconvert it back to a list. One nice side effect of this approach is that\\nif there\'s a lot of overlap in the imp_finsts of imports, the\\nSet doesn\'t really need to grow and we don\'t need to allocate.\\n\\nRunning generateModules from #14693 with DEPTH=16, WIDTH=30 finishes in\\n23s before, and 11s after.\\n-}\\n\\n-- | Given a located import declaration @decl@ from @this_mod@,\\n-- calculate the following pieces of information:\\n--\\n-- 1. An updated \'LImportDecl\', where all unresolved \'RdrName\' in\\n-- the entity lists have been resolved into \'Name\'s,\\n--\\n-- 2. A \'GlobalRdrEnv\' representing the new identifiers that were\\n-- brought into scope (taking into account module qualification\\n-- and hiding),\\n--\\n-- 3. \'ImportAvails\' summarizing the identifiers that were imported\\n-- by this declaration, and\\n--\\n-- 4. A boolean \'AnyHpcUsage\' which is true if the imported module\\n-- used HPC.\\nrnImportDecl :: Module -> (LImportDecl GhcPs, SDoc)\\n -> RnM (LImportDecl GhcRn, ImportUserSpec , GlobalRdrEnv, ImportAvails)\\nrnImportDecl this_mod\\n (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name\\n , ideclPkgQual = raw_pkg_qual\\n , ideclSource = want_boot\\n , ideclSafe = mod_safe\\n , ideclLevelSpec = import_level\\n , ideclQualified = qual_style\\n , ideclExt = XImportDeclPass { ideclOrigin = origin }\\n , ideclAs = as_mod, ideclImportList = imp_details }), import_reason)\\n = setSrcSpanA loc $ do\\n\\n case raw_pkg_qual of\\n NoRawPkgQual -> pure ()\\n RawPkgQual {} -> do\\n pkg_imports <- xoptM LangExt.PackageImports\\n when (not pkg_imports) $ addErr TcRnPackageImportsDisabled\\n\\n let qual_only = isImportDeclQualified qual_style\\n generated = isGeneratedImport origin\\n\\n lookup_scope = importDeclLookupScope origin\\n\\n -- If there\'s an error in loadInterface, (e.g. interface\\n -- file not found) we get lots of spurious errors from \'filterImports\'\\n let imp_mod_name = unLoc loc_imp_mod_name\\n doc = ppr imp_mod_name <+> import_reason\\n\\n hsc_env <- getTopEnv\\n unit_env <- hsc_unit_env <$> getTopEnv\\n let pkg_qual = renameRawPkgQual unit_env imp_mod_name raw_pkg_qual\\n\\n -- Check for self-import, which confuses the typechecker (#9032)\\n -- ghc --make rejects self-import cycles already, but batch-mode may not\\n -- at least not until GHC.IfaceToCore.tcHiBootIface, which is too late to avoid\\n -- typechecker crashes. (Indirect self imports are not caught until\\n -- GHC.IfaceToCore, see #10337 tracking how to make this error better.)\\n --\\n -- Originally, we also allowed \'import {-# SOURCE #-} M\', but this\\n -- caused bug #10182: in one-shot mode, we should never load an hs-boot\\n -- file for the module we are compiling into the EPS. In principle,\\n -- it should be possible to support this mode of use, but we would have to\\n -- extend Provenance to support a local definition in a qualified location.\\n -- For now, we don\'t support it, but see #10336\\n when (imp_mod_name == moduleName this_mod &&\\n (case pkg_qual of -- If we have import \\"\\" M, then we should\\n -- check that \\"\\" is \\"this\\" (which is magic)\\n -- or the name of this_mod\'s package. Yurgh!\\n -- c.f. GHC.findModule, and #9997\\n NoPkgQual -> True\\n ThisPkg uid -> uid == homeUnitId_ (hsc_dflags hsc_env)\\n OtherPkg _ -> False))\\n (addErr (TcRnSelfImport imp_mod_name))\\n\\n -- Check for a missing import list (Opt_WarnMissingImportList also\\n -- checks for T(..) items but that is done in checkDodgyImport below)\\n case imp_details of\\n Just (Exactly, _) -> return () -- Explicit import list\\n _ | generated -> return () -- Do not bleat for generated imports\\n | qual_only -> return ()\\n | otherwise -> addDiagnostic (TcRnNoExplicitImportList imp_mod_name)\\n\\n\\n mb_iface <- loadSrcInterface_maybe doc lookup_scope imp_mod_name want_boot pkg_qual\\n iface <- case mb_iface of\\n Succeeded iface -> return iface\\n Failed err -> failWithTc $\\n importDeclLoadFailure origin imp_mod_name want_boot err\\n\\n -- Compiler sanity check: if the import didn\'t say\\n -- {-# SOURCE #-} we should not get a hi-boot file\\n warnPprTrace ((want_boot == NotBoot) && (mi_boot iface == IsBoot)) \\"rnImportDecl\\" (ppr imp_mod_name) $ do\\n\\n -- Issue a user warning for a redundant {- SOURCE -} import\\n -- NB that we arrange to read all the ordinary imports before\\n -- any of the {- SOURCE -} imports.\\n --\\n -- in --make and GHCi, the compilation manager checks for this,\\n -- and indeed we shouldn\'t do it here because the existence of\\n -- the non-boot module depends on the compilation order, which\\n -- is not deterministic. The hs-boot test can show this up.\\n dflags <- getDynFlags\\n warnIf ((want_boot == IsBoot) && (mi_boot iface == NotBoot) && isOneShot (ghcMode dflags))\\n (TcRnRedundantSourceImport imp_mod_name)\\n when (mod_safe && not (safeImportsOn dflags)) $\\n addErr (TcRnSafeImportsDisabled imp_mod_name)\\n\\n let imp_mod = mi_module iface\\n qual_mod_name = fmap unLoc as_mod `orElse` imp_mod_name\\n imp_spec = ImpDeclSpec { is_mod = imp_mod, is_qual = qual_only,\\n is_dloc = locA loc, is_as = qual_mod_name,\\n is_pkg_qual = pkg_qual, is_isboot = want_boot,\\n is_level = convImportLevel import_level }\\n\\n let filter_imports = do\\n -- filter the imports according to the import declaration\\n (new_imp_details, imp_user_list, gbl_env)\\n <- filterImports hsc_env iface imp_spec imp_details\\n -- for certain error messages, we\\u2019d like to know what could be\\n -- imported here, if everything were imported\\n potential_gres <- (\\\\(_,_,x) -> x) <$> filterImports hsc_env iface imp_spec Nothing\\n return (new_imp_details, imp_user_list, gbl_env, potential_gres)\\n\\n (new_imp_details, imp_user_list, gbl_env, potential_gres) <-\\n case origin of\\n ImplicitEssentialsImport ->\\n -- The implicit GHC.Essentials import does not bring anything into scope.\\n -- See Note [Finding GHC.Essentials] in GHC.Builtin.\\n return (Nothing, ImpUserDependOnly, emptyGlobalRdrEnv, emptyGlobalRdrEnv)\\n UserWrittenImport -> filter_imports\\n ImplicitPreludeImport -> filter_imports\\n PluginImport -> filter_imports\\n\\n let is_hiding | Just (EverythingBut,_) <- imp_details = True\\n | otherwise = False\\n\\n -- should the import be safe?\\n mod_safe\' = mod_safe\\n || (not generated && safeDirectImpsReq dflags)\\n || (generated && safeImplicitImpsReq dflags)\\n\\n hsc_env <- getTopEnv\\n let home_unit = hsc_home_unit hsc_env\\n other_home_units = hsc_all_home_unit_ids hsc_env\\n\\n imported_by\\n | isDependOnlyImport imp_user_list\\n = ImportedBySystem\\n | otherwise\\n = ImportedByUser $ ImportedModsVal\\n { imv_name = is_as imp_spec\\n , imv_span = locA loc\\n , imv_is_safe = mod_safe\'\\n , imv_is_hiding = is_hiding\\n , imv_all_exports = potential_gres\\n , imv_qualified = qual_only\\n , imv_is_level = convImportLevel import_level\\n }\\n imports = calculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by\\n\\n -- Complain if we import a deprecated module\\n case fromIfaceWarnings (mi_warns iface) of\\n WarnAll txt -> addDiagnostic (TcRnDeprecatedModule imp_mod_name txt)\\n _ -> return ()\\n\\n let new_imp_decl = ImportDecl\\n { ideclExt = ideclExt decl\\n , ideclName = ideclName decl\\n , ideclPkgQual = pkg_qual\\n , ideclSource = ideclSource decl\\n , ideclSafe = mod_safe\'\\n , ideclQualified = ideclQualified decl\\n , ideclAs = ideclAs decl\\n , ideclImportList = new_imp_details\\n , ideclLevelSpec = ideclLevelSpec decl\\n }\\n\\n return (L loc new_imp_decl, ImpUserSpec imp_spec imp_user_list, gbl_env, imports)\\n\\n-- | The error message to emit when we failed to load an interface.\\nimportDeclLoadFailure :: ImportDeclOrigin -> ModuleName -> IsBootInterface\\n -> MissingInterfaceError -> TcRnMessage\\nimportDeclLoadFailure ImplicitEssentialsImport _ _ err\\n = TcRnInterfaceError $ CantFindEssentials err LookingForEssentialsModule\\nimportDeclLoadFailure _ mod_name want_boot err\\n = TcRnInterfaceError $ Can\'tFindInterface err $ LookingForModule mod_name want_boot\\n\\n-- | Rename raw package imports\\nrenameRawPkgQual :: UnitEnv -> ModuleName -> RawPkgQual -> PkgQual\\nrenameRawPkgQual unit_env mn = \\\\case\\n NoRawPkgQual -> NoPkgQual\\n RawPkgQual _ fs -> renamePkgQual unit_env mn $ Just fs\\n\\n-- | Rename raw package imports\\nrenamePkgQual :: UnitEnv -> ModuleName -> Maybe FastString -> PkgQual\\nrenamePkgQual unit_env mn mb_pkg = case mb_pkg of\\n Nothing -> NoPkgQual\\n Just pkg_fs\\n | Just uid <- homeUnitId <$> ue_homeUnit unit_env\\n , pkg_fs == fsLit \\"this\\"\\n -> ThisPkg uid\\n\\n | Just (uid, _) <- find (fromMaybe False . fmap (== pkg_fs) . snd) home_names\\n -> ThisPkg uid\\n\\n | Just uid <- resolvePackageImport unit_state mn (PackageName pkg_fs)\\n -> OtherPkg uid\\n\\n | otherwise\\n -> OtherPkg (UnitId pkg_fs)\\n -- not really correct as pkg_fs is unlikely to be a valid unit-id but\\n -- we will report the failure later...\\n where\\n home_names =\\n [ (uid, mkFastString <$> thisPackageName (homeUnitEnv_dflags (ue_findHomeUnitEnv uid unit_env)))\\n | uid <- S.toList hpt_deps\\n ]\\n\\n unit_state = ue_homeUnitState unit_env\\n\\n hpt_deps :: S.Set UnitId\\n hpt_deps = homeUnitDepends unit_state\\n\\n\\n-- | Calculate the \'ImportAvails\' induced by an import of a particular\\n-- interface, but without \'imp_mods\'.\\ncalculateAvails :: HomeUnit\\n -> S.Set UnitId\\n -> ModIface\\n -> IsSafeImport\\n -> IsBootInterface\\n -> ImportedBy\\n -> ImportAvails\\ncalculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by =\\n let imp_mod = mi_module iface\\n imp_sem_mod= mi_semantic_module iface\\n orph_iface = mi_orphan iface\\n has_finsts = mi_finsts iface\\n deps = mi_deps iface\\n trust = getSafeMode $ mi_trust iface\\n trust_pkg = mi_trust_pkg iface\\n is_sig = mi_hsc_src iface == HsigFile\\n\\n -- If the module exports anything defined in this module, just\\n -- ignore it. Reason: otherwise it looks as if there are two\\n -- local definition sites for the thing, and an error gets\\n -- reported. Easiest thing is just to filter them out up\\n -- front. This situation only arises if a module imports\\n -- itself, or another module that imported it. (Necessarily,\\n -- this involves a loop.)\\n --\\n -- We do this *after* filterImports, so that if you say\\n -- module A where\\n -- import B( AType )\\n -- type AType = ...\\n --\\n -- module B( AType ) where\\n -- import {-# SOURCE #-} A( AType )\\n --\\n -- then you won\'t get a \'B does not export AType\' message.\\n\\n\\n -- Compute new transitive dependencies\\n --\\n -- \'dep_orphs\' and \'dep_finsts\' do NOT include the imported module\\n -- itself, but we DO need to include this module in \'imp_orphs\' and\\n -- \'imp_finsts\' if it defines an orphan or instance family; thus the\\n -- orph_iface/has_iface tests.\\n\\n deporphs = dep_orphs deps\\n depfinsts = dep_finsts deps\\n\\n orphans | orph_iface = assertPpr (not (imp_sem_mod `elem` deporphs)) (ppr imp_sem_mod <+> ppr deporphs) $\\n imp_sem_mod : deporphs\\n | otherwise = deporphs\\n\\n finsts | has_finsts = assertPpr (not (imp_sem_mod `elem` depfinsts)) (ppr imp_sem_mod <+> ppr depfinsts) $\\n imp_sem_mod : depfinsts\\n | otherwise = depfinsts\\n\\n -- Trusted packages are a lot like orphans.\\n trusted_pkgs | mod_safe\' = dep_trusted_pkgs deps\\n | otherwise = S.empty\\n\\n\\n pkg = moduleUnit (mi_module iface)\\n ipkg = toUnitId pkg\\n\\n -- Does this import mean we now require our own pkg\\n -- to be trusted? See Note [Trust Own Package]\\n ptrust = trust == Sf_Trustworthy || trust_pkg\\n pkg_trust_req\\n | isHomeUnit home_unit pkg = ptrust\\n | otherwise = False\\n\\n dependent_pkgs = if toUnitId pkg `S.member` other_home_units\\n then S.empty\\n else S.singleton (lvl, ipkg)\\n\\n lvl = case imported_by of\\n ImportedByUser imv -> imv_is_level imv\\n ImportedBySystem -> NormalLevel\\n\\n\\n direct_mods = if toUnitId pkg `S.member` other_home_units\\n then mkPlusModDeps (moduleUnitId imp_mod) lvl (GWIB (moduleName imp_mod) want_boot)\\n else emptyInstalledModuleEnv\\n\\n dep_boot_mods_map = mkModDeps (dep_boot_mods deps)\\n\\n\\n boot_mods\\n -- If we are looking for a boot module, it must be HPT\\n | IsBoot <- want_boot = extendInstalledModuleEnv dep_boot_mods_map (toUnitId <$> imp_mod) (GWIB (moduleName imp_mod) IsBoot)\\n -- Now we are importing A properly, so don\'t go looking for\\n -- A.hs-boot\\n | isHomeUnit home_unit pkg = dep_boot_mods_map\\n -- There\'s no boot files to find in external imports\\n | otherwise = emptyInstalledModuleEnv\\n\\n sig_mods =\\n if is_sig\\n then moduleName imp_mod : dep_sig_mods deps\\n else dep_sig_mods deps\\n\\n\\n in ImportAvails {\\n imp_mods = Map.singleton (mi_module iface) [imported_by],\\n imp_orphs = orphans,\\n imp_finsts = finsts,\\n imp_sig_mods = sig_mods,\\n imp_direct_dep_mods = direct_mods,\\n imp_dep_direct_pkgs = dependent_pkgs,\\n imp_boot_mods = boot_mods,\\n\\n -- Add in the imported modules trusted package\\n -- requirements. ONLY do this though if we import the\\n -- module as a safe import.\\n -- See Note [Tracking Trust Transitively]\\n -- and Note [Trust Transitive Property]\\n imp_trust_pkgs = trusted_pkgs,\\n -- Do we require our own pkg to be trusted?\\n -- See Note [Trust Own Package]\\n imp_trust_own_pkg = pkg_trust_req\\n }\\n\\nmkPlusModDeps :: UnitId -> ImportLevel -> ModuleNameWithIsBoot\\n -> InstalledModuleEnv (S.Set ImportLevel, ModuleNameWithIsBoot)\\nmkPlusModDeps uid st elt = extendInstalledModuleEnv emptyInstalledModuleEnv (mkModule uid (gwib_mod elt)) (S.singleton st, elt)\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{importsFromLocalDecls}\\n* *\\n************************************************************************\\n\\nFrom the top-level declarations of this module produce\\n * the lexical environment\\n * the ImportAvails\\ncreated by its bindings.\\n\\nNote [Top-level Names in Template Haskell decl quotes]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSee also: Note [Interactively-bound Ids in GHCi] in GHC.Driver.Env\\n Note [Looking up Exact RdrNames] in GHC.Rename.Env\\n\\nConsider a Template Haskell declaration quotation like this:\\n module M where\\n f x = h [d| f = 3 |]\\nWhen renaming the declarations inside [d| ...|], we treat the\\ntop level binders specially in two ways\\n\\n1. We give them an Internal Name, not (as usual) an External one.\\n This is done by GHC.Rename.Env.newTopSrcBinder.\\n\\n2. We make them *shadow* the outer bindings.\\n See Note [GlobalRdrEnv shadowing]\\n\\n3. We find out whether we are inside a [d| ... |] by testing the TH\\n level. This is a slight hack, because the level field was really\\n meant for the type checker, and here we are not interested in the\\n fields of Brack, hence the error thunks in thRnBrack.\\n-}\\n\\nextendGlobalRdrEnvRn :: [GlobalRdrElt]\\n -> MiniFixityEnv\\n -> RnM (TcGblEnv, TcLclEnv)\\n-- Updates both the GlobalRdrEnv and the FixityEnv\\n-- We return a new TcLclEnv only because we might have to\\n-- delete some bindings from it;\\n-- see Note [Top-level Names in Template Haskell decl quotes]\\n\\nextendGlobalRdrEnvRn new_gres new_fixities\\n = checkNoErrs $ -- See Note [Fail fast on duplicate definitions]\\n do { (gbl_env, lcl_env) <- getEnvs\\n ; level <- getThLevel\\n ; isGHCi <- getIsGHCi\\n ; let rdr_env = tcg_rdr_env gbl_env\\n fix_env = tcg_fix_env gbl_env\\n th_bndrs = getLclEnvThBndrs lcl_env\\n th_lvl = thLevelIndex level\\n\\n -- Delete new_occs from global and local envs\\n -- If we are in a TemplateHaskell decl bracket,\\n -- we are going to shadow them\\n -- See Note [GlobalRdrEnv shadowing]\\n inBracket = isBrackLevel level\\n\\n lcl_env_TH = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_rdr = minusLocalRdrEnv (tcl_rdr lcl_env) new_gres_env }) lcl_env\\n -- See Note [GlobalRdrEnv shadowing]\\n\\n lcl_env2 | inBracket = lcl_env_TH\\n | otherwise = lcl_env\\n\\n -- Deal with shadowing: see Note [GlobalRdrEnv shadowing]\\n want_shadowing = isGHCi || inBracket\\n rdr_env1 | want_shadowing = shadowNames False rdr_env new_gres_env\\n | otherwise = rdr_env\\n\\n lcl_env3 = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_th_bndrs = extendNameEnvList th_bndrs\\n [ ( n, (TopLevel, th_lvl) )\\n | n <- new_names ] }) lcl_env2\\n\\n ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres\\n\\n ; let fix_env\' = foldl\' extend_fix_env fix_env new_gres\\n gbl_env\' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env\' }\\n\\n ; traceRn \\"extendGlobalRdrEnvRn 2\\" (pprGlobalRdrEnv True rdr_env2)\\n ; return (gbl_env\', lcl_env3) }\\n where\\n new_names = map greName new_gres\\n new_gres_env = mkGlobalRdrEnv new_gres\\n\\n -- If there is a fixity decl for the gre, add it to the fixity env\\n extend_fix_env fix_env gre\\n | Just (L _ fi) <- lookupMiniFixityEnv new_fixities name\\n = extendNameEnv fix_env name (FixItem occ fi)\\n | otherwise\\n = fix_env\\n where\\n name = greName gre\\n occ = greOccName gre\\n\\n add_gre :: GlobalRdrEnv -> GlobalRdrElt -> RnM GlobalRdrEnv\\n -- Extend the GlobalRdrEnv with a LocalDef GRE\\n -- If there is already a LocalDef GRE with the same OccName,\\n -- report an error and discard the new GRE\\n -- This establishes INVARIANT 1 of GlobalRdrEnvs\\n add_gre env gre\\n | not (null dups) -- Same OccName defined twice\\n = do { addDupDeclErr (gre :| dups); return env }\\n\\n | otherwise\\n = return (extendGlobalRdrEnv env gre)\\n where\\n -- See Note [Reporting duplicate local declarations]\\n dups = filter isBadDupGRE\\n $ lookupGRE env (LookupOccName (greOccName gre) (RelevantGREsFOS WantBoth))\\n isBadDupGRE old_gre = isLocalGRE old_gre && greClashesWith gre old_gre\\n\\n{- Note [Fail fast on duplicate definitions]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIf there are duplicate bindings for the same thing, we want to fail\\nfast. Having two bindings for the same thing can cause follow-on errors.\\nExample (test T9975a):\\n data Test = Test { x :: Int }\\n pattern Test wat = Test { x = wat }\\nThis defines \'Test\' twice. The second defn has no field-names; and then\\nwe get an error from Test { x=wat }, saying \\"Test has no field \'x\'\\".\\n\\nEasiest thing is to bale out fast on duplicate definitions, which\\nwe do via `checkNoErrs` on `extendGlobalRdrEnvRn`.\\n\\nNote [Reporting duplicate local declarations]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn general, a single module may not define the same OccName multiple times. This\\nis checked in extendGlobalRdrEnvRn: when adding a new locally-defined GRE to the\\nGlobalRdrEnv we report an error if there are already duplicates in the\\nenvironment. This establishes INVARIANT 1 (see comments on GlobalRdrEnv in\\nGHC.Types.Name.Reader), which says that for a given OccName, all the\\nGlobalRdrElts to which it maps must have distinct \'greName\'s.\\n\\nFor example, the following will be rejected:\\n\\n f x = x\\n g x = x\\n f x = x -- Duplicate!\\n\\nUsers are allowed to introduce new GREs with the same OccName as an imported GRE,\\nas disambiguation is possible through the module system, e.g.:\\n\\n module M where\\n import N (f)\\n f x = x\\n g x = M.f x + N.f x\\n\\nIf both GREs are local, the general rule is that two GREs clash if they have\\nthe same OccName, i.e. they share a textual name and live in the same namespace.\\nHowever, there are additional clashes due to record fields:\\n\\n - a new variable clashes with previously defined record fields\\n which define field selectors,\\n\\n - a new record field shadows:\\n\\n - previously defined variables, if it defines a field selector,\\n - previously defined record fields, unless it is a duplicate record field.\\n\\nThis logic is implemented in the function \'GHC.Types.Name.Reader.greClashesWith\'.\\n\\nSee also Note [Skipping ambiguity errors at use sites of local declarations] in\\nGHC.Rename.Utils.\\n-}\\n\\n\\n{- *********************************************************************\\n* *\\n getLocalDeclBindersd@ returns the names for an HsDecl\\n It\'s used for source code.\\n\\n *** See Note [The Naming story] in GHC.Hs.Decls ****\\n* *\\n********************************************************************* -}\\n\\ngetLocalNonValBinders :: MiniFixityEnv -> HsGroup GhcPs\\n -> RnM ((TcGblEnv, TcLclEnv), NameSet)\\n-- Get all the top-level binders bound the group *except*\\n-- for value bindings, which are treated separately\\n-- Specifically we return AvailInfo for\\n-- * type decls (incl constructors and record selectors)\\n-- * class decls (including class ops)\\n-- * associated types\\n-- * foreign imports\\n-- * value signatures (in hs-boot files only)\\n\\ngetLocalNonValBinders fixity_env\\n (HsGroup { hs_valds = binds,\\n hs_tyclds = tycl_decls,\\n hs_fords = foreign_decls })\\n = do { -- Process all type/class decls *except* family instances\\n ; let inst_decls = tycl_decls >>= group_instds\\n ; dup_fields_ok <- xopt_DuplicateRecordFields <$> getDynFlags\\n ; has_sel <- xopt_FieldSelectors <$> getDynFlags\\n ; tc_gres\\n <- concatMapM\\n (new_tc dup_fields_ok has_sel)\\n (tyClGroupTyClDecls tycl_decls)\\n ; traceRn \\"getLocalNonValBinders 1\\" (ppr tc_gres)\\n ; envs <- extendGlobalRdrEnvRn tc_gres fixity_env\\n ; restoreEnvs envs $ do {\\n -- Bring these things into scope first\\n -- See Note [Looking up family names in family instances]\\n\\n -- Process all family instances\\n -- to bring new data constructors into scope\\n ; nti_gress <- mapM (new_assoc dup_fields_ok has_sel) inst_decls\\n\\n -- Finish off with value binders:\\n -- foreign decls and pattern synonyms for an ordinary module\\n -- type sigs in case of a hs-boot file only\\n ; is_boot <- tcIsHsBootOrSig\\n ; let val_bndrs\\n | is_boot = case binds of\\n ValBinds _ val_binds ->\\n -- In a hs-boot file, the value binders come from the\\n -- *signatures*, and there should be no foreign binders\\n [ L (l2l decl_loc) (unLoc n)\\n | L decl_loc (TypeSig _ _ ns _) <- (val_sigs val_binds), n <- ns]\\n _ -> panic \\"Non-ValBinds in hs-boot group\\"\\n | otherwise = for_hs_bndrs\\n ; val_gres <- mapM new_simple val_bndrs\\n\\n ; let avails = concat nti_gress ++ val_gres\\n new_bndrs = gresToNameSet avails `unionNameSet`\\n gresToNameSet tc_gres\\n ; traceRn \\"getLocalNonValBinders 2\\" (ppr avails)\\n ; envs <- extendGlobalRdrEnvRn avails fixity_env\\n ; return (envs, new_bndrs) } }\\n where\\n for_hs_bndrs :: [LocatedN RdrName]\\n for_hs_bndrs = hsForeignDeclsBinders foreign_decls\\n\\n -- the SrcSpan attached to the input should be the span of the\\n -- declaration, not just the name\\n new_simple :: LocatedN RdrName -> RnM GlobalRdrElt\\n new_simple rdr_name = do { nm <- newTopSrcBinder rdr_name\\n ; return (mkLocalVanillaGRE NoParent nm) }\\n\\n new_tc :: DuplicateRecordFields -> FieldSelectors -> LTyClDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_tc dup_fields_ok has_sel tc_decl -- NOT for type/data instances\\n = do { let TyDeclBinders (main_bndr, tc_flav) at_bndrs sig_bndrs\\n (LConsWithFields cons_with_flds flds) = hsLTyClDeclBinders tc_decl\\n ; tycon_name <- newTopSrcBinder $ la2la main_bndr\\n ; at_names <- mapM (newTopSrcBinder . la2la . fst) at_bndrs\\n ; sig_names <- mapM (newTopSrcBinder . la2la) sig_bndrs\\n ; con_names_with_flds <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst con_names_with_flds) flds\\n ; mapM_ (add_dup_fld_errs flds\') con_names_with_flds\\n ; let tc_gre = mkLocalTyConGRE (fmap (const tycon_name) tc_flav) tycon_name\\n fld_env = mk_fld_env con_names_with_flds flds\'\\n at_gres = zipWith (\\\\ (_, at_flav) at_nm -> mkLocalTyConGRE (fmap (const tycon_name) at_flav) at_nm)\\n at_bndrs at_names\\n sig_gres = map (mkLocalVanillaGRE (ParentIs tycon_name)) sig_names\\n con_gres = map (mkLocalConLikeGRE (ParentIs tycon_name)) fld_env\\n fld_gres = mkLocalFieldGREs (ParentIs tycon_name) fld_env\\n sub_gres = at_gres ++ sig_gres ++ con_gres ++ fld_gres\\n ; traceRn \\"getLocalNonValBinders new_tc\\" $\\n vcat [ text \\"tycon:\\" <+> ppr tycon_name\\n , text \\"tc_gre:\\" <+> ppr tc_gre\\n , text \\"sub_gres:\\" <+> ppr sub_gres ]\\n ; return $ tc_gre : sub_gres }\\n\\n -- Calculate the record field information, which feeds into the GlobalRdrElts\\n -- for DataCons and their fields. It\'s convenient to do this here where\\n -- we are working with a single datatype definition.\\n --\\n -- The information we needed was all set up for us:\\n -- see Note [Collecting record fields in data declarations] in GHC.Hs.Utils.\\n mk_fld_env :: [(Name, Either VisArity [Located Int])] -> IntMap FieldLabel\\n -> [(ConLikeName, ConInfo)]\\n mk_fld_env names flds =\\n [ (DataConName con, ConInfo (ConIsData (map fst names)) fld_info)\\n | (con, con_fl_indxs) <- names\\n , let fld_info = case fmap (map ((flds IntMap.!) . unLoc)) con_fl_indxs of\\n Left 0 -> ConIsNullary\\n Left arity -> ConHasPositionalArgs arity\\n Right [] -> ConIsNullary\\n Right (fld:flds) -> ConHasRecordFields $ fld NE.:| flds ]\\n\\n new_assoc :: DuplicateRecordFields -> FieldSelectors -> LInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_assoc _ _ (L _ (TyFamInstD {})) = return []\\n -- type instances don\'t bind new names\\n\\n new_assoc dup_fields_ok has_sel (L _ (DataFamInstD _ d))\\n = new_di dup_fields_ok has_sel Nothing d\\n new_assoc dup_fields_ok has_sel\\n (L _ (ClsInstD _ (ClsInstDecl { cid_poly_ty = inst_ty\\n , cid_decls = decls })))\\n = do -- First, attempt to grab the name of the class from the instance.\\n -- This step could fail if the instance is not headed by a class,\\n -- such as in the following examples:\\n --\\n -- (1) The class is headed by a bang pattern, such as in\\n -- `instance !Show Int` (#3811c)\\n -- (2) The class is headed by a type variable, such as in\\n -- `instance c` (#16385)\\n --\\n -- If looking up the class name fails, then mb_cls_gre will\\n -- be Nothing.\\n mb_cls_gre <- runMaybeT $ do\\n -- See (1) above\\n L loc cls_rdr <- MaybeT $ pure $ getLHsInstDeclClass_maybe inst_ty\\n -- See (2) above\\n MaybeT $ setSrcSpan (locA loc) $ lookupGlobalOccRn_maybe SameNameSpace cls_rdr\\n -- Assuming the previous step succeeded, process any associated data\\n -- family instances. If the previous step failed, bail out.\\n case mb_cls_gre of\\n Nothing\\n -> pure []\\n Just cls_gre\\n -> let cls_nm = greName cls_gre\\n in concatMapM (new_di dup_fields_ok has_sel (Just cls_nm) . unLoc) (data_fam_insts decls)\\n\\n data_fam_insts decls = concatMap get decls\\n where\\n get (L l (InstD _ (DataFamInstD { dfid_inst = d}))) = [L l d]\\n get _ = []\\n\\n new_di :: DuplicateRecordFields -> FieldSelectors\\n -> Maybe Name -- class name\\n -> DataFamInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_di dup_fields_ok has_sel mb_cls dfid@(DataFamInstDecl { dfid_eqn = ti_decl })\\n = do { main_name <- unLoc <$> lookupFamInstName mb_cls (feqn_tycon ti_decl)\\n ; let LConsWithFields cons_with_flds flds = hsDataFamInstBinders dfid\\n ; sub_names <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst sub_names) flds\\n ; mapM_ (add_dup_fld_errs flds\') sub_names\\n ; let fld_env = mk_fld_env sub_names flds\'\\n con_gres = map (mkLocalConLikeGRE (ParentIs main_name)) fld_env\\n field_gres = mkLocalFieldGREs (ParentIs main_name) fld_env\\n -- NB: the data family name is not bound here,\\n -- so we don\'t return a GlobalRdrElt for it here!\\n ; return $ con_gres ++ field_gres }\\n\\n -- Add errors if a constructor has a duplicate record field.\\n add_dup_fld_errs :: IntMap FieldLabel\\n -> (Name, Either VisArity [Located Int])\\n -> IOEnv (Env TcGblEnv TcLclEnv) ()\\n add_dup_fld_errs all_flds (con, con_flds_or_arity)\\n | Right con_flds <- con_flds_or_arity\\n , let (_, dups) = removeDups (comparing unLoc) con_flds\\n = for_ dups $ \\\\ dup_flds ->\\n -- Report the error at the location of the second occurrence\\n -- of the duplicate field.\\n let loc =\\n case dup_flds of\\n _ :| ( L loc _ : _) -> loc\\n L loc _ :| _ -> loc\\n dup_rdrs = fmap (nameRdrName . flSelector . (all_flds IntMap.!) . unLoc) dup_flds\\n in addErrAt loc $ TcRnDuplicateFieldName (RecordFieldDecl con) dup_rdrs\\n | otherwise\\n = return ()\\n\\nnewRecordFieldLabel :: DuplicateRecordFields -> FieldSelectors -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel\\nnewRecordFieldLabel _ _ [] _ = error \\"newRecordFieldLabel: datatype has no constructors!\\"\\nnewRecordFieldLabel dup_fields_ok has_sel (dc:_) (L loc (FieldOcc _ (L _ fld)))\\n = do { selName <- newTopSrcBinder $ L (l2l loc) $ field\\n ; return $ FieldLabel { flHasDuplicateRecordFields = dup_fields_ok\\n , flHasFieldSelector = has_sel\\n , flSelector = selName } }\\n where\\n fld_occ = rdrNameOcc fld\\n dc_fs = occNameFS $ nameOccName dc\\n field\\n -- Use an Exact RdrName as-is, to preserve the bindings\\n -- of an already renamer-resolved field and its use\\n -- sites. This is needed to correctly support record\\n -- selectors in Template Haskell. See Note [Binders in\\n -- Template Haskell] in \\"GHC.ThToHs\\" and Note [Looking up\\n -- Exact RdrNames] in \\"GHC.Rename.Env\\".\\n | isExact fld\\n = assertPpr (fieldOcc_maybe fld_occ == Just dc_fs)\\n (vcat [ text \\"newRecordFieldLabel: incorrect namespace for exact Name\\" <+> quotes (ppr fld)\\n , text \\"expected namespace:\\" <+> pprNameSpace (fieldName dc_fs)\\n , text \\" actual namespace:\\" <+> pprNameSpace (occNameSpace fld_occ) ])\\n fld\\n\\n -- Field names produced by the parser are namespaced with VarName.\\n -- Here we namespace them according to the first constructor.\\n -- See Note [Record field namespacing] in GHC.Types.Name.Occurrence.\\n | otherwise\\n = mkRdrUnqual $ varToRecFieldOcc dc_fs fld_occ\\n\\n{-\\nNote [Looking up family names in family instances]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider\\n\\n module M where\\n type family T a :: *\\n type instance M.T Int = Bool\\n\\nWe might think that we can simply use \'lookupOccRn\' when processing the type\\ninstance to look up \'M.T\'. Alas, we can\'t! The type family declaration is in\\nthe *same* HsGroup as the type instance declaration. Hence, as we are\\ncurrently collecting the binders declared in that HsGroup, these binders will\\nnot have been added to the global environment yet.\\n\\nSolution is simple: process the type family declarations first, extend\\nthe environment, and then process the type instances.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Filtering imports}\\n* *\\n************************************************************************\\n\\n@filterImports@ takes the @ExportEnv@ telling what the imported module makes\\navailable, and filters it through the import spec (if any).\\n\\nNote [Dealing with imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nFor import M( ies ), we take each AvailInfo from the mi_exports of M, and make\\n\\n imp_occ_env :: OccEnv (NameEnv ImpOccItem)\\n\\nThis map contains one entry for each OccName that M exports, mapping each OccName\\nto the following information:\\n\\n 1. the GlobalRdrElt corresponding to the OccName,\\n 2. whether this GlobalRdrElt was the parent in the AvailInfo we found\\n the OccName in.\\n 3. the GlobalRdrElts that were bundled together in the AvailInfo we found\\n this OccName in (not including the parent),\\n\\nWe need (2) and (3) during the construction of the OccEnv because of associated\\ntypes and bundled pattern synonyms, respectively.\\n(3) is explained in Note [Importing PatternSynonyms].\\n\\nTo explain (2), consider for example:\\n\\n module M where\\n class C a where { data T a }\\n instance C Int where { data T Int = T1 | T2 }\\n instance C Bool where { data T Int = T3 }\\n\\nHere, M\'s exports avails are (recalling the AvailTC invariant from GHC.Types.Avail)\\n\\n C(C,T), T(T,T1,T2,T3)\\n\\nNotice that T appears *twice*, once as a child and once as a parent. From\\nthese two exports, respectively, during construction of the imp_occ_env, we begin\\nby associating the following two elements with the key T:\\n\\n T -> ImpOccItem { imp_item = gre1, imp_bundled = [C,T] , imp_is_parent = False }\\n T -> ImpOccItem { imp_item = gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nwhere `gre1`, `gre2` are two GlobalRdrElts with greName T.\\nWe combine these (in function \'combine\' in \'mkImportOccEnv\') by discarding the\\nnon-parent item, thusly:\\n\\n T -> IE_ITem { imp_item = gre1 `plusGRE` gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nNote the `plusGRE`: this ensures we don\'t drop parent information;\\nsee Note [Preserve parent information when combining import OccEnvs].\\n\\nSo the overall imp_occ_env is:\\n\\n C -> ImpOccItem { imp_item = C, imp_bundled = [T ], imp_is_parent = True }\\n T -> ImpOccItem { imp_item = T , imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n T1 -> ImpOccItem { imp_item = T1, imp_bundled = [T1,T2,T3], imp_is_parent = False }\\n -- similarly for T2, T3\\n\\nNote that the imp_occ_env will have entries for data constructors too,\\nalthough we never look up data constructors.\\n\\nNote [Importing PatternSynonyms]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nAs described in Note [Dealing with imports], associated types can lead to the\\nsame Name appearing twice, both as a child and once as a parent, when\\nconstructing the imp_occ_env. The same thing can happen with pattern synonyms\\nif they are exported bundled with a type.\\n\\nA simplified example, based on #11959:\\n\\n {-# LANGUAGE PatternSynonyms #-}\\n module M (T(P), pattern P) where -- Duplicate export warning, but allowed\\n data T = MkT\\n pattern P = MkT\\n\\nHere we have T(P) and P in export_avails, and respectively construct both\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n P -> ImpOccItem { imp_item = P, imp_bundled = [] , imp_is_parent = False }\\n\\nWe combine these by dropping the one with no siblings, leaving us with:\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n\\nThat is, we simply discard the non-bundled Avail.\\n\\nNote [Importing DuplicateRecordFields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn filterImports, another complicating factor is DuplicateRecordFields.\\nSuppose we have:\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (S(foo), T(foo)) where\\n data S = MkS { foo :: Int }\\n data T = MkT { foo :: Int }\\n\\n module N where\\n import M (foo) -- this is allowed (A)\\n import M (S(foo)) -- this is allowed (B)\\n\\nHere M exports \'foo\' at two different OccNames, with different namespaces for\\nthe two construtors MkS and MkT. Then, when we look up \'foo\' in lookup_names\\nfor case (A), we have a variable foo but must look in all the record field\\nnamespaces to find the two fields (and hence two different Avails).\\nWhereas in case (B) we reach the lookup_ie case for IEThingWith,\\nwhich looks up \'S\' and then finds the unique \'foo\' amongst its children.\\n\\nSee T16745 for a test of this.\\n\\nNote [Preserve parent information when combining import OccEnvs]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen discarding one ImpOccItem in favour of another, as described in\\nNote [Dealing with imports], we must make sure to combine the GREs so that\\nwe don\'t lose information.\\n\\nConsider for example #24084:\\n\\n module M1 where { class C a where { type T a } }\\n module M2 ( module M1 ) where { import M1 }\\n module M3 where { import M2 ( C, T ); instance C () where T () = () }\\n\\nWhen processing the import list of `M3`, we will have two `Avail`s attached\\nto `T`, namely `C(C, T)` and `T(T)`. We combine them in the `combine` function\\nof `mkImportOccEnv`; as described in Note [Dealing with imports] we discard\\n`C(C, T)` in favour of `T(T)`. However, in doing so, we **must not**\\ndiscard the information want that `C` is the parent of `T`. Indeed,\\nlosing track of this information can cause errors when importing,\\nas we could get an error of the form\\n\\n \\u2018T\\u2019 is not a (visible) associated type of class \\u2018C\\u2019\\n\\nThis explains why we use `plusGRE` when combining the two ImpOccItems, even\\nthough we are discarding one in favour of the other.\\n-}\\n\\n-- | All the \'GlobalRdrElt\'s associated with an \'AvailInfo\'.\\ngresFromAvail :: HasDebugCallStack\\n => HscEnv -> Maybe ImportSpec -> AvailInfo -> [GlobalRdrElt]\\ngresFromAvail hsc_env prov avail =\\n [ mk_gre nm info\\n | nm <- availNames avail\\n , let info = lookupGREInfo hsc_env nm ]\\n where\\n\\n mk_gre n info\\n = case prov of\\n -- Nothing => bound locally\\n -- Just is => imported from \'is\'\\n Nothing -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = True, gre_imp = emptyBag\\n , gre_info = info }\\n Just is -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = False, gre_imp = unitBag is\\n , gre_info = info }\\n\\n-- | All the \'GlobalRdrElt\'s associated with a collection of \'AvailInfo\'s.\\ngresFromAvails :: HscEnv -> Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]\\ngresFromAvails hsc_env prov = concatMap (gresFromAvail hsc_env prov)\\n\\nimportsFromIface :: HscEnv -> ModIface -> ImpDeclSpec -> Maybe NameSet -> GlobalRdrEnv\\nimportsFromIface hsc_env iface decl_spec hidden = mkGlobalRdrEnv $ case hidden of\\n Nothing -> all_gres\\n Just hidden_names -> filter (not . (`elemNameSet` hidden_names) . greName) all_gres\\n where\\n all_gres = gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\nrnNamespaceSpecifier :: NamespaceSpecifier GhcPs -> NamespaceSpecifier GhcRn\\nrnNamespaceSpecifier (NoNamespaceSpecifier _) = NoNamespaceSpecifier noExtField\\nrnNamespaceSpecifier (TypeNamespaceSpecifier x) = TypeNamespaceSpecifier x\\nrnNamespaceSpecifier (DataNamespaceSpecifier x) = DataNamespaceSpecifier x\\n\\nfilterImports\\n :: HasDebugCallStack\\n => HscEnv\\n -> ModIface\\n -> ImpDeclSpec\\n -- ^ Import spec\\n -> Maybe (ImportListInterpretation, [LIE GhcPs])\\n -- ^ Whether this is a \\"hiding\\" import list\\n -> RnM (Maybe (ImportListInterpretation, [LIE GhcRn]), -- Import spec w/ Names\\n ImpUserList, -- same, but designed for storage in interfaces\\n GlobalRdrEnv) -- Same again, but in GRE form\\nfilterImports hsc_env iface decl_spec Nothing\\n = return (Nothing, ImpUserAll, importsFromIface hsc_env iface decl_spec Nothing)\\nfilterImports hsc_env iface decl_spec (Just (want_hiding, import_items))\\n = do -- check for errors, convert RdrNames to Names\\n items1 <- mapM lookup_lie import_items\\n\\n let items2 :: [(LIE GhcRn, [GlobalRdrElt])]\\n items2 = concat items1\\n -- NB we may have duplicates, and several items\\n -- for the same parent; e.g N(x) and N(y)\\n\\n (gres, imp_user_list) = case want_hiding of\\n Exactly ->\\n let gres = concatMap (gresFromIE decl_spec) items2\\n gre_env = mkGlobalRdrEnv gres\\n implicit_parents = mkNameSet $ mapMaybe parentOfImplicitlyImportedGRE gres\\n in (gre_env, ImpUserExplicit (gresToAvailInfo $ globalRdrEnvElts $ gre_env) implicit_parents)\\n EverythingBut ->\\n let hidden_names = mkNameSet $ concatMap (map greName . snd) items2\\n in (importsFromIface hsc_env iface decl_spec (Just hidden_names), ImpUserEverythingBut hidden_names)\\n\\n return (Just (want_hiding, map fst items2), imp_user_list, gres)\\n where\\n import_mod = mi_module iface\\n all_avails = mi_exports iface\\n imp_occ_env = mkImportOccEnv hsc_env decl_spec all_avails\\n\\n -- Look up a parent (type constructor, class or data constructor)\\n -- in an import.\\n lookup_parent :: IE GhcPs -> RdrName -> IELookupM ImpOccItem\\n lookup_parent ie rdr =\\n assertPpr (not $ isVarNameSpace ns)\\n (vcat [ text \\"filterImports lookup_parent: unexpected variable\\"\\n , text \\"rdr:\\" <+> ppr rdr\\n , text \\"namespace:\\" <+> pprNameSpace ns ]) $\\n do { xs <- lookup_names ie rdr\\n ; case xs of\\n cax :| [] -> return cax\\n _ -> pprPanic \\"filter_imports lookup_parent ambiguous\\" $\\n vcat [ text \\"rdr:\\" <+> ppr rdr\\n , text \\"lookups:\\" <+> ppr (fmap imp_item xs) ] }\\n -- Looking up non-variables is always unambiguous,\\n -- as there can be at most one corresponding item\\n -- in the imp_occ_env.\\n -- See item (1) of Note [Exporting duplicate declarations]\\n -- in GHC.Tc.Gen.Export.\\n where\\n occ = rdrNameOcc rdr\\n ns = occNameSpace occ\\n\\n -- Look up a RdrName used in an import, returning multiple values if there\\n -- are several fields with the same name exposed by the module\\n lookup_names :: IE GhcPs -> RdrName -> IELookupM (NonEmpty ImpOccItem)\\n lookup_names ie rdr\\n | isQual rdr\\n = failLookupWith (QualImportError rdr)\\n | otherwise\\n = case lookups of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n item:items -> return $ item :| items\\n where\\n lookups = concatMap nonDetNameEnvElts\\n $ lookupImpOccEnv (RelevantGREsFOS WantNormal) imp_occ_env (rdrNameOcc rdr)\\n\\n lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, [GlobalRdrElt])]\\n lookup_lie (L loc ieRdr)\\n = setSrcSpanA loc $\\n do (stuff, warns) <- run_lookup ([],[]) (lookup_ie ieRdr)\\n mapM_ (addTcRnDiagnostic <=< warning_msg) warns\\n return [ (L loc ie, gres) | (ie,gres) <- stuff ]\\n where\\n\\n -- Warn when importing T(..) and no children are brought in scope\\n warning_msg (DodgyImport reason) =\\n pure (TcRnDodgyImports reason)\\n warning_msg MissingImportList =\\n pure (TcRnMissingImportList ieRdr)\\n warning_msg (BadImportW ie sub) = do\\n -- \'BadImportW\' is only constructed below in \'bad_import_w\', in\\n -- the \'EverythingBut\' case, so here we assume a \'hiding\' clause.\\n (reason :| _) <- badImportItemErr iface decl_spec ie sub all_avails\\n pure (TcRnDodgyImports (DodgyImportsHiding reason))\\n warning_msg (DeprecatedExport n w) =\\n pure $ TcRnPragmaWarning\\n PragmaWarningExport\\n { pwarn_occname = occName n\\n , pwarn_impmod = moduleName import_mod }\\n w\\n\\n run_lookup :: a -> IELookupM a -> TcRn a\\n run_lookup def m = case m of\\n Failed err -> do\\n msgs <- lookup_err_msgs err\\n forM_ msgs $ \\\\msg -> addErr (TcRnImportLookup msg)\\n return def\\n Succeeded a -> return a\\n\\n lookup_err_msgs err = case err of\\n BadImport ie sub -> badImportItemErr iface decl_spec ie sub all_avails\\n IllegalImport -> pure $ NE.singleton ImportLookupIllegal\\n QualImportError rdr -> pure $ NE.singleton (ImportLookupQualified rdr)\\n\\n -- For each import item, we convert its RdrNames to Names,\\n -- and at the same time compute all the GlobalRdrElt corresponding\\n -- to what is actually imported by this item.\\n -- Returns Nothing on error.\\n --\\n -- Returns a list because, with DuplicateRecordFields, a naked\\n -- import/export of a record field can correspond to multiple\\n -- different GlobalRdrElts. See Note [Importing DuplicateRecordFields].\\n lookup_ie :: IE GhcPs\\n -> IELookupM ([(IE GhcRn, [GlobalRdrElt])], [IELookupWarning])\\n lookup_ie ie = handle_bad_import $\\n case ie of\\n IEVar _ (L l n) _ -> do\\n -- See Note [Importing DuplicateRecordFields]\\n xs <- lookup_names ie (ieWrappedName n)\\n let gres = map imp_item $ NE.toList xs\\n export_depr_warns\\n | want_hiding == Exactly\\n = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ( [ (IEVar Nothing (L l (replaceWrappedName n name)) noDocstring, [gre])\\n | gre <- gres\\n , let name = greName gre ]\\n , export_depr_warns )\\n\\n IEThingAll x ns_spec (L l tc) _ -> do\\n ImpOccItem { imp_item = gre\\n , imp_bundled = bundled_gres\\n , imp_is_parent = is_par\\n }\\n <- lookup_parent ie $ ieWrappedName tc\\n let name = greName gre\\n\\n child_gres :: [GlobalRdrElt]\\n child_gres\\n | is_par = filterByNamespaceSpecifierGREs ns_spec bundled_gres\\n | otherwise = []\\n\\n imp_list_warn\\n\\n | null child_gres\\n -- e.g. f(..) or T(..) where T is a type synonym\\n = [DodgyImport (DodgyImportsEmptyParent ie ns_spec gre)]\\n\\n -- e.g. import M( T(..) )\\n | not (is_qual decl_spec)\\n = [MissingImportList]\\n\\n | otherwise\\n = []\\n\\n renamed_ie = IEThingAll (x { ieta_warning = Nothing })\\n (rnNamespaceSpecifier ns_spec)\\n (L l (replaceWrappedName tc name))\\n noDocstring\\n export_depr_warn\\n | want_hiding == Exactly\\n = maybeToList $ mk_depr_export_warning gre\\n -- We don\'t want to warn about the children as they\\n -- are not explicitly mentioned; the warning will\\n -- be emitted later on if they are used\\n | otherwise = []\\n\\n return ( [(renamed_ie, gre:child_gres)]\\n , imp_list_warn ++ export_depr_warn)\\n\\n\\n IEThingAbs _ (L l tc\') _\\n | want_hiding == EverythingBut -- hiding ( C )\\n -- Here the \'C\' can be a data constructor\\n -- *or* a type/class, or even both\\n -> let tc = ieWrappedName tc\'\\n tc_name = lookup_parent ie tc\\n dc_name = lookup_parent ie (setRdrNameSpace tc srcDataName)\\n in\\n case catIELookupM [ tc_name, dc_name ] of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n names -> return ( [mkIEThingAbs tc\' l (imp_item name) | name <- names], [])\\n | otherwise\\n -> do ImpOccItem { imp_item = gre } <- lookup_parent ie (ieWrappedName tc\')\\n return ( [mkIEThingAbs tc\' l gre]\\n , maybeToList $ mk_depr_export_warning gre)\\n\\n IEThingWith (deprecation, ann) ltc@(L l rdr_tc) wc rdr_ns _ -> do\\n ImpOccItem { imp_item = gre, imp_bundled = subnames }\\n <- lookup_parent (IEThingAbs Nothing ltc noDocstring) (ieWrappedName rdr_tc)\\n let name = greName gre\\n\\n -- Look up the children in the sub-names of the parent\\n -- See Note [Importing DuplicateRecordFields]\\n let (children_errs, childnames) = lookupChildren subnames rdr_ns\\n\\n bad_import_warns <-\\n if null children_errs then return [] else\\n let items = map lce_wrapped_name children_errs\\n ie = IEThingWith (deprecation, ann) ltc wc items noDocstring\\n -- We are trying to import T( a,b,c,d ), and failed\\n -- to find \'b\' and \'d\'. So we make up an import item\\n -- to report as failing, namely T( b, d ).\\n -- c.f. #15413\\n subordinate_err = mkSubordinateError gre children_errs\\n in bad_import_w ie subordinate_err\\n\\n let name\' = replaceWrappedName rdr_tc name\\n childnames\' = map (to_ie_post_rn . fmap greName) childnames\\n gres = gre : map unLoc childnames\\n export_depr_warns\\n | want_hiding == Exactly = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ([ (IEThingWith (Nothing, ann) (L l name\') wc childnames\' noDocstring\\n ,gres)]\\n , bad_import_warns ++ export_depr_warns)\\n\\n IEWholeNamespace x ns_spec -> do\\n let mod_name = moduleName import_mod\\n names = map greName gres\\n renamed_ie = IEWholeNamespace x { iewn_warning = Nothing\\n , iewn_names = names }\\n (rnNamespaceSpecifier ns_spec)\\n gres = filterByNamespaceSpecifierGREs ns_spec $\\n gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n dodgy_warn\\n | null gres = [DodgyImport (DodgyImportsWildcard mod_name ns_spec)]\\n | otherwise = []\\n return ([(renamed_ie, gres)],\\n dodgy_warn)\\n\\n _other -> failLookupWith IllegalImport\\n -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed...\\n -- all of those constitute errors.\\n\\n where\\n mkIEThingAbs tc l gre\\n = (IEThingAbs Nothing (L l (replaceWrappedName tc n)) noDocstring, [gre])\\n where n = greName gre\\n\\n -- N.B. imports never have docstrings\\n noDocstring = Nothing\\n\\n handle_bad_import m = catchIELookup m $ \\\\case\\n BadImport ie sub -> do\\n ws <- bad_import_w ie sub\\n return ([], ws)\\n err -> failLookupWith err\\n\\n bad_import_w :: IE GhcPs -> IsSubordinateError -> IELookupM [IELookupWarning]\\n bad_import_w ie sub\\n | want_hiding == EverythingBut = return [BadImportW ie sub]\\n | otherwise = failLookupWith (BadImport ie sub)\\n\\n mk_depr_export_warning gre\\n = DeprecatedExport name <$> mi_export_warn_fn iface name\\n where\\n name = greName gre\\n\\n-- | Assuming a subordinate item could not be found, do another lookup for a\\n-- more specific error message.\\nmkBadExportSubordinate :: [GlobalRdrElt] -> LIEWrappedName GhcPs -> BadExportSubordinate\\nmkBadExportSubordinate child_gres n =\\n case lookupChildren child_gres [n] of\\n (LookupChildNonType {lce_nontype_item = g} : _, _) -> BadExportSubordinateNonType g\\n (LookupChildNonData {lce_nondata_item = g} : _, _) -> BadExportSubordinateNonData g\\n _ -> BadExportSubordinateNotFound n\\n\\ntype IELookupM = MaybeErr IELookupError\\n\\ndata IELookupWarning\\n = BadImportW (IE GhcPs) IsSubordinateError\\n | MissingImportList\\n | DodgyImport DodgyImportsReason\\n | DeprecatedExport Name (WarningTxt GhcRn)\\n\\n-- | Is this import/export item a subordinate or not?\\ndata IsSubordinateError\\n = IsSubordinateError { subordinate_err_parent :: !GlobalRdrElt\\n , subordinate_err_unavailable :: [FastString]\\n , subordinate_err_nontype :: [GlobalRdrElt]\\n , subordinate_err_nondata :: [GlobalRdrElt] }\\n | IsNotSubordinate\\n\\nmkSubordinateError :: GlobalRdrElt -> [LookupChildError] -> IsSubordinateError\\nmkSubordinateError gre children_errs = foldr add init_acc children_errs\\n where\\n init_acc :: IsSubordinateError\\n init_acc = IsSubordinateError gre [] [] []\\n\\n add :: LookupChildError -> IsSubordinateError -> IsSubordinateError\\n add children_err sub@IsSubordinateError{} =\\n case children_err of\\n LookupChildNonType{lce_nontype_item = g} ->\\n sub { subordinate_err_nontype = g : subordinate_err_nontype sub }\\n LookupChildNonData{lce_nondata_item = g} ->\\n sub { subordinate_err_nondata = g : subordinate_err_nondata sub }\\n LookupChildNotFound (L _ wname) ->\\n let fs = (occNameFS . rdrNameOcc . ieWrappedName) wname\\n in sub { subordinate_err_unavailable = fs : subordinate_err_unavailable sub }\\n add _ IsNotSubordinate = panic \\"mkSubordinateError: IsNotSubordinate\\"\\n\\ndata IELookupError\\n = QualImportError RdrName\\n | BadImport (IE GhcPs) IsSubordinateError\\n | IllegalImport\\n\\nfailLookupWith :: IELookupError -> IELookupM a\\nfailLookupWith err = Failed err\\n\\ncatchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a\\ncatchIELookup m h = case m of\\n Succeeded r -> return r\\n Failed err -> h err\\n\\ncatIELookupM :: [IELookupM a] -> [a]\\ncatIELookupM ms = [ a | Succeeded a <- ms ]\\n\\n-- | Information associated to an \'AvailInfo\' used in constructing\\n-- an \'OccEnv\' corresponding to imports.\\n--\\n-- See Note [Dealing with imports].\\ndata ImpOccItem\\n = ImpOccItem\\n { imp_item :: GlobalRdrElt\\n -- ^ The import item\\n , imp_bundled :: [GlobalRdrElt]\\n -- ^ Items bundled in the Avail this import item came from,\\n -- not including the import item itself if it is a parent.\\n , imp_is_parent :: Bool\\n -- ^ Is the import item a parent? See Note [Dealing with imports].\\n }\\n\\ninstance Outputable ImpOccItem where\\n ppr (ImpOccItem { imp_item = item, imp_bundled = bundled, imp_is_parent = is_par })\\n = braces $ hsep\\n [ text \\"ImpOccItem\\"\\n , if is_par then text \\"[is_par]\\" else empty\\n , ppr (greName item) <+> ppr (greParent item)\\n , braces $ text \\"bundled:\\" <+> ppr (map greName bundled) ]\\n\\n-- | Make an \'OccEnv\' of all the imports.\\n--\\n-- Complicated by the fact that associated data types and pattern synonyms\\n-- can appear twice. See Note [Dealing with imports].\\nmkImportOccEnv :: HscEnv -> ImpDeclSpec -> [IfaceExport] -> OccEnv (NameEnv ImpOccItem)\\nmkImportOccEnv hsc_env decl_spec all_avails =\\n mkOccEnv_C (plusNameEnv_C combine)\\n [ (occ, mkNameEnv [(nm, item)])\\n | avail <- all_avails\\n , let gres = gresFromAvail hsc_env (Just hiding_spec) avail\\n , gre <- gres\\n , let nm = greName gre\\n occ = greOccName gre\\n (is_parent, bundled) = case avail of\\n AvailTC c _\\n | c == nm -- (Recall the AvailTC invariant from GHC.Types.AvailInfo)\\n -> ( True, drop 1 gres ) -- \\"drop 1\\": don\'t include the parent itself.\\n | otherwise\\n -> ( False, gres )\\n _ -> ( False, [] )\\n item = ImpOccItem\\n { imp_item = gre\\n , imp_bundled = bundled\\n , imp_is_parent = is_parent }\\n ]\\n where\\n\\n hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\n -- See Note [Dealing with imports]\\n -- \'combine\' may be called for associated data types which appear\\n -- twice in the all_avails. In the example, we have two Avails for T,\\n -- namely T(T,T1,T2,T3) and C(C,T), and we combine them by dropping the\\n -- latter, in which T is not the parent.\\n combine :: ImpOccItem -> ImpOccItem -> ImpOccItem\\n combine item1@(ImpOccItem { imp_item = gre1, imp_is_parent = is_parent1 })\\n item2@(ImpOccItem { imp_item = gre2, imp_is_parent = is_parent2 })\\n | is_parent1 || is_parent2\\n , not (isRecFldGRE gre1 || isRecFldGRE gre2) -- NB: does not force GREInfo.\\n , let name1 = greName gre1\\n name2 = greName gre2\\n gre = gre1 `plusGRE` gre2\\n -- See Note [Preserve parent information when combining import OccEnvs]\\n = assertPpr (name1 == name2)\\n (ppr name1 <+> ppr name2) $\\n if is_parent1\\n then item1 { imp_item = gre }\\n else item2 { imp_item = gre }\\n -- Discard C(C,T) in favour of T(T, T1, T2, T3).\\n\\n -- \'combine\' may also be called for pattern synonyms which appear both\\n -- unassociated and associated (see Note [Importing PatternSynonyms]).\\n combine item1@(ImpOccItem { imp_item = c1, imp_bundled = kids1 })\\n item2@(ImpOccItem { imp_item = c2, imp_bundled = kids2 })\\n = assertPpr (greName c1 == greName c2\\n && (not (null kids1 && null kids2)))\\n (ppr c1 <+> ppr c2 <+> ppr kids1 <+> ppr kids2) $\\n if null kids1\\n then item2\\n else item1\\n -- Discard standalone pattern P in favour of T(P).\\n\\n-- | Essentially like @lookupGRE env (LookupOccName occ which_gres)@,\\n-- but working with \'ImpOccItem\'s instead of \'GlobalRdrElt\'s.\\nlookupImpOccEnv :: WhichGREs GREInfo\\n -> OccEnv (NameEnv ImpOccItem) -> OccName -> [NameEnv ImpOccItem]\\nlookupImpOccEnv which_gres env occ =\\n mapMaybe relevant_items $ lookupOccEnv_AllNameSpaces env occ\\n where\\n is_relevant :: ImpOccItem -> Bool\\n is_relevant (ImpOccItem { imp_item = gre }) =\\n greIsRelevant which_gres (occNameSpace occ) gre\\n relevant_items :: NameEnv ImpOccItem -> Maybe (NameEnv ImpOccItem)\\n relevant_items nms\\n | let nms\' = filterNameEnv is_relevant nms\\n = if isEmptyNameEnv nms\'\\n then Nothing\\n else Just nms\'\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{Import/Export Utils}\\n* *\\n************************************************************************\\n-}\\n\\n-- | Given an import\\\\/export spec, appropriately set the @gre_imp@ field\\n-- for the \'GlobalRdrElt\'s.\\ngresFromIE :: ImpDeclSpec -> (LIE GhcRn, [GlobalRdrElt]) -> [GlobalRdrElt]\\ngresFromIE decl_spec (L loc ie, gres)\\n = map set_gre_imp gres\\n where\\n is_explicit = case ie of\\n IEThingAll _ _ name _ -> \\\\n -> n == lieWrappedName name\\n IEWholeNamespace _ _ -> \\\\_ -> False\\n _ -> \\\\_ -> True\\n prov_fn name\\n = ImpSpec { is_decl = decl_spec, is_item = item_spec }\\n where\\n item_spec = ImpSome { is_explicit = is_explicit name\\n , is_iloc = locA loc }\\n set_gre_imp gre@( GRE { gre_name = nm } )\\n = gre { gre_imp = unitBag $ prov_fn nm }\\n\\nparentOfImplicitlyImportedGRE :: Outputable info => GlobalRdrEltX info -> Maybe Name\\nparentOfImplicitlyImportedGRE gre =\\n if any (explicit_import . is_item) $ gre_imp gre\\n then Nothing\\n else greParent_maybe gre\\n where\\n explicit_import :: ImpItemSpec -> Bool\\n explicit_import (ImpAll {}) =\\n pprPanic \\"parentOfImplicitlyImportedGRE: ImpAll\\" (ppr gre)\\n explicit_import (ImpSome { is_explicit }) = is_explicit\\n\\n{- Note [Children for duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider the module\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (F(foo, MkFInt, MkFBool)) where\\n data family F a\\n data instance F Int = MkFInt { foo :: Int }\\n data instance F Bool = MkFBool { foo :: Bool }\\n\\nThe `foo` in the export list refers to *both* selectors! For this\\nreason, lookupChildren builds an environment that maps the FastString\\nto a list of items, rather than a single item.\\n-}\\n\\nmkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]\\nmkChildEnv gres = foldr add emptyNameEnv gres\\n where\\n add gre env = case greParent gre of\\n ParentIs p -> extendNameEnv_Acc (:) Utils.singleton env p gre\\n NoParent -> env\\n\\nfindChildren :: NameEnv [a] -> Name -> [a]\\nfindChildren env n = lookupNameEnv env n `orElse` []\\n\\ndata LookupChildError\\n = LookupChildNotFound { lce_wrapped_name :: !(LIEWrappedName GhcPs) }\\n | LookupChildNonType { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nontype_item :: !GlobalRdrElt }\\n | LookupChildNonData { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nondata_item :: !GlobalRdrElt }\\n\\nlookupChildren :: [GlobalRdrElt]\\n -> [LIEWrappedName GhcPs]\\n -> ( [LookupChildError] -- The ones for which the lookup failed\\n , [LocatedA GlobalRdrElt] )\\n-- (lookupChildren all_kids rdr_items) maps each rdr_item to its\\n-- corresponding Name in all_kids, if the former exists\\n-- The matching is done by FastString, not OccName, so that\\n-- Cls( meth, AssocTy )\\n-- will correctly find AssocTy among the all_kids of Cls, even though\\n-- the RdrName for AssocTy may have a (bogus) DataName namespace\\n-- (Really the rdr_items should be FastStrings in the first place.)\\nlookupChildren all_kids rdr_items = (fails, successes)\\n where\\n mb_xs = map do_one rdr_items\\n fails = [ err | Failed err <- mb_xs ]\\n successes = [ ok | Succeeded oks <- mb_xs, ok <- NE.toList oks ]\\n\\n do_one :: LIEWrappedName GhcPs -> MaybeErr LookupChildError (NonEmpty (LocatedA GlobalRdrElt))\\n do_one item@(L l r) =\\n case r of\\n IEName{}\\n -- IEName (unadorned name) places no restriction on the namespace of\\n -- the imported entity, so we look in both `val_gres` and `typ_gres`.\\n -- In case of conflict (punning), the value namespace takes priority.\\n -- See Note [Prioritise the value namespace in subordinate import lists]\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEType{}\\n -- IEType (\'type\' namespace specifier) restricts the lookup to the\\n -- type namespace, i.e. to `typ_gres`. In case of failure, we check\\n -- `val_gres` to produce a more helpful error message.\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- val_gres -> Failed $ LookupChildNonType item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEData{}\\n -- IEData (\'data\' namespace specifier) restricts the lookup to the\\n -- data namespace, i.e. to `val_gres`. In case of failure, we check\\n -- `typ_gres` to produce a more helpful error message.\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- typ_gres -> Failed $ LookupChildNonData item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEPattern{} -> panic \\"lookupChildren: IEPattern\\" -- Never happens (invalid syntax)\\n IEDefault{} -> panic \\"lookupChildren: IEDefault\\" -- Never happens (invalid syntax)\\n where\\n fs = (occNameFS . rdrNameOcc . ieWrappedName) r\\n gres = fromMaybe [] (lookupFsEnv kid_env fs)\\n (val_gres, typ_gres) = partition (isValNameSpace . greNameSpace) gres\\n\\n -- See Note [Children for duplicate record fields]\\n kid_env :: FastStringEnv [GlobalRdrElt]\\n kid_env = extendFsEnvList_C (++) emptyFsEnv\\n [(occNameFS (occName x), [x]) | x <- all_kids]\\n\\n\\n{- Note [Prioritise the value namespace in subordinate import lists]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider this program that defines a class that has both an associated type\\nnamed (#) and a method named (#)\\n\\n module M_assoc where\\n class C a b where\\n type a # b\\n (#) :: a -> b -> ()\\n module N_assoc where\\n import M_assoc( C((#)) )\\n\\nIn the import declaration, when we see the unadorned name (#) in the subordinate\\nimport list of C, which children should we bring into scope? Our options are:\\n\\n a) only the method (#)\\n b) only the associated type (#)\\n c) both the method and the associated type\\n\\nTo follow the precedent established by top-level items, we go with option (a).\\nIndeed, consider a slightly different program\\n\\n module M_top where\\n type family a # b\\n a # b = ()\\n module N_top where\\n import M_top( (#) )\\n\\nHere the import brings only the function (#) into scope, and one has to say\\n`type (#)` to get the type family.\\n-}\\n\\n-------------------------------\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused names}\\n* *\\n*********************************************************\\n-}\\n\\nreportUnusedNames :: TcGblEnv -> HscSource -> RnM ()\\nreportUnusedNames gbl_env hsc_src\\n = do { keep <- readTcRef (tcg_keep gbl_env)\\n ; traceRn \\"RUN\\" (ppr (tcg_dus gbl_env))\\n ; warnUnusedImportDecls gbl_env hsc_src\\n ; warnUnusedTopBinds $ unused_locals keep\\n ; warnMissingSignatures gbl_env\\n ; warnMissingKindSignatures gbl_env }\\n where\\n used_names :: NameSet -> NameSet\\n used_names keep = findUses (tcg_dus gbl_env) emptyNameSet `unionNameSet` keep\\n -- NB: currently, if f x = g, we only treat \'g\' as used if \'f\' is used\\n -- Hence findUses\\n\\n -- Collect the defined names from the in-scope environment\\n defined_names :: [GlobalRdrElt]\\n defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)\\n\\n kids_env = mkChildEnv defined_names\\n -- This is done in mkExports too; duplicated work\\n\\n gre_is_used :: NameSet -> GlobalRdrElt -> Bool\\n gre_is_used used_names gre0\\n = name `elemNameSet` used_names\\n || any (\\\\ gre -> greName gre `elemNameSet` used_names) (findChildren kids_env name)\\n -- A use of C implies a use of T,\\n -- if C was brought into scope by T(..) or T(C)\\n where\\n name = greName gre0\\n\\n -- Filter out the ones that are\\n -- (a) defined in this module, and\\n -- (b) not defined by a \'deriving\' clause\\n -- The latter have an Internal Name, so we can filter them out easily\\n unused_locals :: NameSet -> [GlobalRdrElt]\\n unused_locals keep =\\n let -- Note that defined_and_used, defined_but_not_used\\n -- are both [GRE]; that\'s why we need defined_and_used\\n -- rather than just used_names\\n _defined_and_used, defined_but_not_used :: [GlobalRdrElt]\\n (_defined_and_used, defined_but_not_used)\\n = partition (gre_is_used (used_names keep)) defined_names\\n\\n in filter is_unused_local defined_but_not_used\\n is_unused_local :: GlobalRdrElt -> Bool\\n is_unused_local gre = isLocalGRE gre\\n && isExternalName (greName gre)\\n\\n{- *********************************************************************\\n* *\\n Missing signatures\\n* *\\n********************************************************************* -}\\n\\n{-\\nNote [Missing signatures]\\n~~~~~~~~~~~~~~~~~~~~~~~~~\\nThere are four warning flags in play:\\n\\n * -Wmissing-exported-signatures\\n Warn about any exported top-level function/value without a type signature.\\n Does not include pattern synonyms.\\n\\n * -Wmissing-signatures\\n Warn about any top-level function/value without a type signature. Does not\\n include pattern synonyms. Takes priority over -Wmissing-exported-signatures.\\n\\n * -Wmissing-exported-pattern-synonym-signatures\\n Warn about any exported pattern synonym without a type signature.\\n\\n * -Wmissing-pattern-synonym-signatures\\n Warn about any pattern synonym without a type signature. Takes priority over\\n -Wmissing-exported-pattern-synonym-signatures.\\n\\n-}\\n\\n-- | Warn the user about top level binders that lack type signatures.\\n-- Called /after/ type inference, so that we can report the\\n-- inferred type of the function\\nwarnMissingSignatures :: TcGblEnv -> RnM ()\\nwarnMissingSignatures gbl_env\\n = do { let exports = availsToNameSet (tcg_exports gbl_env)\\n sig_ns = tcg_sigs gbl_env\\n -- We use sig_ns to exclude top-level bindings that are generated by GHC\\n binds = collectHsBindsBinders CollNoDictBinders $ tcg_binds gbl_env\\n pat_syns = tcg_patsyns gbl_env\\n\\n not_ghc_generated :: Name -> Bool\\n not_ghc_generated name = name `elemNameSet` sig_ns\\n\\n add_binding_warn :: Id -> RnM ()\\n add_binding_warn id =\\n when (not_ghc_generated name) $\\n do { env <- liftZonkM $ tcInitTidyEnv -- Why not use emptyTidyEnv?\\n ; let ty = tidyOpenType env (idType id)\\n missing = MissingTopLevelBindingSig name ty\\n diag = TcRnMissingSignature missing exported\\n ; addDiagnosticAt (getSrcSpan name) diag }\\n where\\n name = idName id\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n add_patsyn_warn :: PatSyn -> RnM ()\\n add_patsyn_warn ps =\\n when (not_ghc_generated name) $\\n addDiagnosticAt (getSrcSpan name)\\n (TcRnMissingSignature missing exported)\\n where\\n name = patSynName ps\\n missing = MissingPatSynSig ps\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n -- Warn about missing signatures\\n -- Do this only when we have a type to offer\\n -- See Note [Missing signatures]\\n ; mapM_ add_binding_warn binds\\n ; mapM_ add_patsyn_warn pat_syns\\n }\\n\\n-- | Warn the user about tycons that lack kind signatures.\\n-- Called /after/ type (and kind) inference, so that we can report the\\n-- inferred kinds.\\nwarnMissingKindSignatures :: TcGblEnv -> RnM ()\\nwarnMissingKindSignatures gbl_env\\n = do { cusks_enabled <- xoptM LangExt.CUSKs\\n ; mapM_ (add_ty_warn cusks_enabled) tcs\\n }\\n where\\n tcs = tcg_tcs gbl_env\\n ksig_ns = tcg_ksigs gbl_env\\n exports = availsToNameSet (tcg_exports gbl_env)\\n\\n has_kind_signature :: Name -> Bool\\n has_kind_signature name = name `elemNameSet` ksig_ns\\n\\n add_ty_warn :: Bool -> TyCon -> RnM ()\\n add_ty_warn cusks_enabled tyCon =\\n when (has_kind_signature name) $\\n addDiagnosticAt (getSrcSpan name) diag\\n where\\n name = tyConName tyCon\\n diag = TcRnMissingSignature missing exported\\n missing = MissingTyConKindSig tyCon cusks_enabled\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused imports}\\n* *\\n*********************************************************\\n\\nThis code finds which import declarations are unused. The\\nspecification and implementation notes are here:\\n https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/unused-imports\\n\\nSee also Note [Choosing the best import declaration] in GHC.Types.Name.Reader\\n-}\\n\\ntype ImportDeclUsage\\n = ( LImportDecl GhcRn -- The import declaration\\n , [GlobalRdrElt] -- What *is* used (normalised)\\n , [Name] -- What is imported but *not* used\\n , [NamespaceSpecifier GhcRn] ) -- Unused wildcards\\n\\nwarnUnusedImportDecls :: TcGblEnv -> HscSource -> RnM ()\\nwarnUnusedImportDecls gbl_env hsc_src\\n = do { uses <- readMutVar (tcg_used_gres gbl_env)\\n ; let imports = tcg_rn_imports gbl_env\\n rdr_env = tcg_rdr_env gbl_env\\n\\n -- We should only warn for unnecessary *user* imports, but deciding\\n -- minimal imports should take generated imports into account\\n ; let usageUserImports = findImportUsage (excludeGenerated imports) uses\\n usageAllImports = findImportUsage imports uses\\n\\n ; traceRn \\"warnUnusedImportDecls\\" $\\n (vcat [ text \\"Uses:\\" <+> ppr uses\\n , text \\"Usage all user imports: \\" <+> ppr usageUserImports\\n , text \\"Usage all imports: \\" <+> ppr usageAllImports])\\n\\n ; mapM_ (warnUnusedImport rdr_env) usageUserImports\\n\\n ; whenGOptM Opt_D_dump_minimal_imports $\\n printMinimalImports hsc_src usageAllImports }\\n\\n-- | Exclude generated imports\\nexcludeGenerated :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\nexcludeGenerated = filterOut (isGeneratedImport . ideclOrigin . ideclExt . unLoc)\\n\\nfindImportUsage :: [LImportDecl GhcRn]\\n -> [GlobalRdrElt]\\n -> [ImportDeclUsage]\\n\\nfindImportUsage imports used_gres\\n = map unused_decl imports\\n where\\n import_usage :: ImportMap\\n import_usage = mkImportMap used_gres\\n\\n unused_decl :: LImportDecl GhcRn -> ImportDeclUsage\\n unused_decl decl@(L _ (ImportDecl { ideclImportList = imps }))\\n = -- pprTrace \\"unused_decl\\" (vcat [ ppr decl\\n -- , text \\"used\\" <+> ppr used_gres\\n -- , text \\"unused\\" <+> ppr unused_names ]) $\\n (decl, used_gres, unused_names, unused_wcs)\\n where\\n used_gres = lookupImportMap decl import_usage\\n\\n used_gre_env = mkGlobalRdrEnv used_gres\\n used_parents = mkNameSet (mapMaybe greParent_maybe used_gres)\\n\\n (unused_names, unused_wcs) -- Not trivial; see eg #7454\\n = case imps of\\n Just (Exactly, imp_ies) ->\\n let unused = foldr (add_unused . unLoc) emptyUnusedNames imp_ies\\n nms = nameSetElemsStable (collectUnusedNames unused)\\n wcs = collectUnusedWildcards unused\\n in (nms, wcs)\\n _other -> ([], []) -- No explicit import list => no unused-name list\\n\\n add_unused :: IE GhcRn -> UnusedNames -> UnusedNames\\n add_unused (IEVar _ n _) acc = add_unused_name (lieWrappedName n) True acc\\n add_unused (IEThingAbs _ n _) acc = add_unused_name (lieWrappedName n) False acc\\n add_unused (IEThingAll _ _ n _) acc = add_unused_all (lieWrappedName n) acc\\n add_unused (IEThingWith _ p wc ns _) acc = add_wc_all (add_unused_with pn xs acc)\\n where pn = lieWrappedName p\\n xs = map lieWrappedName ns\\n add_wc_all = case wc of\\n NoIEWildcard -> id\\n IEWildcard _ -> add_unused_all pn\\n add_unused (IEWholeNamespace x ns_spec) acc = add_unused_wildcard ns_spec (iewn_names x) acc\\n add_unused _ acc = acc\\n\\n add_unused_name :: Name -> Bool -> UnusedNames -> UnusedNames\\n add_unused_name n is_ie_var acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | is_ie_var\\n , isFieldName n\\n -- See Note [Reporting unused imported duplicate record fields]\\n = let\\n fs = getOccFS n\\n (flds, flds_used) = lookupFsEnv acc_fs fs `orElse` (emptyNameSet, Any False)\\n acc_fs\' = extendFsEnv acc_fs fs (extendNameSet flds n, Any used S.<> flds_used)\\n in UnusedNames acc_ns acc_wcs acc_fs\'\\n\\n | used\\n = acc\\n\\n | otherwise\\n = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n where\\n used = isJust $ lookupGRE_Name used_gre_env n\\n\\n add_unused_all :: Name -> UnusedNames -> UnusedNames\\n add_unused_all n acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | Just {} <- lookupGRE_Name used_gre_env n = acc\\n | n `elemNameSet` used_parents = acc\\n | otherwise = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n\\n add_unused_with :: Name -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_with p ns acc\\n | all (`elemNameSet` acc1_ns) ns = add_unused_name p False acc1\\n | otherwise = acc1\\n where\\n acc1@(UnusedNames acc1_ns _ _) = foldr (\\\\n acc\' -> add_unused_name n False acc\') acc ns\\n -- If you use \'signum\' from Num, then the user may well have\\n -- imported Num(signum). We don\'t want to complain that\\n -- Num is not itself mentioned. Hence the two cases in add_unused_with.\\n\\n add_unused_wildcard :: NamespaceSpecifier GhcRn -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_wildcard ns_spec names acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | any_used = acc\\n | otherwise = UnusedNames acc_ns (ns_spec : acc_wcs) acc_fs\\n where\\n -- A wildcard `type ..` or `data ..` is used if at least one of\\n -- the names it expands to is used\\n any_used = any (isJust . lookupGRE_Name used_gre_env) names\\n\\n\\n-- | An accumulator for unused names in an import list.\\n--\\n-- See Note [Reporting unused imported duplicate record fields].\\ndata UnusedNames =\\n UnusedNames\\n { unused_names :: NameSet\\n -- ^ Unused \'Name\'s in an import list, not including record fields\\n -- that are plain \'IEVar\' imports (tracked by \'rec_fld_uses\')\\n -- or wildcard imports (tracked by \'unused_wildcards\').\\n , unused_wildcards :: [NamespaceSpecifier GhcRn]\\n -- ^ Unused wildcards @type ..@ or @data ..@ in an import list.\\n , rec_fld_uses :: FastStringEnv (NameSet, Any)\\n -- ^ Record fields imported without a parent (i.e. an \'IEVar\' import).\\n --\\n -- The \'Any\' value records whether any of the record fields\\n -- sharing the same underlying \'FastString\' have been used.\\n }\\n\\nemptyUnusedNames :: UnusedNames\\nemptyUnusedNames = UnusedNames emptyNameSet [] emptyFsEnv\\n\\ninstance Outputable UnusedNames where\\n ppr (UnusedNames nms wcs flds) =\\n text \\"UnusedNames\\" <+>\\n braces (ppr nms <+> ppr wcs <+> ppr (fmap (second getAny) flds))\\n\\n-- | Collect all unused names from a \'UnusedNames\' value.\\ncollectUnusedNames :: UnusedNames -> NameSet\\ncollectUnusedNames (UnusedNames { unused_names = nms, rec_fld_uses = flds })\\n = nms S.<> unused_flds\\n where\\n unused_flds = nonDetFoldFsEnv collect_unused emptyNameSet flds\\n collect_unused :: (NameSet, Any) -> NameSet -> NameSet\\n collect_unused (nms, Any at_least_one_name_is_used) acc\\n | at_least_one_name_is_used = acc\\n | otherwise = unionNameSet nms acc\\n\\ncollectUnusedWildcards :: UnusedNames -> [NamespaceSpecifier GhcRn]\\ncollectUnusedWildcards = unused_wildcards\\n\\n{- Note [Reporting unused imported duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have (#24035):\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M1 (R1(..), R2(..)) where\\n data R1 = MkR1 { fld :: Int }\\n data R2 = MkR2 { fld :: Int }\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M2 where\\n import M1 (R1(MkR1), R2, fld)\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nIn the import of \'M1\' in \'M2\', the \'fld\' import resolves to two separate GREs,\\nnamely R1(fld) and R2(fld). From the perspective of the renamer, and in particular\\nthe \'findImportUsage\' function, it\'s as if the user had imported the two names\\nseparately (even though no source syntax allows that).\\n\\nThis means that we need to be careful when reporting unused imports: the R2(fld)\\nimport is indeed unused, but because R1(fld) is used, we should not report\\nfld as unused altogether.\\n\\nTo achieve this, we keep track of record field imports without a parent (i.e.\\nusing the IEVar constructor) separately from other import items, using the\\nUnusedNames datatype.\\nOnce we have accumulated usages, we emit warnings for unused record fields\\nwithout parents one whole group (of record fields sharing the same textual name)\\nat a time, and only if *all* of the record fields in the group are unused;\\nsee \'collectUnusedNames\'.\\n\\nNote that this only applies to record fields imported without a parent. If we\\nhad:\\n\\n import M1 (R1(MkR1, fld), R2(fld))\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nthen of course we should report the second \'fld\' as unused.\\n-}\\n\\n\\n{- Note [The ImportMap]\\n~~~~~~~~~~~~~~~~~~~~~~~\\nThe ImportMap is a short-lived intermediate data structure records, for\\neach import declaration, what stuff brought into scope by that\\ndeclaration is actually used in the module.\\n\\nThe [GlobalRdrElt] are the things imported from that decl.\\n-}\\n\\ndata ImportMap = ImportMap\\n { im_imports :: Map RealSrcSpan [GlobalRdrElt]\\n -- ^ See [The ImportMap]\\n -- If loc :-> gres, then\\n -- \'loc\' = the end loc of the bestImport of each GRE in \'gres\'\\n , im_generatedImports :: Map ModuleName [GlobalRdrElt]\\n }\\n\\nmkImportMap :: [GlobalRdrElt] -> ImportMap\\n-- For each of a list of used GREs, find all the import decls that brought\\n-- it into scope; choose one of them (bestImport), and record\\n-- the RdrName in that import decl\'s entry in the ImportMap\\nmkImportMap = foldr insertImportMap $ ImportMap Map.empty Map.empty\\n\\ninsertImportMap :: GlobalRdrElt -> ImportMap -> ImportMap\\ninsertImportMap gre@(GRE { gre_imp = imp_specs }) importMap\\n | RealSrcSpan importSpan _ <- is_dloc best_imp_spec =\\n importMap{im_imports = insertElem importSpan gre $ im_imports importMap}\\n | GeneratedSrcSpan{} <- is_dloc best_imp_spec =\\n importMap{im_generatedImports = insertElem (moduleName $ is_mod best_imp_spec) gre $ im_generatedImports importMap}\\n | otherwise = importMap\\n where\\n best_imp_spec =\\n case bagToList imp_specs of\\n [] -> pprPanic \\"mkImportMap: GRE with no ImportSpecs\\" (ppr gre)\\n is:iss -> is_decl $ bestImport (is NE.:| iss)\\n\\n -- https://github.com/haskell/containers/issues/784\\n insertElem :: Ord k => k -> v -> Map k [v] -> Map k [v]\\n insertElem k v = flip Map.alter k $ \\\\case\\n Just vs -> Just (v : vs)\\n Nothing -> Just [v]\\n\\nlookupImportMap :: LImportDecl GhcRn -> ImportMap -> [GlobalRdrElt]\\nlookupImportMap (L srcSpan ImportDecl{ideclName = L _ modName}) importMap =\\n fromMaybe [] $\\n -- should match logic in insertImportMap\\n case locA srcSpan of\\n RealSrcSpan realSrcSpan _ -> realSrcSpan `Map.lookup` im_imports importMap\\n GeneratedSrcSpan{} -> modName `Map.lookup` im_generatedImports importMap\\n _ -> Nothing\\n\\nlieNames :: LIE (GhcPass p) -> [Located (IdP (GhcPass p))]\\nlieNames = _\\n\\nwarnUnusedImport :: GlobalRdrEnv -> ImportDeclUsage -> RnM ()\\nwarnUnusedImport rdr_env (L loc decl, used, unused, unused_wcs)\\n\\n -- Do not warn for \'import M()\'\\n -- See (UI1) in Note [Unused imports]\\n | Just (Exactly, _) <- ideclImportList decl\\n , null unused && null unused_wcs\\n = return ()\\n\\n -- Note [Do not warn about Prelude hiding]\\n | Just (EverythingBut, hides) <- ideclImportList decl\\n , not (null hides)\\n , pRELUDE_NAME == unLoc (ideclName decl)\\n = return ()\\n\\n -- Do not warn about import X as Rebindable\\n -- See (UI2) in Note [Unused imports]\\n | Just (L _ mod) <- ideclAs decl\\n , mod == rEBINDABLE_MOD_NAME\\n = return ()\\n\\n -- Nothing used; drop entire declaration\\n | null used\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl UnusedImportNone)\\n\\n -- Everything imported is used; nop\\n | null unused && null unused_wcs\\n = return ()\\n\\n -- Some imports are unused: make the `SrcSpan` cover only the unused\\n -- items instead of the whole import statement\\n | Just (_, imports) <- ideclImportList decl\\n , let unused_locs = [ locA loc | L loc ie <- imports\\n , name <- ieNames ie\\n , name `elem` unused ]\\n , loc1 : locs <- unused_locs\\n , let span = foldr1 combineSrcSpans ( loc1 NE.:| locs )\\n = addDiagnosticAt span (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n -- Some imports are unused\\n | otherwise\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n where\\n -- In warning message, pretty-print identifiers unqualified unconditionally\\n -- to improve the consistent for ambiguous/unambiguous identifiers.\\n -- See #14881.\\n possible_field n =\\n case lookupGRE_Name rdr_env n of\\n Just (GRE { gre_par = par, gre_info = IAmRecField info }) ->\\n let fld_occ :: OccName\\n fld_occ = nameOccName $ flSelector $ recFieldLabel info\\n in UnusedImportNameRecField par fld_occ\\n _ -> UnusedImportNameRegular n\\n\\n -- Print unused names in a deterministic (lexicographic) order\\n sort_unused :: [UnusedImportName]\\n sort_unused =\\n [ UnusedImportWildcard wc | wc <- unused_wcs ] ++\\n [ possible_field nm | nm <- sortBy (comparing nameOccName) unused ]\\n\\ngetMinimalImports :: [ImportDeclUsage] -> RnM [LImportDecl GhcRn]\\ngetMinimalImports ie_decls\\n = do { rdr_env <- getGlobalRdrEnv\\n ; fmap combine $ mapM (mk_minimal rdr_env) ie_decls }\\n where\\n mk_minimal rdr_env (L l decl, used_gres, unused, unused_wcs)\\n | null unused && null unused_wcs\\n , Just (Exactly, _) <- ideclImportList decl\\n = return (L l decl)\\n | otherwise\\n = do { let ImportDecl { ideclName = L _ mod_name\\n , ideclSource = is_boot\\n , ideclPkgQual = pkg_qual\\n , ideclExt = XImportDeclPass { ideclOrigin = origin } } = decl\\n ; iface <- loadSrcInterface doc (importDeclLookupScope origin)\\n mod_name is_boot pkg_qual\\n ; let used_avails = gresToAvailInfo used_gres\\n ; lies <- map (L l) <$> concatMapM (to_ie rdr_env iface) used_avails\\n ; return (L l (decl { ideclImportList = Just (Exactly, lies) })) }\\n where\\n doc = text \\"Compute minimal imports for\\" <+> ppr decl\\n\\n to_ie :: GlobalRdrEnv -> ModIface -> AvailInfo -> RnM [IE GhcRn]\\n -- The main trick here is that if we\'re importing all the constructors\\n -- we want to say \\"T(..)\\", but if we\'re importing only a subset we want\\n -- to say \\"T(A,B,C)\\". So we have to find out what the module exports.\\n to_ie rdr_env _ (Avail c) -- Note [Overloaded field import]\\n = do { let\\n gre = expectJust $ lookupGRE_Name rdr_env c\\n ; return $ [IEVar Nothing (to_ie_post_rn $ noLocA $ greName gre) Nothing] }\\n to_ie _ _ avail@(AvailTC n [_]) -- Exporting the main decl and nothing else\\n | availExportsDecl avail\\n = return [IEThingAbs Nothing (to_ie_post_rn $ noLocA n) Nothing]\\n to_ie rdr_env iface (AvailTC n cs) =\\n case [ xs | avail@(AvailTC x xs) <- mi_exports iface\\n , x == n\\n , availExportsDecl avail -- Note [Partial export]\\n ] of\\n [xs]\\n | all_used xs\\n -> return [IEThingAll (IEThingAllExt Nothing noAnn noAnn noAnn)\\n (NoNamespaceSpecifier noExtField)\\n (to_ie_post_rn $ noLocA n)\\n Nothing]\\n | otherwise\\n -> do { let ns_gres = map (expectJust . lookupGRE_Name rdr_env) cs\\n ns = map greName ns_gres\\n ; return [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n -- Note [Overloaded field import]\\n _other\\n -> do { let infos = map (expectJust . lookupGRE_Name rdr_env) cs\\n (ns_gres,fs_gres) = classifyGREs infos\\n ns = map greName (ns_gres ++ fs_gres)\\n fs = map fieldGREInfo fs_gres\\n ; return $\\n if all_non_overloaded fs\\n then map (\\\\nm -> IEVar Nothing (to_ie_post_rn_var $ noLocA nm) Nothing) ns\\n else [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n where\\n\\n all_used avail_cs = all (`elem` cs) avail_cs\\n\\n all_non_overloaded = all (not . flIsOverloaded . recFieldLabel)\\n\\n combine :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\n combine = map merge . NE.groupAllWith getKey\\n\\n getKey :: LImportDecl GhcRn -> (Bool, Maybe ModuleName, ModuleName)\\n getKey decl =\\n ( isImportDeclQualified . ideclQualified $ idecl -- is this qualified? (important that this be first)\\n , unLoc <$> ideclAs idecl -- what is the qualifier (inside Maybe monad)\\n , unLoc . ideclName $ idecl -- Module Name\\n )\\n where\\n idecl :: ImportDecl GhcRn\\n idecl = unLoc decl\\n\\n merge :: NonEmpty (LImportDecl GhcRn) -> LImportDecl GhcRn\\n merge decls@((L l decl) :| _) = L l (decl { ideclImportList = Just (Exactly, lies) })\\n where lies = concatMap snd $ mapMaybe (ideclImportList . unLoc) $ NE.toList decls\\n\\nclassifyGREs :: [GlobalRdrElt] -> ([GlobalRdrElt], [FieldGlobalRdrElt])\\nclassifyGREs = partition (not . isRecFldGRE)\\n\\nprintMinimalImports :: HscSource -> [ImportDeclUsage] -> RnM ()\\n-- See Note [Printing minimal imports]\\nprintMinimalImports hsc_src imports_w_usage\\n = do { imports\' <- excludeGenerated <$> getMinimalImports imports_w_usage\\n ; this_mod <- getModule\\n ; dflags <- getDynFlags\\n ; liftIO $ withFile (mkFilename dflags this_mod) WriteMode $ \\\\h ->\\n printForUser dflags h neverQualify AllTheWay (vcat (map ppr imports\'))\\n -- The neverQualify is important. We are printing Names\\n -- but they are in the context of an \'import\' decl, and\\n -- we never qualify things inside there\\n -- E.g. import Blag( f, b )\\n -- not import Blag( Blag.f, Blag.g )!\\n }\\n where\\n mkFilename dflags this_mod\\n | Just d <- dumpDir dflags = d basefn\\n | otherwise = basefn\\n where\\n suffix = case hsc_src of\\n HsBootFile -> \\".imports-boot\\"\\n HsSrcFile -> \\".imports\\"\\n HsigFile -> \\".imports\\"\\n basefn = moduleNameString (moduleName this_mod) ++ suffix\\n\\n\\nto_ie_post_rn_var :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn_var (L l n)\\n | isDataOcc $ occName n = L l (IEPattern noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n\\n\\nto_ie_post_rn :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn (L l n)\\n | isTcOcc occ && isSymOcc occ = L l (IEType noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n where occ = occName n\\n\\n{- Note [Do not warn about Prelude hiding]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWe do not warn about\\n import Prelude hiding( x, y )\\nbecause even if nothing else from Prelude is used, it may be essential to hide\\nx,y to avoid name-shadowing warnings. Example (#9061)\\n import Prelude hiding( log )\\n f x = log where log = ()\\n\\nNote [Unused imports]\\n~~~~~~~~~~~~~~~~~~~~~\\nIn `warnUnusedImport`, if we see an import with an explicit list imports, thus\\n import M( a, b )\\nand neither `a` nor `b` is used, we report the entire import decl as unused. We\\ncheck this by looking at the names that it brings into scope scope; if there are\\nno ununused names, don\'t report.\\n\\n(UI1) We don\'t want to complain about `import M()`, because that is often used to bring\\n M\'s /instances/ into scope. That is neatly dealt with by the \\"no unused\\n names\\" (nor unused wildcard imports) criterion.\\n\\n(UI2) We don\'t report a decl as unused if it has an `as Rebindable` qualifier.\\n See (KN1) in Note [Overview of known entities] in GHC.Builtin\\n\\n\\nNote [Printing minimal imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nTo print the minimal imports we walk over all import decls (both user-supplied\\nand generated), trim their import lists, then filter out generated decls.\\n\\nNB that\\n\\n * We do *not* change the \'qualified\' or \'as\' parts!\\n\\n * We do not discard a decl altogether; we might need instances\\n from it. Instead we just trim to an empty import list\\n\\nNote [Partial export]\\n~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have\\n\\n module A( op ) where\\n class C a where\\n op :: a -> a\\n\\n module B where\\n import A\\n f = ..op...\\n\\nThen the minimal import for module B is\\n import A( op )\\nnot\\n import A( C( op ) )\\nwhich we would usually generate if C was exported from B. Hence\\nthe availExportsDecl test when deciding what to generate.\\n\\n\\nNote [Overloaded field import]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nOn the other hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n data T = MkT { foo :: Int }\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( T(foo) )\\nbecause when DuplicateRecordFields is enabled, field selectors are\\nnot in scope without their enclosing datatype.\\n\\nOn the third hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n pattern MkT { foo } = Just foo\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( foo )\\nbecause foo doesn\'t have a parent. This might actually be ambiguous if A\\nexports another field called foo, but there is no good answer to return and this\\nis a very obscure corner, so it seems to be the best we can do. See\\nDRFPatSynExport for a test of this.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Errors}\\n* *\\n************************************************************************\\n-}\\n\\nbadImportItemErr\\n :: ModIface -> ImpDeclSpec -> IE GhcPs\\n -> IsSubordinateError\\n -> [AvailInfo]\\n -> TcRn (NonEmpty ImportLookupReason)\\nbadImportItemErr iface decl_spec ie sub avails = do\\n exts <- importLookupExtensions\\n let import_lookup_bad :: BadImportKind -> ImportLookupReason\\n import_lookup_bad k = ImportLookupBad k iface decl_spec ie exts\\n dflags <- getDynFlags\\n hsc_env <- getTopEnv\\n let rdr_env = mkGlobalRdrEnv\\n $ gresFromAvails hsc_env (Just imp_spec) all_avails\\n pure $ fmap import_lookup_bad (importErrorKind dflags rdr_env)\\n where\\n importErrorKind :: DynFlags -> GlobalRdrEnv -> NonEmpty BadImportKind\\n importErrorKind dflags rdr_env\\n | any checkIfTyCon avails = case sub of\\n IsNotSubordinate -> NE.singleton BadImportAvailTyCon\\n IsSubordinateError { subordinate_err_parent = gre\\n , subordinate_err_unavailable = unavailable\\n , subordinate_err_nontype = nontype\\n , subordinate_err_nondata = nondata }\\n -> NE.fromList $ catMaybes $\\n [ fmap (BadImportNotExportedSubordinates gre) (NE.nonEmpty unavailable)\\n , fmap (BadImportNonTypeSubordinates gre) (NE.nonEmpty nontype)\\n , fmap (BadImportNonDataSubordinates gre) (NE.nonEmpty nondata) ]\\n | any checkIfVarName avails = NE.singleton BadImportAvailVar\\n | Just con <- find checkIfDataCon avails = NE.singleton (BadImportAvailDataCon (availOccName con))\\n | otherwise = NE.singleton (BadImportNotExported suggs)\\n where\\n suggs = similar_suggs ++ fieldSelectorSuggestions rdr_env rdr\\n what_look = case sub of\\n IsNotSubordinate -> WL_TyCon_or_TermVar\\n IsSubordinateError { subordinate_err_parent = gre } ->\\n case greInfo gre of\\n IAmTyCon ClassFlavour\\n -> WL_TyCon_or_TermVar\\n _ -> WL_Term\\n similar_names =\\n similarNameSuggestions (Unbound.LF what_look WL_Global)\\n dflags rdr_env emptyLocalRdrEnv rdr\\n similar_suggs =\\n case NE.nonEmpty $ mapMaybe imported_item $ similar_names of\\n Just similar -> [ SuggestSimilarNames rdr similar ]\\n Nothing -> [ ]\\n\\n -- Only keep imported items, and set the \\"HowInScope\\" to\\n -- \\"Nothing\\" to avoid printing \\"imported from...\\" in the suggestion\\n -- error message.\\n imported_item (SimilarRdrName rdr_name gre (Just (ImportedBy {})))\\n = Just (SimilarRdrName rdr_name gre Nothing)\\n imported_item _ = Nothing\\n\\n checkIfDataCon = checkIfAvailMatches isDataConName\\n checkIfTyCon = checkIfAvailMatches isTyConName\\n checkIfVarName =\\n \\\\case\\n AvailTC{} -> False\\n Avail n -> importedFS == occNameFS (occName n)\\n && (isVarOcc <||> isFieldOcc) (occName n)\\n checkIfAvailMatches namePred =\\n \\\\case\\n AvailTC _ ns ->\\n case find (\\\\n -> importedFS == occNameFS (occName n)) ns of\\n Just n -> namePred n\\n Nothing -> False\\n Avail{} -> False\\n availOccName = occName . availName\\n rdr = ieName ie\\n importedFS = occNameFS $ rdrNameOcc rdr\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n all_avails = mi_exports iface\\n\\nimportLookupExtensions :: TcRn ImportLookupExtensions\\nimportLookupExtensions = do\\n ile_pattern_synonyms <- xoptM LangExt.PatternSynonyms\\n ile_explicit_namespaces <- xoptM LangExt.ExplicitNamespaces\\n return ImportLookupExtensions{ile_pattern_synonyms, ile_explicit_namespaces}\\n\\naddDupDeclErr :: NonEmpty GlobalRdrElt -> TcRn ()\\naddDupDeclErr gres@(gre :| _)\\n -- Report the error at the later location\\n = addErrAt (getSrcSpan (NE.last sorted_names)) $ (TcRnDuplicateDecls (greOccName gre) sorted_names)\\n where\\n sorted_names =\\n NE.sortBy (SrcLoc.leftmost_smallest `on` nameSrcSpan)\\n (fmap greName gres)\\n\\n-- This data decl will parse OK\\n-- data T = a Int\\n-- treating \\"a\\" as the constructor.\\n-- It is really hard to make the parser spot this malformation.\\n-- So the renamer has to check that the constructor is legal\\n--\\n-- We can get an operator as the constructor, even in the prefix form:\\n-- data T = :% Int Int\\n-- from interface files, which always print in prefix form\\n--\\n-- We also allow type constructor names, which are defined by \\"type data\\"\\n-- declarations. See Note [Type data declarations] in GHC.Rename.Module.\\n\\ncheckConName :: RdrName -> TcRn ()\\ncheckConName name\\n = checkErr (isRdrDataCon name || isRdrTc name) (TcRnIllegalDataCon name)\\n", "filetypes": ["haskell"]}}}' 2026-10-16 14:45:33,569 - DEBUG - POST b'http://127.0.0.1:37093/run_completer_command' {'content-type': 'application/json', 'x-ycm-hmac': b'lPMv4zINAWocPEKuKhy6E7wvQYsY+V/OMkI6BetrYVA='} b'{"filepath": "/home/enrico/ghc/compiler/GHC/Rename/Names.hs", "line_num": 2248, "column_num": 10, "working_dir": "/home/enrico/ghc", "file_data": {"/home/enrico/ghc/compiler/GHC/Rename/Names.hs": {"contents": "{-\\n(c) The GRASP/AQUA Project, Glasgow University, 1992-1998\\n\\nExtracting imported and top-level names in scope\\n-}\\n\\n{-# LANGUAGE NondecreasingIndentation #-}\\n{-# LANGUAGE TypeFamilies #-}\\n\\nmodule GHC.Rename.Names (\\n rnImports, getLocalNonValBinders, newRecordFieldLabel,\\n importsFromIface,\\n ImportUserSpec(..),\\n extendGlobalRdrEnvRn,\\n gresFromAvails,\\n calculateAvails,\\n reportUnusedNames,\\n checkConName,\\n mkChildEnv,\\n findChildren,\\n mkBadExportSubordinate,\\n findImportUsage,\\n getMinimalImports,\\n printMinimalImports,\\n renamePkgQual, renameRawPkgQual,\\n classifyGREs,\\n ImportDeclUsage,\\n rnNamespaceSpecifier\\n ) where\\n\\nimport GHC.Prelude hiding ( head, init, last, tail )\\n\\nimport GHC.Driver.Env\\nimport GHC.Driver.Session\\nimport GHC.Driver.Ppr\\n\\nimport GHC.Rename.Env\\nimport GHC.Rename.Fixity\\nimport GHC.Rename.Utils ( warnUnusedTopBinds )\\nimport GHC.Rename.Unbound\\nimport qualified GHC.Rename.Unbound as Unbound\\n\\nimport GHC.Tc.Errors.Types\\nimport GHC.Tc.Utils.Env\\nimport GHC.Tc.Utils.Monad\\nimport GHC.Tc.Types.LclEnv\\nimport GHC.Tc.Zonk.TcType ( tcInitTidyEnv )\\n\\nimport GHC.Hs\\nimport GHC.Iface.Load ( loadSrcInterface, loadSrcInterface_maybe )\\nimport GHC.Iface.Errors.Types\\n ( IfaceMessage(..), MissingInterfaceError, InterfaceLookingFor(..)\\n , LoadEssentialsReason(..) )\\nimport GHC.Iface.Syntax ( fromIfaceWarnings )\\nimport GHC.Builtin.Modules( pRELUDE_NAME, rEBINDABLE_MOD_NAME )\\nimport GHC.Parser.PostProcess ( setRdrNameSpace )\\nimport GHC.Core.TyCo.Tidy\\nimport GHC.Core.PatSyn\\nimport GHC.Core.TyCon ( TyCon, tyConName )\\nimport qualified GHC.LanguageExtensions as LangExt\\n\\nimport GHC.Utils.Outputable as Outputable\\nimport GHC.Utils.Misc as Utils\\nimport GHC.Utils.Panic\\n\\nimport GHC.Types.Fixity.Env\\nimport GHC.Types.SafeHaskell\\nimport GHC.Types.Name\\nimport GHC.Types.Name.Env\\nimport GHC.Types.Name.Set\\nimport GHC.Types.Name.Reader\\nimport GHC.Types.Avail\\nimport GHC.Types.FieldLabel\\nimport GHC.Types.Hint\\nimport GHC.Types.SourceFile\\nimport GHC.Types.SrcLoc as SrcLoc\\nimport GHC.Types.Basic (TyConFlavour (..), convImportLevel, VisArity)\\nimport GHC.Types.UnresolvedImport\\nimport GHC.Types.Id\\nimport GHC.Types.PkgQual\\nimport GHC.Types.GREInfo (ConInfo(..), ConFieldInfo (..), ConLikeInfo (ConIsData))\\n\\nimport GHC.Unit\\nimport GHC.Unit.Module.Warnings\\nimport GHC.Unit.Module.ModIface\\nimport GHC.Unit.Module.Imported\\nimport GHC.Unit.Module.Deps\\nimport GHC.Unit.Env\\n\\nimport GHC.Data.Bag\\nimport GHC.Data.FastString\\nimport GHC.Data.FastString.Env\\nimport GHC.Data.Maybe\\nimport GHC.Data.List.SetOps ( removeDups )\\n\\nimport Control.Arrow ( second )\\nimport Control.Monad\\nimport Data.Foldable ( for_ )\\nimport Data.IntMap ( IntMap )\\nimport qualified Data.IntMap as IntMap\\nimport Data.Map ( Map )\\nimport qualified Data.Map as Map\\nimport Data.Ord ( comparing )\\nimport Data.Semigroup ( Any(..) )\\nimport qualified Data.Semigroup as S\\nimport Data.List ( partition, find, sortBy )\\nimport Data.List.NonEmpty (NonEmpty(..))\\nimport qualified Data.List.NonEmpty as NE\\nimport Data.Function ( on )\\nimport qualified Data.Set as S\\nimport System.FilePath (())\\nimport System.IO\\n\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{rnImports}\\n* *\\n************************************************************************\\n\\nNote [Tracking Trust Transitively]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen we import a package as well as checking that the direct imports are safe\\naccording to the rules outlined in the Note [Safe Haskell Trust Check] in GHC.Driver.Main\\nwe must also check that these rules hold transitively for all dependent modules\\nand packages. Doing this without caching any trust information would be very\\nslow as we would need to touch all packages and interface files a module depends\\non. To avoid this we make use of the property that if a modules Safe Haskell\\nmode changes, this triggers a recompilation from that module in the dependency\\ngraph. So we can just worry mostly about direct imports.\\n\\nThere is one trust property that can change for a package though without\\nrecompilation being triggered: package trust. So we must check that all\\npackages a module transitively depends on to be trusted are still trusted when\\nwe are compiling this module (as due to recompilation avoidance some modules\\nbelow may not be considered trusted any more without recompilation being\\ntriggered).\\n\\nWe handle this by augmenting the existing transitive list of packages a module M\\ndepends on with a bool for each package that says if it must be trusted when the\\nmodule M is being checked for trust. This list of trust required packages for a\\nsingle import is gathered in the rnImportDecl function and stored in an\\nImportAvails data structure. The union of these trust required packages for all\\nimports is done by the rnImports function using the combine function which calls\\nthe plusImportAvails function that is a union operation for the ImportAvails\\ntype. This gives us in an ImportAvails structure all packages required to be\\ntrusted for the module we are currently compiling. Checking that these packages\\nare still trusted (and that direct imports are trusted) is done in\\nGHC.Driver.Main.checkSafeImports.\\n\\nSee the note below, [Trust Own Package] for a corner case in this method and\\nhow its handled.\\n\\n\\nNote [Trust Own Package]\\n~~~~~~~~~~~~~~~~~~~~~~~~\\nThere is a corner case of package trust checking that the usual transitive check\\ndoesn\'t cover. (For how the usual check operates see the Note [Tracking Trust\\nTransitively] below). The case is when you import a -XSafe module M and M\\nimports a -XTrustworthy module N. If N resides in a different package than M,\\nthen the usual check works as M will record a package dependency on N\'s package\\nand mark it as required to be trusted. If N resides in the same package as M\\nthough, then importing M should require its own package be trusted due to N\\n(since M is -XSafe so doesn\'t create this requirement by itself). The usual\\ncheck fails as a module doesn\'t record a package dependency of its own package.\\nSo instead we now have a bool field in a modules interface file that simply\\nstates if the module requires its own package to be trusted. This field avoids\\nus having to load all interface files that the module depends on to see if one\\nis trustworthy.\\n\\n\\nNote [Trust Transitive Property]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSo there is an interesting design question in regards to transitive trust\\nchecking. Say I have a module B compiled with -XSafe. B is dependent on a bunch\\nof modules and packages, some packages it requires to be trusted as its using\\n-XTrustworthy modules from them. Now if I have a module A that doesn\'t use safe\\nhaskell at all and simply imports B, should A inherit all the trust\\nrequirements from B? Should A now also require that a package p is trusted since\\nB required it?\\n\\nWe currently say no but saying yes also makes sense. The difference is, if a\\nmodule M that doesn\'t use Safe Haskell imports a module N that does, should all\\nthe trusted package requirements be dropped since M didn\'t declare that it cares\\nabout Safe Haskell (so -XSafe is more strongly associated with the module doing\\nthe importing) or should it be done still since the author of the module N that\\nuses Safe Haskell said they cared (so -XSafe is more strongly associated with\\nthe module that was compiled that used it).\\n\\nGoing with yes is a simpler semantics we think and harder for the user to stuff\\nup but it does mean that Safe Haskell will affect users who don\'t care about\\nSafe Haskell as they might grab a package from Cabal which uses safe haskell (say\\nnetwork) and that packages imports -XTrustworthy modules from another package\\n(say bytestring), so requires that package is trusted. The user may now get\\ncompilation errors in code that doesn\'t do anything with Safe Haskell simply\\nbecause they are using the network package. They will have to call \'ghc-pkg\\ntrust network\' to get everything working. Due to this invasive nature of going\\nwith yes we have gone with no for now.\\n-}\\n\\n-- | Process Import Decls. See \'rnImportDecl\' for a description of what\\n-- the return types represent.\\n-- Note: Do the non SOURCE ones first, so that we get a helpful warning\\n-- for SOURCE ones that are unnecessary\\nrnImports :: [(LImportDecl GhcPs, SDoc)]\\n -> RnM ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\nrnImports imports = do\\n tcg_env <- getGblEnv\\n -- NB: want an identity module here, because it\'s OK for a signature\\n -- module to import from its implementor\\n let this_mod = tcg_mod tcg_env\\n let (source, ordinary) = partition (is_source_import . fst) imports\\n is_source_import (d::LImportDecl GhcPs) = ideclSource (unLoc d) == IsBoot\\n stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary\\n stuff2 <- mapAndReportM (rnImportDecl this_mod) source\\n -- Safe Haskell: See Note [Tracking Trust Transitively]\\n let (decls, imp_user_spec, rdr_env, imp_avails) = combine (stuff1 ++ stuff2)\\n -- Update imp_boot_mods if imp_direct_mods mentions any of them\\n let merged_import_avail = clobberSourceImports imp_avails\\n return (decls, imp_user_spec, rdr_env, merged_import_avail)\\n\\n where\\n clobberSourceImports imp_avails =\\n imp_avails { imp_boot_mods = imp_boot_mods\' }\\n where\\n imp_boot_mods\' = mergeInstalledModuleEnv combJ id (const emptyInstalledModuleEnv)\\n (imp_boot_mods imp_avails)\\n (imp_direct_dep_mods imp_avails)\\n\\n combJ (GWIB _ IsBoot) (_, x) = Just x\\n combJ r _ = Just r\\n -- See Note [Combining ImportAvails]\\n combine :: [(LImportDecl GhcRn, ImportUserSpec, GlobalRdrEnv, ImportAvails)]\\n -> ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\n combine ss =\\n let (decls, imp_user_spec, rdr_env, imp_avails, finsts) = foldr\\n plus\\n ([], [], emptyGlobalRdrEnv, emptyImportAvails, emptyModuleSet)\\n ss\\n in (decls, imp_user_spec, rdr_env, imp_avails { imp_finsts = moduleSetElts finsts })\\n\\n plus (decl, us, gbl_env1, imp_avails1)\\n (decls, uss, gbl_env2, imp_avails2, finsts_set)\\n = ( decl:decls,\\n us:uss,\\n gbl_env1 `plusGlobalRdrEnv` gbl_env2,\\n imp_avails1\' `plusImportAvails` imp_avails2,\\n extendModuleSetList finsts_set new_finsts )\\n where\\n imp_avails1\' = imp_avails1 { imp_finsts = [] }\\n new_finsts = imp_finsts imp_avails1\\n\\n{-\\nNote [Combining ImportAvails]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nimp_finsts in ImportAvails is a list of family instance modules\\ntransitively depended on by an import. imp_finsts for a currently\\ncompiled module is a union of all the imp_finsts of imports.\\nComputing the union of two lists of size N is O(N^2) and if we\\ndo it to M imports we end up with O(M*N^2). That can get very\\nexpensive for bigger module hierarchies.\\n\\nUnion can be optimized to O(N log N) if we use a Set.\\nimp_finsts is converted back and forth between dep_finsts, so\\nchanging a type of imp_finsts means either paying for the conversions\\nor changing the type of dep_finsts as well.\\n\\nI\'ve measured that the conversions would cost 20% of allocations on my\\ntest case, so that can be ruled out.\\n\\nChanging the type of dep_finsts forces checkFamInsts to\\nget the module lists in non-deterministic order. If we wanted to restore\\nthe deterministic order, we\'d have to sort there, which is an additional\\ncost. As far as I can tell, using a non-deterministic order is fine there,\\nbut that\'s a brittle nonlocal property which I\'d like to avoid.\\n\\nAdditionally, dep_finsts is read from an interface file, so its \\"natural\\"\\ntype is a list. Which makes it a natural type for imp_finsts.\\n\\nSince rnImports.combine is really the only place that would benefit from\\nit being a Set, it makes sense to optimize the hot loop in rnImports.combine\\nwithout changing the representation.\\n\\nSo here\'s what we do: instead of naively merging ImportAvails with\\nplusImportAvails in a loop, we make plusImportAvails merge empty imp_finsts\\nand compute the union on the side using Sets. When we\'re done, we can\\nconvert it back to a list. One nice side effect of this approach is that\\nif there\'s a lot of overlap in the imp_finsts of imports, the\\nSet doesn\'t really need to grow and we don\'t need to allocate.\\n\\nRunning generateModules from #14693 with DEPTH=16, WIDTH=30 finishes in\\n23s before, and 11s after.\\n-}\\n\\n-- | Given a located import declaration @decl@ from @this_mod@,\\n-- calculate the following pieces of information:\\n--\\n-- 1. An updated \'LImportDecl\', where all unresolved \'RdrName\' in\\n-- the entity lists have been resolved into \'Name\'s,\\n--\\n-- 2. A \'GlobalRdrEnv\' representing the new identifiers that were\\n-- brought into scope (taking into account module qualification\\n-- and hiding),\\n--\\n-- 3. \'ImportAvails\' summarizing the identifiers that were imported\\n-- by this declaration, and\\n--\\n-- 4. A boolean \'AnyHpcUsage\' which is true if the imported module\\n-- used HPC.\\nrnImportDecl :: Module -> (LImportDecl GhcPs, SDoc)\\n -> RnM (LImportDecl GhcRn, ImportUserSpec , GlobalRdrEnv, ImportAvails)\\nrnImportDecl this_mod\\n (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name\\n , ideclPkgQual = raw_pkg_qual\\n , ideclSource = want_boot\\n , ideclSafe = mod_safe\\n , ideclLevelSpec = import_level\\n , ideclQualified = qual_style\\n , ideclExt = XImportDeclPass { ideclOrigin = origin }\\n , ideclAs = as_mod, ideclImportList = imp_details }), import_reason)\\n = setSrcSpanA loc $ do\\n\\n case raw_pkg_qual of\\n NoRawPkgQual -> pure ()\\n RawPkgQual {} -> do\\n pkg_imports <- xoptM LangExt.PackageImports\\n when (not pkg_imports) $ addErr TcRnPackageImportsDisabled\\n\\n let qual_only = isImportDeclQualified qual_style\\n generated = isGeneratedImport origin\\n\\n lookup_scope = importDeclLookupScope origin\\n\\n -- If there\'s an error in loadInterface, (e.g. interface\\n -- file not found) we get lots of spurious errors from \'filterImports\'\\n let imp_mod_name = unLoc loc_imp_mod_name\\n doc = ppr imp_mod_name <+> import_reason\\n\\n hsc_env <- getTopEnv\\n unit_env <- hsc_unit_env <$> getTopEnv\\n let pkg_qual = renameRawPkgQual unit_env imp_mod_name raw_pkg_qual\\n\\n -- Check for self-import, which confuses the typechecker (#9032)\\n -- ghc --make rejects self-import cycles already, but batch-mode may not\\n -- at least not until GHC.IfaceToCore.tcHiBootIface, which is too late to avoid\\n -- typechecker crashes. (Indirect self imports are not caught until\\n -- GHC.IfaceToCore, see #10337 tracking how to make this error better.)\\n --\\n -- Originally, we also allowed \'import {-# SOURCE #-} M\', but this\\n -- caused bug #10182: in one-shot mode, we should never load an hs-boot\\n -- file for the module we are compiling into the EPS. In principle,\\n -- it should be possible to support this mode of use, but we would have to\\n -- extend Provenance to support a local definition in a qualified location.\\n -- For now, we don\'t support it, but see #10336\\n when (imp_mod_name == moduleName this_mod &&\\n (case pkg_qual of -- If we have import \\"\\" M, then we should\\n -- check that \\"\\" is \\"this\\" (which is magic)\\n -- or the name of this_mod\'s package. Yurgh!\\n -- c.f. GHC.findModule, and #9997\\n NoPkgQual -> True\\n ThisPkg uid -> uid == homeUnitId_ (hsc_dflags hsc_env)\\n OtherPkg _ -> False))\\n (addErr (TcRnSelfImport imp_mod_name))\\n\\n -- Check for a missing import list (Opt_WarnMissingImportList also\\n -- checks for T(..) items but that is done in checkDodgyImport below)\\n case imp_details of\\n Just (Exactly, _) -> return () -- Explicit import list\\n _ | generated -> return () -- Do not bleat for generated imports\\n | qual_only -> return ()\\n | otherwise -> addDiagnostic (TcRnNoExplicitImportList imp_mod_name)\\n\\n\\n mb_iface <- loadSrcInterface_maybe doc lookup_scope imp_mod_name want_boot pkg_qual\\n iface <- case mb_iface of\\n Succeeded iface -> return iface\\n Failed err -> failWithTc $\\n importDeclLoadFailure origin imp_mod_name want_boot err\\n\\n -- Compiler sanity check: if the import didn\'t say\\n -- {-# SOURCE #-} we should not get a hi-boot file\\n warnPprTrace ((want_boot == NotBoot) && (mi_boot iface == IsBoot)) \\"rnImportDecl\\" (ppr imp_mod_name) $ do\\n\\n -- Issue a user warning for a redundant {- SOURCE -} import\\n -- NB that we arrange to read all the ordinary imports before\\n -- any of the {- SOURCE -} imports.\\n --\\n -- in --make and GHCi, the compilation manager checks for this,\\n -- and indeed we shouldn\'t do it here because the existence of\\n -- the non-boot module depends on the compilation order, which\\n -- is not deterministic. The hs-boot test can show this up.\\n dflags <- getDynFlags\\n warnIf ((want_boot == IsBoot) && (mi_boot iface == NotBoot) && isOneShot (ghcMode dflags))\\n (TcRnRedundantSourceImport imp_mod_name)\\n when (mod_safe && not (safeImportsOn dflags)) $\\n addErr (TcRnSafeImportsDisabled imp_mod_name)\\n\\n let imp_mod = mi_module iface\\n qual_mod_name = fmap unLoc as_mod `orElse` imp_mod_name\\n imp_spec = ImpDeclSpec { is_mod = imp_mod, is_qual = qual_only,\\n is_dloc = locA loc, is_as = qual_mod_name,\\n is_pkg_qual = pkg_qual, is_isboot = want_boot,\\n is_level = convImportLevel import_level }\\n\\n let filter_imports = do\\n -- filter the imports according to the import declaration\\n (new_imp_details, imp_user_list, gbl_env)\\n <- filterImports hsc_env iface imp_spec imp_details\\n -- for certain error messages, we\\u2019d like to know what could be\\n -- imported here, if everything were imported\\n potential_gres <- (\\\\(_,_,x) -> x) <$> filterImports hsc_env iface imp_spec Nothing\\n return (new_imp_details, imp_user_list, gbl_env, potential_gres)\\n\\n (new_imp_details, imp_user_list, gbl_env, potential_gres) <-\\n case origin of\\n ImplicitEssentialsImport ->\\n -- The implicit GHC.Essentials import does not bring anything into scope.\\n -- See Note [Finding GHC.Essentials] in GHC.Builtin.\\n return (Nothing, ImpUserDependOnly, emptyGlobalRdrEnv, emptyGlobalRdrEnv)\\n UserWrittenImport -> filter_imports\\n ImplicitPreludeImport -> filter_imports\\n PluginImport -> filter_imports\\n\\n let is_hiding | Just (EverythingBut,_) <- imp_details = True\\n | otherwise = False\\n\\n -- should the import be safe?\\n mod_safe\' = mod_safe\\n || (not generated && safeDirectImpsReq dflags)\\n || (generated && safeImplicitImpsReq dflags)\\n\\n hsc_env <- getTopEnv\\n let home_unit = hsc_home_unit hsc_env\\n other_home_units = hsc_all_home_unit_ids hsc_env\\n\\n imported_by\\n | isDependOnlyImport imp_user_list\\n = ImportedBySystem\\n | otherwise\\n = ImportedByUser $ ImportedModsVal\\n { imv_name = is_as imp_spec\\n , imv_span = locA loc\\n , imv_is_safe = mod_safe\'\\n , imv_is_hiding = is_hiding\\n , imv_all_exports = potential_gres\\n , imv_qualified = qual_only\\n , imv_is_level = convImportLevel import_level\\n }\\n imports = calculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by\\n\\n -- Complain if we import a deprecated module\\n case fromIfaceWarnings (mi_warns iface) of\\n WarnAll txt -> addDiagnostic (TcRnDeprecatedModule imp_mod_name txt)\\n _ -> return ()\\n\\n let new_imp_decl = ImportDecl\\n { ideclExt = ideclExt decl\\n , ideclName = ideclName decl\\n , ideclPkgQual = pkg_qual\\n , ideclSource = ideclSource decl\\n , ideclSafe = mod_safe\'\\n , ideclQualified = ideclQualified decl\\n , ideclAs = ideclAs decl\\n , ideclImportList = new_imp_details\\n , ideclLevelSpec = ideclLevelSpec decl\\n }\\n\\n return (L loc new_imp_decl, ImpUserSpec imp_spec imp_user_list, gbl_env, imports)\\n\\n-- | The error message to emit when we failed to load an interface.\\nimportDeclLoadFailure :: ImportDeclOrigin -> ModuleName -> IsBootInterface\\n -> MissingInterfaceError -> TcRnMessage\\nimportDeclLoadFailure ImplicitEssentialsImport _ _ err\\n = TcRnInterfaceError $ CantFindEssentials err LookingForEssentialsModule\\nimportDeclLoadFailure _ mod_name want_boot err\\n = TcRnInterfaceError $ Can\'tFindInterface err $ LookingForModule mod_name want_boot\\n\\n-- | Rename raw package imports\\nrenameRawPkgQual :: UnitEnv -> ModuleName -> RawPkgQual -> PkgQual\\nrenameRawPkgQual unit_env mn = \\\\case\\n NoRawPkgQual -> NoPkgQual\\n RawPkgQual _ fs -> renamePkgQual unit_env mn $ Just fs\\n\\n-- | Rename raw package imports\\nrenamePkgQual :: UnitEnv -> ModuleName -> Maybe FastString -> PkgQual\\nrenamePkgQual unit_env mn mb_pkg = case mb_pkg of\\n Nothing -> NoPkgQual\\n Just pkg_fs\\n | Just uid <- homeUnitId <$> ue_homeUnit unit_env\\n , pkg_fs == fsLit \\"this\\"\\n -> ThisPkg uid\\n\\n | Just (uid, _) <- find (fromMaybe False . fmap (== pkg_fs) . snd) home_names\\n -> ThisPkg uid\\n\\n | Just uid <- resolvePackageImport unit_state mn (PackageName pkg_fs)\\n -> OtherPkg uid\\n\\n | otherwise\\n -> OtherPkg (UnitId pkg_fs)\\n -- not really correct as pkg_fs is unlikely to be a valid unit-id but\\n -- we will report the failure later...\\n where\\n home_names =\\n [ (uid, mkFastString <$> thisPackageName (homeUnitEnv_dflags (ue_findHomeUnitEnv uid unit_env)))\\n | uid <- S.toList hpt_deps\\n ]\\n\\n unit_state = ue_homeUnitState unit_env\\n\\n hpt_deps :: S.Set UnitId\\n hpt_deps = homeUnitDepends unit_state\\n\\n\\n-- | Calculate the \'ImportAvails\' induced by an import of a particular\\n-- interface, but without \'imp_mods\'.\\ncalculateAvails :: HomeUnit\\n -> S.Set UnitId\\n -> ModIface\\n -> IsSafeImport\\n -> IsBootInterface\\n -> ImportedBy\\n -> ImportAvails\\ncalculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by =\\n let imp_mod = mi_module iface\\n imp_sem_mod= mi_semantic_module iface\\n orph_iface = mi_orphan iface\\n has_finsts = mi_finsts iface\\n deps = mi_deps iface\\n trust = getSafeMode $ mi_trust iface\\n trust_pkg = mi_trust_pkg iface\\n is_sig = mi_hsc_src iface == HsigFile\\n\\n -- If the module exports anything defined in this module, just\\n -- ignore it. Reason: otherwise it looks as if there are two\\n -- local definition sites for the thing, and an error gets\\n -- reported. Easiest thing is just to filter them out up\\n -- front. This situation only arises if a module imports\\n -- itself, or another module that imported it. (Necessarily,\\n -- this involves a loop.)\\n --\\n -- We do this *after* filterImports, so that if you say\\n -- module A where\\n -- import B( AType )\\n -- type AType = ...\\n --\\n -- module B( AType ) where\\n -- import {-# SOURCE #-} A( AType )\\n --\\n -- then you won\'t get a \'B does not export AType\' message.\\n\\n\\n -- Compute new transitive dependencies\\n --\\n -- \'dep_orphs\' and \'dep_finsts\' do NOT include the imported module\\n -- itself, but we DO need to include this module in \'imp_orphs\' and\\n -- \'imp_finsts\' if it defines an orphan or instance family; thus the\\n -- orph_iface/has_iface tests.\\n\\n deporphs = dep_orphs deps\\n depfinsts = dep_finsts deps\\n\\n orphans | orph_iface = assertPpr (not (imp_sem_mod `elem` deporphs)) (ppr imp_sem_mod <+> ppr deporphs) $\\n imp_sem_mod : deporphs\\n | otherwise = deporphs\\n\\n finsts | has_finsts = assertPpr (not (imp_sem_mod `elem` depfinsts)) (ppr imp_sem_mod <+> ppr depfinsts) $\\n imp_sem_mod : depfinsts\\n | otherwise = depfinsts\\n\\n -- Trusted packages are a lot like orphans.\\n trusted_pkgs | mod_safe\' = dep_trusted_pkgs deps\\n | otherwise = S.empty\\n\\n\\n pkg = moduleUnit (mi_module iface)\\n ipkg = toUnitId pkg\\n\\n -- Does this import mean we now require our own pkg\\n -- to be trusted? See Note [Trust Own Package]\\n ptrust = trust == Sf_Trustworthy || trust_pkg\\n pkg_trust_req\\n | isHomeUnit home_unit pkg = ptrust\\n | otherwise = False\\n\\n dependent_pkgs = if toUnitId pkg `S.member` other_home_units\\n then S.empty\\n else S.singleton (lvl, ipkg)\\n\\n lvl = case imported_by of\\n ImportedByUser imv -> imv_is_level imv\\n ImportedBySystem -> NormalLevel\\n\\n\\n direct_mods = if toUnitId pkg `S.member` other_home_units\\n then mkPlusModDeps (moduleUnitId imp_mod) lvl (GWIB (moduleName imp_mod) want_boot)\\n else emptyInstalledModuleEnv\\n\\n dep_boot_mods_map = mkModDeps (dep_boot_mods deps)\\n\\n\\n boot_mods\\n -- If we are looking for a boot module, it must be HPT\\n | IsBoot <- want_boot = extendInstalledModuleEnv dep_boot_mods_map (toUnitId <$> imp_mod) (GWIB (moduleName imp_mod) IsBoot)\\n -- Now we are importing A properly, so don\'t go looking for\\n -- A.hs-boot\\n | isHomeUnit home_unit pkg = dep_boot_mods_map\\n -- There\'s no boot files to find in external imports\\n | otherwise = emptyInstalledModuleEnv\\n\\n sig_mods =\\n if is_sig\\n then moduleName imp_mod : dep_sig_mods deps\\n else dep_sig_mods deps\\n\\n\\n in ImportAvails {\\n imp_mods = Map.singleton (mi_module iface) [imported_by],\\n imp_orphs = orphans,\\n imp_finsts = finsts,\\n imp_sig_mods = sig_mods,\\n imp_direct_dep_mods = direct_mods,\\n imp_dep_direct_pkgs = dependent_pkgs,\\n imp_boot_mods = boot_mods,\\n\\n -- Add in the imported modules trusted package\\n -- requirements. ONLY do this though if we import the\\n -- module as a safe import.\\n -- See Note [Tracking Trust Transitively]\\n -- and Note [Trust Transitive Property]\\n imp_trust_pkgs = trusted_pkgs,\\n -- Do we require our own pkg to be trusted?\\n -- See Note [Trust Own Package]\\n imp_trust_own_pkg = pkg_trust_req\\n }\\n\\nmkPlusModDeps :: UnitId -> ImportLevel -> ModuleNameWithIsBoot\\n -> InstalledModuleEnv (S.Set ImportLevel, ModuleNameWithIsBoot)\\nmkPlusModDeps uid st elt = extendInstalledModuleEnv emptyInstalledModuleEnv (mkModule uid (gwib_mod elt)) (S.singleton st, elt)\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{importsFromLocalDecls}\\n* *\\n************************************************************************\\n\\nFrom the top-level declarations of this module produce\\n * the lexical environment\\n * the ImportAvails\\ncreated by its bindings.\\n\\nNote [Top-level Names in Template Haskell decl quotes]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSee also: Note [Interactively-bound Ids in GHCi] in GHC.Driver.Env\\n Note [Looking up Exact RdrNames] in GHC.Rename.Env\\n\\nConsider a Template Haskell declaration quotation like this:\\n module M where\\n f x = h [d| f = 3 |]\\nWhen renaming the declarations inside [d| ...|], we treat the\\ntop level binders specially in two ways\\n\\n1. We give them an Internal Name, not (as usual) an External one.\\n This is done by GHC.Rename.Env.newTopSrcBinder.\\n\\n2. We make them *shadow* the outer bindings.\\n See Note [GlobalRdrEnv shadowing]\\n\\n3. We find out whether we are inside a [d| ... |] by testing the TH\\n level. This is a slight hack, because the level field was really\\n meant for the type checker, and here we are not interested in the\\n fields of Brack, hence the error thunks in thRnBrack.\\n-}\\n\\nextendGlobalRdrEnvRn :: [GlobalRdrElt]\\n -> MiniFixityEnv\\n -> RnM (TcGblEnv, TcLclEnv)\\n-- Updates both the GlobalRdrEnv and the FixityEnv\\n-- We return a new TcLclEnv only because we might have to\\n-- delete some bindings from it;\\n-- see Note [Top-level Names in Template Haskell decl quotes]\\n\\nextendGlobalRdrEnvRn new_gres new_fixities\\n = checkNoErrs $ -- See Note [Fail fast on duplicate definitions]\\n do { (gbl_env, lcl_env) <- getEnvs\\n ; level <- getThLevel\\n ; isGHCi <- getIsGHCi\\n ; let rdr_env = tcg_rdr_env gbl_env\\n fix_env = tcg_fix_env gbl_env\\n th_bndrs = getLclEnvThBndrs lcl_env\\n th_lvl = thLevelIndex level\\n\\n -- Delete new_occs from global and local envs\\n -- If we are in a TemplateHaskell decl bracket,\\n -- we are going to shadow them\\n -- See Note [GlobalRdrEnv shadowing]\\n inBracket = isBrackLevel level\\n\\n lcl_env_TH = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_rdr = minusLocalRdrEnv (tcl_rdr lcl_env) new_gres_env }) lcl_env\\n -- See Note [GlobalRdrEnv shadowing]\\n\\n lcl_env2 | inBracket = lcl_env_TH\\n | otherwise = lcl_env\\n\\n -- Deal with shadowing: see Note [GlobalRdrEnv shadowing]\\n want_shadowing = isGHCi || inBracket\\n rdr_env1 | want_shadowing = shadowNames False rdr_env new_gres_env\\n | otherwise = rdr_env\\n\\n lcl_env3 = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_th_bndrs = extendNameEnvList th_bndrs\\n [ ( n, (TopLevel, th_lvl) )\\n | n <- new_names ] }) lcl_env2\\n\\n ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres\\n\\n ; let fix_env\' = foldl\' extend_fix_env fix_env new_gres\\n gbl_env\' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env\' }\\n\\n ; traceRn \\"extendGlobalRdrEnvRn 2\\" (pprGlobalRdrEnv True rdr_env2)\\n ; return (gbl_env\', lcl_env3) }\\n where\\n new_names = map greName new_gres\\n new_gres_env = mkGlobalRdrEnv new_gres\\n\\n -- If there is a fixity decl for the gre, add it to the fixity env\\n extend_fix_env fix_env gre\\n | Just (L _ fi) <- lookupMiniFixityEnv new_fixities name\\n = extendNameEnv fix_env name (FixItem occ fi)\\n | otherwise\\n = fix_env\\n where\\n name = greName gre\\n occ = greOccName gre\\n\\n add_gre :: GlobalRdrEnv -> GlobalRdrElt -> RnM GlobalRdrEnv\\n -- Extend the GlobalRdrEnv with a LocalDef GRE\\n -- If there is already a LocalDef GRE with the same OccName,\\n -- report an error and discard the new GRE\\n -- This establishes INVARIANT 1 of GlobalRdrEnvs\\n add_gre env gre\\n | not (null dups) -- Same OccName defined twice\\n = do { addDupDeclErr (gre :| dups); return env }\\n\\n | otherwise\\n = return (extendGlobalRdrEnv env gre)\\n where\\n -- See Note [Reporting duplicate local declarations]\\n dups = filter isBadDupGRE\\n $ lookupGRE env (LookupOccName (greOccName gre) (RelevantGREsFOS WantBoth))\\n isBadDupGRE old_gre = isLocalGRE old_gre && greClashesWith gre old_gre\\n\\n{- Note [Fail fast on duplicate definitions]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIf there are duplicate bindings for the same thing, we want to fail\\nfast. Having two bindings for the same thing can cause follow-on errors.\\nExample (test T9975a):\\n data Test = Test { x :: Int }\\n pattern Test wat = Test { x = wat }\\nThis defines \'Test\' twice. The second defn has no field-names; and then\\nwe get an error from Test { x=wat }, saying \\"Test has no field \'x\'\\".\\n\\nEasiest thing is to bale out fast on duplicate definitions, which\\nwe do via `checkNoErrs` on `extendGlobalRdrEnvRn`.\\n\\nNote [Reporting duplicate local declarations]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn general, a single module may not define the same OccName multiple times. This\\nis checked in extendGlobalRdrEnvRn: when adding a new locally-defined GRE to the\\nGlobalRdrEnv we report an error if there are already duplicates in the\\nenvironment. This establishes INVARIANT 1 (see comments on GlobalRdrEnv in\\nGHC.Types.Name.Reader), which says that for a given OccName, all the\\nGlobalRdrElts to which it maps must have distinct \'greName\'s.\\n\\nFor example, the following will be rejected:\\n\\n f x = x\\n g x = x\\n f x = x -- Duplicate!\\n\\nUsers are allowed to introduce new GREs with the same OccName as an imported GRE,\\nas disambiguation is possible through the module system, e.g.:\\n\\n module M where\\n import N (f)\\n f x = x\\n g x = M.f x + N.f x\\n\\nIf both GREs are local, the general rule is that two GREs clash if they have\\nthe same OccName, i.e. they share a textual name and live in the same namespace.\\nHowever, there are additional clashes due to record fields:\\n\\n - a new variable clashes with previously defined record fields\\n which define field selectors,\\n\\n - a new record field shadows:\\n\\n - previously defined variables, if it defines a field selector,\\n - previously defined record fields, unless it is a duplicate record field.\\n\\nThis logic is implemented in the function \'GHC.Types.Name.Reader.greClashesWith\'.\\n\\nSee also Note [Skipping ambiguity errors at use sites of local declarations] in\\nGHC.Rename.Utils.\\n-}\\n\\n\\n{- *********************************************************************\\n* *\\n getLocalDeclBindersd@ returns the names for an HsDecl\\n It\'s used for source code.\\n\\n *** See Note [The Naming story] in GHC.Hs.Decls ****\\n* *\\n********************************************************************* -}\\n\\ngetLocalNonValBinders :: MiniFixityEnv -> HsGroup GhcPs\\n -> RnM ((TcGblEnv, TcLclEnv), NameSet)\\n-- Get all the top-level binders bound the group *except*\\n-- for value bindings, which are treated separately\\n-- Specifically we return AvailInfo for\\n-- * type decls (incl constructors and record selectors)\\n-- * class decls (including class ops)\\n-- * associated types\\n-- * foreign imports\\n-- * value signatures (in hs-boot files only)\\n\\ngetLocalNonValBinders fixity_env\\n (HsGroup { hs_valds = binds,\\n hs_tyclds = tycl_decls,\\n hs_fords = foreign_decls })\\n = do { -- Process all type/class decls *except* family instances\\n ; let inst_decls = tycl_decls >>= group_instds\\n ; dup_fields_ok <- xopt_DuplicateRecordFields <$> getDynFlags\\n ; has_sel <- xopt_FieldSelectors <$> getDynFlags\\n ; tc_gres\\n <- concatMapM\\n (new_tc dup_fields_ok has_sel)\\n (tyClGroupTyClDecls tycl_decls)\\n ; traceRn \\"getLocalNonValBinders 1\\" (ppr tc_gres)\\n ; envs <- extendGlobalRdrEnvRn tc_gres fixity_env\\n ; restoreEnvs envs $ do {\\n -- Bring these things into scope first\\n -- See Note [Looking up family names in family instances]\\n\\n -- Process all family instances\\n -- to bring new data constructors into scope\\n ; nti_gress <- mapM (new_assoc dup_fields_ok has_sel) inst_decls\\n\\n -- Finish off with value binders:\\n -- foreign decls and pattern synonyms for an ordinary module\\n -- type sigs in case of a hs-boot file only\\n ; is_boot <- tcIsHsBootOrSig\\n ; let val_bndrs\\n | is_boot = case binds of\\n ValBinds _ val_binds ->\\n -- In a hs-boot file, the value binders come from the\\n -- *signatures*, and there should be no foreign binders\\n [ L (l2l decl_loc) (unLoc n)\\n | L decl_loc (TypeSig _ _ ns _) <- (val_sigs val_binds), n <- ns]\\n _ -> panic \\"Non-ValBinds in hs-boot group\\"\\n | otherwise = for_hs_bndrs\\n ; val_gres <- mapM new_simple val_bndrs\\n\\n ; let avails = concat nti_gress ++ val_gres\\n new_bndrs = gresToNameSet avails `unionNameSet`\\n gresToNameSet tc_gres\\n ; traceRn \\"getLocalNonValBinders 2\\" (ppr avails)\\n ; envs <- extendGlobalRdrEnvRn avails fixity_env\\n ; return (envs, new_bndrs) } }\\n where\\n for_hs_bndrs :: [LocatedN RdrName]\\n for_hs_bndrs = hsForeignDeclsBinders foreign_decls\\n\\n -- the SrcSpan attached to the input should be the span of the\\n -- declaration, not just the name\\n new_simple :: LocatedN RdrName -> RnM GlobalRdrElt\\n new_simple rdr_name = do { nm <- newTopSrcBinder rdr_name\\n ; return (mkLocalVanillaGRE NoParent nm) }\\n\\n new_tc :: DuplicateRecordFields -> FieldSelectors -> LTyClDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_tc dup_fields_ok has_sel tc_decl -- NOT for type/data instances\\n = do { let TyDeclBinders (main_bndr, tc_flav) at_bndrs sig_bndrs\\n (LConsWithFields cons_with_flds flds) = hsLTyClDeclBinders tc_decl\\n ; tycon_name <- newTopSrcBinder $ la2la main_bndr\\n ; at_names <- mapM (newTopSrcBinder . la2la . fst) at_bndrs\\n ; sig_names <- mapM (newTopSrcBinder . la2la) sig_bndrs\\n ; con_names_with_flds <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst con_names_with_flds) flds\\n ; mapM_ (add_dup_fld_errs flds\') con_names_with_flds\\n ; let tc_gre = mkLocalTyConGRE (fmap (const tycon_name) tc_flav) tycon_name\\n fld_env = mk_fld_env con_names_with_flds flds\'\\n at_gres = zipWith (\\\\ (_, at_flav) at_nm -> mkLocalTyConGRE (fmap (const tycon_name) at_flav) at_nm)\\n at_bndrs at_names\\n sig_gres = map (mkLocalVanillaGRE (ParentIs tycon_name)) sig_names\\n con_gres = map (mkLocalConLikeGRE (ParentIs tycon_name)) fld_env\\n fld_gres = mkLocalFieldGREs (ParentIs tycon_name) fld_env\\n sub_gres = at_gres ++ sig_gres ++ con_gres ++ fld_gres\\n ; traceRn \\"getLocalNonValBinders new_tc\\" $\\n vcat [ text \\"tycon:\\" <+> ppr tycon_name\\n , text \\"tc_gre:\\" <+> ppr tc_gre\\n , text \\"sub_gres:\\" <+> ppr sub_gres ]\\n ; return $ tc_gre : sub_gres }\\n\\n -- Calculate the record field information, which feeds into the GlobalRdrElts\\n -- for DataCons and their fields. It\'s convenient to do this here where\\n -- we are working with a single datatype definition.\\n --\\n -- The information we needed was all set up for us:\\n -- see Note [Collecting record fields in data declarations] in GHC.Hs.Utils.\\n mk_fld_env :: [(Name, Either VisArity [Located Int])] -> IntMap FieldLabel\\n -> [(ConLikeName, ConInfo)]\\n mk_fld_env names flds =\\n [ (DataConName con, ConInfo (ConIsData (map fst names)) fld_info)\\n | (con, con_fl_indxs) <- names\\n , let fld_info = case fmap (map ((flds IntMap.!) . unLoc)) con_fl_indxs of\\n Left 0 -> ConIsNullary\\n Left arity -> ConHasPositionalArgs arity\\n Right [] -> ConIsNullary\\n Right (fld:flds) -> ConHasRecordFields $ fld NE.:| flds ]\\n\\n new_assoc :: DuplicateRecordFields -> FieldSelectors -> LInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_assoc _ _ (L _ (TyFamInstD {})) = return []\\n -- type instances don\'t bind new names\\n\\n new_assoc dup_fields_ok has_sel (L _ (DataFamInstD _ d))\\n = new_di dup_fields_ok has_sel Nothing d\\n new_assoc dup_fields_ok has_sel\\n (L _ (ClsInstD _ (ClsInstDecl { cid_poly_ty = inst_ty\\n , cid_decls = decls })))\\n = do -- First, attempt to grab the name of the class from the instance.\\n -- This step could fail if the instance is not headed by a class,\\n -- such as in the following examples:\\n --\\n -- (1) The class is headed by a bang pattern, such as in\\n -- `instance !Show Int` (#3811c)\\n -- (2) The class is headed by a type variable, such as in\\n -- `instance c` (#16385)\\n --\\n -- If looking up the class name fails, then mb_cls_gre will\\n -- be Nothing.\\n mb_cls_gre <- runMaybeT $ do\\n -- See (1) above\\n L loc cls_rdr <- MaybeT $ pure $ getLHsInstDeclClass_maybe inst_ty\\n -- See (2) above\\n MaybeT $ setSrcSpan (locA loc) $ lookupGlobalOccRn_maybe SameNameSpace cls_rdr\\n -- Assuming the previous step succeeded, process any associated data\\n -- family instances. If the previous step failed, bail out.\\n case mb_cls_gre of\\n Nothing\\n -> pure []\\n Just cls_gre\\n -> let cls_nm = greName cls_gre\\n in concatMapM (new_di dup_fields_ok has_sel (Just cls_nm) . unLoc) (data_fam_insts decls)\\n\\n data_fam_insts decls = concatMap get decls\\n where\\n get (L l (InstD _ (DataFamInstD { dfid_inst = d}))) = [L l d]\\n get _ = []\\n\\n new_di :: DuplicateRecordFields -> FieldSelectors\\n -> Maybe Name -- class name\\n -> DataFamInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_di dup_fields_ok has_sel mb_cls dfid@(DataFamInstDecl { dfid_eqn = ti_decl })\\n = do { main_name <- unLoc <$> lookupFamInstName mb_cls (feqn_tycon ti_decl)\\n ; let LConsWithFields cons_with_flds flds = hsDataFamInstBinders dfid\\n ; sub_names <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst sub_names) flds\\n ; mapM_ (add_dup_fld_errs flds\') sub_names\\n ; let fld_env = mk_fld_env sub_names flds\'\\n con_gres = map (mkLocalConLikeGRE (ParentIs main_name)) fld_env\\n field_gres = mkLocalFieldGREs (ParentIs main_name) fld_env\\n -- NB: the data family name is not bound here,\\n -- so we don\'t return a GlobalRdrElt for it here!\\n ; return $ con_gres ++ field_gres }\\n\\n -- Add errors if a constructor has a duplicate record field.\\n add_dup_fld_errs :: IntMap FieldLabel\\n -> (Name, Either VisArity [Located Int])\\n -> IOEnv (Env TcGblEnv TcLclEnv) ()\\n add_dup_fld_errs all_flds (con, con_flds_or_arity)\\n | Right con_flds <- con_flds_or_arity\\n , let (_, dups) = removeDups (comparing unLoc) con_flds\\n = for_ dups $ \\\\ dup_flds ->\\n -- Report the error at the location of the second occurrence\\n -- of the duplicate field.\\n let loc =\\n case dup_flds of\\n _ :| ( L loc _ : _) -> loc\\n L loc _ :| _ -> loc\\n dup_rdrs = fmap (nameRdrName . flSelector . (all_flds IntMap.!) . unLoc) dup_flds\\n in addErrAt loc $ TcRnDuplicateFieldName (RecordFieldDecl con) dup_rdrs\\n | otherwise\\n = return ()\\n\\nnewRecordFieldLabel :: DuplicateRecordFields -> FieldSelectors -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel\\nnewRecordFieldLabel _ _ [] _ = error \\"newRecordFieldLabel: datatype has no constructors!\\"\\nnewRecordFieldLabel dup_fields_ok has_sel (dc:_) (L loc (FieldOcc _ (L _ fld)))\\n = do { selName <- newTopSrcBinder $ L (l2l loc) $ field\\n ; return $ FieldLabel { flHasDuplicateRecordFields = dup_fields_ok\\n , flHasFieldSelector = has_sel\\n , flSelector = selName } }\\n where\\n fld_occ = rdrNameOcc fld\\n dc_fs = occNameFS $ nameOccName dc\\n field\\n -- Use an Exact RdrName as-is, to preserve the bindings\\n -- of an already renamer-resolved field and its use\\n -- sites. This is needed to correctly support record\\n -- selectors in Template Haskell. See Note [Binders in\\n -- Template Haskell] in \\"GHC.ThToHs\\" and Note [Looking up\\n -- Exact RdrNames] in \\"GHC.Rename.Env\\".\\n | isExact fld\\n = assertPpr (fieldOcc_maybe fld_occ == Just dc_fs)\\n (vcat [ text \\"newRecordFieldLabel: incorrect namespace for exact Name\\" <+> quotes (ppr fld)\\n , text \\"expected namespace:\\" <+> pprNameSpace (fieldName dc_fs)\\n , text \\" actual namespace:\\" <+> pprNameSpace (occNameSpace fld_occ) ])\\n fld\\n\\n -- Field names produced by the parser are namespaced with VarName.\\n -- Here we namespace them according to the first constructor.\\n -- See Note [Record field namespacing] in GHC.Types.Name.Occurrence.\\n | otherwise\\n = mkRdrUnqual $ varToRecFieldOcc dc_fs fld_occ\\n\\n{-\\nNote [Looking up family names in family instances]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider\\n\\n module M where\\n type family T a :: *\\n type instance M.T Int = Bool\\n\\nWe might think that we can simply use \'lookupOccRn\' when processing the type\\ninstance to look up \'M.T\'. Alas, we can\'t! The type family declaration is in\\nthe *same* HsGroup as the type instance declaration. Hence, as we are\\ncurrently collecting the binders declared in that HsGroup, these binders will\\nnot have been added to the global environment yet.\\n\\nSolution is simple: process the type family declarations first, extend\\nthe environment, and then process the type instances.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Filtering imports}\\n* *\\n************************************************************************\\n\\n@filterImports@ takes the @ExportEnv@ telling what the imported module makes\\navailable, and filters it through the import spec (if any).\\n\\nNote [Dealing with imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nFor import M( ies ), we take each AvailInfo from the mi_exports of M, and make\\n\\n imp_occ_env :: OccEnv (NameEnv ImpOccItem)\\n\\nThis map contains one entry for each OccName that M exports, mapping each OccName\\nto the following information:\\n\\n 1. the GlobalRdrElt corresponding to the OccName,\\n 2. whether this GlobalRdrElt was the parent in the AvailInfo we found\\n the OccName in.\\n 3. the GlobalRdrElts that were bundled together in the AvailInfo we found\\n this OccName in (not including the parent),\\n\\nWe need (2) and (3) during the construction of the OccEnv because of associated\\ntypes and bundled pattern synonyms, respectively.\\n(3) is explained in Note [Importing PatternSynonyms].\\n\\nTo explain (2), consider for example:\\n\\n module M where\\n class C a where { data T a }\\n instance C Int where { data T Int = T1 | T2 }\\n instance C Bool where { data T Int = T3 }\\n\\nHere, M\'s exports avails are (recalling the AvailTC invariant from GHC.Types.Avail)\\n\\n C(C,T), T(T,T1,T2,T3)\\n\\nNotice that T appears *twice*, once as a child and once as a parent. From\\nthese two exports, respectively, during construction of the imp_occ_env, we begin\\nby associating the following two elements with the key T:\\n\\n T -> ImpOccItem { imp_item = gre1, imp_bundled = [C,T] , imp_is_parent = False }\\n T -> ImpOccItem { imp_item = gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nwhere `gre1`, `gre2` are two GlobalRdrElts with greName T.\\nWe combine these (in function \'combine\' in \'mkImportOccEnv\') by discarding the\\nnon-parent item, thusly:\\n\\n T -> IE_ITem { imp_item = gre1 `plusGRE` gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nNote the `plusGRE`: this ensures we don\'t drop parent information;\\nsee Note [Preserve parent information when combining import OccEnvs].\\n\\nSo the overall imp_occ_env is:\\n\\n C -> ImpOccItem { imp_item = C, imp_bundled = [T ], imp_is_parent = True }\\n T -> ImpOccItem { imp_item = T , imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n T1 -> ImpOccItem { imp_item = T1, imp_bundled = [T1,T2,T3], imp_is_parent = False }\\n -- similarly for T2, T3\\n\\nNote that the imp_occ_env will have entries for data constructors too,\\nalthough we never look up data constructors.\\n\\nNote [Importing PatternSynonyms]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nAs described in Note [Dealing with imports], associated types can lead to the\\nsame Name appearing twice, both as a child and once as a parent, when\\nconstructing the imp_occ_env. The same thing can happen with pattern synonyms\\nif they are exported bundled with a type.\\n\\nA simplified example, based on #11959:\\n\\n {-# LANGUAGE PatternSynonyms #-}\\n module M (T(P), pattern P) where -- Duplicate export warning, but allowed\\n data T = MkT\\n pattern P = MkT\\n\\nHere we have T(P) and P in export_avails, and respectively construct both\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n P -> ImpOccItem { imp_item = P, imp_bundled = [] , imp_is_parent = False }\\n\\nWe combine these by dropping the one with no siblings, leaving us with:\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n\\nThat is, we simply discard the non-bundled Avail.\\n\\nNote [Importing DuplicateRecordFields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn filterImports, another complicating factor is DuplicateRecordFields.\\nSuppose we have:\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (S(foo), T(foo)) where\\n data S = MkS { foo :: Int }\\n data T = MkT { foo :: Int }\\n\\n module N where\\n import M (foo) -- this is allowed (A)\\n import M (S(foo)) -- this is allowed (B)\\n\\nHere M exports \'foo\' at two different OccNames, with different namespaces for\\nthe two construtors MkS and MkT. Then, when we look up \'foo\' in lookup_names\\nfor case (A), we have a variable foo but must look in all the record field\\nnamespaces to find the two fields (and hence two different Avails).\\nWhereas in case (B) we reach the lookup_ie case for IEThingWith,\\nwhich looks up \'S\' and then finds the unique \'foo\' amongst its children.\\n\\nSee T16745 for a test of this.\\n\\nNote [Preserve parent information when combining import OccEnvs]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen discarding one ImpOccItem in favour of another, as described in\\nNote [Dealing with imports], we must make sure to combine the GREs so that\\nwe don\'t lose information.\\n\\nConsider for example #24084:\\n\\n module M1 where { class C a where { type T a } }\\n module M2 ( module M1 ) where { import M1 }\\n module M3 where { import M2 ( C, T ); instance C () where T () = () }\\n\\nWhen processing the import list of `M3`, we will have two `Avail`s attached\\nto `T`, namely `C(C, T)` and `T(T)`. We combine them in the `combine` function\\nof `mkImportOccEnv`; as described in Note [Dealing with imports] we discard\\n`C(C, T)` in favour of `T(T)`. However, in doing so, we **must not**\\ndiscard the information want that `C` is the parent of `T`. Indeed,\\nlosing track of this information can cause errors when importing,\\nas we could get an error of the form\\n\\n \\u2018T\\u2019 is not a (visible) associated type of class \\u2018C\\u2019\\n\\nThis explains why we use `plusGRE` when combining the two ImpOccItems, even\\nthough we are discarding one in favour of the other.\\n-}\\n\\n-- | All the \'GlobalRdrElt\'s associated with an \'AvailInfo\'.\\ngresFromAvail :: HasDebugCallStack\\n => HscEnv -> Maybe ImportSpec -> AvailInfo -> [GlobalRdrElt]\\ngresFromAvail hsc_env prov avail =\\n [ mk_gre nm info\\n | nm <- availNames avail\\n , let info = lookupGREInfo hsc_env nm ]\\n where\\n\\n mk_gre n info\\n = case prov of\\n -- Nothing => bound locally\\n -- Just is => imported from \'is\'\\n Nothing -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = True, gre_imp = emptyBag\\n , gre_info = info }\\n Just is -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = False, gre_imp = unitBag is\\n , gre_info = info }\\n\\n-- | All the \'GlobalRdrElt\'s associated with a collection of \'AvailInfo\'s.\\ngresFromAvails :: HscEnv -> Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]\\ngresFromAvails hsc_env prov = concatMap (gresFromAvail hsc_env prov)\\n\\nimportsFromIface :: HscEnv -> ModIface -> ImpDeclSpec -> Maybe NameSet -> GlobalRdrEnv\\nimportsFromIface hsc_env iface decl_spec hidden = mkGlobalRdrEnv $ case hidden of\\n Nothing -> all_gres\\n Just hidden_names -> filter (not . (`elemNameSet` hidden_names) . greName) all_gres\\n where\\n all_gres = gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\nrnNamespaceSpecifier :: NamespaceSpecifier GhcPs -> NamespaceSpecifier GhcRn\\nrnNamespaceSpecifier (NoNamespaceSpecifier _) = NoNamespaceSpecifier noExtField\\nrnNamespaceSpecifier (TypeNamespaceSpecifier x) = TypeNamespaceSpecifier x\\nrnNamespaceSpecifier (DataNamespaceSpecifier x) = DataNamespaceSpecifier x\\n\\nfilterImports\\n :: HasDebugCallStack\\n => HscEnv\\n -> ModIface\\n -> ImpDeclSpec\\n -- ^ Import spec\\n -> Maybe (ImportListInterpretation, [LIE GhcPs])\\n -- ^ Whether this is a \\"hiding\\" import list\\n -> RnM (Maybe (ImportListInterpretation, [LIE GhcRn]), -- Import spec w/ Names\\n ImpUserList, -- same, but designed for storage in interfaces\\n GlobalRdrEnv) -- Same again, but in GRE form\\nfilterImports hsc_env iface decl_spec Nothing\\n = return (Nothing, ImpUserAll, importsFromIface hsc_env iface decl_spec Nothing)\\nfilterImports hsc_env iface decl_spec (Just (want_hiding, import_items))\\n = do -- check for errors, convert RdrNames to Names\\n items1 <- mapM lookup_lie import_items\\n\\n let items2 :: [(LIE GhcRn, [GlobalRdrElt])]\\n items2 = concat items1\\n -- NB we may have duplicates, and several items\\n -- for the same parent; e.g N(x) and N(y)\\n\\n (gres, imp_user_list) = case want_hiding of\\n Exactly ->\\n let gres = concatMap (gresFromIE decl_spec) items2\\n gre_env = mkGlobalRdrEnv gres\\n implicit_parents = mkNameSet $ mapMaybe parentOfImplicitlyImportedGRE gres\\n in (gre_env, ImpUserExplicit (gresToAvailInfo $ globalRdrEnvElts $ gre_env) implicit_parents)\\n EverythingBut ->\\n let hidden_names = mkNameSet $ concatMap (map greName . snd) items2\\n in (importsFromIface hsc_env iface decl_spec (Just hidden_names), ImpUserEverythingBut hidden_names)\\n\\n return (Just (want_hiding, map fst items2), imp_user_list, gres)\\n where\\n import_mod = mi_module iface\\n all_avails = mi_exports iface\\n imp_occ_env = mkImportOccEnv hsc_env decl_spec all_avails\\n\\n -- Look up a parent (type constructor, class or data constructor)\\n -- in an import.\\n lookup_parent :: IE GhcPs -> RdrName -> IELookupM ImpOccItem\\n lookup_parent ie rdr =\\n assertPpr (not $ isVarNameSpace ns)\\n (vcat [ text \\"filterImports lookup_parent: unexpected variable\\"\\n , text \\"rdr:\\" <+> ppr rdr\\n , text \\"namespace:\\" <+> pprNameSpace ns ]) $\\n do { xs <- lookup_names ie rdr\\n ; case xs of\\n cax :| [] -> return cax\\n _ -> pprPanic \\"filter_imports lookup_parent ambiguous\\" $\\n vcat [ text \\"rdr:\\" <+> ppr rdr\\n , text \\"lookups:\\" <+> ppr (fmap imp_item xs) ] }\\n -- Looking up non-variables is always unambiguous,\\n -- as there can be at most one corresponding item\\n -- in the imp_occ_env.\\n -- See item (1) of Note [Exporting duplicate declarations]\\n -- in GHC.Tc.Gen.Export.\\n where\\n occ = rdrNameOcc rdr\\n ns = occNameSpace occ\\n\\n -- Look up a RdrName used in an import, returning multiple values if there\\n -- are several fields with the same name exposed by the module\\n lookup_names :: IE GhcPs -> RdrName -> IELookupM (NonEmpty ImpOccItem)\\n lookup_names ie rdr\\n | isQual rdr\\n = failLookupWith (QualImportError rdr)\\n | otherwise\\n = case lookups of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n item:items -> return $ item :| items\\n where\\n lookups = concatMap nonDetNameEnvElts\\n $ lookupImpOccEnv (RelevantGREsFOS WantNormal) imp_occ_env (rdrNameOcc rdr)\\n\\n lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, [GlobalRdrElt])]\\n lookup_lie (L loc ieRdr)\\n = setSrcSpanA loc $\\n do (stuff, warns) <- run_lookup ([],[]) (lookup_ie ieRdr)\\n mapM_ (addTcRnDiagnostic <=< warning_msg) warns\\n return [ (L loc ie, gres) | (ie,gres) <- stuff ]\\n where\\n\\n -- Warn when importing T(..) and no children are brought in scope\\n warning_msg (DodgyImport reason) =\\n pure (TcRnDodgyImports reason)\\n warning_msg MissingImportList =\\n pure (TcRnMissingImportList ieRdr)\\n warning_msg (BadImportW ie sub) = do\\n -- \'BadImportW\' is only constructed below in \'bad_import_w\', in\\n -- the \'EverythingBut\' case, so here we assume a \'hiding\' clause.\\n (reason :| _) <- badImportItemErr iface decl_spec ie sub all_avails\\n pure (TcRnDodgyImports (DodgyImportsHiding reason))\\n warning_msg (DeprecatedExport n w) =\\n pure $ TcRnPragmaWarning\\n PragmaWarningExport\\n { pwarn_occname = occName n\\n , pwarn_impmod = moduleName import_mod }\\n w\\n\\n run_lookup :: a -> IELookupM a -> TcRn a\\n run_lookup def m = case m of\\n Failed err -> do\\n msgs <- lookup_err_msgs err\\n forM_ msgs $ \\\\msg -> addErr (TcRnImportLookup msg)\\n return def\\n Succeeded a -> return a\\n\\n lookup_err_msgs err = case err of\\n BadImport ie sub -> badImportItemErr iface decl_spec ie sub all_avails\\n IllegalImport -> pure $ NE.singleton ImportLookupIllegal\\n QualImportError rdr -> pure $ NE.singleton (ImportLookupQualified rdr)\\n\\n -- For each import item, we convert its RdrNames to Names,\\n -- and at the same time compute all the GlobalRdrElt corresponding\\n -- to what is actually imported by this item.\\n -- Returns Nothing on error.\\n --\\n -- Returns a list because, with DuplicateRecordFields, a naked\\n -- import/export of a record field can correspond to multiple\\n -- different GlobalRdrElts. See Note [Importing DuplicateRecordFields].\\n lookup_ie :: IE GhcPs\\n -> IELookupM ([(IE GhcRn, [GlobalRdrElt])], [IELookupWarning])\\n lookup_ie ie = handle_bad_import $\\n case ie of\\n IEVar _ (L l n) _ -> do\\n -- See Note [Importing DuplicateRecordFields]\\n xs <- lookup_names ie (ieWrappedName n)\\n let gres = map imp_item $ NE.toList xs\\n export_depr_warns\\n | want_hiding == Exactly\\n = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ( [ (IEVar Nothing (L l (replaceWrappedName n name)) noDocstring, [gre])\\n | gre <- gres\\n , let name = greName gre ]\\n , export_depr_warns )\\n\\n IEThingAll x ns_spec (L l tc) _ -> do\\n ImpOccItem { imp_item = gre\\n , imp_bundled = bundled_gres\\n , imp_is_parent = is_par\\n }\\n <- lookup_parent ie $ ieWrappedName tc\\n let name = greName gre\\n\\n child_gres :: [GlobalRdrElt]\\n child_gres\\n | is_par = filterByNamespaceSpecifierGREs ns_spec bundled_gres\\n | otherwise = []\\n\\n imp_list_warn\\n\\n | null child_gres\\n -- e.g. f(..) or T(..) where T is a type synonym\\n = [DodgyImport (DodgyImportsEmptyParent ie ns_spec gre)]\\n\\n -- e.g. import M( T(..) )\\n | not (is_qual decl_spec)\\n = [MissingImportList]\\n\\n | otherwise\\n = []\\n\\n renamed_ie = IEThingAll (x { ieta_warning = Nothing })\\n (rnNamespaceSpecifier ns_spec)\\n (L l (replaceWrappedName tc name))\\n noDocstring\\n export_depr_warn\\n | want_hiding == Exactly\\n = maybeToList $ mk_depr_export_warning gre\\n -- We don\'t want to warn about the children as they\\n -- are not explicitly mentioned; the warning will\\n -- be emitted later on if they are used\\n | otherwise = []\\n\\n return ( [(renamed_ie, gre:child_gres)]\\n , imp_list_warn ++ export_depr_warn)\\n\\n\\n IEThingAbs _ (L l tc\') _\\n | want_hiding == EverythingBut -- hiding ( C )\\n -- Here the \'C\' can be a data constructor\\n -- *or* a type/class, or even both\\n -> let tc = ieWrappedName tc\'\\n tc_name = lookup_parent ie tc\\n dc_name = lookup_parent ie (setRdrNameSpace tc srcDataName)\\n in\\n case catIELookupM [ tc_name, dc_name ] of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n names -> return ( [mkIEThingAbs tc\' l (imp_item name) | name <- names], [])\\n | otherwise\\n -> do ImpOccItem { imp_item = gre } <- lookup_parent ie (ieWrappedName tc\')\\n return ( [mkIEThingAbs tc\' l gre]\\n , maybeToList $ mk_depr_export_warning gre)\\n\\n IEThingWith (deprecation, ann) ltc@(L l rdr_tc) wc rdr_ns _ -> do\\n ImpOccItem { imp_item = gre, imp_bundled = subnames }\\n <- lookup_parent (IEThingAbs Nothing ltc noDocstring) (ieWrappedName rdr_tc)\\n let name = greName gre\\n\\n -- Look up the children in the sub-names of the parent\\n -- See Note [Importing DuplicateRecordFields]\\n let (children_errs, childnames) = lookupChildren subnames rdr_ns\\n\\n bad_import_warns <-\\n if null children_errs then return [] else\\n let items = map lce_wrapped_name children_errs\\n ie = IEThingWith (deprecation, ann) ltc wc items noDocstring\\n -- We are trying to import T( a,b,c,d ), and failed\\n -- to find \'b\' and \'d\'. So we make up an import item\\n -- to report as failing, namely T( b, d ).\\n -- c.f. #15413\\n subordinate_err = mkSubordinateError gre children_errs\\n in bad_import_w ie subordinate_err\\n\\n let name\' = replaceWrappedName rdr_tc name\\n childnames\' = map (to_ie_post_rn . fmap greName) childnames\\n gres = gre : map unLoc childnames\\n export_depr_warns\\n | want_hiding == Exactly = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ([ (IEThingWith (Nothing, ann) (L l name\') wc childnames\' noDocstring\\n ,gres)]\\n , bad_import_warns ++ export_depr_warns)\\n\\n IEWholeNamespace x ns_spec -> do\\n let mod_name = moduleName import_mod\\n names = map greName gres\\n renamed_ie = IEWholeNamespace x { iewn_warning = Nothing\\n , iewn_names = names }\\n (rnNamespaceSpecifier ns_spec)\\n gres = filterByNamespaceSpecifierGREs ns_spec $\\n gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n dodgy_warn\\n | null gres = [DodgyImport (DodgyImportsWildcard mod_name ns_spec)]\\n | otherwise = []\\n return ([(renamed_ie, gres)],\\n dodgy_warn)\\n\\n _other -> failLookupWith IllegalImport\\n -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed...\\n -- all of those constitute errors.\\n\\n where\\n mkIEThingAbs tc l gre\\n = (IEThingAbs Nothing (L l (replaceWrappedName tc n)) noDocstring, [gre])\\n where n = greName gre\\n\\n -- N.B. imports never have docstrings\\n noDocstring = Nothing\\n\\n handle_bad_import m = catchIELookup m $ \\\\case\\n BadImport ie sub -> do\\n ws <- bad_import_w ie sub\\n return ([], ws)\\n err -> failLookupWith err\\n\\n bad_import_w :: IE GhcPs -> IsSubordinateError -> IELookupM [IELookupWarning]\\n bad_import_w ie sub\\n | want_hiding == EverythingBut = return [BadImportW ie sub]\\n | otherwise = failLookupWith (BadImport ie sub)\\n\\n mk_depr_export_warning gre\\n = DeprecatedExport name <$> mi_export_warn_fn iface name\\n where\\n name = greName gre\\n\\n-- | Assuming a subordinate item could not be found, do another lookup for a\\n-- more specific error message.\\nmkBadExportSubordinate :: [GlobalRdrElt] -> LIEWrappedName GhcPs -> BadExportSubordinate\\nmkBadExportSubordinate child_gres n =\\n case lookupChildren child_gres [n] of\\n (LookupChildNonType {lce_nontype_item = g} : _, _) -> BadExportSubordinateNonType g\\n (LookupChildNonData {lce_nondata_item = g} : _, _) -> BadExportSubordinateNonData g\\n _ -> BadExportSubordinateNotFound n\\n\\ntype IELookupM = MaybeErr IELookupError\\n\\ndata IELookupWarning\\n = BadImportW (IE GhcPs) IsSubordinateError\\n | MissingImportList\\n | DodgyImport DodgyImportsReason\\n | DeprecatedExport Name (WarningTxt GhcRn)\\n\\n-- | Is this import/export item a subordinate or not?\\ndata IsSubordinateError\\n = IsSubordinateError { subordinate_err_parent :: !GlobalRdrElt\\n , subordinate_err_unavailable :: [FastString]\\n , subordinate_err_nontype :: [GlobalRdrElt]\\n , subordinate_err_nondata :: [GlobalRdrElt] }\\n | IsNotSubordinate\\n\\nmkSubordinateError :: GlobalRdrElt -> [LookupChildError] -> IsSubordinateError\\nmkSubordinateError gre children_errs = foldr add init_acc children_errs\\n where\\n init_acc :: IsSubordinateError\\n init_acc = IsSubordinateError gre [] [] []\\n\\n add :: LookupChildError -> IsSubordinateError -> IsSubordinateError\\n add children_err sub@IsSubordinateError{} =\\n case children_err of\\n LookupChildNonType{lce_nontype_item = g} ->\\n sub { subordinate_err_nontype = g : subordinate_err_nontype sub }\\n LookupChildNonData{lce_nondata_item = g} ->\\n sub { subordinate_err_nondata = g : subordinate_err_nondata sub }\\n LookupChildNotFound (L _ wname) ->\\n let fs = (occNameFS . rdrNameOcc . ieWrappedName) wname\\n in sub { subordinate_err_unavailable = fs : subordinate_err_unavailable sub }\\n add _ IsNotSubordinate = panic \\"mkSubordinateError: IsNotSubordinate\\"\\n\\ndata IELookupError\\n = QualImportError RdrName\\n | BadImport (IE GhcPs) IsSubordinateError\\n | IllegalImport\\n\\nfailLookupWith :: IELookupError -> IELookupM a\\nfailLookupWith err = Failed err\\n\\ncatchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a\\ncatchIELookup m h = case m of\\n Succeeded r -> return r\\n Failed err -> h err\\n\\ncatIELookupM :: [IELookupM a] -> [a]\\ncatIELookupM ms = [ a | Succeeded a <- ms ]\\n\\n-- | Information associated to an \'AvailInfo\' used in constructing\\n-- an \'OccEnv\' corresponding to imports.\\n--\\n-- See Note [Dealing with imports].\\ndata ImpOccItem\\n = ImpOccItem\\n { imp_item :: GlobalRdrElt\\n -- ^ The import item\\n , imp_bundled :: [GlobalRdrElt]\\n -- ^ Items bundled in the Avail this import item came from,\\n -- not including the import item itself if it is a parent.\\n , imp_is_parent :: Bool\\n -- ^ Is the import item a parent? See Note [Dealing with imports].\\n }\\n\\ninstance Outputable ImpOccItem where\\n ppr (ImpOccItem { imp_item = item, imp_bundled = bundled, imp_is_parent = is_par })\\n = braces $ hsep\\n [ text \\"ImpOccItem\\"\\n , if is_par then text \\"[is_par]\\" else empty\\n , ppr (greName item) <+> ppr (greParent item)\\n , braces $ text \\"bundled:\\" <+> ppr (map greName bundled) ]\\n\\n-- | Make an \'OccEnv\' of all the imports.\\n--\\n-- Complicated by the fact that associated data types and pattern synonyms\\n-- can appear twice. See Note [Dealing with imports].\\nmkImportOccEnv :: HscEnv -> ImpDeclSpec -> [IfaceExport] -> OccEnv (NameEnv ImpOccItem)\\nmkImportOccEnv hsc_env decl_spec all_avails =\\n mkOccEnv_C (plusNameEnv_C combine)\\n [ (occ, mkNameEnv [(nm, item)])\\n | avail <- all_avails\\n , let gres = gresFromAvail hsc_env (Just hiding_spec) avail\\n , gre <- gres\\n , let nm = greName gre\\n occ = greOccName gre\\n (is_parent, bundled) = case avail of\\n AvailTC c _\\n | c == nm -- (Recall the AvailTC invariant from GHC.Types.AvailInfo)\\n -> ( True, drop 1 gres ) -- \\"drop 1\\": don\'t include the parent itself.\\n | otherwise\\n -> ( False, gres )\\n _ -> ( False, [] )\\n item = ImpOccItem\\n { imp_item = gre\\n , imp_bundled = bundled\\n , imp_is_parent = is_parent }\\n ]\\n where\\n\\n hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\n -- See Note [Dealing with imports]\\n -- \'combine\' may be called for associated data types which appear\\n -- twice in the all_avails. In the example, we have two Avails for T,\\n -- namely T(T,T1,T2,T3) and C(C,T), and we combine them by dropping the\\n -- latter, in which T is not the parent.\\n combine :: ImpOccItem -> ImpOccItem -> ImpOccItem\\n combine item1@(ImpOccItem { imp_item = gre1, imp_is_parent = is_parent1 })\\n item2@(ImpOccItem { imp_item = gre2, imp_is_parent = is_parent2 })\\n | is_parent1 || is_parent2\\n , not (isRecFldGRE gre1 || isRecFldGRE gre2) -- NB: does not force GREInfo.\\n , let name1 = greName gre1\\n name2 = greName gre2\\n gre = gre1 `plusGRE` gre2\\n -- See Note [Preserve parent information when combining import OccEnvs]\\n = assertPpr (name1 == name2)\\n (ppr name1 <+> ppr name2) $\\n if is_parent1\\n then item1 { imp_item = gre }\\n else item2 { imp_item = gre }\\n -- Discard C(C,T) in favour of T(T, T1, T2, T3).\\n\\n -- \'combine\' may also be called for pattern synonyms which appear both\\n -- unassociated and associated (see Note [Importing PatternSynonyms]).\\n combine item1@(ImpOccItem { imp_item = c1, imp_bundled = kids1 })\\n item2@(ImpOccItem { imp_item = c2, imp_bundled = kids2 })\\n = assertPpr (greName c1 == greName c2\\n && (not (null kids1 && null kids2)))\\n (ppr c1 <+> ppr c2 <+> ppr kids1 <+> ppr kids2) $\\n if null kids1\\n then item2\\n else item1\\n -- Discard standalone pattern P in favour of T(P).\\n\\n-- | Essentially like @lookupGRE env (LookupOccName occ which_gres)@,\\n-- but working with \'ImpOccItem\'s instead of \'GlobalRdrElt\'s.\\nlookupImpOccEnv :: WhichGREs GREInfo\\n -> OccEnv (NameEnv ImpOccItem) -> OccName -> [NameEnv ImpOccItem]\\nlookupImpOccEnv which_gres env occ =\\n mapMaybe relevant_items $ lookupOccEnv_AllNameSpaces env occ\\n where\\n is_relevant :: ImpOccItem -> Bool\\n is_relevant (ImpOccItem { imp_item = gre }) =\\n greIsRelevant which_gres (occNameSpace occ) gre\\n relevant_items :: NameEnv ImpOccItem -> Maybe (NameEnv ImpOccItem)\\n relevant_items nms\\n | let nms\' = filterNameEnv is_relevant nms\\n = if isEmptyNameEnv nms\'\\n then Nothing\\n else Just nms\'\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{Import/Export Utils}\\n* *\\n************************************************************************\\n-}\\n\\n-- | Given an import\\\\/export spec, appropriately set the @gre_imp@ field\\n-- for the \'GlobalRdrElt\'s.\\ngresFromIE :: ImpDeclSpec -> (LIE GhcRn, [GlobalRdrElt]) -> [GlobalRdrElt]\\ngresFromIE decl_spec (L loc ie, gres)\\n = map set_gre_imp gres\\n where\\n is_explicit = case ie of\\n IEThingAll _ _ name _ -> \\\\n -> n == lieWrappedName name\\n IEWholeNamespace _ _ -> \\\\_ -> False\\n _ -> \\\\_ -> True\\n prov_fn name\\n = ImpSpec { is_decl = decl_spec, is_item = item_spec }\\n where\\n item_spec = ImpSome { is_explicit = is_explicit name\\n , is_iloc = locA loc }\\n set_gre_imp gre@( GRE { gre_name = nm } )\\n = gre { gre_imp = unitBag $ prov_fn nm }\\n\\nparentOfImplicitlyImportedGRE :: Outputable info => GlobalRdrEltX info -> Maybe Name\\nparentOfImplicitlyImportedGRE gre =\\n if any (explicit_import . is_item) $ gre_imp gre\\n then Nothing\\n else greParent_maybe gre\\n where\\n explicit_import :: ImpItemSpec -> Bool\\n explicit_import (ImpAll {}) =\\n pprPanic \\"parentOfImplicitlyImportedGRE: ImpAll\\" (ppr gre)\\n explicit_import (ImpSome { is_explicit }) = is_explicit\\n\\n{- Note [Children for duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider the module\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (F(foo, MkFInt, MkFBool)) where\\n data family F a\\n data instance F Int = MkFInt { foo :: Int }\\n data instance F Bool = MkFBool { foo :: Bool }\\n\\nThe `foo` in the export list refers to *both* selectors! For this\\nreason, lookupChildren builds an environment that maps the FastString\\nto a list of items, rather than a single item.\\n-}\\n\\nmkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]\\nmkChildEnv gres = foldr add emptyNameEnv gres\\n where\\n add gre env = case greParent gre of\\n ParentIs p -> extendNameEnv_Acc (:) Utils.singleton env p gre\\n NoParent -> env\\n\\nfindChildren :: NameEnv [a] -> Name -> [a]\\nfindChildren env n = lookupNameEnv env n `orElse` []\\n\\ndata LookupChildError\\n = LookupChildNotFound { lce_wrapped_name :: !(LIEWrappedName GhcPs) }\\n | LookupChildNonType { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nontype_item :: !GlobalRdrElt }\\n | LookupChildNonData { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nondata_item :: !GlobalRdrElt }\\n\\nlookupChildren :: [GlobalRdrElt]\\n -> [LIEWrappedName GhcPs]\\n -> ( [LookupChildError] -- The ones for which the lookup failed\\n , [LocatedA GlobalRdrElt] )\\n-- (lookupChildren all_kids rdr_items) maps each rdr_item to its\\n-- corresponding Name in all_kids, if the former exists\\n-- The matching is done by FastString, not OccName, so that\\n-- Cls( meth, AssocTy )\\n-- will correctly find AssocTy among the all_kids of Cls, even though\\n-- the RdrName for AssocTy may have a (bogus) DataName namespace\\n-- (Really the rdr_items should be FastStrings in the first place.)\\nlookupChildren all_kids rdr_items = (fails, successes)\\n where\\n mb_xs = map do_one rdr_items\\n fails = [ err | Failed err <- mb_xs ]\\n successes = [ ok | Succeeded oks <- mb_xs, ok <- NE.toList oks ]\\n\\n do_one :: LIEWrappedName GhcPs -> MaybeErr LookupChildError (NonEmpty (LocatedA GlobalRdrElt))\\n do_one item@(L l r) =\\n case r of\\n IEName{}\\n -- IEName (unadorned name) places no restriction on the namespace of\\n -- the imported entity, so we look in both `val_gres` and `typ_gres`.\\n -- In case of conflict (punning), the value namespace takes priority.\\n -- See Note [Prioritise the value namespace in subordinate import lists]\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEType{}\\n -- IEType (\'type\' namespace specifier) restricts the lookup to the\\n -- type namespace, i.e. to `typ_gres`. In case of failure, we check\\n -- `val_gres` to produce a more helpful error message.\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- val_gres -> Failed $ LookupChildNonType item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEData{}\\n -- IEData (\'data\' namespace specifier) restricts the lookup to the\\n -- data namespace, i.e. to `val_gres`. In case of failure, we check\\n -- `typ_gres` to produce a more helpful error message.\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- typ_gres -> Failed $ LookupChildNonData item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEPattern{} -> panic \\"lookupChildren: IEPattern\\" -- Never happens (invalid syntax)\\n IEDefault{} -> panic \\"lookupChildren: IEDefault\\" -- Never happens (invalid syntax)\\n where\\n fs = (occNameFS . rdrNameOcc . ieWrappedName) r\\n gres = fromMaybe [] (lookupFsEnv kid_env fs)\\n (val_gres, typ_gres) = partition (isValNameSpace . greNameSpace) gres\\n\\n -- See Note [Children for duplicate record fields]\\n kid_env :: FastStringEnv [GlobalRdrElt]\\n kid_env = extendFsEnvList_C (++) emptyFsEnv\\n [(occNameFS (occName x), [x]) | x <- all_kids]\\n\\n\\n{- Note [Prioritise the value namespace in subordinate import lists]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider this program that defines a class that has both an associated type\\nnamed (#) and a method named (#)\\n\\n module M_assoc where\\n class C a b where\\n type a # b\\n (#) :: a -> b -> ()\\n module N_assoc where\\n import M_assoc( C((#)) )\\n\\nIn the import declaration, when we see the unadorned name (#) in the subordinate\\nimport list of C, which children should we bring into scope? Our options are:\\n\\n a) only the method (#)\\n b) only the associated type (#)\\n c) both the method and the associated type\\n\\nTo follow the precedent established by top-level items, we go with option (a).\\nIndeed, consider a slightly different program\\n\\n module M_top where\\n type family a # b\\n a # b = ()\\n module N_top where\\n import M_top( (#) )\\n\\nHere the import brings only the function (#) into scope, and one has to say\\n`type (#)` to get the type family.\\n-}\\n\\n-------------------------------\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused names}\\n* *\\n*********************************************************\\n-}\\n\\nreportUnusedNames :: TcGblEnv -> HscSource -> RnM ()\\nreportUnusedNames gbl_env hsc_src\\n = do { keep <- readTcRef (tcg_keep gbl_env)\\n ; traceRn \\"RUN\\" (ppr (tcg_dus gbl_env))\\n ; warnUnusedImportDecls gbl_env hsc_src\\n ; warnUnusedTopBinds $ unused_locals keep\\n ; warnMissingSignatures gbl_env\\n ; warnMissingKindSignatures gbl_env }\\n where\\n used_names :: NameSet -> NameSet\\n used_names keep = findUses (tcg_dus gbl_env) emptyNameSet `unionNameSet` keep\\n -- NB: currently, if f x = g, we only treat \'g\' as used if \'f\' is used\\n -- Hence findUses\\n\\n -- Collect the defined names from the in-scope environment\\n defined_names :: [GlobalRdrElt]\\n defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)\\n\\n kids_env = mkChildEnv defined_names\\n -- This is done in mkExports too; duplicated work\\n\\n gre_is_used :: NameSet -> GlobalRdrElt -> Bool\\n gre_is_used used_names gre0\\n = name `elemNameSet` used_names\\n || any (\\\\ gre -> greName gre `elemNameSet` used_names) (findChildren kids_env name)\\n -- A use of C implies a use of T,\\n -- if C was brought into scope by T(..) or T(C)\\n where\\n name = greName gre0\\n\\n -- Filter out the ones that are\\n -- (a) defined in this module, and\\n -- (b) not defined by a \'deriving\' clause\\n -- The latter have an Internal Name, so we can filter them out easily\\n unused_locals :: NameSet -> [GlobalRdrElt]\\n unused_locals keep =\\n let -- Note that defined_and_used, defined_but_not_used\\n -- are both [GRE]; that\'s why we need defined_and_used\\n -- rather than just used_names\\n _defined_and_used, defined_but_not_used :: [GlobalRdrElt]\\n (_defined_and_used, defined_but_not_used)\\n = partition (gre_is_used (used_names keep)) defined_names\\n\\n in filter is_unused_local defined_but_not_used\\n is_unused_local :: GlobalRdrElt -> Bool\\n is_unused_local gre = isLocalGRE gre\\n && isExternalName (greName gre)\\n\\n{- *********************************************************************\\n* *\\n Missing signatures\\n* *\\n********************************************************************* -}\\n\\n{-\\nNote [Missing signatures]\\n~~~~~~~~~~~~~~~~~~~~~~~~~\\nThere are four warning flags in play:\\n\\n * -Wmissing-exported-signatures\\n Warn about any exported top-level function/value without a type signature.\\n Does not include pattern synonyms.\\n\\n * -Wmissing-signatures\\n Warn about any top-level function/value without a type signature. Does not\\n include pattern synonyms. Takes priority over -Wmissing-exported-signatures.\\n\\n * -Wmissing-exported-pattern-synonym-signatures\\n Warn about any exported pattern synonym without a type signature.\\n\\n * -Wmissing-pattern-synonym-signatures\\n Warn about any pattern synonym without a type signature. Takes priority over\\n -Wmissing-exported-pattern-synonym-signatures.\\n\\n-}\\n\\n-- | Warn the user about top level binders that lack type signatures.\\n-- Called /after/ type inference, so that we can report the\\n-- inferred type of the function\\nwarnMissingSignatures :: TcGblEnv -> RnM ()\\nwarnMissingSignatures gbl_env\\n = do { let exports = availsToNameSet (tcg_exports gbl_env)\\n sig_ns = tcg_sigs gbl_env\\n -- We use sig_ns to exclude top-level bindings that are generated by GHC\\n binds = collectHsBindsBinders CollNoDictBinders $ tcg_binds gbl_env\\n pat_syns = tcg_patsyns gbl_env\\n\\n not_ghc_generated :: Name -> Bool\\n not_ghc_generated name = name `elemNameSet` sig_ns\\n\\n add_binding_warn :: Id -> RnM ()\\n add_binding_warn id =\\n when (not_ghc_generated name) $\\n do { env <- liftZonkM $ tcInitTidyEnv -- Why not use emptyTidyEnv?\\n ; let ty = tidyOpenType env (idType id)\\n missing = MissingTopLevelBindingSig name ty\\n diag = TcRnMissingSignature missing exported\\n ; addDiagnosticAt (getSrcSpan name) diag }\\n where\\n name = idName id\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n add_patsyn_warn :: PatSyn -> RnM ()\\n add_patsyn_warn ps =\\n when (not_ghc_generated name) $\\n addDiagnosticAt (getSrcSpan name)\\n (TcRnMissingSignature missing exported)\\n where\\n name = patSynName ps\\n missing = MissingPatSynSig ps\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n -- Warn about missing signatures\\n -- Do this only when we have a type to offer\\n -- See Note [Missing signatures]\\n ; mapM_ add_binding_warn binds\\n ; mapM_ add_patsyn_warn pat_syns\\n }\\n\\n-- | Warn the user about tycons that lack kind signatures.\\n-- Called /after/ type (and kind) inference, so that we can report the\\n-- inferred kinds.\\nwarnMissingKindSignatures :: TcGblEnv -> RnM ()\\nwarnMissingKindSignatures gbl_env\\n = do { cusks_enabled <- xoptM LangExt.CUSKs\\n ; mapM_ (add_ty_warn cusks_enabled) tcs\\n }\\n where\\n tcs = tcg_tcs gbl_env\\n ksig_ns = tcg_ksigs gbl_env\\n exports = availsToNameSet (tcg_exports gbl_env)\\n\\n has_kind_signature :: Name -> Bool\\n has_kind_signature name = name `elemNameSet` ksig_ns\\n\\n add_ty_warn :: Bool -> TyCon -> RnM ()\\n add_ty_warn cusks_enabled tyCon =\\n when (has_kind_signature name) $\\n addDiagnosticAt (getSrcSpan name) diag\\n where\\n name = tyConName tyCon\\n diag = TcRnMissingSignature missing exported\\n missing = MissingTyConKindSig tyCon cusks_enabled\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused imports}\\n* *\\n*********************************************************\\n\\nThis code finds which import declarations are unused. The\\nspecification and implementation notes are here:\\n https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/unused-imports\\n\\nSee also Note [Choosing the best import declaration] in GHC.Types.Name.Reader\\n-}\\n\\ntype ImportDeclUsage\\n = ( LImportDecl GhcRn -- The import declaration\\n , [GlobalRdrElt] -- What *is* used (normalised)\\n , [Name] -- What is imported but *not* used\\n , [NamespaceSpecifier GhcRn] ) -- Unused wildcards\\n\\nwarnUnusedImportDecls :: TcGblEnv -> HscSource -> RnM ()\\nwarnUnusedImportDecls gbl_env hsc_src\\n = do { uses <- readMutVar (tcg_used_gres gbl_env)\\n ; let imports = tcg_rn_imports gbl_env\\n rdr_env = tcg_rdr_env gbl_env\\n\\n -- We should only warn for unnecessary *user* imports, but deciding\\n -- minimal imports should take generated imports into account\\n ; let usageUserImports = findImportUsage (excludeGenerated imports) uses\\n usageAllImports = findImportUsage imports uses\\n\\n ; traceRn \\"warnUnusedImportDecls\\" $\\n (vcat [ text \\"Uses:\\" <+> ppr uses\\n , text \\"Usage all user imports: \\" <+> ppr usageUserImports\\n , text \\"Usage all imports: \\" <+> ppr usageAllImports])\\n\\n ; mapM_ (warnUnusedImport rdr_env) usageUserImports\\n\\n ; whenGOptM Opt_D_dump_minimal_imports $\\n printMinimalImports hsc_src usageAllImports }\\n\\n-- | Exclude generated imports\\nexcludeGenerated :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\nexcludeGenerated = filterOut (isGeneratedImport . ideclOrigin . ideclExt . unLoc)\\n\\nfindImportUsage :: [LImportDecl GhcRn]\\n -> [GlobalRdrElt]\\n -> [ImportDeclUsage]\\n\\nfindImportUsage imports used_gres\\n = map unused_decl imports\\n where\\n import_usage :: ImportMap\\n import_usage = mkImportMap used_gres\\n\\n unused_decl :: LImportDecl GhcRn -> ImportDeclUsage\\n unused_decl decl@(L _ (ImportDecl { ideclImportList = imps }))\\n = -- pprTrace \\"unused_decl\\" (vcat [ ppr decl\\n -- , text \\"used\\" <+> ppr used_gres\\n -- , text \\"unused\\" <+> ppr unused_names ]) $\\n (decl, used_gres, unused_names, unused_wcs)\\n where\\n used_gres = lookupImportMap decl import_usage\\n\\n used_gre_env = mkGlobalRdrEnv used_gres\\n used_parents = mkNameSet (mapMaybe greParent_maybe used_gres)\\n\\n (unused_names, unused_wcs) -- Not trivial; see eg #7454\\n = case imps of\\n Just (Exactly, imp_ies) ->\\n let unused = foldr (add_unused . unLoc) emptyUnusedNames imp_ies\\n nms = nameSetElemsStable (collectUnusedNames unused)\\n wcs = collectUnusedWildcards unused\\n in (nms, wcs)\\n _other -> ([], []) -- No explicit import list => no unused-name list\\n\\n add_unused :: IE GhcRn -> UnusedNames -> UnusedNames\\n add_unused (IEVar _ n _) acc = add_unused_name (lieWrappedName n) True acc\\n add_unused (IEThingAbs _ n _) acc = add_unused_name (lieWrappedName n) False acc\\n add_unused (IEThingAll _ _ n _) acc = add_unused_all (lieWrappedName n) acc\\n add_unused (IEThingWith _ p wc ns _) acc = add_wc_all (add_unused_with pn xs acc)\\n where pn = lieWrappedName p\\n xs = map lieWrappedName ns\\n add_wc_all = case wc of\\n NoIEWildcard -> id\\n IEWildcard _ -> add_unused_all pn\\n add_unused (IEWholeNamespace x ns_spec) acc = add_unused_wildcard ns_spec (iewn_names x) acc\\n add_unused _ acc = acc\\n\\n add_unused_name :: Name -> Bool -> UnusedNames -> UnusedNames\\n add_unused_name n is_ie_var acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | is_ie_var\\n , isFieldName n\\n -- See Note [Reporting unused imported duplicate record fields]\\n = let\\n fs = getOccFS n\\n (flds, flds_used) = lookupFsEnv acc_fs fs `orElse` (emptyNameSet, Any False)\\n acc_fs\' = extendFsEnv acc_fs fs (extendNameSet flds n, Any used S.<> flds_used)\\n in UnusedNames acc_ns acc_wcs acc_fs\'\\n\\n | used\\n = acc\\n\\n | otherwise\\n = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n where\\n used = isJust $ lookupGRE_Name used_gre_env n\\n\\n add_unused_all :: Name -> UnusedNames -> UnusedNames\\n add_unused_all n acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | Just {} <- lookupGRE_Name used_gre_env n = acc\\n | n `elemNameSet` used_parents = acc\\n | otherwise = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n\\n add_unused_with :: Name -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_with p ns acc\\n | all (`elemNameSet` acc1_ns) ns = add_unused_name p False acc1\\n | otherwise = acc1\\n where\\n acc1@(UnusedNames acc1_ns _ _) = foldr (\\\\n acc\' -> add_unused_name n False acc\') acc ns\\n -- If you use \'signum\' from Num, then the user may well have\\n -- imported Num(signum). We don\'t want to complain that\\n -- Num is not itself mentioned. Hence the two cases in add_unused_with.\\n\\n add_unused_wildcard :: NamespaceSpecifier GhcRn -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_wildcard ns_spec names acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | any_used = acc\\n | otherwise = UnusedNames acc_ns (ns_spec : acc_wcs) acc_fs\\n where\\n -- A wildcard `type ..` or `data ..` is used if at least one of\\n -- the names it expands to is used\\n any_used = any (isJust . lookupGRE_Name used_gre_env) names\\n\\n\\n-- | An accumulator for unused names in an import list.\\n--\\n-- See Note [Reporting unused imported duplicate record fields].\\ndata UnusedNames =\\n UnusedNames\\n { unused_names :: NameSet\\n -- ^ Unused \'Name\'s in an import list, not including record fields\\n -- that are plain \'IEVar\' imports (tracked by \'rec_fld_uses\')\\n -- or wildcard imports (tracked by \'unused_wildcards\').\\n , unused_wildcards :: [NamespaceSpecifier GhcRn]\\n -- ^ Unused wildcards @type ..@ or @data ..@ in an import list.\\n , rec_fld_uses :: FastStringEnv (NameSet, Any)\\n -- ^ Record fields imported without a parent (i.e. an \'IEVar\' import).\\n --\\n -- The \'Any\' value records whether any of the record fields\\n -- sharing the same underlying \'FastString\' have been used.\\n }\\n\\nemptyUnusedNames :: UnusedNames\\nemptyUnusedNames = UnusedNames emptyNameSet [] emptyFsEnv\\n\\ninstance Outputable UnusedNames where\\n ppr (UnusedNames nms wcs flds) =\\n text \\"UnusedNames\\" <+>\\n braces (ppr nms <+> ppr wcs <+> ppr (fmap (second getAny) flds))\\n\\n-- | Collect all unused names from a \'UnusedNames\' value.\\ncollectUnusedNames :: UnusedNames -> NameSet\\ncollectUnusedNames (UnusedNames { unused_names = nms, rec_fld_uses = flds })\\n = nms S.<> unused_flds\\n where\\n unused_flds = nonDetFoldFsEnv collect_unused emptyNameSet flds\\n collect_unused :: (NameSet, Any) -> NameSet -> NameSet\\n collect_unused (nms, Any at_least_one_name_is_used) acc\\n | at_least_one_name_is_used = acc\\n | otherwise = unionNameSet nms acc\\n\\ncollectUnusedWildcards :: UnusedNames -> [NamespaceSpecifier GhcRn]\\ncollectUnusedWildcards = unused_wildcards\\n\\n{- Note [Reporting unused imported duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have (#24035):\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M1 (R1(..), R2(..)) where\\n data R1 = MkR1 { fld :: Int }\\n data R2 = MkR2 { fld :: Int }\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M2 where\\n import M1 (R1(MkR1), R2, fld)\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nIn the import of \'M1\' in \'M2\', the \'fld\' import resolves to two separate GREs,\\nnamely R1(fld) and R2(fld). From the perspective of the renamer, and in particular\\nthe \'findImportUsage\' function, it\'s as if the user had imported the two names\\nseparately (even though no source syntax allows that).\\n\\nThis means that we need to be careful when reporting unused imports: the R2(fld)\\nimport is indeed unused, but because R1(fld) is used, we should not report\\nfld as unused altogether.\\n\\nTo achieve this, we keep track of record field imports without a parent (i.e.\\nusing the IEVar constructor) separately from other import items, using the\\nUnusedNames datatype.\\nOnce we have accumulated usages, we emit warnings for unused record fields\\nwithout parents one whole group (of record fields sharing the same textual name)\\nat a time, and only if *all* of the record fields in the group are unused;\\nsee \'collectUnusedNames\'.\\n\\nNote that this only applies to record fields imported without a parent. If we\\nhad:\\n\\n import M1 (R1(MkR1, fld), R2(fld))\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nthen of course we should report the second \'fld\' as unused.\\n-}\\n\\n\\n{- Note [The ImportMap]\\n~~~~~~~~~~~~~~~~~~~~~~~\\nThe ImportMap is a short-lived intermediate data structure records, for\\neach import declaration, what stuff brought into scope by that\\ndeclaration is actually used in the module.\\n\\nThe [GlobalRdrElt] are the things imported from that decl.\\n-}\\n\\ndata ImportMap = ImportMap\\n { im_imports :: Map RealSrcSpan [GlobalRdrElt]\\n -- ^ See [The ImportMap]\\n -- If loc :-> gres, then\\n -- \'loc\' = the end loc of the bestImport of each GRE in \'gres\'\\n , im_generatedImports :: Map ModuleName [GlobalRdrElt]\\n }\\n\\nmkImportMap :: [GlobalRdrElt] -> ImportMap\\n-- For each of a list of used GREs, find all the import decls that brought\\n-- it into scope; choose one of them (bestImport), and record\\n-- the RdrName in that import decl\'s entry in the ImportMap\\nmkImportMap = foldr insertImportMap $ ImportMap Map.empty Map.empty\\n\\ninsertImportMap :: GlobalRdrElt -> ImportMap -> ImportMap\\ninsertImportMap gre@(GRE { gre_imp = imp_specs }) importMap\\n | RealSrcSpan importSpan _ <- is_dloc best_imp_spec =\\n importMap{im_imports = insertElem importSpan gre $ im_imports importMap}\\n | GeneratedSrcSpan{} <- is_dloc best_imp_spec =\\n importMap{im_generatedImports = insertElem (moduleName $ is_mod best_imp_spec) gre $ im_generatedImports importMap}\\n | otherwise = importMap\\n where\\n best_imp_spec =\\n case bagToList imp_specs of\\n [] -> pprPanic \\"mkImportMap: GRE with no ImportSpecs\\" (ppr gre)\\n is:iss -> is_decl $ bestImport (is NE.:| iss)\\n\\n -- https://github.com/haskell/containers/issues/784\\n insertElem :: Ord k => k -> v -> Map k [v] -> Map k [v]\\n insertElem k v = flip Map.alter k $ \\\\case\\n Just vs -> Just (v : vs)\\n Nothing -> Just [v]\\n\\nlookupImportMap :: LImportDecl GhcRn -> ImportMap -> [GlobalRdrElt]\\nlookupImportMap (L srcSpan ImportDecl{ideclName = L _ modName}) importMap =\\n fromMaybe [] $\\n -- should match logic in insertImportMap\\n case locA srcSpan of\\n RealSrcSpan realSrcSpan _ -> realSrcSpan `Map.lookup` im_imports importMap\\n GeneratedSrcSpan{} -> modName `Map.lookup` im_generatedImports importMap\\n _ -> Nothing\\n\\nlieNames :: LIE (GhcPass p) -> [Located (IdP (GhcPass p))]\\nlieNames = _\\n\\nwarnUnusedImport :: GlobalRdrEnv -> ImportDeclUsage -> RnM ()\\nwarnUnusedImport rdr_env (L loc decl, used, unused, unused_wcs)\\n\\n -- Do not warn for \'import M()\'\\n -- See (UI1) in Note [Unused imports]\\n | Just (Exactly, _) <- ideclImportList decl\\n , null unused && null unused_wcs\\n = return ()\\n\\n -- Note [Do not warn about Prelude hiding]\\n | Just (EverythingBut, hides) <- ideclImportList decl\\n , not (null hides)\\n , pRELUDE_NAME == unLoc (ideclName decl)\\n = return ()\\n\\n -- Do not warn about import X as Rebindable\\n -- See (UI2) in Note [Unused imports]\\n | Just (L _ mod) <- ideclAs decl\\n , mod == rEBINDABLE_MOD_NAME\\n = return ()\\n\\n -- Nothing used; drop entire declaration\\n | null used\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl UnusedImportNone)\\n\\n -- Everything imported is used; nop\\n | null unused && null unused_wcs\\n = return ()\\n\\n -- Some imports are unused: make the `SrcSpan` cover only the unused\\n -- items instead of the whole import statement\\n | Just (_, imports) <- ideclImportList decl\\n , let unused_locs = [ locA loc | L loc ie <- imports\\n , name <- ieNames ie\\n , name `elem` unused ]\\n , loc1 : locs <- unused_locs\\n , let span = foldr1 combineSrcSpans ( loc1 NE.:| locs )\\n = addDiagnosticAt span (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n -- Some imports are unused\\n | otherwise\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n where\\n -- In warning message, pretty-print identifiers unqualified unconditionally\\n -- to improve the consistent for ambiguous/unambiguous identifiers.\\n -- See #14881.\\n possible_field n =\\n case lookupGRE_Name rdr_env n of\\n Just (GRE { gre_par = par, gre_info = IAmRecField info }) ->\\n let fld_occ :: OccName\\n fld_occ = nameOccName $ flSelector $ recFieldLabel info\\n in UnusedImportNameRecField par fld_occ\\n _ -> UnusedImportNameRegular n\\n\\n -- Print unused names in a deterministic (lexicographic) order\\n sort_unused :: [UnusedImportName]\\n sort_unused =\\n [ UnusedImportWildcard wc | wc <- unused_wcs ] ++\\n [ possible_field nm | nm <- sortBy (comparing nameOccName) unused ]\\n\\ngetMinimalImports :: [ImportDeclUsage] -> RnM [LImportDecl GhcRn]\\ngetMinimalImports ie_decls\\n = do { rdr_env <- getGlobalRdrEnv\\n ; fmap combine $ mapM (mk_minimal rdr_env) ie_decls }\\n where\\n mk_minimal rdr_env (L l decl, used_gres, unused, unused_wcs)\\n | null unused && null unused_wcs\\n , Just (Exactly, _) <- ideclImportList decl\\n = return (L l decl)\\n | otherwise\\n = do { let ImportDecl { ideclName = L _ mod_name\\n , ideclSource = is_boot\\n , ideclPkgQual = pkg_qual\\n , ideclExt = XImportDeclPass { ideclOrigin = origin } } = decl\\n ; iface <- loadSrcInterface doc (importDeclLookupScope origin)\\n mod_name is_boot pkg_qual\\n ; let used_avails = gresToAvailInfo used_gres\\n ; lies <- map (L l) <$> concatMapM (to_ie rdr_env iface) used_avails\\n ; return (L l (decl { ideclImportList = Just (Exactly, lies) })) }\\n where\\n doc = text \\"Compute minimal imports for\\" <+> ppr decl\\n\\n to_ie :: GlobalRdrEnv -> ModIface -> AvailInfo -> RnM [IE GhcRn]\\n -- The main trick here is that if we\'re importing all the constructors\\n -- we want to say \\"T(..)\\", but if we\'re importing only a subset we want\\n -- to say \\"T(A,B,C)\\". So we have to find out what the module exports.\\n to_ie rdr_env _ (Avail c) -- Note [Overloaded field import]\\n = do { let\\n gre = expectJust $ lookupGRE_Name rdr_env c\\n ; return $ [IEVar Nothing (to_ie_post_rn $ noLocA $ greName gre) Nothing] }\\n to_ie _ _ avail@(AvailTC n [_]) -- Exporting the main decl and nothing else\\n | availExportsDecl avail\\n = return [IEThingAbs Nothing (to_ie_post_rn $ noLocA n) Nothing]\\n to_ie rdr_env iface (AvailTC n cs) =\\n case [ xs | avail@(AvailTC x xs) <- mi_exports iface\\n , x == n\\n , availExportsDecl avail -- Note [Partial export]\\n ] of\\n [xs]\\n | all_used xs\\n -> return [IEThingAll (IEThingAllExt Nothing noAnn noAnn noAnn)\\n (NoNamespaceSpecifier noExtField)\\n (to_ie_post_rn $ noLocA n)\\n Nothing]\\n | otherwise\\n -> do { let ns_gres = map (expectJust . lookupGRE_Name rdr_env) cs\\n ns = map greName ns_gres\\n ; return [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n -- Note [Overloaded field import]\\n _other\\n -> do { let infos = map (expectJust . lookupGRE_Name rdr_env) cs\\n (ns_gres,fs_gres) = classifyGREs infos\\n ns = map greName (ns_gres ++ fs_gres)\\n fs = map fieldGREInfo fs_gres\\n ; return $\\n if all_non_overloaded fs\\n then map (\\\\nm -> IEVar Nothing (to_ie_post_rn_var $ noLocA nm) Nothing) ns\\n else [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n where\\n\\n all_used avail_cs = all (`elem` cs) avail_cs\\n\\n all_non_overloaded = all (not . flIsOverloaded . recFieldLabel)\\n\\n combine :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\n combine = map merge . NE.groupAllWith getKey\\n\\n getKey :: LImportDecl GhcRn -> (Bool, Maybe ModuleName, ModuleName)\\n getKey decl =\\n ( isImportDeclQualified . ideclQualified $ idecl -- is this qualified? (important that this be first)\\n , unLoc <$> ideclAs idecl -- what is the qualifier (inside Maybe monad)\\n , unLoc . ideclName $ idecl -- Module Name\\n )\\n where\\n idecl :: ImportDecl GhcRn\\n idecl = unLoc decl\\n\\n merge :: NonEmpty (LImportDecl GhcRn) -> LImportDecl GhcRn\\n merge decls@((L l decl) :| _) = L l (decl { ideclImportList = Just (Exactly, lies) })\\n where lies = concatMap snd $ mapMaybe (ideclImportList . unLoc) $ NE.toList decls\\n\\nclassifyGREs :: [GlobalRdrElt] -> ([GlobalRdrElt], [FieldGlobalRdrElt])\\nclassifyGREs = partition (not . isRecFldGRE)\\n\\nprintMinimalImports :: HscSource -> [ImportDeclUsage] -> RnM ()\\n-- See Note [Printing minimal imports]\\nprintMinimalImports hsc_src imports_w_usage\\n = do { imports\' <- excludeGenerated <$> getMinimalImports imports_w_usage\\n ; this_mod <- getModule\\n ; dflags <- getDynFlags\\n ; liftIO $ withFile (mkFilename dflags this_mod) WriteMode $ \\\\h ->\\n printForUser dflags h neverQualify AllTheWay (vcat (map ppr imports\'))\\n -- The neverQualify is important. We are printing Names\\n -- but they are in the context of an \'import\' decl, and\\n -- we never qualify things inside there\\n -- E.g. import Blag( f, b )\\n -- not import Blag( Blag.f, Blag.g )!\\n }\\n where\\n mkFilename dflags this_mod\\n | Just d <- dumpDir dflags = d basefn\\n | otherwise = basefn\\n where\\n suffix = case hsc_src of\\n HsBootFile -> \\".imports-boot\\"\\n HsSrcFile -> \\".imports\\"\\n HsigFile -> \\".imports\\"\\n basefn = moduleNameString (moduleName this_mod) ++ suffix\\n\\n\\nto_ie_post_rn_var :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn_var (L l n)\\n | isDataOcc $ occName n = L l (IEPattern noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n\\n\\nto_ie_post_rn :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn (L l n)\\n | isTcOcc occ && isSymOcc occ = L l (IEType noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n where occ = occName n\\n\\n{- Note [Do not warn about Prelude hiding]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWe do not warn about\\n import Prelude hiding( x, y )\\nbecause even if nothing else from Prelude is used, it may be essential to hide\\nx,y to avoid name-shadowing warnings. Example (#9061)\\n import Prelude hiding( log )\\n f x = log where log = ()\\n\\nNote [Unused imports]\\n~~~~~~~~~~~~~~~~~~~~~\\nIn `warnUnusedImport`, if we see an import with an explicit list imports, thus\\n import M( a, b )\\nand neither `a` nor `b` is used, we report the entire import decl as unused. We\\ncheck this by looking at the names that it brings into scope scope; if there are\\nno ununused names, don\'t report.\\n\\n(UI1) We don\'t want to complain about `import M()`, because that is often used to bring\\n M\'s /instances/ into scope. That is neatly dealt with by the \\"no unused\\n names\\" (nor unused wildcard imports) criterion.\\n\\n(UI2) We don\'t report a decl as unused if it has an `as Rebindable` qualifier.\\n See (KN1) in Note [Overview of known entities] in GHC.Builtin\\n\\n\\nNote [Printing minimal imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nTo print the minimal imports we walk over all import decls (both user-supplied\\nand generated), trim their import lists, then filter out generated decls.\\n\\nNB that\\n\\n * We do *not* change the \'qualified\' or \'as\' parts!\\n\\n * We do not discard a decl altogether; we might need instances\\n from it. Instead we just trim to an empty import list\\n\\nNote [Partial export]\\n~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have\\n\\n module A( op ) where\\n class C a where\\n op :: a -> a\\n\\n module B where\\n import A\\n f = ..op...\\n\\nThen the minimal import for module B is\\n import A( op )\\nnot\\n import A( C( op ) )\\nwhich we would usually generate if C was exported from B. Hence\\nthe availExportsDecl test when deciding what to generate.\\n\\n\\nNote [Overloaded field import]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nOn the other hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n data T = MkT { foo :: Int }\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( T(foo) )\\nbecause when DuplicateRecordFields is enabled, field selectors are\\nnot in scope without their enclosing datatype.\\n\\nOn the third hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n pattern MkT { foo } = Just foo\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( foo )\\nbecause foo doesn\'t have a parent. This might actually be ambiguous if A\\nexports another field called foo, but there is no good answer to return and this\\nis a very obscure corner, so it seems to be the best we can do. See\\nDRFPatSynExport for a test of this.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Errors}\\n* *\\n************************************************************************\\n-}\\n\\nbadImportItemErr\\n :: ModIface -> ImpDeclSpec -> IE GhcPs\\n -> IsSubordinateError\\n -> [AvailInfo]\\n -> TcRn (NonEmpty ImportLookupReason)\\nbadImportItemErr iface decl_spec ie sub avails = do\\n exts <- importLookupExtensions\\n let import_lookup_bad :: BadImportKind -> ImportLookupReason\\n import_lookup_bad k = ImportLookupBad k iface decl_spec ie exts\\n dflags <- getDynFlags\\n hsc_env <- getTopEnv\\n let rdr_env = mkGlobalRdrEnv\\n $ gresFromAvails hsc_env (Just imp_spec) all_avails\\n pure $ fmap import_lookup_bad (importErrorKind dflags rdr_env)\\n where\\n importErrorKind :: DynFlags -> GlobalRdrEnv -> NonEmpty BadImportKind\\n importErrorKind dflags rdr_env\\n | any checkIfTyCon avails = case sub of\\n IsNotSubordinate -> NE.singleton BadImportAvailTyCon\\n IsSubordinateError { subordinate_err_parent = gre\\n , subordinate_err_unavailable = unavailable\\n , subordinate_err_nontype = nontype\\n , subordinate_err_nondata = nondata }\\n -> NE.fromList $ catMaybes $\\n [ fmap (BadImportNotExportedSubordinates gre) (NE.nonEmpty unavailable)\\n , fmap (BadImportNonTypeSubordinates gre) (NE.nonEmpty nontype)\\n , fmap (BadImportNonDataSubordinates gre) (NE.nonEmpty nondata) ]\\n | any checkIfVarName avails = NE.singleton BadImportAvailVar\\n | Just con <- find checkIfDataCon avails = NE.singleton (BadImportAvailDataCon (availOccName con))\\n | otherwise = NE.singleton (BadImportNotExported suggs)\\n where\\n suggs = similar_suggs ++ fieldSelectorSuggestions rdr_env rdr\\n what_look = case sub of\\n IsNotSubordinate -> WL_TyCon_or_TermVar\\n IsSubordinateError { subordinate_err_parent = gre } ->\\n case greInfo gre of\\n IAmTyCon ClassFlavour\\n -> WL_TyCon_or_TermVar\\n _ -> WL_Term\\n similar_names =\\n similarNameSuggestions (Unbound.LF what_look WL_Global)\\n dflags rdr_env emptyLocalRdrEnv rdr\\n similar_suggs =\\n case NE.nonEmpty $ mapMaybe imported_item $ similar_names of\\n Just similar -> [ SuggestSimilarNames rdr similar ]\\n Nothing -> [ ]\\n\\n -- Only keep imported items, and set the \\"HowInScope\\" to\\n -- \\"Nothing\\" to avoid printing \\"imported from...\\" in the suggestion\\n -- error message.\\n imported_item (SimilarRdrName rdr_name gre (Just (ImportedBy {})))\\n = Just (SimilarRdrName rdr_name gre Nothing)\\n imported_item _ = Nothing\\n\\n checkIfDataCon = checkIfAvailMatches isDataConName\\n checkIfTyCon = checkIfAvailMatches isTyConName\\n checkIfVarName =\\n \\\\case\\n AvailTC{} -> False\\n Avail n -> importedFS == occNameFS (occName n)\\n && (isVarOcc <||> isFieldOcc) (occName n)\\n checkIfAvailMatches namePred =\\n \\\\case\\n AvailTC _ ns ->\\n case find (\\\\n -> importedFS == occNameFS (occName n)) ns of\\n Just n -> namePred n\\n Nothing -> False\\n Avail{} -> False\\n availOccName = occName . availName\\n rdr = ieName ie\\n importedFS = occNameFS $ rdrNameOcc rdr\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n all_avails = mi_exports iface\\n\\nimportLookupExtensions :: TcRn ImportLookupExtensions\\nimportLookupExtensions = do\\n ile_pattern_synonyms <- xoptM LangExt.PatternSynonyms\\n ile_explicit_namespaces <- xoptM LangExt.ExplicitNamespaces\\n return ImportLookupExtensions{ile_pattern_synonyms, ile_explicit_namespaces}\\n\\naddDupDeclErr :: NonEmpty GlobalRdrElt -> TcRn ()\\naddDupDeclErr gres@(gre :| _)\\n -- Report the error at the later location\\n = addErrAt (getSrcSpan (NE.last sorted_names)) $ (TcRnDuplicateDecls (greOccName gre) sorted_names)\\n where\\n sorted_names =\\n NE.sortBy (SrcLoc.leftmost_smallest `on` nameSrcSpan)\\n (fmap greName gres)\\n\\n-- This data decl will parse OK\\n-- data T = a Int\\n-- treating \\"a\\" as the constructor.\\n-- It is really hard to make the parser spot this malformation.\\n-- So the renamer has to check that the constructor is legal\\n--\\n-- We can get an operator as the constructor, even in the prefix form:\\n-- data T = :% Int Int\\n-- from interface files, which always print in prefix form\\n--\\n-- We also allow type constructor names, which are defined by \\"type data\\"\\n-- declarations. See Note [Type data declarations] in GHC.Rename.Module.\\n\\ncheckConName :: RdrName -> TcRn ()\\ncheckConName name\\n = checkErr (isRdrDataCon name || isRdrTc name) (TcRnIllegalDataCon name)\\n", "filetypes": ["haskell"]}}, "options": {"tab_size": 8, "insert_spaces": false}, "command_arguments": ["GetHover"]}' 2026-10-16 14:45:40,343 - DEBUG - POST b'http://127.0.0.1:37093/receive_messages' {'content-type': 'application/json', 'x-ycm-hmac': b'Rga7Yd4l4fgfufwYw+0sxzurvznImlBO0MPmgAlS4EY='} b'{"filepath": "/home/enrico/ghc/compiler/GHC/Rename/Names.hs", "line_num": 1, "column_num": 1, "working_dir": "/home/enrico/ghc", "file_data": {"/home/enrico/ghc/compiler/GHC/Rename/Names.hs": {"contents": "{-\\n(c) The GRASP/AQUA Project, Glasgow University, 1992-1998\\n\\nExtracting imported and top-level names in scope\\n-}\\n\\n{-# LANGUAGE NondecreasingIndentation #-}\\n{-# LANGUAGE TypeFamilies #-}\\n\\nmodule GHC.Rename.Names (\\n rnImports, getLocalNonValBinders, newRecordFieldLabel,\\n importsFromIface,\\n ImportUserSpec(..),\\n extendGlobalRdrEnvRn,\\n gresFromAvails,\\n calculateAvails,\\n reportUnusedNames,\\n checkConName,\\n mkChildEnv,\\n findChildren,\\n mkBadExportSubordinate,\\n findImportUsage,\\n getMinimalImports,\\n printMinimalImports,\\n renamePkgQual, renameRawPkgQual,\\n classifyGREs,\\n ImportDeclUsage,\\n rnNamespaceSpecifier\\n ) where\\n\\nimport GHC.Prelude hiding ( head, init, last, tail )\\n\\nimport GHC.Driver.Env\\nimport GHC.Driver.Session\\nimport GHC.Driver.Ppr\\n\\nimport GHC.Rename.Env\\nimport GHC.Rename.Fixity\\nimport GHC.Rename.Utils ( warnUnusedTopBinds )\\nimport GHC.Rename.Unbound\\nimport qualified GHC.Rename.Unbound as Unbound\\n\\nimport GHC.Tc.Errors.Types\\nimport GHC.Tc.Utils.Env\\nimport GHC.Tc.Utils.Monad\\nimport GHC.Tc.Types.LclEnv\\nimport GHC.Tc.Zonk.TcType ( tcInitTidyEnv )\\n\\nimport GHC.Hs\\nimport GHC.Iface.Load ( loadSrcInterface, loadSrcInterface_maybe )\\nimport GHC.Iface.Errors.Types\\n ( IfaceMessage(..), MissingInterfaceError, InterfaceLookingFor(..)\\n , LoadEssentialsReason(..) )\\nimport GHC.Iface.Syntax ( fromIfaceWarnings )\\nimport GHC.Builtin.Modules( pRELUDE_NAME, rEBINDABLE_MOD_NAME )\\nimport GHC.Parser.PostProcess ( setRdrNameSpace )\\nimport GHC.Core.TyCo.Tidy\\nimport GHC.Core.PatSyn\\nimport GHC.Core.TyCon ( TyCon, tyConName )\\nimport qualified GHC.LanguageExtensions as LangExt\\n\\nimport GHC.Utils.Outputable as Outputable\\nimport GHC.Utils.Misc as Utils\\nimport GHC.Utils.Panic\\n\\nimport GHC.Types.Fixity.Env\\nimport GHC.Types.SafeHaskell\\nimport GHC.Types.Name\\nimport GHC.Types.Name.Env\\nimport GHC.Types.Name.Set\\nimport GHC.Types.Name.Reader\\nimport GHC.Types.Avail\\nimport GHC.Types.FieldLabel\\nimport GHC.Types.Hint\\nimport GHC.Types.SourceFile\\nimport GHC.Types.SrcLoc as SrcLoc\\nimport GHC.Types.Basic (TyConFlavour (..), convImportLevel, VisArity)\\nimport GHC.Types.UnresolvedImport\\nimport GHC.Types.Id\\nimport GHC.Types.PkgQual\\nimport GHC.Types.GREInfo (ConInfo(..), ConFieldInfo (..), ConLikeInfo (ConIsData))\\n\\nimport GHC.Unit\\nimport GHC.Unit.Module.Warnings\\nimport GHC.Unit.Module.ModIface\\nimport GHC.Unit.Module.Imported\\nimport GHC.Unit.Module.Deps\\nimport GHC.Unit.Env\\n\\nimport GHC.Data.Bag\\nimport GHC.Data.FastString\\nimport GHC.Data.FastString.Env\\nimport GHC.Data.Maybe\\nimport GHC.Data.List.SetOps ( removeDups )\\n\\nimport Control.Arrow ( second )\\nimport Control.Monad\\nimport Data.Foldable ( for_ )\\nimport Data.IntMap ( IntMap )\\nimport qualified Data.IntMap as IntMap\\nimport Data.Map ( Map )\\nimport qualified Data.Map as Map\\nimport Data.Ord ( comparing )\\nimport Data.Semigroup ( Any(..) )\\nimport qualified Data.Semigroup as S\\nimport Data.List ( partition, find, sortBy )\\nimport Data.List.NonEmpty (NonEmpty(..))\\nimport qualified Data.List.NonEmpty as NE\\nimport Data.Function ( on )\\nimport qualified Data.Set as S\\nimport System.FilePath (())\\nimport System.IO\\n\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{rnImports}\\n* *\\n************************************************************************\\n\\nNote [Tracking Trust Transitively]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen we import a package as well as checking that the direct imports are safe\\naccording to the rules outlined in the Note [Safe Haskell Trust Check] in GHC.Driver.Main\\nwe must also check that these rules hold transitively for all dependent modules\\nand packages. Doing this without caching any trust information would be very\\nslow as we would need to touch all packages and interface files a module depends\\non. To avoid this we make use of the property that if a modules Safe Haskell\\nmode changes, this triggers a recompilation from that module in the dependency\\ngraph. So we can just worry mostly about direct imports.\\n\\nThere is one trust property that can change for a package though without\\nrecompilation being triggered: package trust. So we must check that all\\npackages a module transitively depends on to be trusted are still trusted when\\nwe are compiling this module (as due to recompilation avoidance some modules\\nbelow may not be considered trusted any more without recompilation being\\ntriggered).\\n\\nWe handle this by augmenting the existing transitive list of packages a module M\\ndepends on with a bool for each package that says if it must be trusted when the\\nmodule M is being checked for trust. This list of trust required packages for a\\nsingle import is gathered in the rnImportDecl function and stored in an\\nImportAvails data structure. The union of these trust required packages for all\\nimports is done by the rnImports function using the combine function which calls\\nthe plusImportAvails function that is a union operation for the ImportAvails\\ntype. This gives us in an ImportAvails structure all packages required to be\\ntrusted for the module we are currently compiling. Checking that these packages\\nare still trusted (and that direct imports are trusted) is done in\\nGHC.Driver.Main.checkSafeImports.\\n\\nSee the note below, [Trust Own Package] for a corner case in this method and\\nhow its handled.\\n\\n\\nNote [Trust Own Package]\\n~~~~~~~~~~~~~~~~~~~~~~~~\\nThere is a corner case of package trust checking that the usual transitive check\\ndoesn\'t cover. (For how the usual check operates see the Note [Tracking Trust\\nTransitively] below). The case is when you import a -XSafe module M and M\\nimports a -XTrustworthy module N. If N resides in a different package than M,\\nthen the usual check works as M will record a package dependency on N\'s package\\nand mark it as required to be trusted. If N resides in the same package as M\\nthough, then importing M should require its own package be trusted due to N\\n(since M is -XSafe so doesn\'t create this requirement by itself). The usual\\ncheck fails as a module doesn\'t record a package dependency of its own package.\\nSo instead we now have a bool field in a modules interface file that simply\\nstates if the module requires its own package to be trusted. This field avoids\\nus having to load all interface files that the module depends on to see if one\\nis trustworthy.\\n\\n\\nNote [Trust Transitive Property]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSo there is an interesting design question in regards to transitive trust\\nchecking. Say I have a module B compiled with -XSafe. B is dependent on a bunch\\nof modules and packages, some packages it requires to be trusted as its using\\n-XTrustworthy modules from them. Now if I have a module A that doesn\'t use safe\\nhaskell at all and simply imports B, should A inherit all the trust\\nrequirements from B? Should A now also require that a package p is trusted since\\nB required it?\\n\\nWe currently say no but saying yes also makes sense. The difference is, if a\\nmodule M that doesn\'t use Safe Haskell imports a module N that does, should all\\nthe trusted package requirements be dropped since M didn\'t declare that it cares\\nabout Safe Haskell (so -XSafe is more strongly associated with the module doing\\nthe importing) or should it be done still since the author of the module N that\\nuses Safe Haskell said they cared (so -XSafe is more strongly associated with\\nthe module that was compiled that used it).\\n\\nGoing with yes is a simpler semantics we think and harder for the user to stuff\\nup but it does mean that Safe Haskell will affect users who don\'t care about\\nSafe Haskell as they might grab a package from Cabal which uses safe haskell (say\\nnetwork) and that packages imports -XTrustworthy modules from another package\\n(say bytestring), so requires that package is trusted. The user may now get\\ncompilation errors in code that doesn\'t do anything with Safe Haskell simply\\nbecause they are using the network package. They will have to call \'ghc-pkg\\ntrust network\' to get everything working. Due to this invasive nature of going\\nwith yes we have gone with no for now.\\n-}\\n\\n-- | Process Import Decls. See \'rnImportDecl\' for a description of what\\n-- the return types represent.\\n-- Note: Do the non SOURCE ones first, so that we get a helpful warning\\n-- for SOURCE ones that are unnecessary\\nrnImports :: [(LImportDecl GhcPs, SDoc)]\\n -> RnM ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\nrnImports imports = do\\n tcg_env <- getGblEnv\\n -- NB: want an identity module here, because it\'s OK for a signature\\n -- module to import from its implementor\\n let this_mod = tcg_mod tcg_env\\n let (source, ordinary) = partition (is_source_import . fst) imports\\n is_source_import (d::LImportDecl GhcPs) = ideclSource (unLoc d) == IsBoot\\n stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary\\n stuff2 <- mapAndReportM (rnImportDecl this_mod) source\\n -- Safe Haskell: See Note [Tracking Trust Transitively]\\n let (decls, imp_user_spec, rdr_env, imp_avails) = combine (stuff1 ++ stuff2)\\n -- Update imp_boot_mods if imp_direct_mods mentions any of them\\n let merged_import_avail = clobberSourceImports imp_avails\\n return (decls, imp_user_spec, rdr_env, merged_import_avail)\\n\\n where\\n clobberSourceImports imp_avails =\\n imp_avails { imp_boot_mods = imp_boot_mods\' }\\n where\\n imp_boot_mods\' = mergeInstalledModuleEnv combJ id (const emptyInstalledModuleEnv)\\n (imp_boot_mods imp_avails)\\n (imp_direct_dep_mods imp_avails)\\n\\n combJ (GWIB _ IsBoot) (_, x) = Just x\\n combJ r _ = Just r\\n -- See Note [Combining ImportAvails]\\n combine :: [(LImportDecl GhcRn, ImportUserSpec, GlobalRdrEnv, ImportAvails)]\\n -> ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\n combine ss =\\n let (decls, imp_user_spec, rdr_env, imp_avails, finsts) = foldr\\n plus\\n ([], [], emptyGlobalRdrEnv, emptyImportAvails, emptyModuleSet)\\n ss\\n in (decls, imp_user_spec, rdr_env, imp_avails { imp_finsts = moduleSetElts finsts })\\n\\n plus (decl, us, gbl_env1, imp_avails1)\\n (decls, uss, gbl_env2, imp_avails2, finsts_set)\\n = ( decl:decls,\\n us:uss,\\n gbl_env1 `plusGlobalRdrEnv` gbl_env2,\\n imp_avails1\' `plusImportAvails` imp_avails2,\\n extendModuleSetList finsts_set new_finsts )\\n where\\n imp_avails1\' = imp_avails1 { imp_finsts = [] }\\n new_finsts = imp_finsts imp_avails1\\n\\n{-\\nNote [Combining ImportAvails]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nimp_finsts in ImportAvails is a list of family instance modules\\ntransitively depended on by an import. imp_finsts for a currently\\ncompiled module is a union of all the imp_finsts of imports.\\nComputing the union of two lists of size N is O(N^2) and if we\\ndo it to M imports we end up with O(M*N^2). That can get very\\nexpensive for bigger module hierarchies.\\n\\nUnion can be optimized to O(N log N) if we use a Set.\\nimp_finsts is converted back and forth between dep_finsts, so\\nchanging a type of imp_finsts means either paying for the conversions\\nor changing the type of dep_finsts as well.\\n\\nI\'ve measured that the conversions would cost 20% of allocations on my\\ntest case, so that can be ruled out.\\n\\nChanging the type of dep_finsts forces checkFamInsts to\\nget the module lists in non-deterministic order. If we wanted to restore\\nthe deterministic order, we\'d have to sort there, which is an additional\\ncost. As far as I can tell, using a non-deterministic order is fine there,\\nbut that\'s a brittle nonlocal property which I\'d like to avoid.\\n\\nAdditionally, dep_finsts is read from an interface file, so its \\"natural\\"\\ntype is a list. Which makes it a natural type for imp_finsts.\\n\\nSince rnImports.combine is really the only place that would benefit from\\nit being a Set, it makes sense to optimize the hot loop in rnImports.combine\\nwithout changing the representation.\\n\\nSo here\'s what we do: instead of naively merging ImportAvails with\\nplusImportAvails in a loop, we make plusImportAvails merge empty imp_finsts\\nand compute the union on the side using Sets. When we\'re done, we can\\nconvert it back to a list. One nice side effect of this approach is that\\nif there\'s a lot of overlap in the imp_finsts of imports, the\\nSet doesn\'t really need to grow and we don\'t need to allocate.\\n\\nRunning generateModules from #14693 with DEPTH=16, WIDTH=30 finishes in\\n23s before, and 11s after.\\n-}\\n\\n-- | Given a located import declaration @decl@ from @this_mod@,\\n-- calculate the following pieces of information:\\n--\\n-- 1. An updated \'LImportDecl\', where all unresolved \'RdrName\' in\\n-- the entity lists have been resolved into \'Name\'s,\\n--\\n-- 2. A \'GlobalRdrEnv\' representing the new identifiers that were\\n-- brought into scope (taking into account module qualification\\n-- and hiding),\\n--\\n-- 3. \'ImportAvails\' summarizing the identifiers that were imported\\n-- by this declaration, and\\n--\\n-- 4. A boolean \'AnyHpcUsage\' which is true if the imported module\\n-- used HPC.\\nrnImportDecl :: Module -> (LImportDecl GhcPs, SDoc)\\n -> RnM (LImportDecl GhcRn, ImportUserSpec , GlobalRdrEnv, ImportAvails)\\nrnImportDecl this_mod\\n (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name\\n , ideclPkgQual = raw_pkg_qual\\n , ideclSource = want_boot\\n , ideclSafe = mod_safe\\n , ideclLevelSpec = import_level\\n , ideclQualified = qual_style\\n , ideclExt = XImportDeclPass { ideclOrigin = origin }\\n , ideclAs = as_mod, ideclImportList = imp_details }), import_reason)\\n = setSrcSpanA loc $ do\\n\\n case raw_pkg_qual of\\n NoRawPkgQual -> pure ()\\n RawPkgQual {} -> do\\n pkg_imports <- xoptM LangExt.PackageImports\\n when (not pkg_imports) $ addErr TcRnPackageImportsDisabled\\n\\n let qual_only = isImportDeclQualified qual_style\\n generated = isGeneratedImport origin\\n\\n lookup_scope = importDeclLookupScope origin\\n\\n -- If there\'s an error in loadInterface, (e.g. interface\\n -- file not found) we get lots of spurious errors from \'filterImports\'\\n let imp_mod_name = unLoc loc_imp_mod_name\\n doc = ppr imp_mod_name <+> import_reason\\n\\n hsc_env <- getTopEnv\\n unit_env <- hsc_unit_env <$> getTopEnv\\n let pkg_qual = renameRawPkgQual unit_env imp_mod_name raw_pkg_qual\\n\\n -- Check for self-import, which confuses the typechecker (#9032)\\n -- ghc --make rejects self-import cycles already, but batch-mode may not\\n -- at least not until GHC.IfaceToCore.tcHiBootIface, which is too late to avoid\\n -- typechecker crashes. (Indirect self imports are not caught until\\n -- GHC.IfaceToCore, see #10337 tracking how to make this error better.)\\n --\\n -- Originally, we also allowed \'import {-# SOURCE #-} M\', but this\\n -- caused bug #10182: in one-shot mode, we should never load an hs-boot\\n -- file for the module we are compiling into the EPS. In principle,\\n -- it should be possible to support this mode of use, but we would have to\\n -- extend Provenance to support a local definition in a qualified location.\\n -- For now, we don\'t support it, but see #10336\\n when (imp_mod_name == moduleName this_mod &&\\n (case pkg_qual of -- If we have import \\"\\" M, then we should\\n -- check that \\"\\" is \\"this\\" (which is magic)\\n -- or the name of this_mod\'s package. Yurgh!\\n -- c.f. GHC.findModule, and #9997\\n NoPkgQual -> True\\n ThisPkg uid -> uid == homeUnitId_ (hsc_dflags hsc_env)\\n OtherPkg _ -> False))\\n (addErr (TcRnSelfImport imp_mod_name))\\n\\n -- Check for a missing import list (Opt_WarnMissingImportList also\\n -- checks for T(..) items but that is done in checkDodgyImport below)\\n case imp_details of\\n Just (Exactly, _) -> return () -- Explicit import list\\n _ | generated -> return () -- Do not bleat for generated imports\\n | qual_only -> return ()\\n | otherwise -> addDiagnostic (TcRnNoExplicitImportList imp_mod_name)\\n\\n\\n mb_iface <- loadSrcInterface_maybe doc lookup_scope imp_mod_name want_boot pkg_qual\\n iface <- case mb_iface of\\n Succeeded iface -> return iface\\n Failed err -> failWithTc $\\n importDeclLoadFailure origin imp_mod_name want_boot err\\n\\n -- Compiler sanity check: if the import didn\'t say\\n -- {-# SOURCE #-} we should not get a hi-boot file\\n warnPprTrace ((want_boot == NotBoot) && (mi_boot iface == IsBoot)) \\"rnImportDecl\\" (ppr imp_mod_name) $ do\\n\\n -- Issue a user warning for a redundant {- SOURCE -} import\\n -- NB that we arrange to read all the ordinary imports before\\n -- any of the {- SOURCE -} imports.\\n --\\n -- in --make and GHCi, the compilation manager checks for this,\\n -- and indeed we shouldn\'t do it here because the existence of\\n -- the non-boot module depends on the compilation order, which\\n -- is not deterministic. The hs-boot test can show this up.\\n dflags <- getDynFlags\\n warnIf ((want_boot == IsBoot) && (mi_boot iface == NotBoot) && isOneShot (ghcMode dflags))\\n (TcRnRedundantSourceImport imp_mod_name)\\n when (mod_safe && not (safeImportsOn dflags)) $\\n addErr (TcRnSafeImportsDisabled imp_mod_name)\\n\\n let imp_mod = mi_module iface\\n qual_mod_name = fmap unLoc as_mod `orElse` imp_mod_name\\n imp_spec = ImpDeclSpec { is_mod = imp_mod, is_qual = qual_only,\\n is_dloc = locA loc, is_as = qual_mod_name,\\n is_pkg_qual = pkg_qual, is_isboot = want_boot,\\n is_level = convImportLevel import_level }\\n\\n let filter_imports = do\\n -- filter the imports according to the import declaration\\n (new_imp_details, imp_user_list, gbl_env)\\n <- filterImports hsc_env iface imp_spec imp_details\\n -- for certain error messages, we\\u2019d like to know what could be\\n -- imported here, if everything were imported\\n potential_gres <- (\\\\(_,_,x) -> x) <$> filterImports hsc_env iface imp_spec Nothing\\n return (new_imp_details, imp_user_list, gbl_env, potential_gres)\\n\\n (new_imp_details, imp_user_list, gbl_env, potential_gres) <-\\n case origin of\\n ImplicitEssentialsImport ->\\n -- The implicit GHC.Essentials import does not bring anything into scope.\\n -- See Note [Finding GHC.Essentials] in GHC.Builtin.\\n return (Nothing, ImpUserDependOnly, emptyGlobalRdrEnv, emptyGlobalRdrEnv)\\n UserWrittenImport -> filter_imports\\n ImplicitPreludeImport -> filter_imports\\n PluginImport -> filter_imports\\n\\n let is_hiding | Just (EverythingBut,_) <- imp_details = True\\n | otherwise = False\\n\\n -- should the import be safe?\\n mod_safe\' = mod_safe\\n || (not generated && safeDirectImpsReq dflags)\\n || (generated && safeImplicitImpsReq dflags)\\n\\n hsc_env <- getTopEnv\\n let home_unit = hsc_home_unit hsc_env\\n other_home_units = hsc_all_home_unit_ids hsc_env\\n\\n imported_by\\n | isDependOnlyImport imp_user_list\\n = ImportedBySystem\\n | otherwise\\n = ImportedByUser $ ImportedModsVal\\n { imv_name = is_as imp_spec\\n , imv_span = locA loc\\n , imv_is_safe = mod_safe\'\\n , imv_is_hiding = is_hiding\\n , imv_all_exports = potential_gres\\n , imv_qualified = qual_only\\n , imv_is_level = convImportLevel import_level\\n }\\n imports = calculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by\\n\\n -- Complain if we import a deprecated module\\n case fromIfaceWarnings (mi_warns iface) of\\n WarnAll txt -> addDiagnostic (TcRnDeprecatedModule imp_mod_name txt)\\n _ -> return ()\\n\\n let new_imp_decl = ImportDecl\\n { ideclExt = ideclExt decl\\n , ideclName = ideclName decl\\n , ideclPkgQual = pkg_qual\\n , ideclSource = ideclSource decl\\n , ideclSafe = mod_safe\'\\n , ideclQualified = ideclQualified decl\\n , ideclAs = ideclAs decl\\n , ideclImportList = new_imp_details\\n , ideclLevelSpec = ideclLevelSpec decl\\n }\\n\\n return (L loc new_imp_decl, ImpUserSpec imp_spec imp_user_list, gbl_env, imports)\\n\\n-- | The error message to emit when we failed to load an interface.\\nimportDeclLoadFailure :: ImportDeclOrigin -> ModuleName -> IsBootInterface\\n -> MissingInterfaceError -> TcRnMessage\\nimportDeclLoadFailure ImplicitEssentialsImport _ _ err\\n = TcRnInterfaceError $ CantFindEssentials err LookingForEssentialsModule\\nimportDeclLoadFailure _ mod_name want_boot err\\n = TcRnInterfaceError $ Can\'tFindInterface err $ LookingForModule mod_name want_boot\\n\\n-- | Rename raw package imports\\nrenameRawPkgQual :: UnitEnv -> ModuleName -> RawPkgQual -> PkgQual\\nrenameRawPkgQual unit_env mn = \\\\case\\n NoRawPkgQual -> NoPkgQual\\n RawPkgQual _ fs -> renamePkgQual unit_env mn $ Just fs\\n\\n-- | Rename raw package imports\\nrenamePkgQual :: UnitEnv -> ModuleName -> Maybe FastString -> PkgQual\\nrenamePkgQual unit_env mn mb_pkg = case mb_pkg of\\n Nothing -> NoPkgQual\\n Just pkg_fs\\n | Just uid <- homeUnitId <$> ue_homeUnit unit_env\\n , pkg_fs == fsLit \\"this\\"\\n -> ThisPkg uid\\n\\n | Just (uid, _) <- find (fromMaybe False . fmap (== pkg_fs) . snd) home_names\\n -> ThisPkg uid\\n\\n | Just uid <- resolvePackageImport unit_state mn (PackageName pkg_fs)\\n -> OtherPkg uid\\n\\n | otherwise\\n -> OtherPkg (UnitId pkg_fs)\\n -- not really correct as pkg_fs is unlikely to be a valid unit-id but\\n -- we will report the failure later...\\n where\\n home_names =\\n [ (uid, mkFastString <$> thisPackageName (homeUnitEnv_dflags (ue_findHomeUnitEnv uid unit_env)))\\n | uid <- S.toList hpt_deps\\n ]\\n\\n unit_state = ue_homeUnitState unit_env\\n\\n hpt_deps :: S.Set UnitId\\n hpt_deps = homeUnitDepends unit_state\\n\\n\\n-- | Calculate the \'ImportAvails\' induced by an import of a particular\\n-- interface, but without \'imp_mods\'.\\ncalculateAvails :: HomeUnit\\n -> S.Set UnitId\\n -> ModIface\\n -> IsSafeImport\\n -> IsBootInterface\\n -> ImportedBy\\n -> ImportAvails\\ncalculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by =\\n let imp_mod = mi_module iface\\n imp_sem_mod= mi_semantic_module iface\\n orph_iface = mi_orphan iface\\n has_finsts = mi_finsts iface\\n deps = mi_deps iface\\n trust = getSafeMode $ mi_trust iface\\n trust_pkg = mi_trust_pkg iface\\n is_sig = mi_hsc_src iface == HsigFile\\n\\n -- If the module exports anything defined in this module, just\\n -- ignore it. Reason: otherwise it looks as if there are two\\n -- local definition sites for the thing, and an error gets\\n -- reported. Easiest thing is just to filter them out up\\n -- front. This situation only arises if a module imports\\n -- itself, or another module that imported it. (Necessarily,\\n -- this involves a loop.)\\n --\\n -- We do this *after* filterImports, so that if you say\\n -- module A where\\n -- import B( AType )\\n -- type AType = ...\\n --\\n -- module B( AType ) where\\n -- import {-# SOURCE #-} A( AType )\\n --\\n -- then you won\'t get a \'B does not export AType\' message.\\n\\n\\n -- Compute new transitive dependencies\\n --\\n -- \'dep_orphs\' and \'dep_finsts\' do NOT include the imported module\\n -- itself, but we DO need to include this module in \'imp_orphs\' and\\n -- \'imp_finsts\' if it defines an orphan or instance family; thus the\\n -- orph_iface/has_iface tests.\\n\\n deporphs = dep_orphs deps\\n depfinsts = dep_finsts deps\\n\\n orphans | orph_iface = assertPpr (not (imp_sem_mod `elem` deporphs)) (ppr imp_sem_mod <+> ppr deporphs) $\\n imp_sem_mod : deporphs\\n | otherwise = deporphs\\n\\n finsts | has_finsts = assertPpr (not (imp_sem_mod `elem` depfinsts)) (ppr imp_sem_mod <+> ppr depfinsts) $\\n imp_sem_mod : depfinsts\\n | otherwise = depfinsts\\n\\n -- Trusted packages are a lot like orphans.\\n trusted_pkgs | mod_safe\' = dep_trusted_pkgs deps\\n | otherwise = S.empty\\n\\n\\n pkg = moduleUnit (mi_module iface)\\n ipkg = toUnitId pkg\\n\\n -- Does this import mean we now require our own pkg\\n -- to be trusted? See Note [Trust Own Package]\\n ptrust = trust == Sf_Trustworthy || trust_pkg\\n pkg_trust_req\\n | isHomeUnit home_unit pkg = ptrust\\n | otherwise = False\\n\\n dependent_pkgs = if toUnitId pkg `S.member` other_home_units\\n then S.empty\\n else S.singleton (lvl, ipkg)\\n\\n lvl = case imported_by of\\n ImportedByUser imv -> imv_is_level imv\\n ImportedBySystem -> NormalLevel\\n\\n\\n direct_mods = if toUnitId pkg `S.member` other_home_units\\n then mkPlusModDeps (moduleUnitId imp_mod) lvl (GWIB (moduleName imp_mod) want_boot)\\n else emptyInstalledModuleEnv\\n\\n dep_boot_mods_map = mkModDeps (dep_boot_mods deps)\\n\\n\\n boot_mods\\n -- If we are looking for a boot module, it must be HPT\\n | IsBoot <- want_boot = extendInstalledModuleEnv dep_boot_mods_map (toUnitId <$> imp_mod) (GWIB (moduleName imp_mod) IsBoot)\\n -- Now we are importing A properly, so don\'t go looking for\\n -- A.hs-boot\\n | isHomeUnit home_unit pkg = dep_boot_mods_map\\n -- There\'s no boot files to find in external imports\\n | otherwise = emptyInstalledModuleEnv\\n\\n sig_mods =\\n if is_sig\\n then moduleName imp_mod : dep_sig_mods deps\\n else dep_sig_mods deps\\n\\n\\n in ImportAvails {\\n imp_mods = Map.singleton (mi_module iface) [imported_by],\\n imp_orphs = orphans,\\n imp_finsts = finsts,\\n imp_sig_mods = sig_mods,\\n imp_direct_dep_mods = direct_mods,\\n imp_dep_direct_pkgs = dependent_pkgs,\\n imp_boot_mods = boot_mods,\\n\\n -- Add in the imported modules trusted package\\n -- requirements. ONLY do this though if we import the\\n -- module as a safe import.\\n -- See Note [Tracking Trust Transitively]\\n -- and Note [Trust Transitive Property]\\n imp_trust_pkgs = trusted_pkgs,\\n -- Do we require our own pkg to be trusted?\\n -- See Note [Trust Own Package]\\n imp_trust_own_pkg = pkg_trust_req\\n }\\n\\nmkPlusModDeps :: UnitId -> ImportLevel -> ModuleNameWithIsBoot\\n -> InstalledModuleEnv (S.Set ImportLevel, ModuleNameWithIsBoot)\\nmkPlusModDeps uid st elt = extendInstalledModuleEnv emptyInstalledModuleEnv (mkModule uid (gwib_mod elt)) (S.singleton st, elt)\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{importsFromLocalDecls}\\n* *\\n************************************************************************\\n\\nFrom the top-level declarations of this module produce\\n * the lexical environment\\n * the ImportAvails\\ncreated by its bindings.\\n\\nNote [Top-level Names in Template Haskell decl quotes]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSee also: Note [Interactively-bound Ids in GHCi] in GHC.Driver.Env\\n Note [Looking up Exact RdrNames] in GHC.Rename.Env\\n\\nConsider a Template Haskell declaration quotation like this:\\n module M where\\n f x = h [d| f = 3 |]\\nWhen renaming the declarations inside [d| ...|], we treat the\\ntop level binders specially in two ways\\n\\n1. We give them an Internal Name, not (as usual) an External one.\\n This is done by GHC.Rename.Env.newTopSrcBinder.\\n\\n2. We make them *shadow* the outer bindings.\\n See Note [GlobalRdrEnv shadowing]\\n\\n3. We find out whether we are inside a [d| ... |] by testing the TH\\n level. This is a slight hack, because the level field was really\\n meant for the type checker, and here we are not interested in the\\n fields of Brack, hence the error thunks in thRnBrack.\\n-}\\n\\nextendGlobalRdrEnvRn :: [GlobalRdrElt]\\n -> MiniFixityEnv\\n -> RnM (TcGblEnv, TcLclEnv)\\n-- Updates both the GlobalRdrEnv and the FixityEnv\\n-- We return a new TcLclEnv only because we might have to\\n-- delete some bindings from it;\\n-- see Note [Top-level Names in Template Haskell decl quotes]\\n\\nextendGlobalRdrEnvRn new_gres new_fixities\\n = checkNoErrs $ -- See Note [Fail fast on duplicate definitions]\\n do { (gbl_env, lcl_env) <- getEnvs\\n ; level <- getThLevel\\n ; isGHCi <- getIsGHCi\\n ; let rdr_env = tcg_rdr_env gbl_env\\n fix_env = tcg_fix_env gbl_env\\n th_bndrs = getLclEnvThBndrs lcl_env\\n th_lvl = thLevelIndex level\\n\\n -- Delete new_occs from global and local envs\\n -- If we are in a TemplateHaskell decl bracket,\\n -- we are going to shadow them\\n -- See Note [GlobalRdrEnv shadowing]\\n inBracket = isBrackLevel level\\n\\n lcl_env_TH = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_rdr = minusLocalRdrEnv (tcl_rdr lcl_env) new_gres_env }) lcl_env\\n -- See Note [GlobalRdrEnv shadowing]\\n\\n lcl_env2 | inBracket = lcl_env_TH\\n | otherwise = lcl_env\\n\\n -- Deal with shadowing: see Note [GlobalRdrEnv shadowing]\\n want_shadowing = isGHCi || inBracket\\n rdr_env1 | want_shadowing = shadowNames False rdr_env new_gres_env\\n | otherwise = rdr_env\\n\\n lcl_env3 = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_th_bndrs = extendNameEnvList th_bndrs\\n [ ( n, (TopLevel, th_lvl) )\\n | n <- new_names ] }) lcl_env2\\n\\n ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres\\n\\n ; let fix_env\' = foldl\' extend_fix_env fix_env new_gres\\n gbl_env\' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env\' }\\n\\n ; traceRn \\"extendGlobalRdrEnvRn 2\\" (pprGlobalRdrEnv True rdr_env2)\\n ; return (gbl_env\', lcl_env3) }\\n where\\n new_names = map greName new_gres\\n new_gres_env = mkGlobalRdrEnv new_gres\\n\\n -- If there is a fixity decl for the gre, add it to the fixity env\\n extend_fix_env fix_env gre\\n | Just (L _ fi) <- lookupMiniFixityEnv new_fixities name\\n = extendNameEnv fix_env name (FixItem occ fi)\\n | otherwise\\n = fix_env\\n where\\n name = greName gre\\n occ = greOccName gre\\n\\n add_gre :: GlobalRdrEnv -> GlobalRdrElt -> RnM GlobalRdrEnv\\n -- Extend the GlobalRdrEnv with a LocalDef GRE\\n -- If there is already a LocalDef GRE with the same OccName,\\n -- report an error and discard the new GRE\\n -- This establishes INVARIANT 1 of GlobalRdrEnvs\\n add_gre env gre\\n | not (null dups) -- Same OccName defined twice\\n = do { addDupDeclErr (gre :| dups); return env }\\n\\n | otherwise\\n = return (extendGlobalRdrEnv env gre)\\n where\\n -- See Note [Reporting duplicate local declarations]\\n dups = filter isBadDupGRE\\n $ lookupGRE env (LookupOccName (greOccName gre) (RelevantGREsFOS WantBoth))\\n isBadDupGRE old_gre = isLocalGRE old_gre && greClashesWith gre old_gre\\n\\n{- Note [Fail fast on duplicate definitions]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIf there are duplicate bindings for the same thing, we want to fail\\nfast. Having two bindings for the same thing can cause follow-on errors.\\nExample (test T9975a):\\n data Test = Test { x :: Int }\\n pattern Test wat = Test { x = wat }\\nThis defines \'Test\' twice. The second defn has no field-names; and then\\nwe get an error from Test { x=wat }, saying \\"Test has no field \'x\'\\".\\n\\nEasiest thing is to bale out fast on duplicate definitions, which\\nwe do via `checkNoErrs` on `extendGlobalRdrEnvRn`.\\n\\nNote [Reporting duplicate local declarations]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn general, a single module may not define the same OccName multiple times. This\\nis checked in extendGlobalRdrEnvRn: when adding a new locally-defined GRE to the\\nGlobalRdrEnv we report an error if there are already duplicates in the\\nenvironment. This establishes INVARIANT 1 (see comments on GlobalRdrEnv in\\nGHC.Types.Name.Reader), which says that for a given OccName, all the\\nGlobalRdrElts to which it maps must have distinct \'greName\'s.\\n\\nFor example, the following will be rejected:\\n\\n f x = x\\n g x = x\\n f x = x -- Duplicate!\\n\\nUsers are allowed to introduce new GREs with the same OccName as an imported GRE,\\nas disambiguation is possible through the module system, e.g.:\\n\\n module M where\\n import N (f)\\n f x = x\\n g x = M.f x + N.f x\\n\\nIf both GREs are local, the general rule is that two GREs clash if they have\\nthe same OccName, i.e. they share a textual name and live in the same namespace.\\nHowever, there are additional clashes due to record fields:\\n\\n - a new variable clashes with previously defined record fields\\n which define field selectors,\\n\\n - a new record field shadows:\\n\\n - previously defined variables, if it defines a field selector,\\n - previously defined record fields, unless it is a duplicate record field.\\n\\nThis logic is implemented in the function \'GHC.Types.Name.Reader.greClashesWith\'.\\n\\nSee also Note [Skipping ambiguity errors at use sites of local declarations] in\\nGHC.Rename.Utils.\\n-}\\n\\n\\n{- *********************************************************************\\n* *\\n getLocalDeclBindersd@ returns the names for an HsDecl\\n It\'s used for source code.\\n\\n *** See Note [The Naming story] in GHC.Hs.Decls ****\\n* *\\n********************************************************************* -}\\n\\ngetLocalNonValBinders :: MiniFixityEnv -> HsGroup GhcPs\\n -> RnM ((TcGblEnv, TcLclEnv), NameSet)\\n-- Get all the top-level binders bound the group *except*\\n-- for value bindings, which are treated separately\\n-- Specifically we return AvailInfo for\\n-- * type decls (incl constructors and record selectors)\\n-- * class decls (including class ops)\\n-- * associated types\\n-- * foreign imports\\n-- * value signatures (in hs-boot files only)\\n\\ngetLocalNonValBinders fixity_env\\n (HsGroup { hs_valds = binds,\\n hs_tyclds = tycl_decls,\\n hs_fords = foreign_decls })\\n = do { -- Process all type/class decls *except* family instances\\n ; let inst_decls = tycl_decls >>= group_instds\\n ; dup_fields_ok <- xopt_DuplicateRecordFields <$> getDynFlags\\n ; has_sel <- xopt_FieldSelectors <$> getDynFlags\\n ; tc_gres\\n <- concatMapM\\n (new_tc dup_fields_ok has_sel)\\n (tyClGroupTyClDecls tycl_decls)\\n ; traceRn \\"getLocalNonValBinders 1\\" (ppr tc_gres)\\n ; envs <- extendGlobalRdrEnvRn tc_gres fixity_env\\n ; restoreEnvs envs $ do {\\n -- Bring these things into scope first\\n -- See Note [Looking up family names in family instances]\\n\\n -- Process all family instances\\n -- to bring new data constructors into scope\\n ; nti_gress <- mapM (new_assoc dup_fields_ok has_sel) inst_decls\\n\\n -- Finish off with value binders:\\n -- foreign decls and pattern synonyms for an ordinary module\\n -- type sigs in case of a hs-boot file only\\n ; is_boot <- tcIsHsBootOrSig\\n ; let val_bndrs\\n | is_boot = case binds of\\n ValBinds _ val_binds ->\\n -- In a hs-boot file, the value binders come from the\\n -- *signatures*, and there should be no foreign binders\\n [ L (l2l decl_loc) (unLoc n)\\n | L decl_loc (TypeSig _ _ ns _) <- (val_sigs val_binds), n <- ns]\\n _ -> panic \\"Non-ValBinds in hs-boot group\\"\\n | otherwise = for_hs_bndrs\\n ; val_gres <- mapM new_simple val_bndrs\\n\\n ; let avails = concat nti_gress ++ val_gres\\n new_bndrs = gresToNameSet avails `unionNameSet`\\n gresToNameSet tc_gres\\n ; traceRn \\"getLocalNonValBinders 2\\" (ppr avails)\\n ; envs <- extendGlobalRdrEnvRn avails fixity_env\\n ; return (envs, new_bndrs) } }\\n where\\n for_hs_bndrs :: [LocatedN RdrName]\\n for_hs_bndrs = hsForeignDeclsBinders foreign_decls\\n\\n -- the SrcSpan attached to the input should be the span of the\\n -- declaration, not just the name\\n new_simple :: LocatedN RdrName -> RnM GlobalRdrElt\\n new_simple rdr_name = do { nm <- newTopSrcBinder rdr_name\\n ; return (mkLocalVanillaGRE NoParent nm) }\\n\\n new_tc :: DuplicateRecordFields -> FieldSelectors -> LTyClDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_tc dup_fields_ok has_sel tc_decl -- NOT for type/data instances\\n = do { let TyDeclBinders (main_bndr, tc_flav) at_bndrs sig_bndrs\\n (LConsWithFields cons_with_flds flds) = hsLTyClDeclBinders tc_decl\\n ; tycon_name <- newTopSrcBinder $ la2la main_bndr\\n ; at_names <- mapM (newTopSrcBinder . la2la . fst) at_bndrs\\n ; sig_names <- mapM (newTopSrcBinder . la2la) sig_bndrs\\n ; con_names_with_flds <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst con_names_with_flds) flds\\n ; mapM_ (add_dup_fld_errs flds\') con_names_with_flds\\n ; let tc_gre = mkLocalTyConGRE (fmap (const tycon_name) tc_flav) tycon_name\\n fld_env = mk_fld_env con_names_with_flds flds\'\\n at_gres = zipWith (\\\\ (_, at_flav) at_nm -> mkLocalTyConGRE (fmap (const tycon_name) at_flav) at_nm)\\n at_bndrs at_names\\n sig_gres = map (mkLocalVanillaGRE (ParentIs tycon_name)) sig_names\\n con_gres = map (mkLocalConLikeGRE (ParentIs tycon_name)) fld_env\\n fld_gres = mkLocalFieldGREs (ParentIs tycon_name) fld_env\\n sub_gres = at_gres ++ sig_gres ++ con_gres ++ fld_gres\\n ; traceRn \\"getLocalNonValBinders new_tc\\" $\\n vcat [ text \\"tycon:\\" <+> ppr tycon_name\\n , text \\"tc_gre:\\" <+> ppr tc_gre\\n , text \\"sub_gres:\\" <+> ppr sub_gres ]\\n ; return $ tc_gre : sub_gres }\\n\\n -- Calculate the record field information, which feeds into the GlobalRdrElts\\n -- for DataCons and their fields. It\'s convenient to do this here where\\n -- we are working with a single datatype definition.\\n --\\n -- The information we needed was all set up for us:\\n -- see Note [Collecting record fields in data declarations] in GHC.Hs.Utils.\\n mk_fld_env :: [(Name, Either VisArity [Located Int])] -> IntMap FieldLabel\\n -> [(ConLikeName, ConInfo)]\\n mk_fld_env names flds =\\n [ (DataConName con, ConInfo (ConIsData (map fst names)) fld_info)\\n | (con, con_fl_indxs) <- names\\n , let fld_info = case fmap (map ((flds IntMap.!) . unLoc)) con_fl_indxs of\\n Left 0 -> ConIsNullary\\n Left arity -> ConHasPositionalArgs arity\\n Right [] -> ConIsNullary\\n Right (fld:flds) -> ConHasRecordFields $ fld NE.:| flds ]\\n\\n new_assoc :: DuplicateRecordFields -> FieldSelectors -> LInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_assoc _ _ (L _ (TyFamInstD {})) = return []\\n -- type instances don\'t bind new names\\n\\n new_assoc dup_fields_ok has_sel (L _ (DataFamInstD _ d))\\n = new_di dup_fields_ok has_sel Nothing d\\n new_assoc dup_fields_ok has_sel\\n (L _ (ClsInstD _ (ClsInstDecl { cid_poly_ty = inst_ty\\n , cid_decls = decls })))\\n = do -- First, attempt to grab the name of the class from the instance.\\n -- This step could fail if the instance is not headed by a class,\\n -- such as in the following examples:\\n --\\n -- (1) The class is headed by a bang pattern, such as in\\n -- `instance !Show Int` (#3811c)\\n -- (2) The class is headed by a type variable, such as in\\n -- `instance c` (#16385)\\n --\\n -- If looking up the class name fails, then mb_cls_gre will\\n -- be Nothing.\\n mb_cls_gre <- runMaybeT $ do\\n -- See (1) above\\n L loc cls_rdr <- MaybeT $ pure $ getLHsInstDeclClass_maybe inst_ty\\n -- See (2) above\\n MaybeT $ setSrcSpan (locA loc) $ lookupGlobalOccRn_maybe SameNameSpace cls_rdr\\n -- Assuming the previous step succeeded, process any associated data\\n -- family instances. If the previous step failed, bail out.\\n case mb_cls_gre of\\n Nothing\\n -> pure []\\n Just cls_gre\\n -> let cls_nm = greName cls_gre\\n in concatMapM (new_di dup_fields_ok has_sel (Just cls_nm) . unLoc) (data_fam_insts decls)\\n\\n data_fam_insts decls = concatMap get decls\\n where\\n get (L l (InstD _ (DataFamInstD { dfid_inst = d}))) = [L l d]\\n get _ = []\\n\\n new_di :: DuplicateRecordFields -> FieldSelectors\\n -> Maybe Name -- class name\\n -> DataFamInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_di dup_fields_ok has_sel mb_cls dfid@(DataFamInstDecl { dfid_eqn = ti_decl })\\n = do { main_name <- unLoc <$> lookupFamInstName mb_cls (feqn_tycon ti_decl)\\n ; let LConsWithFields cons_with_flds flds = hsDataFamInstBinders dfid\\n ; sub_names <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst sub_names) flds\\n ; mapM_ (add_dup_fld_errs flds\') sub_names\\n ; let fld_env = mk_fld_env sub_names flds\'\\n con_gres = map (mkLocalConLikeGRE (ParentIs main_name)) fld_env\\n field_gres = mkLocalFieldGREs (ParentIs main_name) fld_env\\n -- NB: the data family name is not bound here,\\n -- so we don\'t return a GlobalRdrElt for it here!\\n ; return $ con_gres ++ field_gres }\\n\\n -- Add errors if a constructor has a duplicate record field.\\n add_dup_fld_errs :: IntMap FieldLabel\\n -> (Name, Either VisArity [Located Int])\\n -> IOEnv (Env TcGblEnv TcLclEnv) ()\\n add_dup_fld_errs all_flds (con, con_flds_or_arity)\\n | Right con_flds <- con_flds_or_arity\\n , let (_, dups) = removeDups (comparing unLoc) con_flds\\n = for_ dups $ \\\\ dup_flds ->\\n -- Report the error at the location of the second occurrence\\n -- of the duplicate field.\\n let loc =\\n case dup_flds of\\n _ :| ( L loc _ : _) -> loc\\n L loc _ :| _ -> loc\\n dup_rdrs = fmap (nameRdrName . flSelector . (all_flds IntMap.!) . unLoc) dup_flds\\n in addErrAt loc $ TcRnDuplicateFieldName (RecordFieldDecl con) dup_rdrs\\n | otherwise\\n = return ()\\n\\nnewRecordFieldLabel :: DuplicateRecordFields -> FieldSelectors -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel\\nnewRecordFieldLabel _ _ [] _ = error \\"newRecordFieldLabel: datatype has no constructors!\\"\\nnewRecordFieldLabel dup_fields_ok has_sel (dc:_) (L loc (FieldOcc _ (L _ fld)))\\n = do { selName <- newTopSrcBinder $ L (l2l loc) $ field\\n ; return $ FieldLabel { flHasDuplicateRecordFields = dup_fields_ok\\n , flHasFieldSelector = has_sel\\n , flSelector = selName } }\\n where\\n fld_occ = rdrNameOcc fld\\n dc_fs = occNameFS $ nameOccName dc\\n field\\n -- Use an Exact RdrName as-is, to preserve the bindings\\n -- of an already renamer-resolved field and its use\\n -- sites. This is needed to correctly support record\\n -- selectors in Template Haskell. See Note [Binders in\\n -- Template Haskell] in \\"GHC.ThToHs\\" and Note [Looking up\\n -- Exact RdrNames] in \\"GHC.Rename.Env\\".\\n | isExact fld\\n = assertPpr (fieldOcc_maybe fld_occ == Just dc_fs)\\n (vcat [ text \\"newRecordFieldLabel: incorrect namespace for exact Name\\" <+> quotes (ppr fld)\\n , text \\"expected namespace:\\" <+> pprNameSpace (fieldName dc_fs)\\n , text \\" actual namespace:\\" <+> pprNameSpace (occNameSpace fld_occ) ])\\n fld\\n\\n -- Field names produced by the parser are namespaced with VarName.\\n -- Here we namespace them according to the first constructor.\\n -- See Note [Record field namespacing] in GHC.Types.Name.Occurrence.\\n | otherwise\\n = mkRdrUnqual $ varToRecFieldOcc dc_fs fld_occ\\n\\n{-\\nNote [Looking up family names in family instances]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider\\n\\n module M where\\n type family T a :: *\\n type instance M.T Int = Bool\\n\\nWe might think that we can simply use \'lookupOccRn\' when processing the type\\ninstance to look up \'M.T\'. Alas, we can\'t! The type family declaration is in\\nthe *same* HsGroup as the type instance declaration. Hence, as we are\\ncurrently collecting the binders declared in that HsGroup, these binders will\\nnot have been added to the global environment yet.\\n\\nSolution is simple: process the type family declarations first, extend\\nthe environment, and then process the type instances.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Filtering imports}\\n* *\\n************************************************************************\\n\\n@filterImports@ takes the @ExportEnv@ telling what the imported module makes\\navailable, and filters it through the import spec (if any).\\n\\nNote [Dealing with imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nFor import M( ies ), we take each AvailInfo from the mi_exports of M, and make\\n\\n imp_occ_env :: OccEnv (NameEnv ImpOccItem)\\n\\nThis map contains one entry for each OccName that M exports, mapping each OccName\\nto the following information:\\n\\n 1. the GlobalRdrElt corresponding to the OccName,\\n 2. whether this GlobalRdrElt was the parent in the AvailInfo we found\\n the OccName in.\\n 3. the GlobalRdrElts that were bundled together in the AvailInfo we found\\n this OccName in (not including the parent),\\n\\nWe need (2) and (3) during the construction of the OccEnv because of associated\\ntypes and bundled pattern synonyms, respectively.\\n(3) is explained in Note [Importing PatternSynonyms].\\n\\nTo explain (2), consider for example:\\n\\n module M where\\n class C a where { data T a }\\n instance C Int where { data T Int = T1 | T2 }\\n instance C Bool where { data T Int = T3 }\\n\\nHere, M\'s exports avails are (recalling the AvailTC invariant from GHC.Types.Avail)\\n\\n C(C,T), T(T,T1,T2,T3)\\n\\nNotice that T appears *twice*, once as a child and once as a parent. From\\nthese two exports, respectively, during construction of the imp_occ_env, we begin\\nby associating the following two elements with the key T:\\n\\n T -> ImpOccItem { imp_item = gre1, imp_bundled = [C,T] , imp_is_parent = False }\\n T -> ImpOccItem { imp_item = gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nwhere `gre1`, `gre2` are two GlobalRdrElts with greName T.\\nWe combine these (in function \'combine\' in \'mkImportOccEnv\') by discarding the\\nnon-parent item, thusly:\\n\\n T -> IE_ITem { imp_item = gre1 `plusGRE` gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nNote the `plusGRE`: this ensures we don\'t drop parent information;\\nsee Note [Preserve parent information when combining import OccEnvs].\\n\\nSo the overall imp_occ_env is:\\n\\n C -> ImpOccItem { imp_item = C, imp_bundled = [T ], imp_is_parent = True }\\n T -> ImpOccItem { imp_item = T , imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n T1 -> ImpOccItem { imp_item = T1, imp_bundled = [T1,T2,T3], imp_is_parent = False }\\n -- similarly for T2, T3\\n\\nNote that the imp_occ_env will have entries for data constructors too,\\nalthough we never look up data constructors.\\n\\nNote [Importing PatternSynonyms]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nAs described in Note [Dealing with imports], associated types can lead to the\\nsame Name appearing twice, both as a child and once as a parent, when\\nconstructing the imp_occ_env. The same thing can happen with pattern synonyms\\nif they are exported bundled with a type.\\n\\nA simplified example, based on #11959:\\n\\n {-# LANGUAGE PatternSynonyms #-}\\n module M (T(P), pattern P) where -- Duplicate export warning, but allowed\\n data T = MkT\\n pattern P = MkT\\n\\nHere we have T(P) and P in export_avails, and respectively construct both\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n P -> ImpOccItem { imp_item = P, imp_bundled = [] , imp_is_parent = False }\\n\\nWe combine these by dropping the one with no siblings, leaving us with:\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n\\nThat is, we simply discard the non-bundled Avail.\\n\\nNote [Importing DuplicateRecordFields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn filterImports, another complicating factor is DuplicateRecordFields.\\nSuppose we have:\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (S(foo), T(foo)) where\\n data S = MkS { foo :: Int }\\n data T = MkT { foo :: Int }\\n\\n module N where\\n import M (foo) -- this is allowed (A)\\n import M (S(foo)) -- this is allowed (B)\\n\\nHere M exports \'foo\' at two different OccNames, with different namespaces for\\nthe two construtors MkS and MkT. Then, when we look up \'foo\' in lookup_names\\nfor case (A), we have a variable foo but must look in all the record field\\nnamespaces to find the two fields (and hence two different Avails).\\nWhereas in case (B) we reach the lookup_ie case for IEThingWith,\\nwhich looks up \'S\' and then finds the unique \'foo\' amongst its children.\\n\\nSee T16745 for a test of this.\\n\\nNote [Preserve parent information when combining import OccEnvs]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen discarding one ImpOccItem in favour of another, as described in\\nNote [Dealing with imports], we must make sure to combine the GREs so that\\nwe don\'t lose information.\\n\\nConsider for example #24084:\\n\\n module M1 where { class C a where { type T a } }\\n module M2 ( module M1 ) where { import M1 }\\n module M3 where { import M2 ( C, T ); instance C () where T () = () }\\n\\nWhen processing the import list of `M3`, we will have two `Avail`s attached\\nto `T`, namely `C(C, T)` and `T(T)`. We combine them in the `combine` function\\nof `mkImportOccEnv`; as described in Note [Dealing with imports] we discard\\n`C(C, T)` in favour of `T(T)`. However, in doing so, we **must not**\\ndiscard the information want that `C` is the parent of `T`. Indeed,\\nlosing track of this information can cause errors when importing,\\nas we could get an error of the form\\n\\n \\u2018T\\u2019 is not a (visible) associated type of class \\u2018C\\u2019\\n\\nThis explains why we use `plusGRE` when combining the two ImpOccItems, even\\nthough we are discarding one in favour of the other.\\n-}\\n\\n-- | All the \'GlobalRdrElt\'s associated with an \'AvailInfo\'.\\ngresFromAvail :: HasDebugCallStack\\n => HscEnv -> Maybe ImportSpec -> AvailInfo -> [GlobalRdrElt]\\ngresFromAvail hsc_env prov avail =\\n [ mk_gre nm info\\n | nm <- availNames avail\\n , let info = lookupGREInfo hsc_env nm ]\\n where\\n\\n mk_gre n info\\n = case prov of\\n -- Nothing => bound locally\\n -- Just is => imported from \'is\'\\n Nothing -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = True, gre_imp = emptyBag\\n , gre_info = info }\\n Just is -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = False, gre_imp = unitBag is\\n , gre_info = info }\\n\\n-- | All the \'GlobalRdrElt\'s associated with a collection of \'AvailInfo\'s.\\ngresFromAvails :: HscEnv -> Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]\\ngresFromAvails hsc_env prov = concatMap (gresFromAvail hsc_env prov)\\n\\nimportsFromIface :: HscEnv -> ModIface -> ImpDeclSpec -> Maybe NameSet -> GlobalRdrEnv\\nimportsFromIface hsc_env iface decl_spec hidden = mkGlobalRdrEnv $ case hidden of\\n Nothing -> all_gres\\n Just hidden_names -> filter (not . (`elemNameSet` hidden_names) . greName) all_gres\\n where\\n all_gres = gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\nrnNamespaceSpecifier :: NamespaceSpecifier GhcPs -> NamespaceSpecifier GhcRn\\nrnNamespaceSpecifier (NoNamespaceSpecifier _) = NoNamespaceSpecifier noExtField\\nrnNamespaceSpecifier (TypeNamespaceSpecifier x) = TypeNamespaceSpecifier x\\nrnNamespaceSpecifier (DataNamespaceSpecifier x) = DataNamespaceSpecifier x\\n\\nfilterImports\\n :: HasDebugCallStack\\n => HscEnv\\n -> ModIface\\n -> ImpDeclSpec\\n -- ^ Import spec\\n -> Maybe (ImportListInterpretation, [LIE GhcPs])\\n -- ^ Whether this is a \\"hiding\\" import list\\n -> RnM (Maybe (ImportListInterpretation, [LIE GhcRn]), -- Import spec w/ Names\\n ImpUserList, -- same, but designed for storage in interfaces\\n GlobalRdrEnv) -- Same again, but in GRE form\\nfilterImports hsc_env iface decl_spec Nothing\\n = return (Nothing, ImpUserAll, importsFromIface hsc_env iface decl_spec Nothing)\\nfilterImports hsc_env iface decl_spec (Just (want_hiding, import_items))\\n = do -- check for errors, convert RdrNames to Names\\n items1 <- mapM lookup_lie import_items\\n\\n let items2 :: [(LIE GhcRn, [GlobalRdrElt])]\\n items2 = concat items1\\n -- NB we may have duplicates, and several items\\n -- for the same parent; e.g N(x) and N(y)\\n\\n (gres, imp_user_list) = case want_hiding of\\n Exactly ->\\n let gres = concatMap (gresFromIE decl_spec) items2\\n gre_env = mkGlobalRdrEnv gres\\n implicit_parents = mkNameSet $ mapMaybe parentOfImplicitlyImportedGRE gres\\n in (gre_env, ImpUserExplicit (gresToAvailInfo $ globalRdrEnvElts $ gre_env) implicit_parents)\\n EverythingBut ->\\n let hidden_names = mkNameSet $ concatMap (map greName . snd) items2\\n in (importsFromIface hsc_env iface decl_spec (Just hidden_names), ImpUserEverythingBut hidden_names)\\n\\n return (Just (want_hiding, map fst items2), imp_user_list, gres)\\n where\\n import_mod = mi_module iface\\n all_avails = mi_exports iface\\n imp_occ_env = mkImportOccEnv hsc_env decl_spec all_avails\\n\\n -- Look up a parent (type constructor, class or data constructor)\\n -- in an import.\\n lookup_parent :: IE GhcPs -> RdrName -> IELookupM ImpOccItem\\n lookup_parent ie rdr =\\n assertPpr (not $ isVarNameSpace ns)\\n (vcat [ text \\"filterImports lookup_parent: unexpected variable\\"\\n , text \\"rdr:\\" <+> ppr rdr\\n , text \\"namespace:\\" <+> pprNameSpace ns ]) $\\n do { xs <- lookup_names ie rdr\\n ; case xs of\\n cax :| [] -> return cax\\n _ -> pprPanic \\"filter_imports lookup_parent ambiguous\\" $\\n vcat [ text \\"rdr:\\" <+> ppr rdr\\n , text \\"lookups:\\" <+> ppr (fmap imp_item xs) ] }\\n -- Looking up non-variables is always unambiguous,\\n -- as there can be at most one corresponding item\\n -- in the imp_occ_env.\\n -- See item (1) of Note [Exporting duplicate declarations]\\n -- in GHC.Tc.Gen.Export.\\n where\\n occ = rdrNameOcc rdr\\n ns = occNameSpace occ\\n\\n -- Look up a RdrName used in an import, returning multiple values if there\\n -- are several fields with the same name exposed by the module\\n lookup_names :: IE GhcPs -> RdrName -> IELookupM (NonEmpty ImpOccItem)\\n lookup_names ie rdr\\n | isQual rdr\\n = failLookupWith (QualImportError rdr)\\n | otherwise\\n = case lookups of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n item:items -> return $ item :| items\\n where\\n lookups = concatMap nonDetNameEnvElts\\n $ lookupImpOccEnv (RelevantGREsFOS WantNormal) imp_occ_env (rdrNameOcc rdr)\\n\\n lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, [GlobalRdrElt])]\\n lookup_lie (L loc ieRdr)\\n = setSrcSpanA loc $\\n do (stuff, warns) <- run_lookup ([],[]) (lookup_ie ieRdr)\\n mapM_ (addTcRnDiagnostic <=< warning_msg) warns\\n return [ (L loc ie, gres) | (ie,gres) <- stuff ]\\n where\\n\\n -- Warn when importing T(..) and no children are brought in scope\\n warning_msg (DodgyImport reason) =\\n pure (TcRnDodgyImports reason)\\n warning_msg MissingImportList =\\n pure (TcRnMissingImportList ieRdr)\\n warning_msg (BadImportW ie sub) = do\\n -- \'BadImportW\' is only constructed below in \'bad_import_w\', in\\n -- the \'EverythingBut\' case, so here we assume a \'hiding\' clause.\\n (reason :| _) <- badImportItemErr iface decl_spec ie sub all_avails\\n pure (TcRnDodgyImports (DodgyImportsHiding reason))\\n warning_msg (DeprecatedExport n w) =\\n pure $ TcRnPragmaWarning\\n PragmaWarningExport\\n { pwarn_occname = occName n\\n , pwarn_impmod = moduleName import_mod }\\n w\\n\\n run_lookup :: a -> IELookupM a -> TcRn a\\n run_lookup def m = case m of\\n Failed err -> do\\n msgs <- lookup_err_msgs err\\n forM_ msgs $ \\\\msg -> addErr (TcRnImportLookup msg)\\n return def\\n Succeeded a -> return a\\n\\n lookup_err_msgs err = case err of\\n BadImport ie sub -> badImportItemErr iface decl_spec ie sub all_avails\\n IllegalImport -> pure $ NE.singleton ImportLookupIllegal\\n QualImportError rdr -> pure $ NE.singleton (ImportLookupQualified rdr)\\n\\n -- For each import item, we convert its RdrNames to Names,\\n -- and at the same time compute all the GlobalRdrElt corresponding\\n -- to what is actually imported by this item.\\n -- Returns Nothing on error.\\n --\\n -- Returns a list because, with DuplicateRecordFields, a naked\\n -- import/export of a record field can correspond to multiple\\n -- different GlobalRdrElts. See Note [Importing DuplicateRecordFields].\\n lookup_ie :: IE GhcPs\\n -> IELookupM ([(IE GhcRn, [GlobalRdrElt])], [IELookupWarning])\\n lookup_ie ie = handle_bad_import $\\n case ie of\\n IEVar _ (L l n) _ -> do\\n -- See Note [Importing DuplicateRecordFields]\\n xs <- lookup_names ie (ieWrappedName n)\\n let gres = map imp_item $ NE.toList xs\\n export_depr_warns\\n | want_hiding == Exactly\\n = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ( [ (IEVar Nothing (L l (replaceWrappedName n name)) noDocstring, [gre])\\n | gre <- gres\\n , let name = greName gre ]\\n , export_depr_warns )\\n\\n IEThingAll x ns_spec (L l tc) _ -> do\\n ImpOccItem { imp_item = gre\\n , imp_bundled = bundled_gres\\n , imp_is_parent = is_par\\n }\\n <- lookup_parent ie $ ieWrappedName tc\\n let name = greName gre\\n\\n child_gres :: [GlobalRdrElt]\\n child_gres\\n | is_par = filterByNamespaceSpecifierGREs ns_spec bundled_gres\\n | otherwise = []\\n\\n imp_list_warn\\n\\n | null child_gres\\n -- e.g. f(..) or T(..) where T is a type synonym\\n = [DodgyImport (DodgyImportsEmptyParent ie ns_spec gre)]\\n\\n -- e.g. import M( T(..) )\\n | not (is_qual decl_spec)\\n = [MissingImportList]\\n\\n | otherwise\\n = []\\n\\n renamed_ie = IEThingAll (x { ieta_warning = Nothing })\\n (rnNamespaceSpecifier ns_spec)\\n (L l (replaceWrappedName tc name))\\n noDocstring\\n export_depr_warn\\n | want_hiding == Exactly\\n = maybeToList $ mk_depr_export_warning gre\\n -- We don\'t want to warn about the children as they\\n -- are not explicitly mentioned; the warning will\\n -- be emitted later on if they are used\\n | otherwise = []\\n\\n return ( [(renamed_ie, gre:child_gres)]\\n , imp_list_warn ++ export_depr_warn)\\n\\n\\n IEThingAbs _ (L l tc\') _\\n | want_hiding == EverythingBut -- hiding ( C )\\n -- Here the \'C\' can be a data constructor\\n -- *or* a type/class, or even both\\n -> let tc = ieWrappedName tc\'\\n tc_name = lookup_parent ie tc\\n dc_name = lookup_parent ie (setRdrNameSpace tc srcDataName)\\n in\\n case catIELookupM [ tc_name, dc_name ] of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n names -> return ( [mkIEThingAbs tc\' l (imp_item name) | name <- names], [])\\n | otherwise\\n -> do ImpOccItem { imp_item = gre } <- lookup_parent ie (ieWrappedName tc\')\\n return ( [mkIEThingAbs tc\' l gre]\\n , maybeToList $ mk_depr_export_warning gre)\\n\\n IEThingWith (deprecation, ann) ltc@(L l rdr_tc) wc rdr_ns _ -> do\\n ImpOccItem { imp_item = gre, imp_bundled = subnames }\\n <- lookup_parent (IEThingAbs Nothing ltc noDocstring) (ieWrappedName rdr_tc)\\n let name = greName gre\\n\\n -- Look up the children in the sub-names of the parent\\n -- See Note [Importing DuplicateRecordFields]\\n let (children_errs, childnames) = lookupChildren subnames rdr_ns\\n\\n bad_import_warns <-\\n if null children_errs then return [] else\\n let items = map lce_wrapped_name children_errs\\n ie = IEThingWith (deprecation, ann) ltc wc items noDocstring\\n -- We are trying to import T( a,b,c,d ), and failed\\n -- to find \'b\' and \'d\'. So we make up an import item\\n -- to report as failing, namely T( b, d ).\\n -- c.f. #15413\\n subordinate_err = mkSubordinateError gre children_errs\\n in bad_import_w ie subordinate_err\\n\\n let name\' = replaceWrappedName rdr_tc name\\n childnames\' = map (to_ie_post_rn . fmap greName) childnames\\n gres = gre : map unLoc childnames\\n export_depr_warns\\n | want_hiding == Exactly = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ([ (IEThingWith (Nothing, ann) (L l name\') wc childnames\' noDocstring\\n ,gres)]\\n , bad_import_warns ++ export_depr_warns)\\n\\n IEWholeNamespace x ns_spec -> do\\n let mod_name = moduleName import_mod\\n names = map greName gres\\n renamed_ie = IEWholeNamespace x { iewn_warning = Nothing\\n , iewn_names = names }\\n (rnNamespaceSpecifier ns_spec)\\n gres = filterByNamespaceSpecifierGREs ns_spec $\\n gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n dodgy_warn\\n | null gres = [DodgyImport (DodgyImportsWildcard mod_name ns_spec)]\\n | otherwise = []\\n return ([(renamed_ie, gres)],\\n dodgy_warn)\\n\\n _other -> failLookupWith IllegalImport\\n -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed...\\n -- all of those constitute errors.\\n\\n where\\n mkIEThingAbs tc l gre\\n = (IEThingAbs Nothing (L l (replaceWrappedName tc n)) noDocstring, [gre])\\n where n = greName gre\\n\\n -- N.B. imports never have docstrings\\n noDocstring = Nothing\\n\\n handle_bad_import m = catchIELookup m $ \\\\case\\n BadImport ie sub -> do\\n ws <- bad_import_w ie sub\\n return ([], ws)\\n err -> failLookupWith err\\n\\n bad_import_w :: IE GhcPs -> IsSubordinateError -> IELookupM [IELookupWarning]\\n bad_import_w ie sub\\n | want_hiding == EverythingBut = return [BadImportW ie sub]\\n | otherwise = failLookupWith (BadImport ie sub)\\n\\n mk_depr_export_warning gre\\n = DeprecatedExport name <$> mi_export_warn_fn iface name\\n where\\n name = greName gre\\n\\n-- | Assuming a subordinate item could not be found, do another lookup for a\\n-- more specific error message.\\nmkBadExportSubordinate :: [GlobalRdrElt] -> LIEWrappedName GhcPs -> BadExportSubordinate\\nmkBadExportSubordinate child_gres n =\\n case lookupChildren child_gres [n] of\\n (LookupChildNonType {lce_nontype_item = g} : _, _) -> BadExportSubordinateNonType g\\n (LookupChildNonData {lce_nondata_item = g} : _, _) -> BadExportSubordinateNonData g\\n _ -> BadExportSubordinateNotFound n\\n\\ntype IELookupM = MaybeErr IELookupError\\n\\ndata IELookupWarning\\n = BadImportW (IE GhcPs) IsSubordinateError\\n | MissingImportList\\n | DodgyImport DodgyImportsReason\\n | DeprecatedExport Name (WarningTxt GhcRn)\\n\\n-- | Is this import/export item a subordinate or not?\\ndata IsSubordinateError\\n = IsSubordinateError { subordinate_err_parent :: !GlobalRdrElt\\n , subordinate_err_unavailable :: [FastString]\\n , subordinate_err_nontype :: [GlobalRdrElt]\\n , subordinate_err_nondata :: [GlobalRdrElt] }\\n | IsNotSubordinate\\n\\nmkSubordinateError :: GlobalRdrElt -> [LookupChildError] -> IsSubordinateError\\nmkSubordinateError gre children_errs = foldr add init_acc children_errs\\n where\\n init_acc :: IsSubordinateError\\n init_acc = IsSubordinateError gre [] [] []\\n\\n add :: LookupChildError -> IsSubordinateError -> IsSubordinateError\\n add children_err sub@IsSubordinateError{} =\\n case children_err of\\n LookupChildNonType{lce_nontype_item = g} ->\\n sub { subordinate_err_nontype = g : subordinate_err_nontype sub }\\n LookupChildNonData{lce_nondata_item = g} ->\\n sub { subordinate_err_nondata = g : subordinate_err_nondata sub }\\n LookupChildNotFound (L _ wname) ->\\n let fs = (occNameFS . rdrNameOcc . ieWrappedName) wname\\n in sub { subordinate_err_unavailable = fs : subordinate_err_unavailable sub }\\n add _ IsNotSubordinate = panic \\"mkSubordinateError: IsNotSubordinate\\"\\n\\ndata IELookupError\\n = QualImportError RdrName\\n | BadImport (IE GhcPs) IsSubordinateError\\n | IllegalImport\\n\\nfailLookupWith :: IELookupError -> IELookupM a\\nfailLookupWith err = Failed err\\n\\ncatchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a\\ncatchIELookup m h = case m of\\n Succeeded r -> return r\\n Failed err -> h err\\n\\ncatIELookupM :: [IELookupM a] -> [a]\\ncatIELookupM ms = [ a | Succeeded a <- ms ]\\n\\n-- | Information associated to an \'AvailInfo\' used in constructing\\n-- an \'OccEnv\' corresponding to imports.\\n--\\n-- See Note [Dealing with imports].\\ndata ImpOccItem\\n = ImpOccItem\\n { imp_item :: GlobalRdrElt\\n -- ^ The import item\\n , imp_bundled :: [GlobalRdrElt]\\n -- ^ Items bundled in the Avail this import item came from,\\n -- not including the import item itself if it is a parent.\\n , imp_is_parent :: Bool\\n -- ^ Is the import item a parent? See Note [Dealing with imports].\\n }\\n\\ninstance Outputable ImpOccItem where\\n ppr (ImpOccItem { imp_item = item, imp_bundled = bundled, imp_is_parent = is_par })\\n = braces $ hsep\\n [ text \\"ImpOccItem\\"\\n , if is_par then text \\"[is_par]\\" else empty\\n , ppr (greName item) <+> ppr (greParent item)\\n , braces $ text \\"bundled:\\" <+> ppr (map greName bundled) ]\\n\\n-- | Make an \'OccEnv\' of all the imports.\\n--\\n-- Complicated by the fact that associated data types and pattern synonyms\\n-- can appear twice. See Note [Dealing with imports].\\nmkImportOccEnv :: HscEnv -> ImpDeclSpec -> [IfaceExport] -> OccEnv (NameEnv ImpOccItem)\\nmkImportOccEnv hsc_env decl_spec all_avails =\\n mkOccEnv_C (plusNameEnv_C combine)\\n [ (occ, mkNameEnv [(nm, item)])\\n | avail <- all_avails\\n , let gres = gresFromAvail hsc_env (Just hiding_spec) avail\\n , gre <- gres\\n , let nm = greName gre\\n occ = greOccName gre\\n (is_parent, bundled) = case avail of\\n AvailTC c _\\n | c == nm -- (Recall the AvailTC invariant from GHC.Types.AvailInfo)\\n -> ( True, drop 1 gres ) -- \\"drop 1\\": don\'t include the parent itself.\\n | otherwise\\n -> ( False, gres )\\n _ -> ( False, [] )\\n item = ImpOccItem\\n { imp_item = gre\\n , imp_bundled = bundled\\n , imp_is_parent = is_parent }\\n ]\\n where\\n\\n hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\n -- See Note [Dealing with imports]\\n -- \'combine\' may be called for associated data types which appear\\n -- twice in the all_avails. In the example, we have two Avails for T,\\n -- namely T(T,T1,T2,T3) and C(C,T), and we combine them by dropping the\\n -- latter, in which T is not the parent.\\n combine :: ImpOccItem -> ImpOccItem -> ImpOccItem\\n combine item1@(ImpOccItem { imp_item = gre1, imp_is_parent = is_parent1 })\\n item2@(ImpOccItem { imp_item = gre2, imp_is_parent = is_parent2 })\\n | is_parent1 || is_parent2\\n , not (isRecFldGRE gre1 || isRecFldGRE gre2) -- NB: does not force GREInfo.\\n , let name1 = greName gre1\\n name2 = greName gre2\\n gre = gre1 `plusGRE` gre2\\n -- See Note [Preserve parent information when combining import OccEnvs]\\n = assertPpr (name1 == name2)\\n (ppr name1 <+> ppr name2) $\\n if is_parent1\\n then item1 { imp_item = gre }\\n else item2 { imp_item = gre }\\n -- Discard C(C,T) in favour of T(T, T1, T2, T3).\\n\\n -- \'combine\' may also be called for pattern synonyms which appear both\\n -- unassociated and associated (see Note [Importing PatternSynonyms]).\\n combine item1@(ImpOccItem { imp_item = c1, imp_bundled = kids1 })\\n item2@(ImpOccItem { imp_item = c2, imp_bundled = kids2 })\\n = assertPpr (greName c1 == greName c2\\n && (not (null kids1 && null kids2)))\\n (ppr c1 <+> ppr c2 <+> ppr kids1 <+> ppr kids2) $\\n if null kids1\\n then item2\\n else item1\\n -- Discard standalone pattern P in favour of T(P).\\n\\n-- | Essentially like @lookupGRE env (LookupOccName occ which_gres)@,\\n-- but working with \'ImpOccItem\'s instead of \'GlobalRdrElt\'s.\\nlookupImpOccEnv :: WhichGREs GREInfo\\n -> OccEnv (NameEnv ImpOccItem) -> OccName -> [NameEnv ImpOccItem]\\nlookupImpOccEnv which_gres env occ =\\n mapMaybe relevant_items $ lookupOccEnv_AllNameSpaces env occ\\n where\\n is_relevant :: ImpOccItem -> Bool\\n is_relevant (ImpOccItem { imp_item = gre }) =\\n greIsRelevant which_gres (occNameSpace occ) gre\\n relevant_items :: NameEnv ImpOccItem -> Maybe (NameEnv ImpOccItem)\\n relevant_items nms\\n | let nms\' = filterNameEnv is_relevant nms\\n = if isEmptyNameEnv nms\'\\n then Nothing\\n else Just nms\'\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{Import/Export Utils}\\n* *\\n************************************************************************\\n-}\\n\\n-- | Given an import\\\\/export spec, appropriately set the @gre_imp@ field\\n-- for the \'GlobalRdrElt\'s.\\ngresFromIE :: ImpDeclSpec -> (LIE GhcRn, [GlobalRdrElt]) -> [GlobalRdrElt]\\ngresFromIE decl_spec (L loc ie, gres)\\n = map set_gre_imp gres\\n where\\n is_explicit = case ie of\\n IEThingAll _ _ name _ -> \\\\n -> n == lieWrappedName name\\n IEWholeNamespace _ _ -> \\\\_ -> False\\n _ -> \\\\_ -> True\\n prov_fn name\\n = ImpSpec { is_decl = decl_spec, is_item = item_spec }\\n where\\n item_spec = ImpSome { is_explicit = is_explicit name\\n , is_iloc = locA loc }\\n set_gre_imp gre@( GRE { gre_name = nm } )\\n = gre { gre_imp = unitBag $ prov_fn nm }\\n\\nparentOfImplicitlyImportedGRE :: Outputable info => GlobalRdrEltX info -> Maybe Name\\nparentOfImplicitlyImportedGRE gre =\\n if any (explicit_import . is_item) $ gre_imp gre\\n then Nothing\\n else greParent_maybe gre\\n where\\n explicit_import :: ImpItemSpec -> Bool\\n explicit_import (ImpAll {}) =\\n pprPanic \\"parentOfImplicitlyImportedGRE: ImpAll\\" (ppr gre)\\n explicit_import (ImpSome { is_explicit }) = is_explicit\\n\\n{- Note [Children for duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider the module\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (F(foo, MkFInt, MkFBool)) where\\n data family F a\\n data instance F Int = MkFInt { foo :: Int }\\n data instance F Bool = MkFBool { foo :: Bool }\\n\\nThe `foo` in the export list refers to *both* selectors! For this\\nreason, lookupChildren builds an environment that maps the FastString\\nto a list of items, rather than a single item.\\n-}\\n\\nmkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]\\nmkChildEnv gres = foldr add emptyNameEnv gres\\n where\\n add gre env = case greParent gre of\\n ParentIs p -> extendNameEnv_Acc (:) Utils.singleton env p gre\\n NoParent -> env\\n\\nfindChildren :: NameEnv [a] -> Name -> [a]\\nfindChildren env n = lookupNameEnv env n `orElse` []\\n\\ndata LookupChildError\\n = LookupChildNotFound { lce_wrapped_name :: !(LIEWrappedName GhcPs) }\\n | LookupChildNonType { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nontype_item :: !GlobalRdrElt }\\n | LookupChildNonData { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nondata_item :: !GlobalRdrElt }\\n\\nlookupChildren :: [GlobalRdrElt]\\n -> [LIEWrappedName GhcPs]\\n -> ( [LookupChildError] -- The ones for which the lookup failed\\n , [LocatedA GlobalRdrElt] )\\n-- (lookupChildren all_kids rdr_items) maps each rdr_item to its\\n-- corresponding Name in all_kids, if the former exists\\n-- The matching is done by FastString, not OccName, so that\\n-- Cls( meth, AssocTy )\\n-- will correctly find AssocTy among the all_kids of Cls, even though\\n-- the RdrName for AssocTy may have a (bogus) DataName namespace\\n-- (Really the rdr_items should be FastStrings in the first place.)\\nlookupChildren all_kids rdr_items = (fails, successes)\\n where\\n mb_xs = map do_one rdr_items\\n fails = [ err | Failed err <- mb_xs ]\\n successes = [ ok | Succeeded oks <- mb_xs, ok <- NE.toList oks ]\\n\\n do_one :: LIEWrappedName GhcPs -> MaybeErr LookupChildError (NonEmpty (LocatedA GlobalRdrElt))\\n do_one item@(L l r) =\\n case r of\\n IEName{}\\n -- IEName (unadorned name) places no restriction on the namespace of\\n -- the imported entity, so we look in both `val_gres` and `typ_gres`.\\n -- In case of conflict (punning), the value namespace takes priority.\\n -- See Note [Prioritise the value namespace in subordinate import lists]\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEType{}\\n -- IEType (\'type\' namespace specifier) restricts the lookup to the\\n -- type namespace, i.e. to `typ_gres`. In case of failure, we check\\n -- `val_gres` to produce a more helpful error message.\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- val_gres -> Failed $ LookupChildNonType item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEData{}\\n -- IEData (\'data\' namespace specifier) restricts the lookup to the\\n -- data namespace, i.e. to `val_gres`. In case of failure, we check\\n -- `typ_gres` to produce a more helpful error message.\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- typ_gres -> Failed $ LookupChildNonData item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEPattern{} -> panic \\"lookupChildren: IEPattern\\" -- Never happens (invalid syntax)\\n IEDefault{} -> panic \\"lookupChildren: IEDefault\\" -- Never happens (invalid syntax)\\n where\\n fs = (occNameFS . rdrNameOcc . ieWrappedName) r\\n gres = fromMaybe [] (lookupFsEnv kid_env fs)\\n (val_gres, typ_gres) = partition (isValNameSpace . greNameSpace) gres\\n\\n -- See Note [Children for duplicate record fields]\\n kid_env :: FastStringEnv [GlobalRdrElt]\\n kid_env = extendFsEnvList_C (++) emptyFsEnv\\n [(occNameFS (occName x), [x]) | x <- all_kids]\\n\\n\\n{- Note [Prioritise the value namespace in subordinate import lists]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider this program that defines a class that has both an associated type\\nnamed (#) and a method named (#)\\n\\n module M_assoc where\\n class C a b where\\n type a # b\\n (#) :: a -> b -> ()\\n module N_assoc where\\n import M_assoc( C((#)) )\\n\\nIn the import declaration, when we see the unadorned name (#) in the subordinate\\nimport list of C, which children should we bring into scope? Our options are:\\n\\n a) only the method (#)\\n b) only the associated type (#)\\n c) both the method and the associated type\\n\\nTo follow the precedent established by top-level items, we go with option (a).\\nIndeed, consider a slightly different program\\n\\n module M_top where\\n type family a # b\\n a # b = ()\\n module N_top where\\n import M_top( (#) )\\n\\nHere the import brings only the function (#) into scope, and one has to say\\n`type (#)` to get the type family.\\n-}\\n\\n-------------------------------\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused names}\\n* *\\n*********************************************************\\n-}\\n\\nreportUnusedNames :: TcGblEnv -> HscSource -> RnM ()\\nreportUnusedNames gbl_env hsc_src\\n = do { keep <- readTcRef (tcg_keep gbl_env)\\n ; traceRn \\"RUN\\" (ppr (tcg_dus gbl_env))\\n ; warnUnusedImportDecls gbl_env hsc_src\\n ; warnUnusedTopBinds $ unused_locals keep\\n ; warnMissingSignatures gbl_env\\n ; warnMissingKindSignatures gbl_env }\\n where\\n used_names :: NameSet -> NameSet\\n used_names keep = findUses (tcg_dus gbl_env) emptyNameSet `unionNameSet` keep\\n -- NB: currently, if f x = g, we only treat \'g\' as used if \'f\' is used\\n -- Hence findUses\\n\\n -- Collect the defined names from the in-scope environment\\n defined_names :: [GlobalRdrElt]\\n defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)\\n\\n kids_env = mkChildEnv defined_names\\n -- This is done in mkExports too; duplicated work\\n\\n gre_is_used :: NameSet -> GlobalRdrElt -> Bool\\n gre_is_used used_names gre0\\n = name `elemNameSet` used_names\\n || any (\\\\ gre -> greName gre `elemNameSet` used_names) (findChildren kids_env name)\\n -- A use of C implies a use of T,\\n -- if C was brought into scope by T(..) or T(C)\\n where\\n name = greName gre0\\n\\n -- Filter out the ones that are\\n -- (a) defined in this module, and\\n -- (b) not defined by a \'deriving\' clause\\n -- The latter have an Internal Name, so we can filter them out easily\\n unused_locals :: NameSet -> [GlobalRdrElt]\\n unused_locals keep =\\n let -- Note that defined_and_used, defined_but_not_used\\n -- are both [GRE]; that\'s why we need defined_and_used\\n -- rather than just used_names\\n _defined_and_used, defined_but_not_used :: [GlobalRdrElt]\\n (_defined_and_used, defined_but_not_used)\\n = partition (gre_is_used (used_names keep)) defined_names\\n\\n in filter is_unused_local defined_but_not_used\\n is_unused_local :: GlobalRdrElt -> Bool\\n is_unused_local gre = isLocalGRE gre\\n && isExternalName (greName gre)\\n\\n{- *********************************************************************\\n* *\\n Missing signatures\\n* *\\n********************************************************************* -}\\n\\n{-\\nNote [Missing signatures]\\n~~~~~~~~~~~~~~~~~~~~~~~~~\\nThere are four warning flags in play:\\n\\n * -Wmissing-exported-signatures\\n Warn about any exported top-level function/value without a type signature.\\n Does not include pattern synonyms.\\n\\n * -Wmissing-signatures\\n Warn about any top-level function/value without a type signature. Does not\\n include pattern synonyms. Takes priority over -Wmissing-exported-signatures.\\n\\n * -Wmissing-exported-pattern-synonym-signatures\\n Warn about any exported pattern synonym without a type signature.\\n\\n * -Wmissing-pattern-synonym-signatures\\n Warn about any pattern synonym without a type signature. Takes priority over\\n -Wmissing-exported-pattern-synonym-signatures.\\n\\n-}\\n\\n-- | Warn the user about top level binders that lack type signatures.\\n-- Called /after/ type inference, so that we can report the\\n-- inferred type of the function\\nwarnMissingSignatures :: TcGblEnv -> RnM ()\\nwarnMissingSignatures gbl_env\\n = do { let exports = availsToNameSet (tcg_exports gbl_env)\\n sig_ns = tcg_sigs gbl_env\\n -- We use sig_ns to exclude top-level bindings that are generated by GHC\\n binds = collectHsBindsBinders CollNoDictBinders $ tcg_binds gbl_env\\n pat_syns = tcg_patsyns gbl_env\\n\\n not_ghc_generated :: Name -> Bool\\n not_ghc_generated name = name `elemNameSet` sig_ns\\n\\n add_binding_warn :: Id -> RnM ()\\n add_binding_warn id =\\n when (not_ghc_generated name) $\\n do { env <- liftZonkM $ tcInitTidyEnv -- Why not use emptyTidyEnv?\\n ; let ty = tidyOpenType env (idType id)\\n missing = MissingTopLevelBindingSig name ty\\n diag = TcRnMissingSignature missing exported\\n ; addDiagnosticAt (getSrcSpan name) diag }\\n where\\n name = idName id\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n add_patsyn_warn :: PatSyn -> RnM ()\\n add_patsyn_warn ps =\\n when (not_ghc_generated name) $\\n addDiagnosticAt (getSrcSpan name)\\n (TcRnMissingSignature missing exported)\\n where\\n name = patSynName ps\\n missing = MissingPatSynSig ps\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n -- Warn about missing signatures\\n -- Do this only when we have a type to offer\\n -- See Note [Missing signatures]\\n ; mapM_ add_binding_warn binds\\n ; mapM_ add_patsyn_warn pat_syns\\n }\\n\\n-- | Warn the user about tycons that lack kind signatures.\\n-- Called /after/ type (and kind) inference, so that we can report the\\n-- inferred kinds.\\nwarnMissingKindSignatures :: TcGblEnv -> RnM ()\\nwarnMissingKindSignatures gbl_env\\n = do { cusks_enabled <- xoptM LangExt.CUSKs\\n ; mapM_ (add_ty_warn cusks_enabled) tcs\\n }\\n where\\n tcs = tcg_tcs gbl_env\\n ksig_ns = tcg_ksigs gbl_env\\n exports = availsToNameSet (tcg_exports gbl_env)\\n\\n has_kind_signature :: Name -> Bool\\n has_kind_signature name = name `elemNameSet` ksig_ns\\n\\n add_ty_warn :: Bool -> TyCon -> RnM ()\\n add_ty_warn cusks_enabled tyCon =\\n when (has_kind_signature name) $\\n addDiagnosticAt (getSrcSpan name) diag\\n where\\n name = tyConName tyCon\\n diag = TcRnMissingSignature missing exported\\n missing = MissingTyConKindSig tyCon cusks_enabled\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused imports}\\n* *\\n*********************************************************\\n\\nThis code finds which import declarations are unused. The\\nspecification and implementation notes are here:\\n https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/unused-imports\\n\\nSee also Note [Choosing the best import declaration] in GHC.Types.Name.Reader\\n-}\\n\\ntype ImportDeclUsage\\n = ( LImportDecl GhcRn -- The import declaration\\n , [GlobalRdrElt] -- What *is* used (normalised)\\n , [Name] -- What is imported but *not* used\\n , [NamespaceSpecifier GhcRn] ) -- Unused wildcards\\n\\nwarnUnusedImportDecls :: TcGblEnv -> HscSource -> RnM ()\\nwarnUnusedImportDecls gbl_env hsc_src\\n = do { uses <- readMutVar (tcg_used_gres gbl_env)\\n ; let imports = tcg_rn_imports gbl_env\\n rdr_env = tcg_rdr_env gbl_env\\n\\n -- We should only warn for unnecessary *user* imports, but deciding\\n -- minimal imports should take generated imports into account\\n ; let usageUserImports = findImportUsage (excludeGenerated imports) uses\\n usageAllImports = findImportUsage imports uses\\n\\n ; traceRn \\"warnUnusedImportDecls\\" $\\n (vcat [ text \\"Uses:\\" <+> ppr uses\\n , text \\"Usage all user imports: \\" <+> ppr usageUserImports\\n , text \\"Usage all imports: \\" <+> ppr usageAllImports])\\n\\n ; mapM_ (warnUnusedImport rdr_env) usageUserImports\\n\\n ; whenGOptM Opt_D_dump_minimal_imports $\\n printMinimalImports hsc_src usageAllImports }\\n\\n-- | Exclude generated imports\\nexcludeGenerated :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\nexcludeGenerated = filterOut (isGeneratedImport . ideclOrigin . ideclExt . unLoc)\\n\\nfindImportUsage :: [LImportDecl GhcRn]\\n -> [GlobalRdrElt]\\n -> [ImportDeclUsage]\\n\\nfindImportUsage imports used_gres\\n = map unused_decl imports\\n where\\n import_usage :: ImportMap\\n import_usage = mkImportMap used_gres\\n\\n unused_decl :: LImportDecl GhcRn -> ImportDeclUsage\\n unused_decl decl@(L _ (ImportDecl { ideclImportList = imps }))\\n = -- pprTrace \\"unused_decl\\" (vcat [ ppr decl\\n -- , text \\"used\\" <+> ppr used_gres\\n -- , text \\"unused\\" <+> ppr unused_names ]) $\\n (decl, used_gres, unused_names, unused_wcs)\\n where\\n used_gres = lookupImportMap decl import_usage\\n\\n used_gre_env = mkGlobalRdrEnv used_gres\\n used_parents = mkNameSet (mapMaybe greParent_maybe used_gres)\\n\\n (unused_names, unused_wcs) -- Not trivial; see eg #7454\\n = case imps of\\n Just (Exactly, imp_ies) ->\\n let unused = foldr (add_unused . unLoc) emptyUnusedNames imp_ies\\n nms = nameSetElemsStable (collectUnusedNames unused)\\n wcs = collectUnusedWildcards unused\\n in (nms, wcs)\\n _other -> ([], []) -- No explicit import list => no unused-name list\\n\\n add_unused :: IE GhcRn -> UnusedNames -> UnusedNames\\n add_unused (IEVar _ n _) acc = add_unused_name (lieWrappedName n) True acc\\n add_unused (IEThingAbs _ n _) acc = add_unused_name (lieWrappedName n) False acc\\n add_unused (IEThingAll _ _ n _) acc = add_unused_all (lieWrappedName n) acc\\n add_unused (IEThingWith _ p wc ns _) acc = add_wc_all (add_unused_with pn xs acc)\\n where pn = lieWrappedName p\\n xs = map lieWrappedName ns\\n add_wc_all = case wc of\\n NoIEWildcard -> id\\n IEWildcard _ -> add_unused_all pn\\n add_unused (IEWholeNamespace x ns_spec) acc = add_unused_wildcard ns_spec (iewn_names x) acc\\n add_unused _ acc = acc\\n\\n add_unused_name :: Name -> Bool -> UnusedNames -> UnusedNames\\n add_unused_name n is_ie_var acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | is_ie_var\\n , isFieldName n\\n -- See Note [Reporting unused imported duplicate record fields]\\n = let\\n fs = getOccFS n\\n (flds, flds_used) = lookupFsEnv acc_fs fs `orElse` (emptyNameSet, Any False)\\n acc_fs\' = extendFsEnv acc_fs fs (extendNameSet flds n, Any used S.<> flds_used)\\n in UnusedNames acc_ns acc_wcs acc_fs\'\\n\\n | used\\n = acc\\n\\n | otherwise\\n = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n where\\n used = isJust $ lookupGRE_Name used_gre_env n\\n\\n add_unused_all :: Name -> UnusedNames -> UnusedNames\\n add_unused_all n acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | Just {} <- lookupGRE_Name used_gre_env n = acc\\n | n `elemNameSet` used_parents = acc\\n | otherwise = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n\\n add_unused_with :: Name -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_with p ns acc\\n | all (`elemNameSet` acc1_ns) ns = add_unused_name p False acc1\\n | otherwise = acc1\\n where\\n acc1@(UnusedNames acc1_ns _ _) = foldr (\\\\n acc\' -> add_unused_name n False acc\') acc ns\\n -- If you use \'signum\' from Num, then the user may well have\\n -- imported Num(signum). We don\'t want to complain that\\n -- Num is not itself mentioned. Hence the two cases in add_unused_with.\\n\\n add_unused_wildcard :: NamespaceSpecifier GhcRn -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_wildcard ns_spec names acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | any_used = acc\\n | otherwise = UnusedNames acc_ns (ns_spec : acc_wcs) acc_fs\\n where\\n -- A wildcard `type ..` or `data ..` is used if at least one of\\n -- the names it expands to is used\\n any_used = any (isJust . lookupGRE_Name used_gre_env) names\\n\\n\\n-- | An accumulator for unused names in an import list.\\n--\\n-- See Note [Reporting unused imported duplicate record fields].\\ndata UnusedNames =\\n UnusedNames\\n { unused_names :: NameSet\\n -- ^ Unused \'Name\'s in an import list, not including record fields\\n -- that are plain \'IEVar\' imports (tracked by \'rec_fld_uses\')\\n -- or wildcard imports (tracked by \'unused_wildcards\').\\n , unused_wildcards :: [NamespaceSpecifier GhcRn]\\n -- ^ Unused wildcards @type ..@ or @data ..@ in an import list.\\n , rec_fld_uses :: FastStringEnv (NameSet, Any)\\n -- ^ Record fields imported without a parent (i.e. an \'IEVar\' import).\\n --\\n -- The \'Any\' value records whether any of the record fields\\n -- sharing the same underlying \'FastString\' have been used.\\n }\\n\\nemptyUnusedNames :: UnusedNames\\nemptyUnusedNames = UnusedNames emptyNameSet [] emptyFsEnv\\n\\ninstance Outputable UnusedNames where\\n ppr (UnusedNames nms wcs flds) =\\n text \\"UnusedNames\\" <+>\\n braces (ppr nms <+> ppr wcs <+> ppr (fmap (second getAny) flds))\\n\\n-- | Collect all unused names from a \'UnusedNames\' value.\\ncollectUnusedNames :: UnusedNames -> NameSet\\ncollectUnusedNames (UnusedNames { unused_names = nms, rec_fld_uses = flds })\\n = nms S.<> unused_flds\\n where\\n unused_flds = nonDetFoldFsEnv collect_unused emptyNameSet flds\\n collect_unused :: (NameSet, Any) -> NameSet -> NameSet\\n collect_unused (nms, Any at_least_one_name_is_used) acc\\n | at_least_one_name_is_used = acc\\n | otherwise = unionNameSet nms acc\\n\\ncollectUnusedWildcards :: UnusedNames -> [NamespaceSpecifier GhcRn]\\ncollectUnusedWildcards = unused_wildcards\\n\\n{- Note [Reporting unused imported duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have (#24035):\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M1 (R1(..), R2(..)) where\\n data R1 = MkR1 { fld :: Int }\\n data R2 = MkR2 { fld :: Int }\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M2 where\\n import M1 (R1(MkR1), R2, fld)\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nIn the import of \'M1\' in \'M2\', the \'fld\' import resolves to two separate GREs,\\nnamely R1(fld) and R2(fld). From the perspective of the renamer, and in particular\\nthe \'findImportUsage\' function, it\'s as if the user had imported the two names\\nseparately (even though no source syntax allows that).\\n\\nThis means that we need to be careful when reporting unused imports: the R2(fld)\\nimport is indeed unused, but because R1(fld) is used, we should not report\\nfld as unused altogether.\\n\\nTo achieve this, we keep track of record field imports without a parent (i.e.\\nusing the IEVar constructor) separately from other import items, using the\\nUnusedNames datatype.\\nOnce we have accumulated usages, we emit warnings for unused record fields\\nwithout parents one whole group (of record fields sharing the same textual name)\\nat a time, and only if *all* of the record fields in the group are unused;\\nsee \'collectUnusedNames\'.\\n\\nNote that this only applies to record fields imported without a parent. If we\\nhad:\\n\\n import M1 (R1(MkR1, fld), R2(fld))\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nthen of course we should report the second \'fld\' as unused.\\n-}\\n\\n\\n{- Note [The ImportMap]\\n~~~~~~~~~~~~~~~~~~~~~~~\\nThe ImportMap is a short-lived intermediate data structure records, for\\neach import declaration, what stuff brought into scope by that\\ndeclaration is actually used in the module.\\n\\nThe [GlobalRdrElt] are the things imported from that decl.\\n-}\\n\\ndata ImportMap = ImportMap\\n { im_imports :: Map RealSrcSpan [GlobalRdrElt]\\n -- ^ See [The ImportMap]\\n -- If loc :-> gres, then\\n -- \'loc\' = the end loc of the bestImport of each GRE in \'gres\'\\n , im_generatedImports :: Map ModuleName [GlobalRdrElt]\\n }\\n\\nmkImportMap :: [GlobalRdrElt] -> ImportMap\\n-- For each of a list of used GREs, find all the import decls that brought\\n-- it into scope; choose one of them (bestImport), and record\\n-- the RdrName in that import decl\'s entry in the ImportMap\\nmkImportMap = foldr insertImportMap $ ImportMap Map.empty Map.empty\\n\\ninsertImportMap :: GlobalRdrElt -> ImportMap -> ImportMap\\ninsertImportMap gre@(GRE { gre_imp = imp_specs }) importMap\\n | RealSrcSpan importSpan _ <- is_dloc best_imp_spec =\\n importMap{im_imports = insertElem importSpan gre $ im_imports importMap}\\n | GeneratedSrcSpan{} <- is_dloc best_imp_spec =\\n importMap{im_generatedImports = insertElem (moduleName $ is_mod best_imp_spec) gre $ im_generatedImports importMap}\\n | otherwise = importMap\\n where\\n best_imp_spec =\\n case bagToList imp_specs of\\n [] -> pprPanic \\"mkImportMap: GRE with no ImportSpecs\\" (ppr gre)\\n is:iss -> is_decl $ bestImport (is NE.:| iss)\\n\\n -- https://github.com/haskell/containers/issues/784\\n insertElem :: Ord k => k -> v -> Map k [v] -> Map k [v]\\n insertElem k v = flip Map.alter k $ \\\\case\\n Just vs -> Just (v : vs)\\n Nothing -> Just [v]\\n\\nlookupImportMap :: LImportDecl GhcRn -> ImportMap -> [GlobalRdrElt]\\nlookupImportMap (L srcSpan ImportDecl{ideclName = L _ modName}) importMap =\\n fromMaybe [] $\\n -- should match logic in insertImportMap\\n case locA srcSpan of\\n RealSrcSpan realSrcSpan _ -> realSrcSpan `Map.lookup` im_imports importMap\\n GeneratedSrcSpan{} -> modName `Map.lookup` im_generatedImports importMap\\n _ -> Nothing\\n\\nlieNames :: LIE (GhcPass p) -> [Located (IdP (GhcPass p))]\\nlieNames = _\\n\\nwarnUnusedImport :: GlobalRdrEnv -> ImportDeclUsage -> RnM ()\\nwarnUnusedImport rdr_env (L loc decl, used, unused, unused_wcs)\\n\\n -- Do not warn for \'import M()\'\\n -- See (UI1) in Note [Unused imports]\\n | Just (Exactly, _) <- ideclImportList decl\\n , null unused && null unused_wcs\\n = return ()\\n\\n -- Note [Do not warn about Prelude hiding]\\n | Just (EverythingBut, hides) <- ideclImportList decl\\n , not (null hides)\\n , pRELUDE_NAME == unLoc (ideclName decl)\\n = return ()\\n\\n -- Do not warn about import X as Rebindable\\n -- See (UI2) in Note [Unused imports]\\n | Just (L _ mod) <- ideclAs decl\\n , mod == rEBINDABLE_MOD_NAME\\n = return ()\\n\\n -- Nothing used; drop entire declaration\\n | null used\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl UnusedImportNone)\\n\\n -- Everything imported is used; nop\\n | null unused && null unused_wcs\\n = return ()\\n\\n -- Some imports are unused: make the `SrcSpan` cover only the unused\\n -- items instead of the whole import statement\\n | Just (_, imports) <- ideclImportList decl\\n , let unused_locs = [ locA loc | L loc ie <- imports\\n , name <- ieNames ie\\n , name `elem` unused ]\\n , loc1 : locs <- unused_locs\\n , let span = foldr1 combineSrcSpans ( loc1 NE.:| locs )\\n = addDiagnosticAt span (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n -- Some imports are unused\\n | otherwise\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n where\\n -- In warning message, pretty-print identifiers unqualified unconditionally\\n -- to improve the consistent for ambiguous/unambiguous identifiers.\\n -- See #14881.\\n possible_field n =\\n case lookupGRE_Name rdr_env n of\\n Just (GRE { gre_par = par, gre_info = IAmRecField info }) ->\\n let fld_occ :: OccName\\n fld_occ = nameOccName $ flSelector $ recFieldLabel info\\n in UnusedImportNameRecField par fld_occ\\n _ -> UnusedImportNameRegular n\\n\\n -- Print unused names in a deterministic (lexicographic) order\\n sort_unused :: [UnusedImportName]\\n sort_unused =\\n [ UnusedImportWildcard wc | wc <- unused_wcs ] ++\\n [ possible_field nm | nm <- sortBy (comparing nameOccName) unused ]\\n\\ngetMinimalImports :: [ImportDeclUsage] -> RnM [LImportDecl GhcRn]\\ngetMinimalImports ie_decls\\n = do { rdr_env <- getGlobalRdrEnv\\n ; fmap combine $ mapM (mk_minimal rdr_env) ie_decls }\\n where\\n mk_minimal rdr_env (L l decl, used_gres, unused, unused_wcs)\\n | null unused && null unused_wcs\\n , Just (Exactly, _) <- ideclImportList decl\\n = return (L l decl)\\n | otherwise\\n = do { let ImportDecl { ideclName = L _ mod_name\\n , ideclSource = is_boot\\n , ideclPkgQual = pkg_qual\\n , ideclExt = XImportDeclPass { ideclOrigin = origin } } = decl\\n ; iface <- loadSrcInterface doc (importDeclLookupScope origin)\\n mod_name is_boot pkg_qual\\n ; let used_avails = gresToAvailInfo used_gres\\n ; lies <- map (L l) <$> concatMapM (to_ie rdr_env iface) used_avails\\n ; return (L l (decl { ideclImportList = Just (Exactly, lies) })) }\\n where\\n doc = text \\"Compute minimal imports for\\" <+> ppr decl\\n\\n to_ie :: GlobalRdrEnv -> ModIface -> AvailInfo -> RnM [IE GhcRn]\\n -- The main trick here is that if we\'re importing all the constructors\\n -- we want to say \\"T(..)\\", but if we\'re importing only a subset we want\\n -- to say \\"T(A,B,C)\\". So we have to find out what the module exports.\\n to_ie rdr_env _ (Avail c) -- Note [Overloaded field import]\\n = do { let\\n gre = expectJust $ lookupGRE_Name rdr_env c\\n ; return $ [IEVar Nothing (to_ie_post_rn $ noLocA $ greName gre) Nothing] }\\n to_ie _ _ avail@(AvailTC n [_]) -- Exporting the main decl and nothing else\\n | availExportsDecl avail\\n = return [IEThingAbs Nothing (to_ie_post_rn $ noLocA n) Nothing]\\n to_ie rdr_env iface (AvailTC n cs) =\\n case [ xs | avail@(AvailTC x xs) <- mi_exports iface\\n , x == n\\n , availExportsDecl avail -- Note [Partial export]\\n ] of\\n [xs]\\n | all_used xs\\n -> return [IEThingAll (IEThingAllExt Nothing noAnn noAnn noAnn)\\n (NoNamespaceSpecifier noExtField)\\n (to_ie_post_rn $ noLocA n)\\n Nothing]\\n | otherwise\\n -> do { let ns_gres = map (expectJust . lookupGRE_Name rdr_env) cs\\n ns = map greName ns_gres\\n ; return [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n -- Note [Overloaded field import]\\n _other\\n -> do { let infos = map (expectJust . lookupGRE_Name rdr_env) cs\\n (ns_gres,fs_gres) = classifyGREs infos\\n ns = map greName (ns_gres ++ fs_gres)\\n fs = map fieldGREInfo fs_gres\\n ; return $\\n if all_non_overloaded fs\\n then map (\\\\nm -> IEVar Nothing (to_ie_post_rn_var $ noLocA nm) Nothing) ns\\n else [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n where\\n\\n all_used avail_cs = all (`elem` cs) avail_cs\\n\\n all_non_overloaded = all (not . flIsOverloaded . recFieldLabel)\\n\\n combine :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\n combine = map merge . NE.groupAllWith getKey\\n\\n getKey :: LImportDecl GhcRn -> (Bool, Maybe ModuleName, ModuleName)\\n getKey decl =\\n ( isImportDeclQualified . ideclQualified $ idecl -- is this qualified? (important that this be first)\\n , unLoc <$> ideclAs idecl -- what is the qualifier (inside Maybe monad)\\n , unLoc . ideclName $ idecl -- Module Name\\n )\\n where\\n idecl :: ImportDecl GhcRn\\n idecl = unLoc decl\\n\\n merge :: NonEmpty (LImportDecl GhcRn) -> LImportDecl GhcRn\\n merge decls@((L l decl) :| _) = L l (decl { ideclImportList = Just (Exactly, lies) })\\n where lies = concatMap snd $ mapMaybe (ideclImportList . unLoc) $ NE.toList decls\\n\\nclassifyGREs :: [GlobalRdrElt] -> ([GlobalRdrElt], [FieldGlobalRdrElt])\\nclassifyGREs = partition (not . isRecFldGRE)\\n\\nprintMinimalImports :: HscSource -> [ImportDeclUsage] -> RnM ()\\n-- See Note [Printing minimal imports]\\nprintMinimalImports hsc_src imports_w_usage\\n = do { imports\' <- excludeGenerated <$> getMinimalImports imports_w_usage\\n ; this_mod <- getModule\\n ; dflags <- getDynFlags\\n ; liftIO $ withFile (mkFilename dflags this_mod) WriteMode $ \\\\h ->\\n printForUser dflags h neverQualify AllTheWay (vcat (map ppr imports\'))\\n -- The neverQualify is important. We are printing Names\\n -- but they are in the context of an \'import\' decl, and\\n -- we never qualify things inside there\\n -- E.g. import Blag( f, b )\\n -- not import Blag( Blag.f, Blag.g )!\\n }\\n where\\n mkFilename dflags this_mod\\n | Just d <- dumpDir dflags = d basefn\\n | otherwise = basefn\\n where\\n suffix = case hsc_src of\\n HsBootFile -> \\".imports-boot\\"\\n HsSrcFile -> \\".imports\\"\\n HsigFile -> \\".imports\\"\\n basefn = moduleNameString (moduleName this_mod) ++ suffix\\n\\n\\nto_ie_post_rn_var :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn_var (L l n)\\n | isDataOcc $ occName n = L l (IEPattern noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n\\n\\nto_ie_post_rn :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn (L l n)\\n | isTcOcc occ && isSymOcc occ = L l (IEType noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n where occ = occName n\\n\\n{- Note [Do not warn about Prelude hiding]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWe do not warn about\\n import Prelude hiding( x, y )\\nbecause even if nothing else from Prelude is used, it may be essential to hide\\nx,y to avoid name-shadowing warnings. Example (#9061)\\n import Prelude hiding( log )\\n f x = log where log = ()\\n\\nNote [Unused imports]\\n~~~~~~~~~~~~~~~~~~~~~\\nIn `warnUnusedImport`, if we see an import with an explicit list imports, thus\\n import M( a, b )\\nand neither `a` nor `b` is used, we report the entire import decl as unused. We\\ncheck this by looking at the names that it brings into scope scope; if there are\\nno ununused names, don\'t report.\\n\\n(UI1) We don\'t want to complain about `import M()`, because that is often used to bring\\n M\'s /instances/ into scope. That is neatly dealt with by the \\"no unused\\n names\\" (nor unused wildcard imports) criterion.\\n\\n(UI2) We don\'t report a decl as unused if it has an `as Rebindable` qualifier.\\n See (KN1) in Note [Overview of known entities] in GHC.Builtin\\n\\n\\nNote [Printing minimal imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nTo print the minimal imports we walk over all import decls (both user-supplied\\nand generated), trim their import lists, then filter out generated decls.\\n\\nNB that\\n\\n * We do *not* change the \'qualified\' or \'as\' parts!\\n\\n * We do not discard a decl altogether; we might need instances\\n from it. Instead we just trim to an empty import list\\n\\nNote [Partial export]\\n~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have\\n\\n module A( op ) where\\n class C a where\\n op :: a -> a\\n\\n module B where\\n import A\\n f = ..op...\\n\\nThen the minimal import for module B is\\n import A( op )\\nnot\\n import A( C( op ) )\\nwhich we would usually generate if C was exported from B. Hence\\nthe availExportsDecl test when deciding what to generate.\\n\\n\\nNote [Overloaded field import]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nOn the other hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n data T = MkT { foo :: Int }\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( T(foo) )\\nbecause when DuplicateRecordFields is enabled, field selectors are\\nnot in scope without their enclosing datatype.\\n\\nOn the third hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n pattern MkT { foo } = Just foo\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( foo )\\nbecause foo doesn\'t have a parent. This might actually be ambiguous if A\\nexports another field called foo, but there is no good answer to return and this\\nis a very obscure corner, so it seems to be the best we can do. See\\nDRFPatSynExport for a test of this.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Errors}\\n* *\\n************************************************************************\\n-}\\n\\nbadImportItemErr\\n :: ModIface -> ImpDeclSpec -> IE GhcPs\\n -> IsSubordinateError\\n -> [AvailInfo]\\n -> TcRn (NonEmpty ImportLookupReason)\\nbadImportItemErr iface decl_spec ie sub avails = do\\n exts <- importLookupExtensions\\n let import_lookup_bad :: BadImportKind -> ImportLookupReason\\n import_lookup_bad k = ImportLookupBad k iface decl_spec ie exts\\n dflags <- getDynFlags\\n hsc_env <- getTopEnv\\n let rdr_env = mkGlobalRdrEnv\\n $ gresFromAvails hsc_env (Just imp_spec) all_avails\\n pure $ fmap import_lookup_bad (importErrorKind dflags rdr_env)\\n where\\n importErrorKind :: DynFlags -> GlobalRdrEnv -> NonEmpty BadImportKind\\n importErrorKind dflags rdr_env\\n | any checkIfTyCon avails = case sub of\\n IsNotSubordinate -> NE.singleton BadImportAvailTyCon\\n IsSubordinateError { subordinate_err_parent = gre\\n , subordinate_err_unavailable = unavailable\\n , subordinate_err_nontype = nontype\\n , subordinate_err_nondata = nondata }\\n -> NE.fromList $ catMaybes $\\n [ fmap (BadImportNotExportedSubordinates gre) (NE.nonEmpty unavailable)\\n , fmap (BadImportNonTypeSubordinates gre) (NE.nonEmpty nontype)\\n , fmap (BadImportNonDataSubordinates gre) (NE.nonEmpty nondata) ]\\n | any checkIfVarName avails = NE.singleton BadImportAvailVar\\n | Just con <- find checkIfDataCon avails = NE.singleton (BadImportAvailDataCon (availOccName con))\\n | otherwise = NE.singleton (BadImportNotExported suggs)\\n where\\n suggs = similar_suggs ++ fieldSelectorSuggestions rdr_env rdr\\n what_look = case sub of\\n IsNotSubordinate -> WL_TyCon_or_TermVar\\n IsSubordinateError { subordinate_err_parent = gre } ->\\n case greInfo gre of\\n IAmTyCon ClassFlavour\\n -> WL_TyCon_or_TermVar\\n _ -> WL_Term\\n similar_names =\\n similarNameSuggestions (Unbound.LF what_look WL_Global)\\n dflags rdr_env emptyLocalRdrEnv rdr\\n similar_suggs =\\n case NE.nonEmpty $ mapMaybe imported_item $ similar_names of\\n Just similar -> [ SuggestSimilarNames rdr similar ]\\n Nothing -> [ ]\\n\\n -- Only keep imported items, and set the \\"HowInScope\\" to\\n -- \\"Nothing\\" to avoid printing \\"imported from...\\" in the suggestion\\n -- error message.\\n imported_item (SimilarRdrName rdr_name gre (Just (ImportedBy {})))\\n = Just (SimilarRdrName rdr_name gre Nothing)\\n imported_item _ = Nothing\\n\\n checkIfDataCon = checkIfAvailMatches isDataConName\\n checkIfTyCon = checkIfAvailMatches isTyConName\\n checkIfVarName =\\n \\\\case\\n AvailTC{} -> False\\n Avail n -> importedFS == occNameFS (occName n)\\n && (isVarOcc <||> isFieldOcc) (occName n)\\n checkIfAvailMatches namePred =\\n \\\\case\\n AvailTC _ ns ->\\n case find (\\\\n -> importedFS == occNameFS (occName n)) ns of\\n Just n -> namePred n\\n Nothing -> False\\n Avail{} -> False\\n availOccName = occName . availName\\n rdr = ieName ie\\n importedFS = occNameFS $ rdrNameOcc rdr\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n all_avails = mi_exports iface\\n\\nimportLookupExtensions :: TcRn ImportLookupExtensions\\nimportLookupExtensions = do\\n ile_pattern_synonyms <- xoptM LangExt.PatternSynonyms\\n ile_explicit_namespaces <- xoptM LangExt.ExplicitNamespaces\\n return ImportLookupExtensions{ile_pattern_synonyms, ile_explicit_namespaces}\\n\\naddDupDeclErr :: NonEmpty GlobalRdrElt -> TcRn ()\\naddDupDeclErr gres@(gre :| _)\\n -- Report the error at the later location\\n = addErrAt (getSrcSpan (NE.last sorted_names)) $ (TcRnDuplicateDecls (greOccName gre) sorted_names)\\n where\\n sorted_names =\\n NE.sortBy (SrcLoc.leftmost_smallest `on` nameSrcSpan)\\n (fmap greName gres)\\n\\n-- This data decl will parse OK\\n-- data T = a Int\\n-- treating \\"a\\" as the constructor.\\n-- It is really hard to make the parser spot this malformation.\\n-- So the renamer has to check that the constructor is legal\\n--\\n-- We can get an operator as the constructor, even in the prefix form:\\n-- data T = :% Int Int\\n-- from interface files, which always print in prefix form\\n--\\n-- We also allow type constructor names, which are defined by \\"type data\\"\\n-- declarations. See Note [Type data declarations] in GHC.Rename.Module.\\n\\ncheckConName :: RdrName -> TcRn ()\\ncheckConName name\\n = checkErr (isRdrDataCon name || isRdrTc name) (TcRnIllegalDataCon name)\\n", "filetypes": ["haskell"]}}}' 2026-10-16 14:45:50,447 - DEBUG - POST b'http://127.0.0.1:37093/receive_messages' {'content-type': 'application/json', 'x-ycm-hmac': b'Rga7Yd4l4fgfufwYw+0sxzurvznImlBO0MPmgAlS4EY='} b'{"filepath": "/home/enrico/ghc/compiler/GHC/Rename/Names.hs", "line_num": 1, "column_num": 1, "working_dir": "/home/enrico/ghc", "file_data": {"/home/enrico/ghc/compiler/GHC/Rename/Names.hs": {"contents": "{-\\n(c) The GRASP/AQUA Project, Glasgow University, 1992-1998\\n\\nExtracting imported and top-level names in scope\\n-}\\n\\n{-# LANGUAGE NondecreasingIndentation #-}\\n{-# LANGUAGE TypeFamilies #-}\\n\\nmodule GHC.Rename.Names (\\n rnImports, getLocalNonValBinders, newRecordFieldLabel,\\n importsFromIface,\\n ImportUserSpec(..),\\n extendGlobalRdrEnvRn,\\n gresFromAvails,\\n calculateAvails,\\n reportUnusedNames,\\n checkConName,\\n mkChildEnv,\\n findChildren,\\n mkBadExportSubordinate,\\n findImportUsage,\\n getMinimalImports,\\n printMinimalImports,\\n renamePkgQual, renameRawPkgQual,\\n classifyGREs,\\n ImportDeclUsage,\\n rnNamespaceSpecifier\\n ) where\\n\\nimport GHC.Prelude hiding ( head, init, last, tail )\\n\\nimport GHC.Driver.Env\\nimport GHC.Driver.Session\\nimport GHC.Driver.Ppr\\n\\nimport GHC.Rename.Env\\nimport GHC.Rename.Fixity\\nimport GHC.Rename.Utils ( warnUnusedTopBinds )\\nimport GHC.Rename.Unbound\\nimport qualified GHC.Rename.Unbound as Unbound\\n\\nimport GHC.Tc.Errors.Types\\nimport GHC.Tc.Utils.Env\\nimport GHC.Tc.Utils.Monad\\nimport GHC.Tc.Types.LclEnv\\nimport GHC.Tc.Zonk.TcType ( tcInitTidyEnv )\\n\\nimport GHC.Hs\\nimport GHC.Iface.Load ( loadSrcInterface, loadSrcInterface_maybe )\\nimport GHC.Iface.Errors.Types\\n ( IfaceMessage(..), MissingInterfaceError, InterfaceLookingFor(..)\\n , LoadEssentialsReason(..) )\\nimport GHC.Iface.Syntax ( fromIfaceWarnings )\\nimport GHC.Builtin.Modules( pRELUDE_NAME, rEBINDABLE_MOD_NAME )\\nimport GHC.Parser.PostProcess ( setRdrNameSpace )\\nimport GHC.Core.TyCo.Tidy\\nimport GHC.Core.PatSyn\\nimport GHC.Core.TyCon ( TyCon, tyConName )\\nimport qualified GHC.LanguageExtensions as LangExt\\n\\nimport GHC.Utils.Outputable as Outputable\\nimport GHC.Utils.Misc as Utils\\nimport GHC.Utils.Panic\\n\\nimport GHC.Types.Fixity.Env\\nimport GHC.Types.SafeHaskell\\nimport GHC.Types.Name\\nimport GHC.Types.Name.Env\\nimport GHC.Types.Name.Set\\nimport GHC.Types.Name.Reader\\nimport GHC.Types.Avail\\nimport GHC.Types.FieldLabel\\nimport GHC.Types.Hint\\nimport GHC.Types.SourceFile\\nimport GHC.Types.SrcLoc as SrcLoc\\nimport GHC.Types.Basic (TyConFlavour (..), convImportLevel, VisArity)\\nimport GHC.Types.UnresolvedImport\\nimport GHC.Types.Id\\nimport GHC.Types.PkgQual\\nimport GHC.Types.GREInfo (ConInfo(..), ConFieldInfo (..), ConLikeInfo (ConIsData))\\n\\nimport GHC.Unit\\nimport GHC.Unit.Module.Warnings\\nimport GHC.Unit.Module.ModIface\\nimport GHC.Unit.Module.Imported\\nimport GHC.Unit.Module.Deps\\nimport GHC.Unit.Env\\n\\nimport GHC.Data.Bag\\nimport GHC.Data.FastString\\nimport GHC.Data.FastString.Env\\nimport GHC.Data.Maybe\\nimport GHC.Data.List.SetOps ( removeDups )\\n\\nimport Control.Arrow ( second )\\nimport Control.Monad\\nimport Data.Foldable ( for_ )\\nimport Data.IntMap ( IntMap )\\nimport qualified Data.IntMap as IntMap\\nimport Data.Map ( Map )\\nimport qualified Data.Map as Map\\nimport Data.Ord ( comparing )\\nimport Data.Semigroup ( Any(..) )\\nimport qualified Data.Semigroup as S\\nimport Data.List ( partition, find, sortBy )\\nimport Data.List.NonEmpty (NonEmpty(..))\\nimport qualified Data.List.NonEmpty as NE\\nimport Data.Function ( on )\\nimport qualified Data.Set as S\\nimport System.FilePath (())\\nimport System.IO\\n\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{rnImports}\\n* *\\n************************************************************************\\n\\nNote [Tracking Trust Transitively]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen we import a package as well as checking that the direct imports are safe\\naccording to the rules outlined in the Note [Safe Haskell Trust Check] in GHC.Driver.Main\\nwe must also check that these rules hold transitively for all dependent modules\\nand packages. Doing this without caching any trust information would be very\\nslow as we would need to touch all packages and interface files a module depends\\non. To avoid this we make use of the property that if a modules Safe Haskell\\nmode changes, this triggers a recompilation from that module in the dependency\\ngraph. So we can just worry mostly about direct imports.\\n\\nThere is one trust property that can change for a package though without\\nrecompilation being triggered: package trust. So we must check that all\\npackages a module transitively depends on to be trusted are still trusted when\\nwe are compiling this module (as due to recompilation avoidance some modules\\nbelow may not be considered trusted any more without recompilation being\\ntriggered).\\n\\nWe handle this by augmenting the existing transitive list of packages a module M\\ndepends on with a bool for each package that says if it must be trusted when the\\nmodule M is being checked for trust. This list of trust required packages for a\\nsingle import is gathered in the rnImportDecl function and stored in an\\nImportAvails data structure. The union of these trust required packages for all\\nimports is done by the rnImports function using the combine function which calls\\nthe plusImportAvails function that is a union operation for the ImportAvails\\ntype. This gives us in an ImportAvails structure all packages required to be\\ntrusted for the module we are currently compiling. Checking that these packages\\nare still trusted (and that direct imports are trusted) is done in\\nGHC.Driver.Main.checkSafeImports.\\n\\nSee the note below, [Trust Own Package] for a corner case in this method and\\nhow its handled.\\n\\n\\nNote [Trust Own Package]\\n~~~~~~~~~~~~~~~~~~~~~~~~\\nThere is a corner case of package trust checking that the usual transitive check\\ndoesn\'t cover. (For how the usual check operates see the Note [Tracking Trust\\nTransitively] below). The case is when you import a -XSafe module M and M\\nimports a -XTrustworthy module N. If N resides in a different package than M,\\nthen the usual check works as M will record a package dependency on N\'s package\\nand mark it as required to be trusted. If N resides in the same package as M\\nthough, then importing M should require its own package be trusted due to N\\n(since M is -XSafe so doesn\'t create this requirement by itself). The usual\\ncheck fails as a module doesn\'t record a package dependency of its own package.\\nSo instead we now have a bool field in a modules interface file that simply\\nstates if the module requires its own package to be trusted. This field avoids\\nus having to load all interface files that the module depends on to see if one\\nis trustworthy.\\n\\n\\nNote [Trust Transitive Property]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSo there is an interesting design question in regards to transitive trust\\nchecking. Say I have a module B compiled with -XSafe. B is dependent on a bunch\\nof modules and packages, some packages it requires to be trusted as its using\\n-XTrustworthy modules from them. Now if I have a module A that doesn\'t use safe\\nhaskell at all and simply imports B, should A inherit all the trust\\nrequirements from B? Should A now also require that a package p is trusted since\\nB required it?\\n\\nWe currently say no but saying yes also makes sense. The difference is, if a\\nmodule M that doesn\'t use Safe Haskell imports a module N that does, should all\\nthe trusted package requirements be dropped since M didn\'t declare that it cares\\nabout Safe Haskell (so -XSafe is more strongly associated with the module doing\\nthe importing) or should it be done still since the author of the module N that\\nuses Safe Haskell said they cared (so -XSafe is more strongly associated with\\nthe module that was compiled that used it).\\n\\nGoing with yes is a simpler semantics we think and harder for the user to stuff\\nup but it does mean that Safe Haskell will affect users who don\'t care about\\nSafe Haskell as they might grab a package from Cabal which uses safe haskell (say\\nnetwork) and that packages imports -XTrustworthy modules from another package\\n(say bytestring), so requires that package is trusted. The user may now get\\ncompilation errors in code that doesn\'t do anything with Safe Haskell simply\\nbecause they are using the network package. They will have to call \'ghc-pkg\\ntrust network\' to get everything working. Due to this invasive nature of going\\nwith yes we have gone with no for now.\\n-}\\n\\n-- | Process Import Decls. See \'rnImportDecl\' for a description of what\\n-- the return types represent.\\n-- Note: Do the non SOURCE ones first, so that we get a helpful warning\\n-- for SOURCE ones that are unnecessary\\nrnImports :: [(LImportDecl GhcPs, SDoc)]\\n -> RnM ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\nrnImports imports = do\\n tcg_env <- getGblEnv\\n -- NB: want an identity module here, because it\'s OK for a signature\\n -- module to import from its implementor\\n let this_mod = tcg_mod tcg_env\\n let (source, ordinary) = partition (is_source_import . fst) imports\\n is_source_import (d::LImportDecl GhcPs) = ideclSource (unLoc d) == IsBoot\\n stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary\\n stuff2 <- mapAndReportM (rnImportDecl this_mod) source\\n -- Safe Haskell: See Note [Tracking Trust Transitively]\\n let (decls, imp_user_spec, rdr_env, imp_avails) = combine (stuff1 ++ stuff2)\\n -- Update imp_boot_mods if imp_direct_mods mentions any of them\\n let merged_import_avail = clobberSourceImports imp_avails\\n return (decls, imp_user_spec, rdr_env, merged_import_avail)\\n\\n where\\n clobberSourceImports imp_avails =\\n imp_avails { imp_boot_mods = imp_boot_mods\' }\\n where\\n imp_boot_mods\' = mergeInstalledModuleEnv combJ id (const emptyInstalledModuleEnv)\\n (imp_boot_mods imp_avails)\\n (imp_direct_dep_mods imp_avails)\\n\\n combJ (GWIB _ IsBoot) (_, x) = Just x\\n combJ r _ = Just r\\n -- See Note [Combining ImportAvails]\\n combine :: [(LImportDecl GhcRn, ImportUserSpec, GlobalRdrEnv, ImportAvails)]\\n -> ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\n combine ss =\\n let (decls, imp_user_spec, rdr_env, imp_avails, finsts) = foldr\\n plus\\n ([], [], emptyGlobalRdrEnv, emptyImportAvails, emptyModuleSet)\\n ss\\n in (decls, imp_user_spec, rdr_env, imp_avails { imp_finsts = moduleSetElts finsts })\\n\\n plus (decl, us, gbl_env1, imp_avails1)\\n (decls, uss, gbl_env2, imp_avails2, finsts_set)\\n = ( decl:decls,\\n us:uss,\\n gbl_env1 `plusGlobalRdrEnv` gbl_env2,\\n imp_avails1\' `plusImportAvails` imp_avails2,\\n extendModuleSetList finsts_set new_finsts )\\n where\\n imp_avails1\' = imp_avails1 { imp_finsts = [] }\\n new_finsts = imp_finsts imp_avails1\\n\\n{-\\nNote [Combining ImportAvails]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nimp_finsts in ImportAvails is a list of family instance modules\\ntransitively depended on by an import. imp_finsts for a currently\\ncompiled module is a union of all the imp_finsts of imports.\\nComputing the union of two lists of size N is O(N^2) and if we\\ndo it to M imports we end up with O(M*N^2). That can get very\\nexpensive for bigger module hierarchies.\\n\\nUnion can be optimized to O(N log N) if we use a Set.\\nimp_finsts is converted back and forth between dep_finsts, so\\nchanging a type of imp_finsts means either paying for the conversions\\nor changing the type of dep_finsts as well.\\n\\nI\'ve measured that the conversions would cost 20% of allocations on my\\ntest case, so that can be ruled out.\\n\\nChanging the type of dep_finsts forces checkFamInsts to\\nget the module lists in non-deterministic order. If we wanted to restore\\nthe deterministic order, we\'d have to sort there, which is an additional\\ncost. As far as I can tell, using a non-deterministic order is fine there,\\nbut that\'s a brittle nonlocal property which I\'d like to avoid.\\n\\nAdditionally, dep_finsts is read from an interface file, so its \\"natural\\"\\ntype is a list. Which makes it a natural type for imp_finsts.\\n\\nSince rnImports.combine is really the only place that would benefit from\\nit being a Set, it makes sense to optimize the hot loop in rnImports.combine\\nwithout changing the representation.\\n\\nSo here\'s what we do: instead of naively merging ImportAvails with\\nplusImportAvails in a loop, we make plusImportAvails merge empty imp_finsts\\nand compute the union on the side using Sets. When we\'re done, we can\\nconvert it back to a list. One nice side effect of this approach is that\\nif there\'s a lot of overlap in the imp_finsts of imports, the\\nSet doesn\'t really need to grow and we don\'t need to allocate.\\n\\nRunning generateModules from #14693 with DEPTH=16, WIDTH=30 finishes in\\n23s before, and 11s after.\\n-}\\n\\n-- | Given a located import declaration @decl@ from @this_mod@,\\n-- calculate the following pieces of information:\\n--\\n-- 1. An updated \'LImportDecl\', where all unresolved \'RdrName\' in\\n-- the entity lists have been resolved into \'Name\'s,\\n--\\n-- 2. A \'GlobalRdrEnv\' representing the new identifiers that were\\n-- brought into scope (taking into account module qualification\\n-- and hiding),\\n--\\n-- 3. \'ImportAvails\' summarizing the identifiers that were imported\\n-- by this declaration, and\\n--\\n-- 4. A boolean \'AnyHpcUsage\' which is true if the imported module\\n-- used HPC.\\nrnImportDecl :: Module -> (LImportDecl GhcPs, SDoc)\\n -> RnM (LImportDecl GhcRn, ImportUserSpec , GlobalRdrEnv, ImportAvails)\\nrnImportDecl this_mod\\n (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name\\n , ideclPkgQual = raw_pkg_qual\\n , ideclSource = want_boot\\n , ideclSafe = mod_safe\\n , ideclLevelSpec = import_level\\n , ideclQualified = qual_style\\n , ideclExt = XImportDeclPass { ideclOrigin = origin }\\n , ideclAs = as_mod, ideclImportList = imp_details }), import_reason)\\n = setSrcSpanA loc $ do\\n\\n case raw_pkg_qual of\\n NoRawPkgQual -> pure ()\\n RawPkgQual {} -> do\\n pkg_imports <- xoptM LangExt.PackageImports\\n when (not pkg_imports) $ addErr TcRnPackageImportsDisabled\\n\\n let qual_only = isImportDeclQualified qual_style\\n generated = isGeneratedImport origin\\n\\n lookup_scope = importDeclLookupScope origin\\n\\n -- If there\'s an error in loadInterface, (e.g. interface\\n -- file not found) we get lots of spurious errors from \'filterImports\'\\n let imp_mod_name = unLoc loc_imp_mod_name\\n doc = ppr imp_mod_name <+> import_reason\\n\\n hsc_env <- getTopEnv\\n unit_env <- hsc_unit_env <$> getTopEnv\\n let pkg_qual = renameRawPkgQual unit_env imp_mod_name raw_pkg_qual\\n\\n -- Check for self-import, which confuses the typechecker (#9032)\\n -- ghc --make rejects self-import cycles already, but batch-mode may not\\n -- at least not until GHC.IfaceToCore.tcHiBootIface, which is too late to avoid\\n -- typechecker crashes. (Indirect self imports are not caught until\\n -- GHC.IfaceToCore, see #10337 tracking how to make this error better.)\\n --\\n -- Originally, we also allowed \'import {-# SOURCE #-} M\', but this\\n -- caused bug #10182: in one-shot mode, we should never load an hs-boot\\n -- file for the module we are compiling into the EPS. In principle,\\n -- it should be possible to support this mode of use, but we would have to\\n -- extend Provenance to support a local definition in a qualified location.\\n -- For now, we don\'t support it, but see #10336\\n when (imp_mod_name == moduleName this_mod &&\\n (case pkg_qual of -- If we have import \\"\\" M, then we should\\n -- check that \\"\\" is \\"this\\" (which is magic)\\n -- or the name of this_mod\'s package. Yurgh!\\n -- c.f. GHC.findModule, and #9997\\n NoPkgQual -> True\\n ThisPkg uid -> uid == homeUnitId_ (hsc_dflags hsc_env)\\n OtherPkg _ -> False))\\n (addErr (TcRnSelfImport imp_mod_name))\\n\\n -- Check for a missing import list (Opt_WarnMissingImportList also\\n -- checks for T(..) items but that is done in checkDodgyImport below)\\n case imp_details of\\n Just (Exactly, _) -> return () -- Explicit import list\\n _ | generated -> return () -- Do not bleat for generated imports\\n | qual_only -> return ()\\n | otherwise -> addDiagnostic (TcRnNoExplicitImportList imp_mod_name)\\n\\n\\n mb_iface <- loadSrcInterface_maybe doc lookup_scope imp_mod_name want_boot pkg_qual\\n iface <- case mb_iface of\\n Succeeded iface -> return iface\\n Failed err -> failWithTc $\\n importDeclLoadFailure origin imp_mod_name want_boot err\\n\\n -- Compiler sanity check: if the import didn\'t say\\n -- {-# SOURCE #-} we should not get a hi-boot file\\n warnPprTrace ((want_boot == NotBoot) && (mi_boot iface == IsBoot)) \\"rnImportDecl\\" (ppr imp_mod_name) $ do\\n\\n -- Issue a user warning for a redundant {- SOURCE -} import\\n -- NB that we arrange to read all the ordinary imports before\\n -- any of the {- SOURCE -} imports.\\n --\\n -- in --make and GHCi, the compilation manager checks for this,\\n -- and indeed we shouldn\'t do it here because the existence of\\n -- the non-boot module depends on the compilation order, which\\n -- is not deterministic. The hs-boot test can show this up.\\n dflags <- getDynFlags\\n warnIf ((want_boot == IsBoot) && (mi_boot iface == NotBoot) && isOneShot (ghcMode dflags))\\n (TcRnRedundantSourceImport imp_mod_name)\\n when (mod_safe && not (safeImportsOn dflags)) $\\n addErr (TcRnSafeImportsDisabled imp_mod_name)\\n\\n let imp_mod = mi_module iface\\n qual_mod_name = fmap unLoc as_mod `orElse` imp_mod_name\\n imp_spec = ImpDeclSpec { is_mod = imp_mod, is_qual = qual_only,\\n is_dloc = locA loc, is_as = qual_mod_name,\\n is_pkg_qual = pkg_qual, is_isboot = want_boot,\\n is_level = convImportLevel import_level }\\n\\n let filter_imports = do\\n -- filter the imports according to the import declaration\\n (new_imp_details, imp_user_list, gbl_env)\\n <- filterImports hsc_env iface imp_spec imp_details\\n -- for certain error messages, we\\u2019d like to know what could be\\n -- imported here, if everything were imported\\n potential_gres <- (\\\\(_,_,x) -> x) <$> filterImports hsc_env iface imp_spec Nothing\\n return (new_imp_details, imp_user_list, gbl_env, potential_gres)\\n\\n (new_imp_details, imp_user_list, gbl_env, potential_gres) <-\\n case origin of\\n ImplicitEssentialsImport ->\\n -- The implicit GHC.Essentials import does not bring anything into scope.\\n -- See Note [Finding GHC.Essentials] in GHC.Builtin.\\n return (Nothing, ImpUserDependOnly, emptyGlobalRdrEnv, emptyGlobalRdrEnv)\\n UserWrittenImport -> filter_imports\\n ImplicitPreludeImport -> filter_imports\\n PluginImport -> filter_imports\\n\\n let is_hiding | Just (EverythingBut,_) <- imp_details = True\\n | otherwise = False\\n\\n -- should the import be safe?\\n mod_safe\' = mod_safe\\n || (not generated && safeDirectImpsReq dflags)\\n || (generated && safeImplicitImpsReq dflags)\\n\\n hsc_env <- getTopEnv\\n let home_unit = hsc_home_unit hsc_env\\n other_home_units = hsc_all_home_unit_ids hsc_env\\n\\n imported_by\\n | isDependOnlyImport imp_user_list\\n = ImportedBySystem\\n | otherwise\\n = ImportedByUser $ ImportedModsVal\\n { imv_name = is_as imp_spec\\n , imv_span = locA loc\\n , imv_is_safe = mod_safe\'\\n , imv_is_hiding = is_hiding\\n , imv_all_exports = potential_gres\\n , imv_qualified = qual_only\\n , imv_is_level = convImportLevel import_level\\n }\\n imports = calculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by\\n\\n -- Complain if we import a deprecated module\\n case fromIfaceWarnings (mi_warns iface) of\\n WarnAll txt -> addDiagnostic (TcRnDeprecatedModule imp_mod_name txt)\\n _ -> return ()\\n\\n let new_imp_decl = ImportDecl\\n { ideclExt = ideclExt decl\\n , ideclName = ideclName decl\\n , ideclPkgQual = pkg_qual\\n , ideclSource = ideclSource decl\\n , ideclSafe = mod_safe\'\\n , ideclQualified = ideclQualified decl\\n , ideclAs = ideclAs decl\\n , ideclImportList = new_imp_details\\n , ideclLevelSpec = ideclLevelSpec decl\\n }\\n\\n return (L loc new_imp_decl, ImpUserSpec imp_spec imp_user_list, gbl_env, imports)\\n\\n-- | The error message to emit when we failed to load an interface.\\nimportDeclLoadFailure :: ImportDeclOrigin -> ModuleName -> IsBootInterface\\n -> MissingInterfaceError -> TcRnMessage\\nimportDeclLoadFailure ImplicitEssentialsImport _ _ err\\n = TcRnInterfaceError $ CantFindEssentials err LookingForEssentialsModule\\nimportDeclLoadFailure _ mod_name want_boot err\\n = TcRnInterfaceError $ Can\'tFindInterface err $ LookingForModule mod_name want_boot\\n\\n-- | Rename raw package imports\\nrenameRawPkgQual :: UnitEnv -> ModuleName -> RawPkgQual -> PkgQual\\nrenameRawPkgQual unit_env mn = \\\\case\\n NoRawPkgQual -> NoPkgQual\\n RawPkgQual _ fs -> renamePkgQual unit_env mn $ Just fs\\n\\n-- | Rename raw package imports\\nrenamePkgQual :: UnitEnv -> ModuleName -> Maybe FastString -> PkgQual\\nrenamePkgQual unit_env mn mb_pkg = case mb_pkg of\\n Nothing -> NoPkgQual\\n Just pkg_fs\\n | Just uid <- homeUnitId <$> ue_homeUnit unit_env\\n , pkg_fs == fsLit \\"this\\"\\n -> ThisPkg uid\\n\\n | Just (uid, _) <- find (fromMaybe False . fmap (== pkg_fs) . snd) home_names\\n -> ThisPkg uid\\n\\n | Just uid <- resolvePackageImport unit_state mn (PackageName pkg_fs)\\n -> OtherPkg uid\\n\\n | otherwise\\n -> OtherPkg (UnitId pkg_fs)\\n -- not really correct as pkg_fs is unlikely to be a valid unit-id but\\n -- we will report the failure later...\\n where\\n home_names =\\n [ (uid, mkFastString <$> thisPackageName (homeUnitEnv_dflags (ue_findHomeUnitEnv uid unit_env)))\\n | uid <- S.toList hpt_deps\\n ]\\n\\n unit_state = ue_homeUnitState unit_env\\n\\n hpt_deps :: S.Set UnitId\\n hpt_deps = homeUnitDepends unit_state\\n\\n\\n-- | Calculate the \'ImportAvails\' induced by an import of a particular\\n-- interface, but without \'imp_mods\'.\\ncalculateAvails :: HomeUnit\\n -> S.Set UnitId\\n -> ModIface\\n -> IsSafeImport\\n -> IsBootInterface\\n -> ImportedBy\\n -> ImportAvails\\ncalculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by =\\n let imp_mod = mi_module iface\\n imp_sem_mod= mi_semantic_module iface\\n orph_iface = mi_orphan iface\\n has_finsts = mi_finsts iface\\n deps = mi_deps iface\\n trust = getSafeMode $ mi_trust iface\\n trust_pkg = mi_trust_pkg iface\\n is_sig = mi_hsc_src iface == HsigFile\\n\\n -- If the module exports anything defined in this module, just\\n -- ignore it. Reason: otherwise it looks as if there are two\\n -- local definition sites for the thing, and an error gets\\n -- reported. Easiest thing is just to filter them out up\\n -- front. This situation only arises if a module imports\\n -- itself, or another module that imported it. (Necessarily,\\n -- this involves a loop.)\\n --\\n -- We do this *after* filterImports, so that if you say\\n -- module A where\\n -- import B( AType )\\n -- type AType = ...\\n --\\n -- module B( AType ) where\\n -- import {-# SOURCE #-} A( AType )\\n --\\n -- then you won\'t get a \'B does not export AType\' message.\\n\\n\\n -- Compute new transitive dependencies\\n --\\n -- \'dep_orphs\' and \'dep_finsts\' do NOT include the imported module\\n -- itself, but we DO need to include this module in \'imp_orphs\' and\\n -- \'imp_finsts\' if it defines an orphan or instance family; thus the\\n -- orph_iface/has_iface tests.\\n\\n deporphs = dep_orphs deps\\n depfinsts = dep_finsts deps\\n\\n orphans | orph_iface = assertPpr (not (imp_sem_mod `elem` deporphs)) (ppr imp_sem_mod <+> ppr deporphs) $\\n imp_sem_mod : deporphs\\n | otherwise = deporphs\\n\\n finsts | has_finsts = assertPpr (not (imp_sem_mod `elem` depfinsts)) (ppr imp_sem_mod <+> ppr depfinsts) $\\n imp_sem_mod : depfinsts\\n | otherwise = depfinsts\\n\\n -- Trusted packages are a lot like orphans.\\n trusted_pkgs | mod_safe\' = dep_trusted_pkgs deps\\n | otherwise = S.empty\\n\\n\\n pkg = moduleUnit (mi_module iface)\\n ipkg = toUnitId pkg\\n\\n -- Does this import mean we now require our own pkg\\n -- to be trusted? See Note [Trust Own Package]\\n ptrust = trust == Sf_Trustworthy || trust_pkg\\n pkg_trust_req\\n | isHomeUnit home_unit pkg = ptrust\\n | otherwise = False\\n\\n dependent_pkgs = if toUnitId pkg `S.member` other_home_units\\n then S.empty\\n else S.singleton (lvl, ipkg)\\n\\n lvl = case imported_by of\\n ImportedByUser imv -> imv_is_level imv\\n ImportedBySystem -> NormalLevel\\n\\n\\n direct_mods = if toUnitId pkg `S.member` other_home_units\\n then mkPlusModDeps (moduleUnitId imp_mod) lvl (GWIB (moduleName imp_mod) want_boot)\\n else emptyInstalledModuleEnv\\n\\n dep_boot_mods_map = mkModDeps (dep_boot_mods deps)\\n\\n\\n boot_mods\\n -- If we are looking for a boot module, it must be HPT\\n | IsBoot <- want_boot = extendInstalledModuleEnv dep_boot_mods_map (toUnitId <$> imp_mod) (GWIB (moduleName imp_mod) IsBoot)\\n -- Now we are importing A properly, so don\'t go looking for\\n -- A.hs-boot\\n | isHomeUnit home_unit pkg = dep_boot_mods_map\\n -- There\'s no boot files to find in external imports\\n | otherwise = emptyInstalledModuleEnv\\n\\n sig_mods =\\n if is_sig\\n then moduleName imp_mod : dep_sig_mods deps\\n else dep_sig_mods deps\\n\\n\\n in ImportAvails {\\n imp_mods = Map.singleton (mi_module iface) [imported_by],\\n imp_orphs = orphans,\\n imp_finsts = finsts,\\n imp_sig_mods = sig_mods,\\n imp_direct_dep_mods = direct_mods,\\n imp_dep_direct_pkgs = dependent_pkgs,\\n imp_boot_mods = boot_mods,\\n\\n -- Add in the imported modules trusted package\\n -- requirements. ONLY do this though if we import the\\n -- module as a safe import.\\n -- See Note [Tracking Trust Transitively]\\n -- and Note [Trust Transitive Property]\\n imp_trust_pkgs = trusted_pkgs,\\n -- Do we require our own pkg to be trusted?\\n -- See Note [Trust Own Package]\\n imp_trust_own_pkg = pkg_trust_req\\n }\\n\\nmkPlusModDeps :: UnitId -> ImportLevel -> ModuleNameWithIsBoot\\n -> InstalledModuleEnv (S.Set ImportLevel, ModuleNameWithIsBoot)\\nmkPlusModDeps uid st elt = extendInstalledModuleEnv emptyInstalledModuleEnv (mkModule uid (gwib_mod elt)) (S.singleton st, elt)\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{importsFromLocalDecls}\\n* *\\n************************************************************************\\n\\nFrom the top-level declarations of this module produce\\n * the lexical environment\\n * the ImportAvails\\ncreated by its bindings.\\n\\nNote [Top-level Names in Template Haskell decl quotes]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSee also: Note [Interactively-bound Ids in GHCi] in GHC.Driver.Env\\n Note [Looking up Exact RdrNames] in GHC.Rename.Env\\n\\nConsider a Template Haskell declaration quotation like this:\\n module M where\\n f x = h [d| f = 3 |]\\nWhen renaming the declarations inside [d| ...|], we treat the\\ntop level binders specially in two ways\\n\\n1. We give them an Internal Name, not (as usual) an External one.\\n This is done by GHC.Rename.Env.newTopSrcBinder.\\n\\n2. We make them *shadow* the outer bindings.\\n See Note [GlobalRdrEnv shadowing]\\n\\n3. We find out whether we are inside a [d| ... |] by testing the TH\\n level. This is a slight hack, because the level field was really\\n meant for the type checker, and here we are not interested in the\\n fields of Brack, hence the error thunks in thRnBrack.\\n-}\\n\\nextendGlobalRdrEnvRn :: [GlobalRdrElt]\\n -> MiniFixityEnv\\n -> RnM (TcGblEnv, TcLclEnv)\\n-- Updates both the GlobalRdrEnv and the FixityEnv\\n-- We return a new TcLclEnv only because we might have to\\n-- delete some bindings from it;\\n-- see Note [Top-level Names in Template Haskell decl quotes]\\n\\nextendGlobalRdrEnvRn new_gres new_fixities\\n = checkNoErrs $ -- See Note [Fail fast on duplicate definitions]\\n do { (gbl_env, lcl_env) <- getEnvs\\n ; level <- getThLevel\\n ; isGHCi <- getIsGHCi\\n ; let rdr_env = tcg_rdr_env gbl_env\\n fix_env = tcg_fix_env gbl_env\\n th_bndrs = getLclEnvThBndrs lcl_env\\n th_lvl = thLevelIndex level\\n\\n -- Delete new_occs from global and local envs\\n -- If we are in a TemplateHaskell decl bracket,\\n -- we are going to shadow them\\n -- See Note [GlobalRdrEnv shadowing]\\n inBracket = isBrackLevel level\\n\\n lcl_env_TH = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_rdr = minusLocalRdrEnv (tcl_rdr lcl_env) new_gres_env }) lcl_env\\n -- See Note [GlobalRdrEnv shadowing]\\n\\n lcl_env2 | inBracket = lcl_env_TH\\n | otherwise = lcl_env\\n\\n -- Deal with shadowing: see Note [GlobalRdrEnv shadowing]\\n want_shadowing = isGHCi || inBracket\\n rdr_env1 | want_shadowing = shadowNames False rdr_env new_gres_env\\n | otherwise = rdr_env\\n\\n lcl_env3 = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_th_bndrs = extendNameEnvList th_bndrs\\n [ ( n, (TopLevel, th_lvl) )\\n | n <- new_names ] }) lcl_env2\\n\\n ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres\\n\\n ; let fix_env\' = foldl\' extend_fix_env fix_env new_gres\\n gbl_env\' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env\' }\\n\\n ; traceRn \\"extendGlobalRdrEnvRn 2\\" (pprGlobalRdrEnv True rdr_env2)\\n ; return (gbl_env\', lcl_env3) }\\n where\\n new_names = map greName new_gres\\n new_gres_env = mkGlobalRdrEnv new_gres\\n\\n -- If there is a fixity decl for the gre, add it to the fixity env\\n extend_fix_env fix_env gre\\n | Just (L _ fi) <- lookupMiniFixityEnv new_fixities name\\n = extendNameEnv fix_env name (FixItem occ fi)\\n | otherwise\\n = fix_env\\n where\\n name = greName gre\\n occ = greOccName gre\\n\\n add_gre :: GlobalRdrEnv -> GlobalRdrElt -> RnM GlobalRdrEnv\\n -- Extend the GlobalRdrEnv with a LocalDef GRE\\n -- If there is already a LocalDef GRE with the same OccName,\\n -- report an error and discard the new GRE\\n -- This establishes INVARIANT 1 of GlobalRdrEnvs\\n add_gre env gre\\n | not (null dups) -- Same OccName defined twice\\n = do { addDupDeclErr (gre :| dups); return env }\\n\\n | otherwise\\n = return (extendGlobalRdrEnv env gre)\\n where\\n -- See Note [Reporting duplicate local declarations]\\n dups = filter isBadDupGRE\\n $ lookupGRE env (LookupOccName (greOccName gre) (RelevantGREsFOS WantBoth))\\n isBadDupGRE old_gre = isLocalGRE old_gre && greClashesWith gre old_gre\\n\\n{- Note [Fail fast on duplicate definitions]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIf there are duplicate bindings for the same thing, we want to fail\\nfast. Having two bindings for the same thing can cause follow-on errors.\\nExample (test T9975a):\\n data Test = Test { x :: Int }\\n pattern Test wat = Test { x = wat }\\nThis defines \'Test\' twice. The second defn has no field-names; and then\\nwe get an error from Test { x=wat }, saying \\"Test has no field \'x\'\\".\\n\\nEasiest thing is to bale out fast on duplicate definitions, which\\nwe do via `checkNoErrs` on `extendGlobalRdrEnvRn`.\\n\\nNote [Reporting duplicate local declarations]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn general, a single module may not define the same OccName multiple times. This\\nis checked in extendGlobalRdrEnvRn: when adding a new locally-defined GRE to the\\nGlobalRdrEnv we report an error if there are already duplicates in the\\nenvironment. This establishes INVARIANT 1 (see comments on GlobalRdrEnv in\\nGHC.Types.Name.Reader), which says that for a given OccName, all the\\nGlobalRdrElts to which it maps must have distinct \'greName\'s.\\n\\nFor example, the following will be rejected:\\n\\n f x = x\\n g x = x\\n f x = x -- Duplicate!\\n\\nUsers are allowed to introduce new GREs with the same OccName as an imported GRE,\\nas disambiguation is possible through the module system, e.g.:\\n\\n module M where\\n import N (f)\\n f x = x\\n g x = M.f x + N.f x\\n\\nIf both GREs are local, the general rule is that two GREs clash if they have\\nthe same OccName, i.e. they share a textual name and live in the same namespace.\\nHowever, there are additional clashes due to record fields:\\n\\n - a new variable clashes with previously defined record fields\\n which define field selectors,\\n\\n - a new record field shadows:\\n\\n - previously defined variables, if it defines a field selector,\\n - previously defined record fields, unless it is a duplicate record field.\\n\\nThis logic is implemented in the function \'GHC.Types.Name.Reader.greClashesWith\'.\\n\\nSee also Note [Skipping ambiguity errors at use sites of local declarations] in\\nGHC.Rename.Utils.\\n-}\\n\\n\\n{- *********************************************************************\\n* *\\n getLocalDeclBindersd@ returns the names for an HsDecl\\n It\'s used for source code.\\n\\n *** See Note [The Naming story] in GHC.Hs.Decls ****\\n* *\\n********************************************************************* -}\\n\\ngetLocalNonValBinders :: MiniFixityEnv -> HsGroup GhcPs\\n -> RnM ((TcGblEnv, TcLclEnv), NameSet)\\n-- Get all the top-level binders bound the group *except*\\n-- for value bindings, which are treated separately\\n-- Specifically we return AvailInfo for\\n-- * type decls (incl constructors and record selectors)\\n-- * class decls (including class ops)\\n-- * associated types\\n-- * foreign imports\\n-- * value signatures (in hs-boot files only)\\n\\ngetLocalNonValBinders fixity_env\\n (HsGroup { hs_valds = binds,\\n hs_tyclds = tycl_decls,\\n hs_fords = foreign_decls })\\n = do { -- Process all type/class decls *except* family instances\\n ; let inst_decls = tycl_decls >>= group_instds\\n ; dup_fields_ok <- xopt_DuplicateRecordFields <$> getDynFlags\\n ; has_sel <- xopt_FieldSelectors <$> getDynFlags\\n ; tc_gres\\n <- concatMapM\\n (new_tc dup_fields_ok has_sel)\\n (tyClGroupTyClDecls tycl_decls)\\n ; traceRn \\"getLocalNonValBinders 1\\" (ppr tc_gres)\\n ; envs <- extendGlobalRdrEnvRn tc_gres fixity_env\\n ; restoreEnvs envs $ do {\\n -- Bring these things into scope first\\n -- See Note [Looking up family names in family instances]\\n\\n -- Process all family instances\\n -- to bring new data constructors into scope\\n ; nti_gress <- mapM (new_assoc dup_fields_ok has_sel) inst_decls\\n\\n -- Finish off with value binders:\\n -- foreign decls and pattern synonyms for an ordinary module\\n -- type sigs in case of a hs-boot file only\\n ; is_boot <- tcIsHsBootOrSig\\n ; let val_bndrs\\n | is_boot = case binds of\\n ValBinds _ val_binds ->\\n -- In a hs-boot file, the value binders come from the\\n -- *signatures*, and there should be no foreign binders\\n [ L (l2l decl_loc) (unLoc n)\\n | L decl_loc (TypeSig _ _ ns _) <- (val_sigs val_binds), n <- ns]\\n _ -> panic \\"Non-ValBinds in hs-boot group\\"\\n | otherwise = for_hs_bndrs\\n ; val_gres <- mapM new_simple val_bndrs\\n\\n ; let avails = concat nti_gress ++ val_gres\\n new_bndrs = gresToNameSet avails `unionNameSet`\\n gresToNameSet tc_gres\\n ; traceRn \\"getLocalNonValBinders 2\\" (ppr avails)\\n ; envs <- extendGlobalRdrEnvRn avails fixity_env\\n ; return (envs, new_bndrs) } }\\n where\\n for_hs_bndrs :: [LocatedN RdrName]\\n for_hs_bndrs = hsForeignDeclsBinders foreign_decls\\n\\n -- the SrcSpan attached to the input should be the span of the\\n -- declaration, not just the name\\n new_simple :: LocatedN RdrName -> RnM GlobalRdrElt\\n new_simple rdr_name = do { nm <- newTopSrcBinder rdr_name\\n ; return (mkLocalVanillaGRE NoParent nm) }\\n\\n new_tc :: DuplicateRecordFields -> FieldSelectors -> LTyClDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_tc dup_fields_ok has_sel tc_decl -- NOT for type/data instances\\n = do { let TyDeclBinders (main_bndr, tc_flav) at_bndrs sig_bndrs\\n (LConsWithFields cons_with_flds flds) = hsLTyClDeclBinders tc_decl\\n ; tycon_name <- newTopSrcBinder $ la2la main_bndr\\n ; at_names <- mapM (newTopSrcBinder . la2la . fst) at_bndrs\\n ; sig_names <- mapM (newTopSrcBinder . la2la) sig_bndrs\\n ; con_names_with_flds <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst con_names_with_flds) flds\\n ; mapM_ (add_dup_fld_errs flds\') con_names_with_flds\\n ; let tc_gre = mkLocalTyConGRE (fmap (const tycon_name) tc_flav) tycon_name\\n fld_env = mk_fld_env con_names_with_flds flds\'\\n at_gres = zipWith (\\\\ (_, at_flav) at_nm -> mkLocalTyConGRE (fmap (const tycon_name) at_flav) at_nm)\\n at_bndrs at_names\\n sig_gres = map (mkLocalVanillaGRE (ParentIs tycon_name)) sig_names\\n con_gres = map (mkLocalConLikeGRE (ParentIs tycon_name)) fld_env\\n fld_gres = mkLocalFieldGREs (ParentIs tycon_name) fld_env\\n sub_gres = at_gres ++ sig_gres ++ con_gres ++ fld_gres\\n ; traceRn \\"getLocalNonValBinders new_tc\\" $\\n vcat [ text \\"tycon:\\" <+> ppr tycon_name\\n , text \\"tc_gre:\\" <+> ppr tc_gre\\n , text \\"sub_gres:\\" <+> ppr sub_gres ]\\n ; return $ tc_gre : sub_gres }\\n\\n -- Calculate the record field information, which feeds into the GlobalRdrElts\\n -- for DataCons and their fields. It\'s convenient to do this here where\\n -- we are working with a single datatype definition.\\n --\\n -- The information we needed was all set up for us:\\n -- see Note [Collecting record fields in data declarations] in GHC.Hs.Utils.\\n mk_fld_env :: [(Name, Either VisArity [Located Int])] -> IntMap FieldLabel\\n -> [(ConLikeName, ConInfo)]\\n mk_fld_env names flds =\\n [ (DataConName con, ConInfo (ConIsData (map fst names)) fld_info)\\n | (con, con_fl_indxs) <- names\\n , let fld_info = case fmap (map ((flds IntMap.!) . unLoc)) con_fl_indxs of\\n Left 0 -> ConIsNullary\\n Left arity -> ConHasPositionalArgs arity\\n Right [] -> ConIsNullary\\n Right (fld:flds) -> ConHasRecordFields $ fld NE.:| flds ]\\n\\n new_assoc :: DuplicateRecordFields -> FieldSelectors -> LInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_assoc _ _ (L _ (TyFamInstD {})) = return []\\n -- type instances don\'t bind new names\\n\\n new_assoc dup_fields_ok has_sel (L _ (DataFamInstD _ d))\\n = new_di dup_fields_ok has_sel Nothing d\\n new_assoc dup_fields_ok has_sel\\n (L _ (ClsInstD _ (ClsInstDecl { cid_poly_ty = inst_ty\\n , cid_decls = decls })))\\n = do -- First, attempt to grab the name of the class from the instance.\\n -- This step could fail if the instance is not headed by a class,\\n -- such as in the following examples:\\n --\\n -- (1) The class is headed by a bang pattern, such as in\\n -- `instance !Show Int` (#3811c)\\n -- (2) The class is headed by a type variable, such as in\\n -- `instance c` (#16385)\\n --\\n -- If looking up the class name fails, then mb_cls_gre will\\n -- be Nothing.\\n mb_cls_gre <- runMaybeT $ do\\n -- See (1) above\\n L loc cls_rdr <- MaybeT $ pure $ getLHsInstDeclClass_maybe inst_ty\\n -- See (2) above\\n MaybeT $ setSrcSpan (locA loc) $ lookupGlobalOccRn_maybe SameNameSpace cls_rdr\\n -- Assuming the previous step succeeded, process any associated data\\n -- family instances. If the previous step failed, bail out.\\n case mb_cls_gre of\\n Nothing\\n -> pure []\\n Just cls_gre\\n -> let cls_nm = greName cls_gre\\n in concatMapM (new_di dup_fields_ok has_sel (Just cls_nm) . unLoc) (data_fam_insts decls)\\n\\n data_fam_insts decls = concatMap get decls\\n where\\n get (L l (InstD _ (DataFamInstD { dfid_inst = d}))) = [L l d]\\n get _ = []\\n\\n new_di :: DuplicateRecordFields -> FieldSelectors\\n -> Maybe Name -- class name\\n -> DataFamInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_di dup_fields_ok has_sel mb_cls dfid@(DataFamInstDecl { dfid_eqn = ti_decl })\\n = do { main_name <- unLoc <$> lookupFamInstName mb_cls (feqn_tycon ti_decl)\\n ; let LConsWithFields cons_with_flds flds = hsDataFamInstBinders dfid\\n ; sub_names <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst sub_names) flds\\n ; mapM_ (add_dup_fld_errs flds\') sub_names\\n ; let fld_env = mk_fld_env sub_names flds\'\\n con_gres = map (mkLocalConLikeGRE (ParentIs main_name)) fld_env\\n field_gres = mkLocalFieldGREs (ParentIs main_name) fld_env\\n -- NB: the data family name is not bound here,\\n -- so we don\'t return a GlobalRdrElt for it here!\\n ; return $ con_gres ++ field_gres }\\n\\n -- Add errors if a constructor has a duplicate record field.\\n add_dup_fld_errs :: IntMap FieldLabel\\n -> (Name, Either VisArity [Located Int])\\n -> IOEnv (Env TcGblEnv TcLclEnv) ()\\n add_dup_fld_errs all_flds (con, con_flds_or_arity)\\n | Right con_flds <- con_flds_or_arity\\n , let (_, dups) = removeDups (comparing unLoc) con_flds\\n = for_ dups $ \\\\ dup_flds ->\\n -- Report the error at the location of the second occurrence\\n -- of the duplicate field.\\n let loc =\\n case dup_flds of\\n _ :| ( L loc _ : _) -> loc\\n L loc _ :| _ -> loc\\n dup_rdrs = fmap (nameRdrName . flSelector . (all_flds IntMap.!) . unLoc) dup_flds\\n in addErrAt loc $ TcRnDuplicateFieldName (RecordFieldDecl con) dup_rdrs\\n | otherwise\\n = return ()\\n\\nnewRecordFieldLabel :: DuplicateRecordFields -> FieldSelectors -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel\\nnewRecordFieldLabel _ _ [] _ = error \\"newRecordFieldLabel: datatype has no constructors!\\"\\nnewRecordFieldLabel dup_fields_ok has_sel (dc:_) (L loc (FieldOcc _ (L _ fld)))\\n = do { selName <- newTopSrcBinder $ L (l2l loc) $ field\\n ; return $ FieldLabel { flHasDuplicateRecordFields = dup_fields_ok\\n , flHasFieldSelector = has_sel\\n , flSelector = selName } }\\n where\\n fld_occ = rdrNameOcc fld\\n dc_fs = occNameFS $ nameOccName dc\\n field\\n -- Use an Exact RdrName as-is, to preserve the bindings\\n -- of an already renamer-resolved field and its use\\n -- sites. This is needed to correctly support record\\n -- selectors in Template Haskell. See Note [Binders in\\n -- Template Haskell] in \\"GHC.ThToHs\\" and Note [Looking up\\n -- Exact RdrNames] in \\"GHC.Rename.Env\\".\\n | isExact fld\\n = assertPpr (fieldOcc_maybe fld_occ == Just dc_fs)\\n (vcat [ text \\"newRecordFieldLabel: incorrect namespace for exact Name\\" <+> quotes (ppr fld)\\n , text \\"expected namespace:\\" <+> pprNameSpace (fieldName dc_fs)\\n , text \\" actual namespace:\\" <+> pprNameSpace (occNameSpace fld_occ) ])\\n fld\\n\\n -- Field names produced by the parser are namespaced with VarName.\\n -- Here we namespace them according to the first constructor.\\n -- See Note [Record field namespacing] in GHC.Types.Name.Occurrence.\\n | otherwise\\n = mkRdrUnqual $ varToRecFieldOcc dc_fs fld_occ\\n\\n{-\\nNote [Looking up family names in family instances]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider\\n\\n module M where\\n type family T a :: *\\n type instance M.T Int = Bool\\n\\nWe might think that we can simply use \'lookupOccRn\' when processing the type\\ninstance to look up \'M.T\'. Alas, we can\'t! The type family declaration is in\\nthe *same* HsGroup as the type instance declaration. Hence, as we are\\ncurrently collecting the binders declared in that HsGroup, these binders will\\nnot have been added to the global environment yet.\\n\\nSolution is simple: process the type family declarations first, extend\\nthe environment, and then process the type instances.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Filtering imports}\\n* *\\n************************************************************************\\n\\n@filterImports@ takes the @ExportEnv@ telling what the imported module makes\\navailable, and filters it through the import spec (if any).\\n\\nNote [Dealing with imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nFor import M( ies ), we take each AvailInfo from the mi_exports of M, and make\\n\\n imp_occ_env :: OccEnv (NameEnv ImpOccItem)\\n\\nThis map contains one entry for each OccName that M exports, mapping each OccName\\nto the following information:\\n\\n 1. the GlobalRdrElt corresponding to the OccName,\\n 2. whether this GlobalRdrElt was the parent in the AvailInfo we found\\n the OccName in.\\n 3. the GlobalRdrElts that were bundled together in the AvailInfo we found\\n this OccName in (not including the parent),\\n\\nWe need (2) and (3) during the construction of the OccEnv because of associated\\ntypes and bundled pattern synonyms, respectively.\\n(3) is explained in Note [Importing PatternSynonyms].\\n\\nTo explain (2), consider for example:\\n\\n module M where\\n class C a where { data T a }\\n instance C Int where { data T Int = T1 | T2 }\\n instance C Bool where { data T Int = T3 }\\n\\nHere, M\'s exports avails are (recalling the AvailTC invariant from GHC.Types.Avail)\\n\\n C(C,T), T(T,T1,T2,T3)\\n\\nNotice that T appears *twice*, once as a child and once as a parent. From\\nthese two exports, respectively, during construction of the imp_occ_env, we begin\\nby associating the following two elements with the key T:\\n\\n T -> ImpOccItem { imp_item = gre1, imp_bundled = [C,T] , imp_is_parent = False }\\n T -> ImpOccItem { imp_item = gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nwhere `gre1`, `gre2` are two GlobalRdrElts with greName T.\\nWe combine these (in function \'combine\' in \'mkImportOccEnv\') by discarding the\\nnon-parent item, thusly:\\n\\n T -> IE_ITem { imp_item = gre1 `plusGRE` gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nNote the `plusGRE`: this ensures we don\'t drop parent information;\\nsee Note [Preserve parent information when combining import OccEnvs].\\n\\nSo the overall imp_occ_env is:\\n\\n C -> ImpOccItem { imp_item = C, imp_bundled = [T ], imp_is_parent = True }\\n T -> ImpOccItem { imp_item = T , imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n T1 -> ImpOccItem { imp_item = T1, imp_bundled = [T1,T2,T3], imp_is_parent = False }\\n -- similarly for T2, T3\\n\\nNote that the imp_occ_env will have entries for data constructors too,\\nalthough we never look up data constructors.\\n\\nNote [Importing PatternSynonyms]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nAs described in Note [Dealing with imports], associated types can lead to the\\nsame Name appearing twice, both as a child and once as a parent, when\\nconstructing the imp_occ_env. The same thing can happen with pattern synonyms\\nif they are exported bundled with a type.\\n\\nA simplified example, based on #11959:\\n\\n {-# LANGUAGE PatternSynonyms #-}\\n module M (T(P), pattern P) where -- Duplicate export warning, but allowed\\n data T = MkT\\n pattern P = MkT\\n\\nHere we have T(P) and P in export_avails, and respectively construct both\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n P -> ImpOccItem { imp_item = P, imp_bundled = [] , imp_is_parent = False }\\n\\nWe combine these by dropping the one with no siblings, leaving us with:\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n\\nThat is, we simply discard the non-bundled Avail.\\n\\nNote [Importing DuplicateRecordFields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn filterImports, another complicating factor is DuplicateRecordFields.\\nSuppose we have:\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (S(foo), T(foo)) where\\n data S = MkS { foo :: Int }\\n data T = MkT { foo :: Int }\\n\\n module N where\\n import M (foo) -- this is allowed (A)\\n import M (S(foo)) -- this is allowed (B)\\n\\nHere M exports \'foo\' at two different OccNames, with different namespaces for\\nthe two construtors MkS and MkT. Then, when we look up \'foo\' in lookup_names\\nfor case (A), we have a variable foo but must look in all the record field\\nnamespaces to find the two fields (and hence two different Avails).\\nWhereas in case (B) we reach the lookup_ie case for IEThingWith,\\nwhich looks up \'S\' and then finds the unique \'foo\' amongst its children.\\n\\nSee T16745 for a test of this.\\n\\nNote [Preserve parent information when combining import OccEnvs]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen discarding one ImpOccItem in favour of another, as described in\\nNote [Dealing with imports], we must make sure to combine the GREs so that\\nwe don\'t lose information.\\n\\nConsider for example #24084:\\n\\n module M1 where { class C a where { type T a } }\\n module M2 ( module M1 ) where { import M1 }\\n module M3 where { import M2 ( C, T ); instance C () where T () = () }\\n\\nWhen processing the import list of `M3`, we will have two `Avail`s attached\\nto `T`, namely `C(C, T)` and `T(T)`. We combine them in the `combine` function\\nof `mkImportOccEnv`; as described in Note [Dealing with imports] we discard\\n`C(C, T)` in favour of `T(T)`. However, in doing so, we **must not**\\ndiscard the information want that `C` is the parent of `T`. Indeed,\\nlosing track of this information can cause errors when importing,\\nas we could get an error of the form\\n\\n \\u2018T\\u2019 is not a (visible) associated type of class \\u2018C\\u2019\\n\\nThis explains why we use `plusGRE` when combining the two ImpOccItems, even\\nthough we are discarding one in favour of the other.\\n-}\\n\\n-- | All the \'GlobalRdrElt\'s associated with an \'AvailInfo\'.\\ngresFromAvail :: HasDebugCallStack\\n => HscEnv -> Maybe ImportSpec -> AvailInfo -> [GlobalRdrElt]\\ngresFromAvail hsc_env prov avail =\\n [ mk_gre nm info\\n | nm <- availNames avail\\n , let info = lookupGREInfo hsc_env nm ]\\n where\\n\\n mk_gre n info\\n = case prov of\\n -- Nothing => bound locally\\n -- Just is => imported from \'is\'\\n Nothing -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = True, gre_imp = emptyBag\\n , gre_info = info }\\n Just is -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = False, gre_imp = unitBag is\\n , gre_info = info }\\n\\n-- | All the \'GlobalRdrElt\'s associated with a collection of \'AvailInfo\'s.\\ngresFromAvails :: HscEnv -> Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]\\ngresFromAvails hsc_env prov = concatMap (gresFromAvail hsc_env prov)\\n\\nimportsFromIface :: HscEnv -> ModIface -> ImpDeclSpec -> Maybe NameSet -> GlobalRdrEnv\\nimportsFromIface hsc_env iface decl_spec hidden = mkGlobalRdrEnv $ case hidden of\\n Nothing -> all_gres\\n Just hidden_names -> filter (not . (`elemNameSet` hidden_names) . greName) all_gres\\n where\\n all_gres = gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\nrnNamespaceSpecifier :: NamespaceSpecifier GhcPs -> NamespaceSpecifier GhcRn\\nrnNamespaceSpecifier (NoNamespaceSpecifier _) = NoNamespaceSpecifier noExtField\\nrnNamespaceSpecifier (TypeNamespaceSpecifier x) = TypeNamespaceSpecifier x\\nrnNamespaceSpecifier (DataNamespaceSpecifier x) = DataNamespaceSpecifier x\\n\\nfilterImports\\n :: HasDebugCallStack\\n => HscEnv\\n -> ModIface\\n -> ImpDeclSpec\\n -- ^ Import spec\\n -> Maybe (ImportListInterpretation, [LIE GhcPs])\\n -- ^ Whether this is a \\"hiding\\" import list\\n -> RnM (Maybe (ImportListInterpretation, [LIE GhcRn]), -- Import spec w/ Names\\n ImpUserList, -- same, but designed for storage in interfaces\\n GlobalRdrEnv) -- Same again, but in GRE form\\nfilterImports hsc_env iface decl_spec Nothing\\n = return (Nothing, ImpUserAll, importsFromIface hsc_env iface decl_spec Nothing)\\nfilterImports hsc_env iface decl_spec (Just (want_hiding, import_items))\\n = do -- check for errors, convert RdrNames to Names\\n items1 <- mapM lookup_lie import_items\\n\\n let items2 :: [(LIE GhcRn, [GlobalRdrElt])]\\n items2 = concat items1\\n -- NB we may have duplicates, and several items\\n -- for the same parent; e.g N(x) and N(y)\\n\\n (gres, imp_user_list) = case want_hiding of\\n Exactly ->\\n let gres = concatMap (gresFromIE decl_spec) items2\\n gre_env = mkGlobalRdrEnv gres\\n implicit_parents = mkNameSet $ mapMaybe parentOfImplicitlyImportedGRE gres\\n in (gre_env, ImpUserExplicit (gresToAvailInfo $ globalRdrEnvElts $ gre_env) implicit_parents)\\n EverythingBut ->\\n let hidden_names = mkNameSet $ concatMap (map greName . snd) items2\\n in (importsFromIface hsc_env iface decl_spec (Just hidden_names), ImpUserEverythingBut hidden_names)\\n\\n return (Just (want_hiding, map fst items2), imp_user_list, gres)\\n where\\n import_mod = mi_module iface\\n all_avails = mi_exports iface\\n imp_occ_env = mkImportOccEnv hsc_env decl_spec all_avails\\n\\n -- Look up a parent (type constructor, class or data constructor)\\n -- in an import.\\n lookup_parent :: IE GhcPs -> RdrName -> IELookupM ImpOccItem\\n lookup_parent ie rdr =\\n assertPpr (not $ isVarNameSpace ns)\\n (vcat [ text \\"filterImports lookup_parent: unexpected variable\\"\\n , text \\"rdr:\\" <+> ppr rdr\\n , text \\"namespace:\\" <+> pprNameSpace ns ]) $\\n do { xs <- lookup_names ie rdr\\n ; case xs of\\n cax :| [] -> return cax\\n _ -> pprPanic \\"filter_imports lookup_parent ambiguous\\" $\\n vcat [ text \\"rdr:\\" <+> ppr rdr\\n , text \\"lookups:\\" <+> ppr (fmap imp_item xs) ] }\\n -- Looking up non-variables is always unambiguous,\\n -- as there can be at most one corresponding item\\n -- in the imp_occ_env.\\n -- See item (1) of Note [Exporting duplicate declarations]\\n -- in GHC.Tc.Gen.Export.\\n where\\n occ = rdrNameOcc rdr\\n ns = occNameSpace occ\\n\\n -- Look up a RdrName used in an import, returning multiple values if there\\n -- are several fields with the same name exposed by the module\\n lookup_names :: IE GhcPs -> RdrName -> IELookupM (NonEmpty ImpOccItem)\\n lookup_names ie rdr\\n | isQual rdr\\n = failLookupWith (QualImportError rdr)\\n | otherwise\\n = case lookups of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n item:items -> return $ item :| items\\n where\\n lookups = concatMap nonDetNameEnvElts\\n $ lookupImpOccEnv (RelevantGREsFOS WantNormal) imp_occ_env (rdrNameOcc rdr)\\n\\n lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, [GlobalRdrElt])]\\n lookup_lie (L loc ieRdr)\\n = setSrcSpanA loc $\\n do (stuff, warns) <- run_lookup ([],[]) (lookup_ie ieRdr)\\n mapM_ (addTcRnDiagnostic <=< warning_msg) warns\\n return [ (L loc ie, gres) | (ie,gres) <- stuff ]\\n where\\n\\n -- Warn when importing T(..) and no children are brought in scope\\n warning_msg (DodgyImport reason) =\\n pure (TcRnDodgyImports reason)\\n warning_msg MissingImportList =\\n pure (TcRnMissingImportList ieRdr)\\n warning_msg (BadImportW ie sub) = do\\n -- \'BadImportW\' is only constructed below in \'bad_import_w\', in\\n -- the \'EverythingBut\' case, so here we assume a \'hiding\' clause.\\n (reason :| _) <- badImportItemErr iface decl_spec ie sub all_avails\\n pure (TcRnDodgyImports (DodgyImportsHiding reason))\\n warning_msg (DeprecatedExport n w) =\\n pure $ TcRnPragmaWarning\\n PragmaWarningExport\\n { pwarn_occname = occName n\\n , pwarn_impmod = moduleName import_mod }\\n w\\n\\n run_lookup :: a -> IELookupM a -> TcRn a\\n run_lookup def m = case m of\\n Failed err -> do\\n msgs <- lookup_err_msgs err\\n forM_ msgs $ \\\\msg -> addErr (TcRnImportLookup msg)\\n return def\\n Succeeded a -> return a\\n\\n lookup_err_msgs err = case err of\\n BadImport ie sub -> badImportItemErr iface decl_spec ie sub all_avails\\n IllegalImport -> pure $ NE.singleton ImportLookupIllegal\\n QualImportError rdr -> pure $ NE.singleton (ImportLookupQualified rdr)\\n\\n -- For each import item, we convert its RdrNames to Names,\\n -- and at the same time compute all the GlobalRdrElt corresponding\\n -- to what is actually imported by this item.\\n -- Returns Nothing on error.\\n --\\n -- Returns a list because, with DuplicateRecordFields, a naked\\n -- import/export of a record field can correspond to multiple\\n -- different GlobalRdrElts. See Note [Importing DuplicateRecordFields].\\n lookup_ie :: IE GhcPs\\n -> IELookupM ([(IE GhcRn, [GlobalRdrElt])], [IELookupWarning])\\n lookup_ie ie = handle_bad_import $\\n case ie of\\n IEVar _ (L l n) _ -> do\\n -- See Note [Importing DuplicateRecordFields]\\n xs <- lookup_names ie (ieWrappedName n)\\n let gres = map imp_item $ NE.toList xs\\n export_depr_warns\\n | want_hiding == Exactly\\n = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ( [ (IEVar Nothing (L l (replaceWrappedName n name)) noDocstring, [gre])\\n | gre <- gres\\n , let name = greName gre ]\\n , export_depr_warns )\\n\\n IEThingAll x ns_spec (L l tc) _ -> do\\n ImpOccItem { imp_item = gre\\n , imp_bundled = bundled_gres\\n , imp_is_parent = is_par\\n }\\n <- lookup_parent ie $ ieWrappedName tc\\n let name = greName gre\\n\\n child_gres :: [GlobalRdrElt]\\n child_gres\\n | is_par = filterByNamespaceSpecifierGREs ns_spec bundled_gres\\n | otherwise = []\\n\\n imp_list_warn\\n\\n | null child_gres\\n -- e.g. f(..) or T(..) where T is a type synonym\\n = [DodgyImport (DodgyImportsEmptyParent ie ns_spec gre)]\\n\\n -- e.g. import M( T(..) )\\n | not (is_qual decl_spec)\\n = [MissingImportList]\\n\\n | otherwise\\n = []\\n\\n renamed_ie = IEThingAll (x { ieta_warning = Nothing })\\n (rnNamespaceSpecifier ns_spec)\\n (L l (replaceWrappedName tc name))\\n noDocstring\\n export_depr_warn\\n | want_hiding == Exactly\\n = maybeToList $ mk_depr_export_warning gre\\n -- We don\'t want to warn about the children as they\\n -- are not explicitly mentioned; the warning will\\n -- be emitted later on if they are used\\n | otherwise = []\\n\\n return ( [(renamed_ie, gre:child_gres)]\\n , imp_list_warn ++ export_depr_warn)\\n\\n\\n IEThingAbs _ (L l tc\') _\\n | want_hiding == EverythingBut -- hiding ( C )\\n -- Here the \'C\' can be a data constructor\\n -- *or* a type/class, or even both\\n -> let tc = ieWrappedName tc\'\\n tc_name = lookup_parent ie tc\\n dc_name = lookup_parent ie (setRdrNameSpace tc srcDataName)\\n in\\n case catIELookupM [ tc_name, dc_name ] of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n names -> return ( [mkIEThingAbs tc\' l (imp_item name) | name <- names], [])\\n | otherwise\\n -> do ImpOccItem { imp_item = gre } <- lookup_parent ie (ieWrappedName tc\')\\n return ( [mkIEThingAbs tc\' l gre]\\n , maybeToList $ mk_depr_export_warning gre)\\n\\n IEThingWith (deprecation, ann) ltc@(L l rdr_tc) wc rdr_ns _ -> do\\n ImpOccItem { imp_item = gre, imp_bundled = subnames }\\n <- lookup_parent (IEThingAbs Nothing ltc noDocstring) (ieWrappedName rdr_tc)\\n let name = greName gre\\n\\n -- Look up the children in the sub-names of the parent\\n -- See Note [Importing DuplicateRecordFields]\\n let (children_errs, childnames) = lookupChildren subnames rdr_ns\\n\\n bad_import_warns <-\\n if null children_errs then return [] else\\n let items = map lce_wrapped_name children_errs\\n ie = IEThingWith (deprecation, ann) ltc wc items noDocstring\\n -- We are trying to import T( a,b,c,d ), and failed\\n -- to find \'b\' and \'d\'. So we make up an import item\\n -- to report as failing, namely T( b, d ).\\n -- c.f. #15413\\n subordinate_err = mkSubordinateError gre children_errs\\n in bad_import_w ie subordinate_err\\n\\n let name\' = replaceWrappedName rdr_tc name\\n childnames\' = map (to_ie_post_rn . fmap greName) childnames\\n gres = gre : map unLoc childnames\\n export_depr_warns\\n | want_hiding == Exactly = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ([ (IEThingWith (Nothing, ann) (L l name\') wc childnames\' noDocstring\\n ,gres)]\\n , bad_import_warns ++ export_depr_warns)\\n\\n IEWholeNamespace x ns_spec -> do\\n let mod_name = moduleName import_mod\\n names = map greName gres\\n renamed_ie = IEWholeNamespace x { iewn_warning = Nothing\\n , iewn_names = names }\\n (rnNamespaceSpecifier ns_spec)\\n gres = filterByNamespaceSpecifierGREs ns_spec $\\n gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n dodgy_warn\\n | null gres = [DodgyImport (DodgyImportsWildcard mod_name ns_spec)]\\n | otherwise = []\\n return ([(renamed_ie, gres)],\\n dodgy_warn)\\n\\n _other -> failLookupWith IllegalImport\\n -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed...\\n -- all of those constitute errors.\\n\\n where\\n mkIEThingAbs tc l gre\\n = (IEThingAbs Nothing (L l (replaceWrappedName tc n)) noDocstring, [gre])\\n where n = greName gre\\n\\n -- N.B. imports never have docstrings\\n noDocstring = Nothing\\n\\n handle_bad_import m = catchIELookup m $ \\\\case\\n BadImport ie sub -> do\\n ws <- bad_import_w ie sub\\n return ([], ws)\\n err -> failLookupWith err\\n\\n bad_import_w :: IE GhcPs -> IsSubordinateError -> IELookupM [IELookupWarning]\\n bad_import_w ie sub\\n | want_hiding == EverythingBut = return [BadImportW ie sub]\\n | otherwise = failLookupWith (BadImport ie sub)\\n\\n mk_depr_export_warning gre\\n = DeprecatedExport name <$> mi_export_warn_fn iface name\\n where\\n name = greName gre\\n\\n-- | Assuming a subordinate item could not be found, do another lookup for a\\n-- more specific error message.\\nmkBadExportSubordinate :: [GlobalRdrElt] -> LIEWrappedName GhcPs -> BadExportSubordinate\\nmkBadExportSubordinate child_gres n =\\n case lookupChildren child_gres [n] of\\n (LookupChildNonType {lce_nontype_item = g} : _, _) -> BadExportSubordinateNonType g\\n (LookupChildNonData {lce_nondata_item = g} : _, _) -> BadExportSubordinateNonData g\\n _ -> BadExportSubordinateNotFound n\\n\\ntype IELookupM = MaybeErr IELookupError\\n\\ndata IELookupWarning\\n = BadImportW (IE GhcPs) IsSubordinateError\\n | MissingImportList\\n | DodgyImport DodgyImportsReason\\n | DeprecatedExport Name (WarningTxt GhcRn)\\n\\n-- | Is this import/export item a subordinate or not?\\ndata IsSubordinateError\\n = IsSubordinateError { subordinate_err_parent :: !GlobalRdrElt\\n , subordinate_err_unavailable :: [FastString]\\n , subordinate_err_nontype :: [GlobalRdrElt]\\n , subordinate_err_nondata :: [GlobalRdrElt] }\\n | IsNotSubordinate\\n\\nmkSubordinateError :: GlobalRdrElt -> [LookupChildError] -> IsSubordinateError\\nmkSubordinateError gre children_errs = foldr add init_acc children_errs\\n where\\n init_acc :: IsSubordinateError\\n init_acc = IsSubordinateError gre [] [] []\\n\\n add :: LookupChildError -> IsSubordinateError -> IsSubordinateError\\n add children_err sub@IsSubordinateError{} =\\n case children_err of\\n LookupChildNonType{lce_nontype_item = g} ->\\n sub { subordinate_err_nontype = g : subordinate_err_nontype sub }\\n LookupChildNonData{lce_nondata_item = g} ->\\n sub { subordinate_err_nondata = g : subordinate_err_nondata sub }\\n LookupChildNotFound (L _ wname) ->\\n let fs = (occNameFS . rdrNameOcc . ieWrappedName) wname\\n in sub { subordinate_err_unavailable = fs : subordinate_err_unavailable sub }\\n add _ IsNotSubordinate = panic \\"mkSubordinateError: IsNotSubordinate\\"\\n\\ndata IELookupError\\n = QualImportError RdrName\\n | BadImport (IE GhcPs) IsSubordinateError\\n | IllegalImport\\n\\nfailLookupWith :: IELookupError -> IELookupM a\\nfailLookupWith err = Failed err\\n\\ncatchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a\\ncatchIELookup m h = case m of\\n Succeeded r -> return r\\n Failed err -> h err\\n\\ncatIELookupM :: [IELookupM a] -> [a]\\ncatIELookupM ms = [ a | Succeeded a <- ms ]\\n\\n-- | Information associated to an \'AvailInfo\' used in constructing\\n-- an \'OccEnv\' corresponding to imports.\\n--\\n-- See Note [Dealing with imports].\\ndata ImpOccItem\\n = ImpOccItem\\n { imp_item :: GlobalRdrElt\\n -- ^ The import item\\n , imp_bundled :: [GlobalRdrElt]\\n -- ^ Items bundled in the Avail this import item came from,\\n -- not including the import item itself if it is a parent.\\n , imp_is_parent :: Bool\\n -- ^ Is the import item a parent? See Note [Dealing with imports].\\n }\\n\\ninstance Outputable ImpOccItem where\\n ppr (ImpOccItem { imp_item = item, imp_bundled = bundled, imp_is_parent = is_par })\\n = braces $ hsep\\n [ text \\"ImpOccItem\\"\\n , if is_par then text \\"[is_par]\\" else empty\\n , ppr (greName item) <+> ppr (greParent item)\\n , braces $ text \\"bundled:\\" <+> ppr (map greName bundled) ]\\n\\n-- | Make an \'OccEnv\' of all the imports.\\n--\\n-- Complicated by the fact that associated data types and pattern synonyms\\n-- can appear twice. See Note [Dealing with imports].\\nmkImportOccEnv :: HscEnv -> ImpDeclSpec -> [IfaceExport] -> OccEnv (NameEnv ImpOccItem)\\nmkImportOccEnv hsc_env decl_spec all_avails =\\n mkOccEnv_C (plusNameEnv_C combine)\\n [ (occ, mkNameEnv [(nm, item)])\\n | avail <- all_avails\\n , let gres = gresFromAvail hsc_env (Just hiding_spec) avail\\n , gre <- gres\\n , let nm = greName gre\\n occ = greOccName gre\\n (is_parent, bundled) = case avail of\\n AvailTC c _\\n | c == nm -- (Recall the AvailTC invariant from GHC.Types.AvailInfo)\\n -> ( True, drop 1 gres ) -- \\"drop 1\\": don\'t include the parent itself.\\n | otherwise\\n -> ( False, gres )\\n _ -> ( False, [] )\\n item = ImpOccItem\\n { imp_item = gre\\n , imp_bundled = bundled\\n , imp_is_parent = is_parent }\\n ]\\n where\\n\\n hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\n -- See Note [Dealing with imports]\\n -- \'combine\' may be called for associated data types which appear\\n -- twice in the all_avails. In the example, we have two Avails for T,\\n -- namely T(T,T1,T2,T3) and C(C,T), and we combine them by dropping the\\n -- latter, in which T is not the parent.\\n combine :: ImpOccItem -> ImpOccItem -> ImpOccItem\\n combine item1@(ImpOccItem { imp_item = gre1, imp_is_parent = is_parent1 })\\n item2@(ImpOccItem { imp_item = gre2, imp_is_parent = is_parent2 })\\n | is_parent1 || is_parent2\\n , not (isRecFldGRE gre1 || isRecFldGRE gre2) -- NB: does not force GREInfo.\\n , let name1 = greName gre1\\n name2 = greName gre2\\n gre = gre1 `plusGRE` gre2\\n -- See Note [Preserve parent information when combining import OccEnvs]\\n = assertPpr (name1 == name2)\\n (ppr name1 <+> ppr name2) $\\n if is_parent1\\n then item1 { imp_item = gre }\\n else item2 { imp_item = gre }\\n -- Discard C(C,T) in favour of T(T, T1, T2, T3).\\n\\n -- \'combine\' may also be called for pattern synonyms which appear both\\n -- unassociated and associated (see Note [Importing PatternSynonyms]).\\n combine item1@(ImpOccItem { imp_item = c1, imp_bundled = kids1 })\\n item2@(ImpOccItem { imp_item = c2, imp_bundled = kids2 })\\n = assertPpr (greName c1 == greName c2\\n && (not (null kids1 && null kids2)))\\n (ppr c1 <+> ppr c2 <+> ppr kids1 <+> ppr kids2) $\\n if null kids1\\n then item2\\n else item1\\n -- Discard standalone pattern P in favour of T(P).\\n\\n-- | Essentially like @lookupGRE env (LookupOccName occ which_gres)@,\\n-- but working with \'ImpOccItem\'s instead of \'GlobalRdrElt\'s.\\nlookupImpOccEnv :: WhichGREs GREInfo\\n -> OccEnv (NameEnv ImpOccItem) -> OccName -> [NameEnv ImpOccItem]\\nlookupImpOccEnv which_gres env occ =\\n mapMaybe relevant_items $ lookupOccEnv_AllNameSpaces env occ\\n where\\n is_relevant :: ImpOccItem -> Bool\\n is_relevant (ImpOccItem { imp_item = gre }) =\\n greIsRelevant which_gres (occNameSpace occ) gre\\n relevant_items :: NameEnv ImpOccItem -> Maybe (NameEnv ImpOccItem)\\n relevant_items nms\\n | let nms\' = filterNameEnv is_relevant nms\\n = if isEmptyNameEnv nms\'\\n then Nothing\\n else Just nms\'\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{Import/Export Utils}\\n* *\\n************************************************************************\\n-}\\n\\n-- | Given an import\\\\/export spec, appropriately set the @gre_imp@ field\\n-- for the \'GlobalRdrElt\'s.\\ngresFromIE :: ImpDeclSpec -> (LIE GhcRn, [GlobalRdrElt]) -> [GlobalRdrElt]\\ngresFromIE decl_spec (L loc ie, gres)\\n = map set_gre_imp gres\\n where\\n is_explicit = case ie of\\n IEThingAll _ _ name _ -> \\\\n -> n == lieWrappedName name\\n IEWholeNamespace _ _ -> \\\\_ -> False\\n _ -> \\\\_ -> True\\n prov_fn name\\n = ImpSpec { is_decl = decl_spec, is_item = item_spec }\\n where\\n item_spec = ImpSome { is_explicit = is_explicit name\\n , is_iloc = locA loc }\\n set_gre_imp gre@( GRE { gre_name = nm } )\\n = gre { gre_imp = unitBag $ prov_fn nm }\\n\\nparentOfImplicitlyImportedGRE :: Outputable info => GlobalRdrEltX info -> Maybe Name\\nparentOfImplicitlyImportedGRE gre =\\n if any (explicit_import . is_item) $ gre_imp gre\\n then Nothing\\n else greParent_maybe gre\\n where\\n explicit_import :: ImpItemSpec -> Bool\\n explicit_import (ImpAll {}) =\\n pprPanic \\"parentOfImplicitlyImportedGRE: ImpAll\\" (ppr gre)\\n explicit_import (ImpSome { is_explicit }) = is_explicit\\n\\n{- Note [Children for duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider the module\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (F(foo, MkFInt, MkFBool)) where\\n data family F a\\n data instance F Int = MkFInt { foo :: Int }\\n data instance F Bool = MkFBool { foo :: Bool }\\n\\nThe `foo` in the export list refers to *both* selectors! For this\\nreason, lookupChildren builds an environment that maps the FastString\\nto a list of items, rather than a single item.\\n-}\\n\\nmkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]\\nmkChildEnv gres = foldr add emptyNameEnv gres\\n where\\n add gre env = case greParent gre of\\n ParentIs p -> extendNameEnv_Acc (:) Utils.singleton env p gre\\n NoParent -> env\\n\\nfindChildren :: NameEnv [a] -> Name -> [a]\\nfindChildren env n = lookupNameEnv env n `orElse` []\\n\\ndata LookupChildError\\n = LookupChildNotFound { lce_wrapped_name :: !(LIEWrappedName GhcPs) }\\n | LookupChildNonType { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nontype_item :: !GlobalRdrElt }\\n | LookupChildNonData { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nondata_item :: !GlobalRdrElt }\\n\\nlookupChildren :: [GlobalRdrElt]\\n -> [LIEWrappedName GhcPs]\\n -> ( [LookupChildError] -- The ones for which the lookup failed\\n , [LocatedA GlobalRdrElt] )\\n-- (lookupChildren all_kids rdr_items) maps each rdr_item to its\\n-- corresponding Name in all_kids, if the former exists\\n-- The matching is done by FastString, not OccName, so that\\n-- Cls( meth, AssocTy )\\n-- will correctly find AssocTy among the all_kids of Cls, even though\\n-- the RdrName for AssocTy may have a (bogus) DataName namespace\\n-- (Really the rdr_items should be FastStrings in the first place.)\\nlookupChildren all_kids rdr_items = (fails, successes)\\n where\\n mb_xs = map do_one rdr_items\\n fails = [ err | Failed err <- mb_xs ]\\n successes = [ ok | Succeeded oks <- mb_xs, ok <- NE.toList oks ]\\n\\n do_one :: LIEWrappedName GhcPs -> MaybeErr LookupChildError (NonEmpty (LocatedA GlobalRdrElt))\\n do_one item@(L l r) =\\n case r of\\n IEName{}\\n -- IEName (unadorned name) places no restriction on the namespace of\\n -- the imported entity, so we look in both `val_gres` and `typ_gres`.\\n -- In case of conflict (punning), the value namespace takes priority.\\n -- See Note [Prioritise the value namespace in subordinate import lists]\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEType{}\\n -- IEType (\'type\' namespace specifier) restricts the lookup to the\\n -- type namespace, i.e. to `typ_gres`. In case of failure, we check\\n -- `val_gres` to produce a more helpful error message.\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- val_gres -> Failed $ LookupChildNonType item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEData{}\\n -- IEData (\'data\' namespace specifier) restricts the lookup to the\\n -- data namespace, i.e. to `val_gres`. In case of failure, we check\\n -- `typ_gres` to produce a more helpful error message.\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- typ_gres -> Failed $ LookupChildNonData item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEPattern{} -> panic \\"lookupChildren: IEPattern\\" -- Never happens (invalid syntax)\\n IEDefault{} -> panic \\"lookupChildren: IEDefault\\" -- Never happens (invalid syntax)\\n where\\n fs = (occNameFS . rdrNameOcc . ieWrappedName) r\\n gres = fromMaybe [] (lookupFsEnv kid_env fs)\\n (val_gres, typ_gres) = partition (isValNameSpace . greNameSpace) gres\\n\\n -- See Note [Children for duplicate record fields]\\n kid_env :: FastStringEnv [GlobalRdrElt]\\n kid_env = extendFsEnvList_C (++) emptyFsEnv\\n [(occNameFS (occName x), [x]) | x <- all_kids]\\n\\n\\n{- Note [Prioritise the value namespace in subordinate import lists]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider this program that defines a class that has both an associated type\\nnamed (#) and a method named (#)\\n\\n module M_assoc where\\n class C a b where\\n type a # b\\n (#) :: a -> b -> ()\\n module N_assoc where\\n import M_assoc( C((#)) )\\n\\nIn the import declaration, when we see the unadorned name (#) in the subordinate\\nimport list of C, which children should we bring into scope? Our options are:\\n\\n a) only the method (#)\\n b) only the associated type (#)\\n c) both the method and the associated type\\n\\nTo follow the precedent established by top-level items, we go with option (a).\\nIndeed, consider a slightly different program\\n\\n module M_top where\\n type family a # b\\n a # b = ()\\n module N_top where\\n import M_top( (#) )\\n\\nHere the import brings only the function (#) into scope, and one has to say\\n`type (#)` to get the type family.\\n-}\\n\\n-------------------------------\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused names}\\n* *\\n*********************************************************\\n-}\\n\\nreportUnusedNames :: TcGblEnv -> HscSource -> RnM ()\\nreportUnusedNames gbl_env hsc_src\\n = do { keep <- readTcRef (tcg_keep gbl_env)\\n ; traceRn \\"RUN\\" (ppr (tcg_dus gbl_env))\\n ; warnUnusedImportDecls gbl_env hsc_src\\n ; warnUnusedTopBinds $ unused_locals keep\\n ; warnMissingSignatures gbl_env\\n ; warnMissingKindSignatures gbl_env }\\n where\\n used_names :: NameSet -> NameSet\\n used_names keep = findUses (tcg_dus gbl_env) emptyNameSet `unionNameSet` keep\\n -- NB: currently, if f x = g, we only treat \'g\' as used if \'f\' is used\\n -- Hence findUses\\n\\n -- Collect the defined names from the in-scope environment\\n defined_names :: [GlobalRdrElt]\\n defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)\\n\\n kids_env = mkChildEnv defined_names\\n -- This is done in mkExports too; duplicated work\\n\\n gre_is_used :: NameSet -> GlobalRdrElt -> Bool\\n gre_is_used used_names gre0\\n = name `elemNameSet` used_names\\n || any (\\\\ gre -> greName gre `elemNameSet` used_names) (findChildren kids_env name)\\n -- A use of C implies a use of T,\\n -- if C was brought into scope by T(..) or T(C)\\n where\\n name = greName gre0\\n\\n -- Filter out the ones that are\\n -- (a) defined in this module, and\\n -- (b) not defined by a \'deriving\' clause\\n -- The latter have an Internal Name, so we can filter them out easily\\n unused_locals :: NameSet -> [GlobalRdrElt]\\n unused_locals keep =\\n let -- Note that defined_and_used, defined_but_not_used\\n -- are both [GRE]; that\'s why we need defined_and_used\\n -- rather than just used_names\\n _defined_and_used, defined_but_not_used :: [GlobalRdrElt]\\n (_defined_and_used, defined_but_not_used)\\n = partition (gre_is_used (used_names keep)) defined_names\\n\\n in filter is_unused_local defined_but_not_used\\n is_unused_local :: GlobalRdrElt -> Bool\\n is_unused_local gre = isLocalGRE gre\\n && isExternalName (greName gre)\\n\\n{- *********************************************************************\\n* *\\n Missing signatures\\n* *\\n********************************************************************* -}\\n\\n{-\\nNote [Missing signatures]\\n~~~~~~~~~~~~~~~~~~~~~~~~~\\nThere are four warning flags in play:\\n\\n * -Wmissing-exported-signatures\\n Warn about any exported top-level function/value without a type signature.\\n Does not include pattern synonyms.\\n\\n * -Wmissing-signatures\\n Warn about any top-level function/value without a type signature. Does not\\n include pattern synonyms. Takes priority over -Wmissing-exported-signatures.\\n\\n * -Wmissing-exported-pattern-synonym-signatures\\n Warn about any exported pattern synonym without a type signature.\\n\\n * -Wmissing-pattern-synonym-signatures\\n Warn about any pattern synonym without a type signature. Takes priority over\\n -Wmissing-exported-pattern-synonym-signatures.\\n\\n-}\\n\\n-- | Warn the user about top level binders that lack type signatures.\\n-- Called /after/ type inference, so that we can report the\\n-- inferred type of the function\\nwarnMissingSignatures :: TcGblEnv -> RnM ()\\nwarnMissingSignatures gbl_env\\n = do { let exports = availsToNameSet (tcg_exports gbl_env)\\n sig_ns = tcg_sigs gbl_env\\n -- We use sig_ns to exclude top-level bindings that are generated by GHC\\n binds = collectHsBindsBinders CollNoDictBinders $ tcg_binds gbl_env\\n pat_syns = tcg_patsyns gbl_env\\n\\n not_ghc_generated :: Name -> Bool\\n not_ghc_generated name = name `elemNameSet` sig_ns\\n\\n add_binding_warn :: Id -> RnM ()\\n add_binding_warn id =\\n when (not_ghc_generated name) $\\n do { env <- liftZonkM $ tcInitTidyEnv -- Why not use emptyTidyEnv?\\n ; let ty = tidyOpenType env (idType id)\\n missing = MissingTopLevelBindingSig name ty\\n diag = TcRnMissingSignature missing exported\\n ; addDiagnosticAt (getSrcSpan name) diag }\\n where\\n name = idName id\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n add_patsyn_warn :: PatSyn -> RnM ()\\n add_patsyn_warn ps =\\n when (not_ghc_generated name) $\\n addDiagnosticAt (getSrcSpan name)\\n (TcRnMissingSignature missing exported)\\n where\\n name = patSynName ps\\n missing = MissingPatSynSig ps\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n -- Warn about missing signatures\\n -- Do this only when we have a type to offer\\n -- See Note [Missing signatures]\\n ; mapM_ add_binding_warn binds\\n ; mapM_ add_patsyn_warn pat_syns\\n }\\n\\n-- | Warn the user about tycons that lack kind signatures.\\n-- Called /after/ type (and kind) inference, so that we can report the\\n-- inferred kinds.\\nwarnMissingKindSignatures :: TcGblEnv -> RnM ()\\nwarnMissingKindSignatures gbl_env\\n = do { cusks_enabled <- xoptM LangExt.CUSKs\\n ; mapM_ (add_ty_warn cusks_enabled) tcs\\n }\\n where\\n tcs = tcg_tcs gbl_env\\n ksig_ns = tcg_ksigs gbl_env\\n exports = availsToNameSet (tcg_exports gbl_env)\\n\\n has_kind_signature :: Name -> Bool\\n has_kind_signature name = name `elemNameSet` ksig_ns\\n\\n add_ty_warn :: Bool -> TyCon -> RnM ()\\n add_ty_warn cusks_enabled tyCon =\\n when (has_kind_signature name) $\\n addDiagnosticAt (getSrcSpan name) diag\\n where\\n name = tyConName tyCon\\n diag = TcRnMissingSignature missing exported\\n missing = MissingTyConKindSig tyCon cusks_enabled\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused imports}\\n* *\\n*********************************************************\\n\\nThis code finds which import declarations are unused. The\\nspecification and implementation notes are here:\\n https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/unused-imports\\n\\nSee also Note [Choosing the best import declaration] in GHC.Types.Name.Reader\\n-}\\n\\ntype ImportDeclUsage\\n = ( LImportDecl GhcRn -- The import declaration\\n , [GlobalRdrElt] -- What *is* used (normalised)\\n , [Name] -- What is imported but *not* used\\n , [NamespaceSpecifier GhcRn] ) -- Unused wildcards\\n\\nwarnUnusedImportDecls :: TcGblEnv -> HscSource -> RnM ()\\nwarnUnusedImportDecls gbl_env hsc_src\\n = do { uses <- readMutVar (tcg_used_gres gbl_env)\\n ; let imports = tcg_rn_imports gbl_env\\n rdr_env = tcg_rdr_env gbl_env\\n\\n -- We should only warn for unnecessary *user* imports, but deciding\\n -- minimal imports should take generated imports into account\\n ; let usageUserImports = findImportUsage (excludeGenerated imports) uses\\n usageAllImports = findImportUsage imports uses\\n\\n ; traceRn \\"warnUnusedImportDecls\\" $\\n (vcat [ text \\"Uses:\\" <+> ppr uses\\n , text \\"Usage all user imports: \\" <+> ppr usageUserImports\\n , text \\"Usage all imports: \\" <+> ppr usageAllImports])\\n\\n ; mapM_ (warnUnusedImport rdr_env) usageUserImports\\n\\n ; whenGOptM Opt_D_dump_minimal_imports $\\n printMinimalImports hsc_src usageAllImports }\\n\\n-- | Exclude generated imports\\nexcludeGenerated :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\nexcludeGenerated = filterOut (isGeneratedImport . ideclOrigin . ideclExt . unLoc)\\n\\nfindImportUsage :: [LImportDecl GhcRn]\\n -> [GlobalRdrElt]\\n -> [ImportDeclUsage]\\n\\nfindImportUsage imports used_gres\\n = map unused_decl imports\\n where\\n import_usage :: ImportMap\\n import_usage = mkImportMap used_gres\\n\\n unused_decl :: LImportDecl GhcRn -> ImportDeclUsage\\n unused_decl decl@(L _ (ImportDecl { ideclImportList = imps }))\\n = -- pprTrace \\"unused_decl\\" (vcat [ ppr decl\\n -- , text \\"used\\" <+> ppr used_gres\\n -- , text \\"unused\\" <+> ppr unused_names ]) $\\n (decl, used_gres, unused_names, unused_wcs)\\n where\\n used_gres = lookupImportMap decl import_usage\\n\\n used_gre_env = mkGlobalRdrEnv used_gres\\n used_parents = mkNameSet (mapMaybe greParent_maybe used_gres)\\n\\n (unused_names, unused_wcs) -- Not trivial; see eg #7454\\n = case imps of\\n Just (Exactly, imp_ies) ->\\n let unused = foldr (add_unused . unLoc) emptyUnusedNames imp_ies\\n nms = nameSetElemsStable (collectUnusedNames unused)\\n wcs = collectUnusedWildcards unused\\n in (nms, wcs)\\n _other -> ([], []) -- No explicit import list => no unused-name list\\n\\n add_unused :: IE GhcRn -> UnusedNames -> UnusedNames\\n add_unused (IEVar _ n _) acc = add_unused_name (lieWrappedName n) True acc\\n add_unused (IEThingAbs _ n _) acc = add_unused_name (lieWrappedName n) False acc\\n add_unused (IEThingAll _ _ n _) acc = add_unused_all (lieWrappedName n) acc\\n add_unused (IEThingWith _ p wc ns _) acc = add_wc_all (add_unused_with pn xs acc)\\n where pn = lieWrappedName p\\n xs = map lieWrappedName ns\\n add_wc_all = case wc of\\n NoIEWildcard -> id\\n IEWildcard _ -> add_unused_all pn\\n add_unused (IEWholeNamespace x ns_spec) acc = add_unused_wildcard ns_spec (iewn_names x) acc\\n add_unused _ acc = acc\\n\\n add_unused_name :: Name -> Bool -> UnusedNames -> UnusedNames\\n add_unused_name n is_ie_var acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | is_ie_var\\n , isFieldName n\\n -- See Note [Reporting unused imported duplicate record fields]\\n = let\\n fs = getOccFS n\\n (flds, flds_used) = lookupFsEnv acc_fs fs `orElse` (emptyNameSet, Any False)\\n acc_fs\' = extendFsEnv acc_fs fs (extendNameSet flds n, Any used S.<> flds_used)\\n in UnusedNames acc_ns acc_wcs acc_fs\'\\n\\n | used\\n = acc\\n\\n | otherwise\\n = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n where\\n used = isJust $ lookupGRE_Name used_gre_env n\\n\\n add_unused_all :: Name -> UnusedNames -> UnusedNames\\n add_unused_all n acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | Just {} <- lookupGRE_Name used_gre_env n = acc\\n | n `elemNameSet` used_parents = acc\\n | otherwise = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n\\n add_unused_with :: Name -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_with p ns acc\\n | all (`elemNameSet` acc1_ns) ns = add_unused_name p False acc1\\n | otherwise = acc1\\n where\\n acc1@(UnusedNames acc1_ns _ _) = foldr (\\\\n acc\' -> add_unused_name n False acc\') acc ns\\n -- If you use \'signum\' from Num, then the user may well have\\n -- imported Num(signum). We don\'t want to complain that\\n -- Num is not itself mentioned. Hence the two cases in add_unused_with.\\n\\n add_unused_wildcard :: NamespaceSpecifier GhcRn -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_wildcard ns_spec names acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | any_used = acc\\n | otherwise = UnusedNames acc_ns (ns_spec : acc_wcs) acc_fs\\n where\\n -- A wildcard `type ..` or `data ..` is used if at least one of\\n -- the names it expands to is used\\n any_used = any (isJust . lookupGRE_Name used_gre_env) names\\n\\n\\n-- | An accumulator for unused names in an import list.\\n--\\n-- See Note [Reporting unused imported duplicate record fields].\\ndata UnusedNames =\\n UnusedNames\\n { unused_names :: NameSet\\n -- ^ Unused \'Name\'s in an import list, not including record fields\\n -- that are plain \'IEVar\' imports (tracked by \'rec_fld_uses\')\\n -- or wildcard imports (tracked by \'unused_wildcards\').\\n , unused_wildcards :: [NamespaceSpecifier GhcRn]\\n -- ^ Unused wildcards @type ..@ or @data ..@ in an import list.\\n , rec_fld_uses :: FastStringEnv (NameSet, Any)\\n -- ^ Record fields imported without a parent (i.e. an \'IEVar\' import).\\n --\\n -- The \'Any\' value records whether any of the record fields\\n -- sharing the same underlying \'FastString\' have been used.\\n }\\n\\nemptyUnusedNames :: UnusedNames\\nemptyUnusedNames = UnusedNames emptyNameSet [] emptyFsEnv\\n\\ninstance Outputable UnusedNames where\\n ppr (UnusedNames nms wcs flds) =\\n text \\"UnusedNames\\" <+>\\n braces (ppr nms <+> ppr wcs <+> ppr (fmap (second getAny) flds))\\n\\n-- | Collect all unused names from a \'UnusedNames\' value.\\ncollectUnusedNames :: UnusedNames -> NameSet\\ncollectUnusedNames (UnusedNames { unused_names = nms, rec_fld_uses = flds })\\n = nms S.<> unused_flds\\n where\\n unused_flds = nonDetFoldFsEnv collect_unused emptyNameSet flds\\n collect_unused :: (NameSet, Any) -> NameSet -> NameSet\\n collect_unused (nms, Any at_least_one_name_is_used) acc\\n | at_least_one_name_is_used = acc\\n | otherwise = unionNameSet nms acc\\n\\ncollectUnusedWildcards :: UnusedNames -> [NamespaceSpecifier GhcRn]\\ncollectUnusedWildcards = unused_wildcards\\n\\n{- Note [Reporting unused imported duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have (#24035):\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M1 (R1(..), R2(..)) where\\n data R1 = MkR1 { fld :: Int }\\n data R2 = MkR2 { fld :: Int }\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M2 where\\n import M1 (R1(MkR1), R2, fld)\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nIn the import of \'M1\' in \'M2\', the \'fld\' import resolves to two separate GREs,\\nnamely R1(fld) and R2(fld). From the perspective of the renamer, and in particular\\nthe \'findImportUsage\' function, it\'s as if the user had imported the two names\\nseparately (even though no source syntax allows that).\\n\\nThis means that we need to be careful when reporting unused imports: the R2(fld)\\nimport is indeed unused, but because R1(fld) is used, we should not report\\nfld as unused altogether.\\n\\nTo achieve this, we keep track of record field imports without a parent (i.e.\\nusing the IEVar constructor) separately from other import items, using the\\nUnusedNames datatype.\\nOnce we have accumulated usages, we emit warnings for unused record fields\\nwithout parents one whole group (of record fields sharing the same textual name)\\nat a time, and only if *all* of the record fields in the group are unused;\\nsee \'collectUnusedNames\'.\\n\\nNote that this only applies to record fields imported without a parent. If we\\nhad:\\n\\n import M1 (R1(MkR1, fld), R2(fld))\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nthen of course we should report the second \'fld\' as unused.\\n-}\\n\\n\\n{- Note [The ImportMap]\\n~~~~~~~~~~~~~~~~~~~~~~~\\nThe ImportMap is a short-lived intermediate data structure records, for\\neach import declaration, what stuff brought into scope by that\\ndeclaration is actually used in the module.\\n\\nThe [GlobalRdrElt] are the things imported from that decl.\\n-}\\n\\ndata ImportMap = ImportMap\\n { im_imports :: Map RealSrcSpan [GlobalRdrElt]\\n -- ^ See [The ImportMap]\\n -- If loc :-> gres, then\\n -- \'loc\' = the end loc of the bestImport of each GRE in \'gres\'\\n , im_generatedImports :: Map ModuleName [GlobalRdrElt]\\n }\\n\\nmkImportMap :: [GlobalRdrElt] -> ImportMap\\n-- For each of a list of used GREs, find all the import decls that brought\\n-- it into scope; choose one of them (bestImport), and record\\n-- the RdrName in that import decl\'s entry in the ImportMap\\nmkImportMap = foldr insertImportMap $ ImportMap Map.empty Map.empty\\n\\ninsertImportMap :: GlobalRdrElt -> ImportMap -> ImportMap\\ninsertImportMap gre@(GRE { gre_imp = imp_specs }) importMap\\n | RealSrcSpan importSpan _ <- is_dloc best_imp_spec =\\n importMap{im_imports = insertElem importSpan gre $ im_imports importMap}\\n | GeneratedSrcSpan{} <- is_dloc best_imp_spec =\\n importMap{im_generatedImports = insertElem (moduleName $ is_mod best_imp_spec) gre $ im_generatedImports importMap}\\n | otherwise = importMap\\n where\\n best_imp_spec =\\n case bagToList imp_specs of\\n [] -> pprPanic \\"mkImportMap: GRE with no ImportSpecs\\" (ppr gre)\\n is:iss -> is_decl $ bestImport (is NE.:| iss)\\n\\n -- https://github.com/haskell/containers/issues/784\\n insertElem :: Ord k => k -> v -> Map k [v] -> Map k [v]\\n insertElem k v = flip Map.alter k $ \\\\case\\n Just vs -> Just (v : vs)\\n Nothing -> Just [v]\\n\\nlookupImportMap :: LImportDecl GhcRn -> ImportMap -> [GlobalRdrElt]\\nlookupImportMap (L srcSpan ImportDecl{ideclName = L _ modName}) importMap =\\n fromMaybe [] $\\n -- should match logic in insertImportMap\\n case locA srcSpan of\\n RealSrcSpan realSrcSpan _ -> realSrcSpan `Map.lookup` im_imports importMap\\n GeneratedSrcSpan{} -> modName `Map.lookup` im_generatedImports importMap\\n _ -> Nothing\\n\\nlieNames :: LIE (GhcPass p) -> [Located (IdP (GhcPass p))]\\nlieNames = _\\n\\nwarnUnusedImport :: GlobalRdrEnv -> ImportDeclUsage -> RnM ()\\nwarnUnusedImport rdr_env (L loc decl, used, unused, unused_wcs)\\n\\n -- Do not warn for \'import M()\'\\n -- See (UI1) in Note [Unused imports]\\n | Just (Exactly, _) <- ideclImportList decl\\n , null unused && null unused_wcs\\n = return ()\\n\\n -- Note [Do not warn about Prelude hiding]\\n | Just (EverythingBut, hides) <- ideclImportList decl\\n , not (null hides)\\n , pRELUDE_NAME == unLoc (ideclName decl)\\n = return ()\\n\\n -- Do not warn about import X as Rebindable\\n -- See (UI2) in Note [Unused imports]\\n | Just (L _ mod) <- ideclAs decl\\n , mod == rEBINDABLE_MOD_NAME\\n = return ()\\n\\n -- Nothing used; drop entire declaration\\n | null used\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl UnusedImportNone)\\n\\n -- Everything imported is used; nop\\n | null unused && null unused_wcs\\n = return ()\\n\\n -- Some imports are unused: make the `SrcSpan` cover only the unused\\n -- items instead of the whole import statement\\n | Just (_, imports) <- ideclImportList decl\\n , let unused_locs = [ locA loc | L loc ie <- imports\\n , name <- ieNames ie\\n , name `elem` unused ]\\n , loc1 : locs <- unused_locs\\n , let span = foldr1 combineSrcSpans ( loc1 NE.:| locs )\\n = addDiagnosticAt span (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n -- Some imports are unused\\n | otherwise\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n where\\n -- In warning message, pretty-print identifiers unqualified unconditionally\\n -- to improve the consistent for ambiguous/unambiguous identifiers.\\n -- See #14881.\\n possible_field n =\\n case lookupGRE_Name rdr_env n of\\n Just (GRE { gre_par = par, gre_info = IAmRecField info }) ->\\n let fld_occ :: OccName\\n fld_occ = nameOccName $ flSelector $ recFieldLabel info\\n in UnusedImportNameRecField par fld_occ\\n _ -> UnusedImportNameRegular n\\n\\n -- Print unused names in a deterministic (lexicographic) order\\n sort_unused :: [UnusedImportName]\\n sort_unused =\\n [ UnusedImportWildcard wc | wc <- unused_wcs ] ++\\n [ possible_field nm | nm <- sortBy (comparing nameOccName) unused ]\\n\\ngetMinimalImports :: [ImportDeclUsage] -> RnM [LImportDecl GhcRn]\\ngetMinimalImports ie_decls\\n = do { rdr_env <- getGlobalRdrEnv\\n ; fmap combine $ mapM (mk_minimal rdr_env) ie_decls }\\n where\\n mk_minimal rdr_env (L l decl, used_gres, unused, unused_wcs)\\n | null unused && null unused_wcs\\n , Just (Exactly, _) <- ideclImportList decl\\n = return (L l decl)\\n | otherwise\\n = do { let ImportDecl { ideclName = L _ mod_name\\n , ideclSource = is_boot\\n , ideclPkgQual = pkg_qual\\n , ideclExt = XImportDeclPass { ideclOrigin = origin } } = decl\\n ; iface <- loadSrcInterface doc (importDeclLookupScope origin)\\n mod_name is_boot pkg_qual\\n ; let used_avails = gresToAvailInfo used_gres\\n ; lies <- map (L l) <$> concatMapM (to_ie rdr_env iface) used_avails\\n ; return (L l (decl { ideclImportList = Just (Exactly, lies) })) }\\n where\\n doc = text \\"Compute minimal imports for\\" <+> ppr decl\\n\\n to_ie :: GlobalRdrEnv -> ModIface -> AvailInfo -> RnM [IE GhcRn]\\n -- The main trick here is that if we\'re importing all the constructors\\n -- we want to say \\"T(..)\\", but if we\'re importing only a subset we want\\n -- to say \\"T(A,B,C)\\". So we have to find out what the module exports.\\n to_ie rdr_env _ (Avail c) -- Note [Overloaded field import]\\n = do { let\\n gre = expectJust $ lookupGRE_Name rdr_env c\\n ; return $ [IEVar Nothing (to_ie_post_rn $ noLocA $ greName gre) Nothing] }\\n to_ie _ _ avail@(AvailTC n [_]) -- Exporting the main decl and nothing else\\n | availExportsDecl avail\\n = return [IEThingAbs Nothing (to_ie_post_rn $ noLocA n) Nothing]\\n to_ie rdr_env iface (AvailTC n cs) =\\n case [ xs | avail@(AvailTC x xs) <- mi_exports iface\\n , x == n\\n , availExportsDecl avail -- Note [Partial export]\\n ] of\\n [xs]\\n | all_used xs\\n -> return [IEThingAll (IEThingAllExt Nothing noAnn noAnn noAnn)\\n (NoNamespaceSpecifier noExtField)\\n (to_ie_post_rn $ noLocA n)\\n Nothing]\\n | otherwise\\n -> do { let ns_gres = map (expectJust . lookupGRE_Name rdr_env) cs\\n ns = map greName ns_gres\\n ; return [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n -- Note [Overloaded field import]\\n _other\\n -> do { let infos = map (expectJust . lookupGRE_Name rdr_env) cs\\n (ns_gres,fs_gres) = classifyGREs infos\\n ns = map greName (ns_gres ++ fs_gres)\\n fs = map fieldGREInfo fs_gres\\n ; return $\\n if all_non_overloaded fs\\n then map (\\\\nm -> IEVar Nothing (to_ie_post_rn_var $ noLocA nm) Nothing) ns\\n else [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n where\\n\\n all_used avail_cs = all (`elem` cs) avail_cs\\n\\n all_non_overloaded = all (not . flIsOverloaded . recFieldLabel)\\n\\n combine :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\n combine = map merge . NE.groupAllWith getKey\\n\\n getKey :: LImportDecl GhcRn -> (Bool, Maybe ModuleName, ModuleName)\\n getKey decl =\\n ( isImportDeclQualified . ideclQualified $ idecl -- is this qualified? (important that this be first)\\n , unLoc <$> ideclAs idecl -- what is the qualifier (inside Maybe monad)\\n , unLoc . ideclName $ idecl -- Module Name\\n )\\n where\\n idecl :: ImportDecl GhcRn\\n idecl = unLoc decl\\n\\n merge :: NonEmpty (LImportDecl GhcRn) -> LImportDecl GhcRn\\n merge decls@((L l decl) :| _) = L l (decl { ideclImportList = Just (Exactly, lies) })\\n where lies = concatMap snd $ mapMaybe (ideclImportList . unLoc) $ NE.toList decls\\n\\nclassifyGREs :: [GlobalRdrElt] -> ([GlobalRdrElt], [FieldGlobalRdrElt])\\nclassifyGREs = partition (not . isRecFldGRE)\\n\\nprintMinimalImports :: HscSource -> [ImportDeclUsage] -> RnM ()\\n-- See Note [Printing minimal imports]\\nprintMinimalImports hsc_src imports_w_usage\\n = do { imports\' <- excludeGenerated <$> getMinimalImports imports_w_usage\\n ; this_mod <- getModule\\n ; dflags <- getDynFlags\\n ; liftIO $ withFile (mkFilename dflags this_mod) WriteMode $ \\\\h ->\\n printForUser dflags h neverQualify AllTheWay (vcat (map ppr imports\'))\\n -- The neverQualify is important. We are printing Names\\n -- but they are in the context of an \'import\' decl, and\\n -- we never qualify things inside there\\n -- E.g. import Blag( f, b )\\n -- not import Blag( Blag.f, Blag.g )!\\n }\\n where\\n mkFilename dflags this_mod\\n | Just d <- dumpDir dflags = d basefn\\n | otherwise = basefn\\n where\\n suffix = case hsc_src of\\n HsBootFile -> \\".imports-boot\\"\\n HsSrcFile -> \\".imports\\"\\n HsigFile -> \\".imports\\"\\n basefn = moduleNameString (moduleName this_mod) ++ suffix\\n\\n\\nto_ie_post_rn_var :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn_var (L l n)\\n | isDataOcc $ occName n = L l (IEPattern noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n\\n\\nto_ie_post_rn :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn (L l n)\\n | isTcOcc occ && isSymOcc occ = L l (IEType noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n where occ = occName n\\n\\n{- Note [Do not warn about Prelude hiding]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWe do not warn about\\n import Prelude hiding( x, y )\\nbecause even if nothing else from Prelude is used, it may be essential to hide\\nx,y to avoid name-shadowing warnings. Example (#9061)\\n import Prelude hiding( log )\\n f x = log where log = ()\\n\\nNote [Unused imports]\\n~~~~~~~~~~~~~~~~~~~~~\\nIn `warnUnusedImport`, if we see an import with an explicit list imports, thus\\n import M( a, b )\\nand neither `a` nor `b` is used, we report the entire import decl as unused. We\\ncheck this by looking at the names that it brings into scope scope; if there are\\nno ununused names, don\'t report.\\n\\n(UI1) We don\'t want to complain about `import M()`, because that is often used to bring\\n M\'s /instances/ into scope. That is neatly dealt with by the \\"no unused\\n names\\" (nor unused wildcard imports) criterion.\\n\\n(UI2) We don\'t report a decl as unused if it has an `as Rebindable` qualifier.\\n See (KN1) in Note [Overview of known entities] in GHC.Builtin\\n\\n\\nNote [Printing minimal imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nTo print the minimal imports we walk over all import decls (both user-supplied\\nand generated), trim their import lists, then filter out generated decls.\\n\\nNB that\\n\\n * We do *not* change the \'qualified\' or \'as\' parts!\\n\\n * We do not discard a decl altogether; we might need instances\\n from it. Instead we just trim to an empty import list\\n\\nNote [Partial export]\\n~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have\\n\\n module A( op ) where\\n class C a where\\n op :: a -> a\\n\\n module B where\\n import A\\n f = ..op...\\n\\nThen the minimal import for module B is\\n import A( op )\\nnot\\n import A( C( op ) )\\nwhich we would usually generate if C was exported from B. Hence\\nthe availExportsDecl test when deciding what to generate.\\n\\n\\nNote [Overloaded field import]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nOn the other hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n data T = MkT { foo :: Int }\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( T(foo) )\\nbecause when DuplicateRecordFields is enabled, field selectors are\\nnot in scope without their enclosing datatype.\\n\\nOn the third hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n pattern MkT { foo } = Just foo\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( foo )\\nbecause foo doesn\'t have a parent. This might actually be ambiguous if A\\nexports another field called foo, but there is no good answer to return and this\\nis a very obscure corner, so it seems to be the best we can do. See\\nDRFPatSynExport for a test of this.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Errors}\\n* *\\n************************************************************************\\n-}\\n\\nbadImportItemErr\\n :: ModIface -> ImpDeclSpec -> IE GhcPs\\n -> IsSubordinateError\\n -> [AvailInfo]\\n -> TcRn (NonEmpty ImportLookupReason)\\nbadImportItemErr iface decl_spec ie sub avails = do\\n exts <- importLookupExtensions\\n let import_lookup_bad :: BadImportKind -> ImportLookupReason\\n import_lookup_bad k = ImportLookupBad k iface decl_spec ie exts\\n dflags <- getDynFlags\\n hsc_env <- getTopEnv\\n let rdr_env = mkGlobalRdrEnv\\n $ gresFromAvails hsc_env (Just imp_spec) all_avails\\n pure $ fmap import_lookup_bad (importErrorKind dflags rdr_env)\\n where\\n importErrorKind :: DynFlags -> GlobalRdrEnv -> NonEmpty BadImportKind\\n importErrorKind dflags rdr_env\\n | any checkIfTyCon avails = case sub of\\n IsNotSubordinate -> NE.singleton BadImportAvailTyCon\\n IsSubordinateError { subordinate_err_parent = gre\\n , subordinate_err_unavailable = unavailable\\n , subordinate_err_nontype = nontype\\n , subordinate_err_nondata = nondata }\\n -> NE.fromList $ catMaybes $\\n [ fmap (BadImportNotExportedSubordinates gre) (NE.nonEmpty unavailable)\\n , fmap (BadImportNonTypeSubordinates gre) (NE.nonEmpty nontype)\\n , fmap (BadImportNonDataSubordinates gre) (NE.nonEmpty nondata) ]\\n | any checkIfVarName avails = NE.singleton BadImportAvailVar\\n | Just con <- find checkIfDataCon avails = NE.singleton (BadImportAvailDataCon (availOccName con))\\n | otherwise = NE.singleton (BadImportNotExported suggs)\\n where\\n suggs = similar_suggs ++ fieldSelectorSuggestions rdr_env rdr\\n what_look = case sub of\\n IsNotSubordinate -> WL_TyCon_or_TermVar\\n IsSubordinateError { subordinate_err_parent = gre } ->\\n case greInfo gre of\\n IAmTyCon ClassFlavour\\n -> WL_TyCon_or_TermVar\\n _ -> WL_Term\\n similar_names =\\n similarNameSuggestions (Unbound.LF what_look WL_Global)\\n dflags rdr_env emptyLocalRdrEnv rdr\\n similar_suggs =\\n case NE.nonEmpty $ mapMaybe imported_item $ similar_names of\\n Just similar -> [ SuggestSimilarNames rdr similar ]\\n Nothing -> [ ]\\n\\n -- Only keep imported items, and set the \\"HowInScope\\" to\\n -- \\"Nothing\\" to avoid printing \\"imported from...\\" in the suggestion\\n -- error message.\\n imported_item (SimilarRdrName rdr_name gre (Just (ImportedBy {})))\\n = Just (SimilarRdrName rdr_name gre Nothing)\\n imported_item _ = Nothing\\n\\n checkIfDataCon = checkIfAvailMatches isDataConName\\n checkIfTyCon = checkIfAvailMatches isTyConName\\n checkIfVarName =\\n \\\\case\\n AvailTC{} -> False\\n Avail n -> importedFS == occNameFS (occName n)\\n && (isVarOcc <||> isFieldOcc) (occName n)\\n checkIfAvailMatches namePred =\\n \\\\case\\n AvailTC _ ns ->\\n case find (\\\\n -> importedFS == occNameFS (occName n)) ns of\\n Just n -> namePred n\\n Nothing -> False\\n Avail{} -> False\\n availOccName = occName . availName\\n rdr = ieName ie\\n importedFS = occNameFS $ rdrNameOcc rdr\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n all_avails = mi_exports iface\\n\\nimportLookupExtensions :: TcRn ImportLookupExtensions\\nimportLookupExtensions = do\\n ile_pattern_synonyms <- xoptM LangExt.PatternSynonyms\\n ile_explicit_namespaces <- xoptM LangExt.ExplicitNamespaces\\n return ImportLookupExtensions{ile_pattern_synonyms, ile_explicit_namespaces}\\n\\naddDupDeclErr :: NonEmpty GlobalRdrElt -> TcRn ()\\naddDupDeclErr gres@(gre :| _)\\n -- Report the error at the later location\\n = addErrAt (getSrcSpan (NE.last sorted_names)) $ (TcRnDuplicateDecls (greOccName gre) sorted_names)\\n where\\n sorted_names =\\n NE.sortBy (SrcLoc.leftmost_smallest `on` nameSrcSpan)\\n (fmap greName gres)\\n\\n-- This data decl will parse OK\\n-- data T = a Int\\n-- treating \\"a\\" as the constructor.\\n-- It is really hard to make the parser spot this malformation.\\n-- So the renamer has to check that the constructor is legal\\n--\\n-- We can get an operator as the constructor, even in the prefix form:\\n-- data T = :% Int Int\\n-- from interface files, which always print in prefix form\\n--\\n-- We also allow type constructor names, which are defined by \\"type data\\"\\n-- declarations. See Note [Type data declarations] in GHC.Rename.Module.\\n\\ncheckConName :: RdrName -> TcRn ()\\ncheckConName name\\n = checkErr (isRdrDataCon name || isRdrTc name) (TcRnIllegalDataCon name)\\n", "filetypes": ["haskell"]}}}' 2026-10-16 14:46:00,550 - DEBUG - POST b'http://127.0.0.1:37093/receive_messages' {'content-type': 'application/json', 'x-ycm-hmac': b'Rga7Yd4l4fgfufwYw+0sxzurvznImlBO0MPmgAlS4EY='} b'{"filepath": "/home/enrico/ghc/compiler/GHC/Rename/Names.hs", "line_num": 1, "column_num": 1, "working_dir": "/home/enrico/ghc", "file_data": {"/home/enrico/ghc/compiler/GHC/Rename/Names.hs": {"contents": "{-\\n(c) The GRASP/AQUA Project, Glasgow University, 1992-1998\\n\\nExtracting imported and top-level names in scope\\n-}\\n\\n{-# LANGUAGE NondecreasingIndentation #-}\\n{-# LANGUAGE TypeFamilies #-}\\n\\nmodule GHC.Rename.Names (\\n rnImports, getLocalNonValBinders, newRecordFieldLabel,\\n importsFromIface,\\n ImportUserSpec(..),\\n extendGlobalRdrEnvRn,\\n gresFromAvails,\\n calculateAvails,\\n reportUnusedNames,\\n checkConName,\\n mkChildEnv,\\n findChildren,\\n mkBadExportSubordinate,\\n findImportUsage,\\n getMinimalImports,\\n printMinimalImports,\\n renamePkgQual, renameRawPkgQual,\\n classifyGREs,\\n ImportDeclUsage,\\n rnNamespaceSpecifier\\n ) where\\n\\nimport GHC.Prelude hiding ( head, init, last, tail )\\n\\nimport GHC.Driver.Env\\nimport GHC.Driver.Session\\nimport GHC.Driver.Ppr\\n\\nimport GHC.Rename.Env\\nimport GHC.Rename.Fixity\\nimport GHC.Rename.Utils ( warnUnusedTopBinds )\\nimport GHC.Rename.Unbound\\nimport qualified GHC.Rename.Unbound as Unbound\\n\\nimport GHC.Tc.Errors.Types\\nimport GHC.Tc.Utils.Env\\nimport GHC.Tc.Utils.Monad\\nimport GHC.Tc.Types.LclEnv\\nimport GHC.Tc.Zonk.TcType ( tcInitTidyEnv )\\n\\nimport GHC.Hs\\nimport GHC.Iface.Load ( loadSrcInterface, loadSrcInterface_maybe )\\nimport GHC.Iface.Errors.Types\\n ( IfaceMessage(..), MissingInterfaceError, InterfaceLookingFor(..)\\n , LoadEssentialsReason(..) )\\nimport GHC.Iface.Syntax ( fromIfaceWarnings )\\nimport GHC.Builtin.Modules( pRELUDE_NAME, rEBINDABLE_MOD_NAME )\\nimport GHC.Parser.PostProcess ( setRdrNameSpace )\\nimport GHC.Core.TyCo.Tidy\\nimport GHC.Core.PatSyn\\nimport GHC.Core.TyCon ( TyCon, tyConName )\\nimport qualified GHC.LanguageExtensions as LangExt\\n\\nimport GHC.Utils.Outputable as Outputable\\nimport GHC.Utils.Misc as Utils\\nimport GHC.Utils.Panic\\n\\nimport GHC.Types.Fixity.Env\\nimport GHC.Types.SafeHaskell\\nimport GHC.Types.Name\\nimport GHC.Types.Name.Env\\nimport GHC.Types.Name.Set\\nimport GHC.Types.Name.Reader\\nimport GHC.Types.Avail\\nimport GHC.Types.FieldLabel\\nimport GHC.Types.Hint\\nimport GHC.Types.SourceFile\\nimport GHC.Types.SrcLoc as SrcLoc\\nimport GHC.Types.Basic (TyConFlavour (..), convImportLevel, VisArity)\\nimport GHC.Types.UnresolvedImport\\nimport GHC.Types.Id\\nimport GHC.Types.PkgQual\\nimport GHC.Types.GREInfo (ConInfo(..), ConFieldInfo (..), ConLikeInfo (ConIsData))\\n\\nimport GHC.Unit\\nimport GHC.Unit.Module.Warnings\\nimport GHC.Unit.Module.ModIface\\nimport GHC.Unit.Module.Imported\\nimport GHC.Unit.Module.Deps\\nimport GHC.Unit.Env\\n\\nimport GHC.Data.Bag\\nimport GHC.Data.FastString\\nimport GHC.Data.FastString.Env\\nimport GHC.Data.Maybe\\nimport GHC.Data.List.SetOps ( removeDups )\\n\\nimport Control.Arrow ( second )\\nimport Control.Monad\\nimport Data.Foldable ( for_ )\\nimport Data.IntMap ( IntMap )\\nimport qualified Data.IntMap as IntMap\\nimport Data.Map ( Map )\\nimport qualified Data.Map as Map\\nimport Data.Ord ( comparing )\\nimport Data.Semigroup ( Any(..) )\\nimport qualified Data.Semigroup as S\\nimport Data.List ( partition, find, sortBy )\\nimport Data.List.NonEmpty (NonEmpty(..))\\nimport qualified Data.List.NonEmpty as NE\\nimport Data.Function ( on )\\nimport qualified Data.Set as S\\nimport System.FilePath (())\\nimport System.IO\\n\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{rnImports}\\n* *\\n************************************************************************\\n\\nNote [Tracking Trust Transitively]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen we import a package as well as checking that the direct imports are safe\\naccording to the rules outlined in the Note [Safe Haskell Trust Check] in GHC.Driver.Main\\nwe must also check that these rules hold transitively for all dependent modules\\nand packages. Doing this without caching any trust information would be very\\nslow as we would need to touch all packages and interface files a module depends\\non. To avoid this we make use of the property that if a modules Safe Haskell\\nmode changes, this triggers a recompilation from that module in the dependency\\ngraph. So we can just worry mostly about direct imports.\\n\\nThere is one trust property that can change for a package though without\\nrecompilation being triggered: package trust. So we must check that all\\npackages a module transitively depends on to be trusted are still trusted when\\nwe are compiling this module (as due to recompilation avoidance some modules\\nbelow may not be considered trusted any more without recompilation being\\ntriggered).\\n\\nWe handle this by augmenting the existing transitive list of packages a module M\\ndepends on with a bool for each package that says if it must be trusted when the\\nmodule M is being checked for trust. This list of trust required packages for a\\nsingle import is gathered in the rnImportDecl function and stored in an\\nImportAvails data structure. The union of these trust required packages for all\\nimports is done by the rnImports function using the combine function which calls\\nthe plusImportAvails function that is a union operation for the ImportAvails\\ntype. This gives us in an ImportAvails structure all packages required to be\\ntrusted for the module we are currently compiling. Checking that these packages\\nare still trusted (and that direct imports are trusted) is done in\\nGHC.Driver.Main.checkSafeImports.\\n\\nSee the note below, [Trust Own Package] for a corner case in this method and\\nhow its handled.\\n\\n\\nNote [Trust Own Package]\\n~~~~~~~~~~~~~~~~~~~~~~~~\\nThere is a corner case of package trust checking that the usual transitive check\\ndoesn\'t cover. (For how the usual check operates see the Note [Tracking Trust\\nTransitively] below). The case is when you import a -XSafe module M and M\\nimports a -XTrustworthy module N. If N resides in a different package than M,\\nthen the usual check works as M will record a package dependency on N\'s package\\nand mark it as required to be trusted. If N resides in the same package as M\\nthough, then importing M should require its own package be trusted due to N\\n(since M is -XSafe so doesn\'t create this requirement by itself). The usual\\ncheck fails as a module doesn\'t record a package dependency of its own package.\\nSo instead we now have a bool field in a modules interface file that simply\\nstates if the module requires its own package to be trusted. This field avoids\\nus having to load all interface files that the module depends on to see if one\\nis trustworthy.\\n\\n\\nNote [Trust Transitive Property]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSo there is an interesting design question in regards to transitive trust\\nchecking. Say I have a module B compiled with -XSafe. B is dependent on a bunch\\nof modules and packages, some packages it requires to be trusted as its using\\n-XTrustworthy modules from them. Now if I have a module A that doesn\'t use safe\\nhaskell at all and simply imports B, should A inherit all the trust\\nrequirements from B? Should A now also require that a package p is trusted since\\nB required it?\\n\\nWe currently say no but saying yes also makes sense. The difference is, if a\\nmodule M that doesn\'t use Safe Haskell imports a module N that does, should all\\nthe trusted package requirements be dropped since M didn\'t declare that it cares\\nabout Safe Haskell (so -XSafe is more strongly associated with the module doing\\nthe importing) or should it be done still since the author of the module N that\\nuses Safe Haskell said they cared (so -XSafe is more strongly associated with\\nthe module that was compiled that used it).\\n\\nGoing with yes is a simpler semantics we think and harder for the user to stuff\\nup but it does mean that Safe Haskell will affect users who don\'t care about\\nSafe Haskell as they might grab a package from Cabal which uses safe haskell (say\\nnetwork) and that packages imports -XTrustworthy modules from another package\\n(say bytestring), so requires that package is trusted. The user may now get\\ncompilation errors in code that doesn\'t do anything with Safe Haskell simply\\nbecause they are using the network package. They will have to call \'ghc-pkg\\ntrust network\' to get everything working. Due to this invasive nature of going\\nwith yes we have gone with no for now.\\n-}\\n\\n-- | Process Import Decls. See \'rnImportDecl\' for a description of what\\n-- the return types represent.\\n-- Note: Do the non SOURCE ones first, so that we get a helpful warning\\n-- for SOURCE ones that are unnecessary\\nrnImports :: [(LImportDecl GhcPs, SDoc)]\\n -> RnM ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\nrnImports imports = do\\n tcg_env <- getGblEnv\\n -- NB: want an identity module here, because it\'s OK for a signature\\n -- module to import from its implementor\\n let this_mod = tcg_mod tcg_env\\n let (source, ordinary) = partition (is_source_import . fst) imports\\n is_source_import (d::LImportDecl GhcPs) = ideclSource (unLoc d) == IsBoot\\n stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary\\n stuff2 <- mapAndReportM (rnImportDecl this_mod) source\\n -- Safe Haskell: See Note [Tracking Trust Transitively]\\n let (decls, imp_user_spec, rdr_env, imp_avails) = combine (stuff1 ++ stuff2)\\n -- Update imp_boot_mods if imp_direct_mods mentions any of them\\n let merged_import_avail = clobberSourceImports imp_avails\\n return (decls, imp_user_spec, rdr_env, merged_import_avail)\\n\\n where\\n clobberSourceImports imp_avails =\\n imp_avails { imp_boot_mods = imp_boot_mods\' }\\n where\\n imp_boot_mods\' = mergeInstalledModuleEnv combJ id (const emptyInstalledModuleEnv)\\n (imp_boot_mods imp_avails)\\n (imp_direct_dep_mods imp_avails)\\n\\n combJ (GWIB _ IsBoot) (_, x) = Just x\\n combJ r _ = Just r\\n -- See Note [Combining ImportAvails]\\n combine :: [(LImportDecl GhcRn, ImportUserSpec, GlobalRdrEnv, ImportAvails)]\\n -> ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\n combine ss =\\n let (decls, imp_user_spec, rdr_env, imp_avails, finsts) = foldr\\n plus\\n ([], [], emptyGlobalRdrEnv, emptyImportAvails, emptyModuleSet)\\n ss\\n in (decls, imp_user_spec, rdr_env, imp_avails { imp_finsts = moduleSetElts finsts })\\n\\n plus (decl, us, gbl_env1, imp_avails1)\\n (decls, uss, gbl_env2, imp_avails2, finsts_set)\\n = ( decl:decls,\\n us:uss,\\n gbl_env1 `plusGlobalRdrEnv` gbl_env2,\\n imp_avails1\' `plusImportAvails` imp_avails2,\\n extendModuleSetList finsts_set new_finsts )\\n where\\n imp_avails1\' = imp_avails1 { imp_finsts = [] }\\n new_finsts = imp_finsts imp_avails1\\n\\n{-\\nNote [Combining ImportAvails]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nimp_finsts in ImportAvails is a list of family instance modules\\ntransitively depended on by an import. imp_finsts for a currently\\ncompiled module is a union of all the imp_finsts of imports.\\nComputing the union of two lists of size N is O(N^2) and if we\\ndo it to M imports we end up with O(M*N^2). That can get very\\nexpensive for bigger module hierarchies.\\n\\nUnion can be optimized to O(N log N) if we use a Set.\\nimp_finsts is converted back and forth between dep_finsts, so\\nchanging a type of imp_finsts means either paying for the conversions\\nor changing the type of dep_finsts as well.\\n\\nI\'ve measured that the conversions would cost 20% of allocations on my\\ntest case, so that can be ruled out.\\n\\nChanging the type of dep_finsts forces checkFamInsts to\\nget the module lists in non-deterministic order. If we wanted to restore\\nthe deterministic order, we\'d have to sort there, which is an additional\\ncost. As far as I can tell, using a non-deterministic order is fine there,\\nbut that\'s a brittle nonlocal property which I\'d like to avoid.\\n\\nAdditionally, dep_finsts is read from an interface file, so its \\"natural\\"\\ntype is a list. Which makes it a natural type for imp_finsts.\\n\\nSince rnImports.combine is really the only place that would benefit from\\nit being a Set, it makes sense to optimize the hot loop in rnImports.combine\\nwithout changing the representation.\\n\\nSo here\'s what we do: instead of naively merging ImportAvails with\\nplusImportAvails in a loop, we make plusImportAvails merge empty imp_finsts\\nand compute the union on the side using Sets. When we\'re done, we can\\nconvert it back to a list. One nice side effect of this approach is that\\nif there\'s a lot of overlap in the imp_finsts of imports, the\\nSet doesn\'t really need to grow and we don\'t need to allocate.\\n\\nRunning generateModules from #14693 with DEPTH=16, WIDTH=30 finishes in\\n23s before, and 11s after.\\n-}\\n\\n-- | Given a located import declaration @decl@ from @this_mod@,\\n-- calculate the following pieces of information:\\n--\\n-- 1. An updated \'LImportDecl\', where all unresolved \'RdrName\' in\\n-- the entity lists have been resolved into \'Name\'s,\\n--\\n-- 2. A \'GlobalRdrEnv\' representing the new identifiers that were\\n-- brought into scope (taking into account module qualification\\n-- and hiding),\\n--\\n-- 3. \'ImportAvails\' summarizing the identifiers that were imported\\n-- by this declaration, and\\n--\\n-- 4. A boolean \'AnyHpcUsage\' which is true if the imported module\\n-- used HPC.\\nrnImportDecl :: Module -> (LImportDecl GhcPs, SDoc)\\n -> RnM (LImportDecl GhcRn, ImportUserSpec , GlobalRdrEnv, ImportAvails)\\nrnImportDecl this_mod\\n (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name\\n , ideclPkgQual = raw_pkg_qual\\n , ideclSource = want_boot\\n , ideclSafe = mod_safe\\n , ideclLevelSpec = import_level\\n , ideclQualified = qual_style\\n , ideclExt = XImportDeclPass { ideclOrigin = origin }\\n , ideclAs = as_mod, ideclImportList = imp_details }), import_reason)\\n = setSrcSpanA loc $ do\\n\\n case raw_pkg_qual of\\n NoRawPkgQual -> pure ()\\n RawPkgQual {} -> do\\n pkg_imports <- xoptM LangExt.PackageImports\\n when (not pkg_imports) $ addErr TcRnPackageImportsDisabled\\n\\n let qual_only = isImportDeclQualified qual_style\\n generated = isGeneratedImport origin\\n\\n lookup_scope = importDeclLookupScope origin\\n\\n -- If there\'s an error in loadInterface, (e.g. interface\\n -- file not found) we get lots of spurious errors from \'filterImports\'\\n let imp_mod_name = unLoc loc_imp_mod_name\\n doc = ppr imp_mod_name <+> import_reason\\n\\n hsc_env <- getTopEnv\\n unit_env <- hsc_unit_env <$> getTopEnv\\n let pkg_qual = renameRawPkgQual unit_env imp_mod_name raw_pkg_qual\\n\\n -- Check for self-import, which confuses the typechecker (#9032)\\n -- ghc --make rejects self-import cycles already, but batch-mode may not\\n -- at least not until GHC.IfaceToCore.tcHiBootIface, which is too late to avoid\\n -- typechecker crashes. (Indirect self imports are not caught until\\n -- GHC.IfaceToCore, see #10337 tracking how to make this error better.)\\n --\\n -- Originally, we also allowed \'import {-# SOURCE #-} M\', but this\\n -- caused bug #10182: in one-shot mode, we should never load an hs-boot\\n -- file for the module we are compiling into the EPS. In principle,\\n -- it should be possible to support this mode of use, but we would have to\\n -- extend Provenance to support a local definition in a qualified location.\\n -- For now, we don\'t support it, but see #10336\\n when (imp_mod_name == moduleName this_mod &&\\n (case pkg_qual of -- If we have import \\"\\" M, then we should\\n -- check that \\"\\" is \\"this\\" (which is magic)\\n -- or the name of this_mod\'s package. Yurgh!\\n -- c.f. GHC.findModule, and #9997\\n NoPkgQual -> True\\n ThisPkg uid -> uid == homeUnitId_ (hsc_dflags hsc_env)\\n OtherPkg _ -> False))\\n (addErr (TcRnSelfImport imp_mod_name))\\n\\n -- Check for a missing import list (Opt_WarnMissingImportList also\\n -- checks for T(..) items but that is done in checkDodgyImport below)\\n case imp_details of\\n Just (Exactly, _) -> return () -- Explicit import list\\n _ | generated -> return () -- Do not bleat for generated imports\\n | qual_only -> return ()\\n | otherwise -> addDiagnostic (TcRnNoExplicitImportList imp_mod_name)\\n\\n\\n mb_iface <- loadSrcInterface_maybe doc lookup_scope imp_mod_name want_boot pkg_qual\\n iface <- case mb_iface of\\n Succeeded iface -> return iface\\n Failed err -> failWithTc $\\n importDeclLoadFailure origin imp_mod_name want_boot err\\n\\n -- Compiler sanity check: if the import didn\'t say\\n -- {-# SOURCE #-} we should not get a hi-boot file\\n warnPprTrace ((want_boot == NotBoot) && (mi_boot iface == IsBoot)) \\"rnImportDecl\\" (ppr imp_mod_name) $ do\\n\\n -- Issue a user warning for a redundant {- SOURCE -} import\\n -- NB that we arrange to read all the ordinary imports before\\n -- any of the {- SOURCE -} imports.\\n --\\n -- in --make and GHCi, the compilation manager checks for this,\\n -- and indeed we shouldn\'t do it here because the existence of\\n -- the non-boot module depends on the compilation order, which\\n -- is not deterministic. The hs-boot test can show this up.\\n dflags <- getDynFlags\\n warnIf ((want_boot == IsBoot) && (mi_boot iface == NotBoot) && isOneShot (ghcMode dflags))\\n (TcRnRedundantSourceImport imp_mod_name)\\n when (mod_safe && not (safeImportsOn dflags)) $\\n addErr (TcRnSafeImportsDisabled imp_mod_name)\\n\\n let imp_mod = mi_module iface\\n qual_mod_name = fmap unLoc as_mod `orElse` imp_mod_name\\n imp_spec = ImpDeclSpec { is_mod = imp_mod, is_qual = qual_only,\\n is_dloc = locA loc, is_as = qual_mod_name,\\n is_pkg_qual = pkg_qual, is_isboot = want_boot,\\n is_level = convImportLevel import_level }\\n\\n let filter_imports = do\\n -- filter the imports according to the import declaration\\n (new_imp_details, imp_user_list, gbl_env)\\n <- filterImports hsc_env iface imp_spec imp_details\\n -- for certain error messages, we\\u2019d like to know what could be\\n -- imported here, if everything were imported\\n potential_gres <- (\\\\(_,_,x) -> x) <$> filterImports hsc_env iface imp_spec Nothing\\n return (new_imp_details, imp_user_list, gbl_env, potential_gres)\\n\\n (new_imp_details, imp_user_list, gbl_env, potential_gres) <-\\n case origin of\\n ImplicitEssentialsImport ->\\n -- The implicit GHC.Essentials import does not bring anything into scope.\\n -- See Note [Finding GHC.Essentials] in GHC.Builtin.\\n return (Nothing, ImpUserDependOnly, emptyGlobalRdrEnv, emptyGlobalRdrEnv)\\n UserWrittenImport -> filter_imports\\n ImplicitPreludeImport -> filter_imports\\n PluginImport -> filter_imports\\n\\n let is_hiding | Just (EverythingBut,_) <- imp_details = True\\n | otherwise = False\\n\\n -- should the import be safe?\\n mod_safe\' = mod_safe\\n || (not generated && safeDirectImpsReq dflags)\\n || (generated && safeImplicitImpsReq dflags)\\n\\n hsc_env <- getTopEnv\\n let home_unit = hsc_home_unit hsc_env\\n other_home_units = hsc_all_home_unit_ids hsc_env\\n\\n imported_by\\n | isDependOnlyImport imp_user_list\\n = ImportedBySystem\\n | otherwise\\n = ImportedByUser $ ImportedModsVal\\n { imv_name = is_as imp_spec\\n , imv_span = locA loc\\n , imv_is_safe = mod_safe\'\\n , imv_is_hiding = is_hiding\\n , imv_all_exports = potential_gres\\n , imv_qualified = qual_only\\n , imv_is_level = convImportLevel import_level\\n }\\n imports = calculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by\\n\\n -- Complain if we import a deprecated module\\n case fromIfaceWarnings (mi_warns iface) of\\n WarnAll txt -> addDiagnostic (TcRnDeprecatedModule imp_mod_name txt)\\n _ -> return ()\\n\\n let new_imp_decl = ImportDecl\\n { ideclExt = ideclExt decl\\n , ideclName = ideclName decl\\n , ideclPkgQual = pkg_qual\\n , ideclSource = ideclSource decl\\n , ideclSafe = mod_safe\'\\n , ideclQualified = ideclQualified decl\\n , ideclAs = ideclAs decl\\n , ideclImportList = new_imp_details\\n , ideclLevelSpec = ideclLevelSpec decl\\n }\\n\\n return (L loc new_imp_decl, ImpUserSpec imp_spec imp_user_list, gbl_env, imports)\\n\\n-- | The error message to emit when we failed to load an interface.\\nimportDeclLoadFailure :: ImportDeclOrigin -> ModuleName -> IsBootInterface\\n -> MissingInterfaceError -> TcRnMessage\\nimportDeclLoadFailure ImplicitEssentialsImport _ _ err\\n = TcRnInterfaceError $ CantFindEssentials err LookingForEssentialsModule\\nimportDeclLoadFailure _ mod_name want_boot err\\n = TcRnInterfaceError $ Can\'tFindInterface err $ LookingForModule mod_name want_boot\\n\\n-- | Rename raw package imports\\nrenameRawPkgQual :: UnitEnv -> ModuleName -> RawPkgQual -> PkgQual\\nrenameRawPkgQual unit_env mn = \\\\case\\n NoRawPkgQual -> NoPkgQual\\n RawPkgQual _ fs -> renamePkgQual unit_env mn $ Just fs\\n\\n-- | Rename raw package imports\\nrenamePkgQual :: UnitEnv -> ModuleName -> Maybe FastString -> PkgQual\\nrenamePkgQual unit_env mn mb_pkg = case mb_pkg of\\n Nothing -> NoPkgQual\\n Just pkg_fs\\n | Just uid <- homeUnitId <$> ue_homeUnit unit_env\\n , pkg_fs == fsLit \\"this\\"\\n -> ThisPkg uid\\n\\n | Just (uid, _) <- find (fromMaybe False . fmap (== pkg_fs) . snd) home_names\\n -> ThisPkg uid\\n\\n | Just uid <- resolvePackageImport unit_state mn (PackageName pkg_fs)\\n -> OtherPkg uid\\n\\n | otherwise\\n -> OtherPkg (UnitId pkg_fs)\\n -- not really correct as pkg_fs is unlikely to be a valid unit-id but\\n -- we will report the failure later...\\n where\\n home_names =\\n [ (uid, mkFastString <$> thisPackageName (homeUnitEnv_dflags (ue_findHomeUnitEnv uid unit_env)))\\n | uid <- S.toList hpt_deps\\n ]\\n\\n unit_state = ue_homeUnitState unit_env\\n\\n hpt_deps :: S.Set UnitId\\n hpt_deps = homeUnitDepends unit_state\\n\\n\\n-- | Calculate the \'ImportAvails\' induced by an import of a particular\\n-- interface, but without \'imp_mods\'.\\ncalculateAvails :: HomeUnit\\n -> S.Set UnitId\\n -> ModIface\\n -> IsSafeImport\\n -> IsBootInterface\\n -> ImportedBy\\n -> ImportAvails\\ncalculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by =\\n let imp_mod = mi_module iface\\n imp_sem_mod= mi_semantic_module iface\\n orph_iface = mi_orphan iface\\n has_finsts = mi_finsts iface\\n deps = mi_deps iface\\n trust = getSafeMode $ mi_trust iface\\n trust_pkg = mi_trust_pkg iface\\n is_sig = mi_hsc_src iface == HsigFile\\n\\n -- If the module exports anything defined in this module, just\\n -- ignore it. Reason: otherwise it looks as if there are two\\n -- local definition sites for the thing, and an error gets\\n -- reported. Easiest thing is just to filter them out up\\n -- front. This situation only arises if a module imports\\n -- itself, or another module that imported it. (Necessarily,\\n -- this involves a loop.)\\n --\\n -- We do this *after* filterImports, so that if you say\\n -- module A where\\n -- import B( AType )\\n -- type AType = ...\\n --\\n -- module B( AType ) where\\n -- import {-# SOURCE #-} A( AType )\\n --\\n -- then you won\'t get a \'B does not export AType\' message.\\n\\n\\n -- Compute new transitive dependencies\\n --\\n -- \'dep_orphs\' and \'dep_finsts\' do NOT include the imported module\\n -- itself, but we DO need to include this module in \'imp_orphs\' and\\n -- \'imp_finsts\' if it defines an orphan or instance family; thus the\\n -- orph_iface/has_iface tests.\\n\\n deporphs = dep_orphs deps\\n depfinsts = dep_finsts deps\\n\\n orphans | orph_iface = assertPpr (not (imp_sem_mod `elem` deporphs)) (ppr imp_sem_mod <+> ppr deporphs) $\\n imp_sem_mod : deporphs\\n | otherwise = deporphs\\n\\n finsts | has_finsts = assertPpr (not (imp_sem_mod `elem` depfinsts)) (ppr imp_sem_mod <+> ppr depfinsts) $\\n imp_sem_mod : depfinsts\\n | otherwise = depfinsts\\n\\n -- Trusted packages are a lot like orphans.\\n trusted_pkgs | mod_safe\' = dep_trusted_pkgs deps\\n | otherwise = S.empty\\n\\n\\n pkg = moduleUnit (mi_module iface)\\n ipkg = toUnitId pkg\\n\\n -- Does this import mean we now require our own pkg\\n -- to be trusted? See Note [Trust Own Package]\\n ptrust = trust == Sf_Trustworthy || trust_pkg\\n pkg_trust_req\\n | isHomeUnit home_unit pkg = ptrust\\n | otherwise = False\\n\\n dependent_pkgs = if toUnitId pkg `S.member` other_home_units\\n then S.empty\\n else S.singleton (lvl, ipkg)\\n\\n lvl = case imported_by of\\n ImportedByUser imv -> imv_is_level imv\\n ImportedBySystem -> NormalLevel\\n\\n\\n direct_mods = if toUnitId pkg `S.member` other_home_units\\n then mkPlusModDeps (moduleUnitId imp_mod) lvl (GWIB (moduleName imp_mod) want_boot)\\n else emptyInstalledModuleEnv\\n\\n dep_boot_mods_map = mkModDeps (dep_boot_mods deps)\\n\\n\\n boot_mods\\n -- If we are looking for a boot module, it must be HPT\\n | IsBoot <- want_boot = extendInstalledModuleEnv dep_boot_mods_map (toUnitId <$> imp_mod) (GWIB (moduleName imp_mod) IsBoot)\\n -- Now we are importing A properly, so don\'t go looking for\\n -- A.hs-boot\\n | isHomeUnit home_unit pkg = dep_boot_mods_map\\n -- There\'s no boot files to find in external imports\\n | otherwise = emptyInstalledModuleEnv\\n\\n sig_mods =\\n if is_sig\\n then moduleName imp_mod : dep_sig_mods deps\\n else dep_sig_mods deps\\n\\n\\n in ImportAvails {\\n imp_mods = Map.singleton (mi_module iface) [imported_by],\\n imp_orphs = orphans,\\n imp_finsts = finsts,\\n imp_sig_mods = sig_mods,\\n imp_direct_dep_mods = direct_mods,\\n imp_dep_direct_pkgs = dependent_pkgs,\\n imp_boot_mods = boot_mods,\\n\\n -- Add in the imported modules trusted package\\n -- requirements. ONLY do this though if we import the\\n -- module as a safe import.\\n -- See Note [Tracking Trust Transitively]\\n -- and Note [Trust Transitive Property]\\n imp_trust_pkgs = trusted_pkgs,\\n -- Do we require our own pkg to be trusted?\\n -- See Note [Trust Own Package]\\n imp_trust_own_pkg = pkg_trust_req\\n }\\n\\nmkPlusModDeps :: UnitId -> ImportLevel -> ModuleNameWithIsBoot\\n -> InstalledModuleEnv (S.Set ImportLevel, ModuleNameWithIsBoot)\\nmkPlusModDeps uid st elt = extendInstalledModuleEnv emptyInstalledModuleEnv (mkModule uid (gwib_mod elt)) (S.singleton st, elt)\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{importsFromLocalDecls}\\n* *\\n************************************************************************\\n\\nFrom the top-level declarations of this module produce\\n * the lexical environment\\n * the ImportAvails\\ncreated by its bindings.\\n\\nNote [Top-level Names in Template Haskell decl quotes]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSee also: Note [Interactively-bound Ids in GHCi] in GHC.Driver.Env\\n Note [Looking up Exact RdrNames] in GHC.Rename.Env\\n\\nConsider a Template Haskell declaration quotation like this:\\n module M where\\n f x = h [d| f = 3 |]\\nWhen renaming the declarations inside [d| ...|], we treat the\\ntop level binders specially in two ways\\n\\n1. We give them an Internal Name, not (as usual) an External one.\\n This is done by GHC.Rename.Env.newTopSrcBinder.\\n\\n2. We make them *shadow* the outer bindings.\\n See Note [GlobalRdrEnv shadowing]\\n\\n3. We find out whether we are inside a [d| ... |] by testing the TH\\n level. This is a slight hack, because the level field was really\\n meant for the type checker, and here we are not interested in the\\n fields of Brack, hence the error thunks in thRnBrack.\\n-}\\n\\nextendGlobalRdrEnvRn :: [GlobalRdrElt]\\n -> MiniFixityEnv\\n -> RnM (TcGblEnv, TcLclEnv)\\n-- Updates both the GlobalRdrEnv and the FixityEnv\\n-- We return a new TcLclEnv only because we might have to\\n-- delete some bindings from it;\\n-- see Note [Top-level Names in Template Haskell decl quotes]\\n\\nextendGlobalRdrEnvRn new_gres new_fixities\\n = checkNoErrs $ -- See Note [Fail fast on duplicate definitions]\\n do { (gbl_env, lcl_env) <- getEnvs\\n ; level <- getThLevel\\n ; isGHCi <- getIsGHCi\\n ; let rdr_env = tcg_rdr_env gbl_env\\n fix_env = tcg_fix_env gbl_env\\n th_bndrs = getLclEnvThBndrs lcl_env\\n th_lvl = thLevelIndex level\\n\\n -- Delete new_occs from global and local envs\\n -- If we are in a TemplateHaskell decl bracket,\\n -- we are going to shadow them\\n -- See Note [GlobalRdrEnv shadowing]\\n inBracket = isBrackLevel level\\n\\n lcl_env_TH = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_rdr = minusLocalRdrEnv (tcl_rdr lcl_env) new_gres_env }) lcl_env\\n -- See Note [GlobalRdrEnv shadowing]\\n\\n lcl_env2 | inBracket = lcl_env_TH\\n | otherwise = lcl_env\\n\\n -- Deal with shadowing: see Note [GlobalRdrEnv shadowing]\\n want_shadowing = isGHCi || inBracket\\n rdr_env1 | want_shadowing = shadowNames False rdr_env new_gres_env\\n | otherwise = rdr_env\\n\\n lcl_env3 = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_th_bndrs = extendNameEnvList th_bndrs\\n [ ( n, (TopLevel, th_lvl) )\\n | n <- new_names ] }) lcl_env2\\n\\n ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres\\n\\n ; let fix_env\' = foldl\' extend_fix_env fix_env new_gres\\n gbl_env\' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env\' }\\n\\n ; traceRn \\"extendGlobalRdrEnvRn 2\\" (pprGlobalRdrEnv True rdr_env2)\\n ; return (gbl_env\', lcl_env3) }\\n where\\n new_names = map greName new_gres\\n new_gres_env = mkGlobalRdrEnv new_gres\\n\\n -- If there is a fixity decl for the gre, add it to the fixity env\\n extend_fix_env fix_env gre\\n | Just (L _ fi) <- lookupMiniFixityEnv new_fixities name\\n = extendNameEnv fix_env name (FixItem occ fi)\\n | otherwise\\n = fix_env\\n where\\n name = greName gre\\n occ = greOccName gre\\n\\n add_gre :: GlobalRdrEnv -> GlobalRdrElt -> RnM GlobalRdrEnv\\n -- Extend the GlobalRdrEnv with a LocalDef GRE\\n -- If there is already a LocalDef GRE with the same OccName,\\n -- report an error and discard the new GRE\\n -- This establishes INVARIANT 1 of GlobalRdrEnvs\\n add_gre env gre\\n | not (null dups) -- Same OccName defined twice\\n = do { addDupDeclErr (gre :| dups); return env }\\n\\n | otherwise\\n = return (extendGlobalRdrEnv env gre)\\n where\\n -- See Note [Reporting duplicate local declarations]\\n dups = filter isBadDupGRE\\n $ lookupGRE env (LookupOccName (greOccName gre) (RelevantGREsFOS WantBoth))\\n isBadDupGRE old_gre = isLocalGRE old_gre && greClashesWith gre old_gre\\n\\n{- Note [Fail fast on duplicate definitions]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIf there are duplicate bindings for the same thing, we want to fail\\nfast. Having two bindings for the same thing can cause follow-on errors.\\nExample (test T9975a):\\n data Test = Test { x :: Int }\\n pattern Test wat = Test { x = wat }\\nThis defines \'Test\' twice. The second defn has no field-names; and then\\nwe get an error from Test { x=wat }, saying \\"Test has no field \'x\'\\".\\n\\nEasiest thing is to bale out fast on duplicate definitions, which\\nwe do via `checkNoErrs` on `extendGlobalRdrEnvRn`.\\n\\nNote [Reporting duplicate local declarations]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn general, a single module may not define the same OccName multiple times. This\\nis checked in extendGlobalRdrEnvRn: when adding a new locally-defined GRE to the\\nGlobalRdrEnv we report an error if there are already duplicates in the\\nenvironment. This establishes INVARIANT 1 (see comments on GlobalRdrEnv in\\nGHC.Types.Name.Reader), which says that for a given OccName, all the\\nGlobalRdrElts to which it maps must have distinct \'greName\'s.\\n\\nFor example, the following will be rejected:\\n\\n f x = x\\n g x = x\\n f x = x -- Duplicate!\\n\\nUsers are allowed to introduce new GREs with the same OccName as an imported GRE,\\nas disambiguation is possible through the module system, e.g.:\\n\\n module M where\\n import N (f)\\n f x = x\\n g x = M.f x + N.f x\\n\\nIf both GREs are local, the general rule is that two GREs clash if they have\\nthe same OccName, i.e. they share a textual name and live in the same namespace.\\nHowever, there are additional clashes due to record fields:\\n\\n - a new variable clashes with previously defined record fields\\n which define field selectors,\\n\\n - a new record field shadows:\\n\\n - previously defined variables, if it defines a field selector,\\n - previously defined record fields, unless it is a duplicate record field.\\n\\nThis logic is implemented in the function \'GHC.Types.Name.Reader.greClashesWith\'.\\n\\nSee also Note [Skipping ambiguity errors at use sites of local declarations] in\\nGHC.Rename.Utils.\\n-}\\n\\n\\n{- *********************************************************************\\n* *\\n getLocalDeclBindersd@ returns the names for an HsDecl\\n It\'s used for source code.\\n\\n *** See Note [The Naming story] in GHC.Hs.Decls ****\\n* *\\n********************************************************************* -}\\n\\ngetLocalNonValBinders :: MiniFixityEnv -> HsGroup GhcPs\\n -> RnM ((TcGblEnv, TcLclEnv), NameSet)\\n-- Get all the top-level binders bound the group *except*\\n-- for value bindings, which are treated separately\\n-- Specifically we return AvailInfo for\\n-- * type decls (incl constructors and record selectors)\\n-- * class decls (including class ops)\\n-- * associated types\\n-- * foreign imports\\n-- * value signatures (in hs-boot files only)\\n\\ngetLocalNonValBinders fixity_env\\n (HsGroup { hs_valds = binds,\\n hs_tyclds = tycl_decls,\\n hs_fords = foreign_decls })\\n = do { -- Process all type/class decls *except* family instances\\n ; let inst_decls = tycl_decls >>= group_instds\\n ; dup_fields_ok <- xopt_DuplicateRecordFields <$> getDynFlags\\n ; has_sel <- xopt_FieldSelectors <$> getDynFlags\\n ; tc_gres\\n <- concatMapM\\n (new_tc dup_fields_ok has_sel)\\n (tyClGroupTyClDecls tycl_decls)\\n ; traceRn \\"getLocalNonValBinders 1\\" (ppr tc_gres)\\n ; envs <- extendGlobalRdrEnvRn tc_gres fixity_env\\n ; restoreEnvs envs $ do {\\n -- Bring these things into scope first\\n -- See Note [Looking up family names in family instances]\\n\\n -- Process all family instances\\n -- to bring new data constructors into scope\\n ; nti_gress <- mapM (new_assoc dup_fields_ok has_sel) inst_decls\\n\\n -- Finish off with value binders:\\n -- foreign decls and pattern synonyms for an ordinary module\\n -- type sigs in case of a hs-boot file only\\n ; is_boot <- tcIsHsBootOrSig\\n ; let val_bndrs\\n | is_boot = case binds of\\n ValBinds _ val_binds ->\\n -- In a hs-boot file, the value binders come from the\\n -- *signatures*, and there should be no foreign binders\\n [ L (l2l decl_loc) (unLoc n)\\n | L decl_loc (TypeSig _ _ ns _) <- (val_sigs val_binds), n <- ns]\\n _ -> panic \\"Non-ValBinds in hs-boot group\\"\\n | otherwise = for_hs_bndrs\\n ; val_gres <- mapM new_simple val_bndrs\\n\\n ; let avails = concat nti_gress ++ val_gres\\n new_bndrs = gresToNameSet avails `unionNameSet`\\n gresToNameSet tc_gres\\n ; traceRn \\"getLocalNonValBinders 2\\" (ppr avails)\\n ; envs <- extendGlobalRdrEnvRn avails fixity_env\\n ; return (envs, new_bndrs) } }\\n where\\n for_hs_bndrs :: [LocatedN RdrName]\\n for_hs_bndrs = hsForeignDeclsBinders foreign_decls\\n\\n -- the SrcSpan attached to the input should be the span of the\\n -- declaration, not just the name\\n new_simple :: LocatedN RdrName -> RnM GlobalRdrElt\\n new_simple rdr_name = do { nm <- newTopSrcBinder rdr_name\\n ; return (mkLocalVanillaGRE NoParent nm) }\\n\\n new_tc :: DuplicateRecordFields -> FieldSelectors -> LTyClDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_tc dup_fields_ok has_sel tc_decl -- NOT for type/data instances\\n = do { let TyDeclBinders (main_bndr, tc_flav) at_bndrs sig_bndrs\\n (LConsWithFields cons_with_flds flds) = hsLTyClDeclBinders tc_decl\\n ; tycon_name <- newTopSrcBinder $ la2la main_bndr\\n ; at_names <- mapM (newTopSrcBinder . la2la . fst) at_bndrs\\n ; sig_names <- mapM (newTopSrcBinder . la2la) sig_bndrs\\n ; con_names_with_flds <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst con_names_with_flds) flds\\n ; mapM_ (add_dup_fld_errs flds\') con_names_with_flds\\n ; let tc_gre = mkLocalTyConGRE (fmap (const tycon_name) tc_flav) tycon_name\\n fld_env = mk_fld_env con_names_with_flds flds\'\\n at_gres = zipWith (\\\\ (_, at_flav) at_nm -> mkLocalTyConGRE (fmap (const tycon_name) at_flav) at_nm)\\n at_bndrs at_names\\n sig_gres = map (mkLocalVanillaGRE (ParentIs tycon_name)) sig_names\\n con_gres = map (mkLocalConLikeGRE (ParentIs tycon_name)) fld_env\\n fld_gres = mkLocalFieldGREs (ParentIs tycon_name) fld_env\\n sub_gres = at_gres ++ sig_gres ++ con_gres ++ fld_gres\\n ; traceRn \\"getLocalNonValBinders new_tc\\" $\\n vcat [ text \\"tycon:\\" <+> ppr tycon_name\\n , text \\"tc_gre:\\" <+> ppr tc_gre\\n , text \\"sub_gres:\\" <+> ppr sub_gres ]\\n ; return $ tc_gre : sub_gres }\\n\\n -- Calculate the record field information, which feeds into the GlobalRdrElts\\n -- for DataCons and their fields. It\'s convenient to do this here where\\n -- we are working with a single datatype definition.\\n --\\n -- The information we needed was all set up for us:\\n -- see Note [Collecting record fields in data declarations] in GHC.Hs.Utils.\\n mk_fld_env :: [(Name, Either VisArity [Located Int])] -> IntMap FieldLabel\\n -> [(ConLikeName, ConInfo)]\\n mk_fld_env names flds =\\n [ (DataConName con, ConInfo (ConIsData (map fst names)) fld_info)\\n | (con, con_fl_indxs) <- names\\n , let fld_info = case fmap (map ((flds IntMap.!) . unLoc)) con_fl_indxs of\\n Left 0 -> ConIsNullary\\n Left arity -> ConHasPositionalArgs arity\\n Right [] -> ConIsNullary\\n Right (fld:flds) -> ConHasRecordFields $ fld NE.:| flds ]\\n\\n new_assoc :: DuplicateRecordFields -> FieldSelectors -> LInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_assoc _ _ (L _ (TyFamInstD {})) = return []\\n -- type instances don\'t bind new names\\n\\n new_assoc dup_fields_ok has_sel (L _ (DataFamInstD _ d))\\n = new_di dup_fields_ok has_sel Nothing d\\n new_assoc dup_fields_ok has_sel\\n (L _ (ClsInstD _ (ClsInstDecl { cid_poly_ty = inst_ty\\n , cid_decls = decls })))\\n = do -- First, attempt to grab the name of the class from the instance.\\n -- This step could fail if the instance is not headed by a class,\\n -- such as in the following examples:\\n --\\n -- (1) The class is headed by a bang pattern, such as in\\n -- `instance !Show Int` (#3811c)\\n -- (2) The class is headed by a type variable, such as in\\n -- `instance c` (#16385)\\n --\\n -- If looking up the class name fails, then mb_cls_gre will\\n -- be Nothing.\\n mb_cls_gre <- runMaybeT $ do\\n -- See (1) above\\n L loc cls_rdr <- MaybeT $ pure $ getLHsInstDeclClass_maybe inst_ty\\n -- See (2) above\\n MaybeT $ setSrcSpan (locA loc) $ lookupGlobalOccRn_maybe SameNameSpace cls_rdr\\n -- Assuming the previous step succeeded, process any associated data\\n -- family instances. If the previous step failed, bail out.\\n case mb_cls_gre of\\n Nothing\\n -> pure []\\n Just cls_gre\\n -> let cls_nm = greName cls_gre\\n in concatMapM (new_di dup_fields_ok has_sel (Just cls_nm) . unLoc) (data_fam_insts decls)\\n\\n data_fam_insts decls = concatMap get decls\\n where\\n get (L l (InstD _ (DataFamInstD { dfid_inst = d}))) = [L l d]\\n get _ = []\\n\\n new_di :: DuplicateRecordFields -> FieldSelectors\\n -> Maybe Name -- class name\\n -> DataFamInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_di dup_fields_ok has_sel mb_cls dfid@(DataFamInstDecl { dfid_eqn = ti_decl })\\n = do { main_name <- unLoc <$> lookupFamInstName mb_cls (feqn_tycon ti_decl)\\n ; let LConsWithFields cons_with_flds flds = hsDataFamInstBinders dfid\\n ; sub_names <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst sub_names) flds\\n ; mapM_ (add_dup_fld_errs flds\') sub_names\\n ; let fld_env = mk_fld_env sub_names flds\'\\n con_gres = map (mkLocalConLikeGRE (ParentIs main_name)) fld_env\\n field_gres = mkLocalFieldGREs (ParentIs main_name) fld_env\\n -- NB: the data family name is not bound here,\\n -- so we don\'t return a GlobalRdrElt for it here!\\n ; return $ con_gres ++ field_gres }\\n\\n -- Add errors if a constructor has a duplicate record field.\\n add_dup_fld_errs :: IntMap FieldLabel\\n -> (Name, Either VisArity [Located Int])\\n -> IOEnv (Env TcGblEnv TcLclEnv) ()\\n add_dup_fld_errs all_flds (con, con_flds_or_arity)\\n | Right con_flds <- con_flds_or_arity\\n , let (_, dups) = removeDups (comparing unLoc) con_flds\\n = for_ dups $ \\\\ dup_flds ->\\n -- Report the error at the location of the second occurrence\\n -- of the duplicate field.\\n let loc =\\n case dup_flds of\\n _ :| ( L loc _ : _) -> loc\\n L loc _ :| _ -> loc\\n dup_rdrs = fmap (nameRdrName . flSelector . (all_flds IntMap.!) . unLoc) dup_flds\\n in addErrAt loc $ TcRnDuplicateFieldName (RecordFieldDecl con) dup_rdrs\\n | otherwise\\n = return ()\\n\\nnewRecordFieldLabel :: DuplicateRecordFields -> FieldSelectors -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel\\nnewRecordFieldLabel _ _ [] _ = error \\"newRecordFieldLabel: datatype has no constructors!\\"\\nnewRecordFieldLabel dup_fields_ok has_sel (dc:_) (L loc (FieldOcc _ (L _ fld)))\\n = do { selName <- newTopSrcBinder $ L (l2l loc) $ field\\n ; return $ FieldLabel { flHasDuplicateRecordFields = dup_fields_ok\\n , flHasFieldSelector = has_sel\\n , flSelector = selName } }\\n where\\n fld_occ = rdrNameOcc fld\\n dc_fs = occNameFS $ nameOccName dc\\n field\\n -- Use an Exact RdrName as-is, to preserve the bindings\\n -- of an already renamer-resolved field and its use\\n -- sites. This is needed to correctly support record\\n -- selectors in Template Haskell. See Note [Binders in\\n -- Template Haskell] in \\"GHC.ThToHs\\" and Note [Looking up\\n -- Exact RdrNames] in \\"GHC.Rename.Env\\".\\n | isExact fld\\n = assertPpr (fieldOcc_maybe fld_occ == Just dc_fs)\\n (vcat [ text \\"newRecordFieldLabel: incorrect namespace for exact Name\\" <+> quotes (ppr fld)\\n , text \\"expected namespace:\\" <+> pprNameSpace (fieldName dc_fs)\\n , text \\" actual namespace:\\" <+> pprNameSpace (occNameSpace fld_occ) ])\\n fld\\n\\n -- Field names produced by the parser are namespaced with VarName.\\n -- Here we namespace them according to the first constructor.\\n -- See Note [Record field namespacing] in GHC.Types.Name.Occurrence.\\n | otherwise\\n = mkRdrUnqual $ varToRecFieldOcc dc_fs fld_occ\\n\\n{-\\nNote [Looking up family names in family instances]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider\\n\\n module M where\\n type family T a :: *\\n type instance M.T Int = Bool\\n\\nWe might think that we can simply use \'lookupOccRn\' when processing the type\\ninstance to look up \'M.T\'. Alas, we can\'t! The type family declaration is in\\nthe *same* HsGroup as the type instance declaration. Hence, as we are\\ncurrently collecting the binders declared in that HsGroup, these binders will\\nnot have been added to the global environment yet.\\n\\nSolution is simple: process the type family declarations first, extend\\nthe environment, and then process the type instances.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Filtering imports}\\n* *\\n************************************************************************\\n\\n@filterImports@ takes the @ExportEnv@ telling what the imported module makes\\navailable, and filters it through the import spec (if any).\\n\\nNote [Dealing with imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nFor import M( ies ), we take each AvailInfo from the mi_exports of M, and make\\n\\n imp_occ_env :: OccEnv (NameEnv ImpOccItem)\\n\\nThis map contains one entry for each OccName that M exports, mapping each OccName\\nto the following information:\\n\\n 1. the GlobalRdrElt corresponding to the OccName,\\n 2. whether this GlobalRdrElt was the parent in the AvailInfo we found\\n the OccName in.\\n 3. the GlobalRdrElts that were bundled together in the AvailInfo we found\\n this OccName in (not including the parent),\\n\\nWe need (2) and (3) during the construction of the OccEnv because of associated\\ntypes and bundled pattern synonyms, respectively.\\n(3) is explained in Note [Importing PatternSynonyms].\\n\\nTo explain (2), consider for example:\\n\\n module M where\\n class C a where { data T a }\\n instance C Int where { data T Int = T1 | T2 }\\n instance C Bool where { data T Int = T3 }\\n\\nHere, M\'s exports avails are (recalling the AvailTC invariant from GHC.Types.Avail)\\n\\n C(C,T), T(T,T1,T2,T3)\\n\\nNotice that T appears *twice*, once as a child and once as a parent. From\\nthese two exports, respectively, during construction of the imp_occ_env, we begin\\nby associating the following two elements with the key T:\\n\\n T -> ImpOccItem { imp_item = gre1, imp_bundled = [C,T] , imp_is_parent = False }\\n T -> ImpOccItem { imp_item = gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nwhere `gre1`, `gre2` are two GlobalRdrElts with greName T.\\nWe combine these (in function \'combine\' in \'mkImportOccEnv\') by discarding the\\nnon-parent item, thusly:\\n\\n T -> IE_ITem { imp_item = gre1 `plusGRE` gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nNote the `plusGRE`: this ensures we don\'t drop parent information;\\nsee Note [Preserve parent information when combining import OccEnvs].\\n\\nSo the overall imp_occ_env is:\\n\\n C -> ImpOccItem { imp_item = C, imp_bundled = [T ], imp_is_parent = True }\\n T -> ImpOccItem { imp_item = T , imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n T1 -> ImpOccItem { imp_item = T1, imp_bundled = [T1,T2,T3], imp_is_parent = False }\\n -- similarly for T2, T3\\n\\nNote that the imp_occ_env will have entries for data constructors too,\\nalthough we never look up data constructors.\\n\\nNote [Importing PatternSynonyms]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nAs described in Note [Dealing with imports], associated types can lead to the\\nsame Name appearing twice, both as a child and once as a parent, when\\nconstructing the imp_occ_env. The same thing can happen with pattern synonyms\\nif they are exported bundled with a type.\\n\\nA simplified example, based on #11959:\\n\\n {-# LANGUAGE PatternSynonyms #-}\\n module M (T(P), pattern P) where -- Duplicate export warning, but allowed\\n data T = MkT\\n pattern P = MkT\\n\\nHere we have T(P) and P in export_avails, and respectively construct both\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n P -> ImpOccItem { imp_item = P, imp_bundled = [] , imp_is_parent = False }\\n\\nWe combine these by dropping the one with no siblings, leaving us with:\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n\\nThat is, we simply discard the non-bundled Avail.\\n\\nNote [Importing DuplicateRecordFields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn filterImports, another complicating factor is DuplicateRecordFields.\\nSuppose we have:\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (S(foo), T(foo)) where\\n data S = MkS { foo :: Int }\\n data T = MkT { foo :: Int }\\n\\n module N where\\n import M (foo) -- this is allowed (A)\\n import M (S(foo)) -- this is allowed (B)\\n\\nHere M exports \'foo\' at two different OccNames, with different namespaces for\\nthe two construtors MkS and MkT. Then, when we look up \'foo\' in lookup_names\\nfor case (A), we have a variable foo but must look in all the record field\\nnamespaces to find the two fields (and hence two different Avails).\\nWhereas in case (B) we reach the lookup_ie case for IEThingWith,\\nwhich looks up \'S\' and then finds the unique \'foo\' amongst its children.\\n\\nSee T16745 for a test of this.\\n\\nNote [Preserve parent information when combining import OccEnvs]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen discarding one ImpOccItem in favour of another, as described in\\nNote [Dealing with imports], we must make sure to combine the GREs so that\\nwe don\'t lose information.\\n\\nConsider for example #24084:\\n\\n module M1 where { class C a where { type T a } }\\n module M2 ( module M1 ) where { import M1 }\\n module M3 where { import M2 ( C, T ); instance C () where T () = () }\\n\\nWhen processing the import list of `M3`, we will have two `Avail`s attached\\nto `T`, namely `C(C, T)` and `T(T)`. We combine them in the `combine` function\\nof `mkImportOccEnv`; as described in Note [Dealing with imports] we discard\\n`C(C, T)` in favour of `T(T)`. However, in doing so, we **must not**\\ndiscard the information want that `C` is the parent of `T`. Indeed,\\nlosing track of this information can cause errors when importing,\\nas we could get an error of the form\\n\\n \\u2018T\\u2019 is not a (visible) associated type of class \\u2018C\\u2019\\n\\nThis explains why we use `plusGRE` when combining the two ImpOccItems, even\\nthough we are discarding one in favour of the other.\\n-}\\n\\n-- | All the \'GlobalRdrElt\'s associated with an \'AvailInfo\'.\\ngresFromAvail :: HasDebugCallStack\\n => HscEnv -> Maybe ImportSpec -> AvailInfo -> [GlobalRdrElt]\\ngresFromAvail hsc_env prov avail =\\n [ mk_gre nm info\\n | nm <- availNames avail\\n , let info = lookupGREInfo hsc_env nm ]\\n where\\n\\n mk_gre n info\\n = case prov of\\n -- Nothing => bound locally\\n -- Just is => imported from \'is\'\\n Nothing -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = True, gre_imp = emptyBag\\n , gre_info = info }\\n Just is -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = False, gre_imp = unitBag is\\n , gre_info = info }\\n\\n-- | All the \'GlobalRdrElt\'s associated with a collection of \'AvailInfo\'s.\\ngresFromAvails :: HscEnv -> Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]\\ngresFromAvails hsc_env prov = concatMap (gresFromAvail hsc_env prov)\\n\\nimportsFromIface :: HscEnv -> ModIface -> ImpDeclSpec -> Maybe NameSet -> GlobalRdrEnv\\nimportsFromIface hsc_env iface decl_spec hidden = mkGlobalRdrEnv $ case hidden of\\n Nothing -> all_gres\\n Just hidden_names -> filter (not . (`elemNameSet` hidden_names) . greName) all_gres\\n where\\n all_gres = gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\nrnNamespaceSpecifier :: NamespaceSpecifier GhcPs -> NamespaceSpecifier GhcRn\\nrnNamespaceSpecifier (NoNamespaceSpecifier _) = NoNamespaceSpecifier noExtField\\nrnNamespaceSpecifier (TypeNamespaceSpecifier x) = TypeNamespaceSpecifier x\\nrnNamespaceSpecifier (DataNamespaceSpecifier x) = DataNamespaceSpecifier x\\n\\nfilterImports\\n :: HasDebugCallStack\\n => HscEnv\\n -> ModIface\\n -> ImpDeclSpec\\n -- ^ Import spec\\n -> Maybe (ImportListInterpretation, [LIE GhcPs])\\n -- ^ Whether this is a \\"hiding\\" import list\\n -> RnM (Maybe (ImportListInterpretation, [LIE GhcRn]), -- Import spec w/ Names\\n ImpUserList, -- same, but designed for storage in interfaces\\n GlobalRdrEnv) -- Same again, but in GRE form\\nfilterImports hsc_env iface decl_spec Nothing\\n = return (Nothing, ImpUserAll, importsFromIface hsc_env iface decl_spec Nothing)\\nfilterImports hsc_env iface decl_spec (Just (want_hiding, import_items))\\n = do -- check for errors, convert RdrNames to Names\\n items1 <- mapM lookup_lie import_items\\n\\n let items2 :: [(LIE GhcRn, [GlobalRdrElt])]\\n items2 = concat items1\\n -- NB we may have duplicates, and several items\\n -- for the same parent; e.g N(x) and N(y)\\n\\n (gres, imp_user_list) = case want_hiding of\\n Exactly ->\\n let gres = concatMap (gresFromIE decl_spec) items2\\n gre_env = mkGlobalRdrEnv gres\\n implicit_parents = mkNameSet $ mapMaybe parentOfImplicitlyImportedGRE gres\\n in (gre_env, ImpUserExplicit (gresToAvailInfo $ globalRdrEnvElts $ gre_env) implicit_parents)\\n EverythingBut ->\\n let hidden_names = mkNameSet $ concatMap (map greName . snd) items2\\n in (importsFromIface hsc_env iface decl_spec (Just hidden_names), ImpUserEverythingBut hidden_names)\\n\\n return (Just (want_hiding, map fst items2), imp_user_list, gres)\\n where\\n import_mod = mi_module iface\\n all_avails = mi_exports iface\\n imp_occ_env = mkImportOccEnv hsc_env decl_spec all_avails\\n\\n -- Look up a parent (type constructor, class or data constructor)\\n -- in an import.\\n lookup_parent :: IE GhcPs -> RdrName -> IELookupM ImpOccItem\\n lookup_parent ie rdr =\\n assertPpr (not $ isVarNameSpace ns)\\n (vcat [ text \\"filterImports lookup_parent: unexpected variable\\"\\n , text \\"rdr:\\" <+> ppr rdr\\n , text \\"namespace:\\" <+> pprNameSpace ns ]) $\\n do { xs <- lookup_names ie rdr\\n ; case xs of\\n cax :| [] -> return cax\\n _ -> pprPanic \\"filter_imports lookup_parent ambiguous\\" $\\n vcat [ text \\"rdr:\\" <+> ppr rdr\\n , text \\"lookups:\\" <+> ppr (fmap imp_item xs) ] }\\n -- Looking up non-variables is always unambiguous,\\n -- as there can be at most one corresponding item\\n -- in the imp_occ_env.\\n -- See item (1) of Note [Exporting duplicate declarations]\\n -- in GHC.Tc.Gen.Export.\\n where\\n occ = rdrNameOcc rdr\\n ns = occNameSpace occ\\n\\n -- Look up a RdrName used in an import, returning multiple values if there\\n -- are several fields with the same name exposed by the module\\n lookup_names :: IE GhcPs -> RdrName -> IELookupM (NonEmpty ImpOccItem)\\n lookup_names ie rdr\\n | isQual rdr\\n = failLookupWith (QualImportError rdr)\\n | otherwise\\n = case lookups of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n item:items -> return $ item :| items\\n where\\n lookups = concatMap nonDetNameEnvElts\\n $ lookupImpOccEnv (RelevantGREsFOS WantNormal) imp_occ_env (rdrNameOcc rdr)\\n\\n lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, [GlobalRdrElt])]\\n lookup_lie (L loc ieRdr)\\n = setSrcSpanA loc $\\n do (stuff, warns) <- run_lookup ([],[]) (lookup_ie ieRdr)\\n mapM_ (addTcRnDiagnostic <=< warning_msg) warns\\n return [ (L loc ie, gres) | (ie,gres) <- stuff ]\\n where\\n\\n -- Warn when importing T(..) and no children are brought in scope\\n warning_msg (DodgyImport reason) =\\n pure (TcRnDodgyImports reason)\\n warning_msg MissingImportList =\\n pure (TcRnMissingImportList ieRdr)\\n warning_msg (BadImportW ie sub) = do\\n -- \'BadImportW\' is only constructed below in \'bad_import_w\', in\\n -- the \'EverythingBut\' case, so here we assume a \'hiding\' clause.\\n (reason :| _) <- badImportItemErr iface decl_spec ie sub all_avails\\n pure (TcRnDodgyImports (DodgyImportsHiding reason))\\n warning_msg (DeprecatedExport n w) =\\n pure $ TcRnPragmaWarning\\n PragmaWarningExport\\n { pwarn_occname = occName n\\n , pwarn_impmod = moduleName import_mod }\\n w\\n\\n run_lookup :: a -> IELookupM a -> TcRn a\\n run_lookup def m = case m of\\n Failed err -> do\\n msgs <- lookup_err_msgs err\\n forM_ msgs $ \\\\msg -> addErr (TcRnImportLookup msg)\\n return def\\n Succeeded a -> return a\\n\\n lookup_err_msgs err = case err of\\n BadImport ie sub -> badImportItemErr iface decl_spec ie sub all_avails\\n IllegalImport -> pure $ NE.singleton ImportLookupIllegal\\n QualImportError rdr -> pure $ NE.singleton (ImportLookupQualified rdr)\\n\\n -- For each import item, we convert its RdrNames to Names,\\n -- and at the same time compute all the GlobalRdrElt corresponding\\n -- to what is actually imported by this item.\\n -- Returns Nothing on error.\\n --\\n -- Returns a list because, with DuplicateRecordFields, a naked\\n -- import/export of a record field can correspond to multiple\\n -- different GlobalRdrElts. See Note [Importing DuplicateRecordFields].\\n lookup_ie :: IE GhcPs\\n -> IELookupM ([(IE GhcRn, [GlobalRdrElt])], [IELookupWarning])\\n lookup_ie ie = handle_bad_import $\\n case ie of\\n IEVar _ (L l n) _ -> do\\n -- See Note [Importing DuplicateRecordFields]\\n xs <- lookup_names ie (ieWrappedName n)\\n let gres = map imp_item $ NE.toList xs\\n export_depr_warns\\n | want_hiding == Exactly\\n = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ( [ (IEVar Nothing (L l (replaceWrappedName n name)) noDocstring, [gre])\\n | gre <- gres\\n , let name = greName gre ]\\n , export_depr_warns )\\n\\n IEThingAll x ns_spec (L l tc) _ -> do\\n ImpOccItem { imp_item = gre\\n , imp_bundled = bundled_gres\\n , imp_is_parent = is_par\\n }\\n <- lookup_parent ie $ ieWrappedName tc\\n let name = greName gre\\n\\n child_gres :: [GlobalRdrElt]\\n child_gres\\n | is_par = filterByNamespaceSpecifierGREs ns_spec bundled_gres\\n | otherwise = []\\n\\n imp_list_warn\\n\\n | null child_gres\\n -- e.g. f(..) or T(..) where T is a type synonym\\n = [DodgyImport (DodgyImportsEmptyParent ie ns_spec gre)]\\n\\n -- e.g. import M( T(..) )\\n | not (is_qual decl_spec)\\n = [MissingImportList]\\n\\n | otherwise\\n = []\\n\\n renamed_ie = IEThingAll (x { ieta_warning = Nothing })\\n (rnNamespaceSpecifier ns_spec)\\n (L l (replaceWrappedName tc name))\\n noDocstring\\n export_depr_warn\\n | want_hiding == Exactly\\n = maybeToList $ mk_depr_export_warning gre\\n -- We don\'t want to warn about the children as they\\n -- are not explicitly mentioned; the warning will\\n -- be emitted later on if they are used\\n | otherwise = []\\n\\n return ( [(renamed_ie, gre:child_gres)]\\n , imp_list_warn ++ export_depr_warn)\\n\\n\\n IEThingAbs _ (L l tc\') _\\n | want_hiding == EverythingBut -- hiding ( C )\\n -- Here the \'C\' can be a data constructor\\n -- *or* a type/class, or even both\\n -> let tc = ieWrappedName tc\'\\n tc_name = lookup_parent ie tc\\n dc_name = lookup_parent ie (setRdrNameSpace tc srcDataName)\\n in\\n case catIELookupM [ tc_name, dc_name ] of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n names -> return ( [mkIEThingAbs tc\' l (imp_item name) | name <- names], [])\\n | otherwise\\n -> do ImpOccItem { imp_item = gre } <- lookup_parent ie (ieWrappedName tc\')\\n return ( [mkIEThingAbs tc\' l gre]\\n , maybeToList $ mk_depr_export_warning gre)\\n\\n IEThingWith (deprecation, ann) ltc@(L l rdr_tc) wc rdr_ns _ -> do\\n ImpOccItem { imp_item = gre, imp_bundled = subnames }\\n <- lookup_parent (IEThingAbs Nothing ltc noDocstring) (ieWrappedName rdr_tc)\\n let name = greName gre\\n\\n -- Look up the children in the sub-names of the parent\\n -- See Note [Importing DuplicateRecordFields]\\n let (children_errs, childnames) = lookupChildren subnames rdr_ns\\n\\n bad_import_warns <-\\n if null children_errs then return [] else\\n let items = map lce_wrapped_name children_errs\\n ie = IEThingWith (deprecation, ann) ltc wc items noDocstring\\n -- We are trying to import T( a,b,c,d ), and failed\\n -- to find \'b\' and \'d\'. So we make up an import item\\n -- to report as failing, namely T( b, d ).\\n -- c.f. #15413\\n subordinate_err = mkSubordinateError gre children_errs\\n in bad_import_w ie subordinate_err\\n\\n let name\' = replaceWrappedName rdr_tc name\\n childnames\' = map (to_ie_post_rn . fmap greName) childnames\\n gres = gre : map unLoc childnames\\n export_depr_warns\\n | want_hiding == Exactly = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ([ (IEThingWith (Nothing, ann) (L l name\') wc childnames\' noDocstring\\n ,gres)]\\n , bad_import_warns ++ export_depr_warns)\\n\\n IEWholeNamespace x ns_spec -> do\\n let mod_name = moduleName import_mod\\n names = map greName gres\\n renamed_ie = IEWholeNamespace x { iewn_warning = Nothing\\n , iewn_names = names }\\n (rnNamespaceSpecifier ns_spec)\\n gres = filterByNamespaceSpecifierGREs ns_spec $\\n gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n dodgy_warn\\n | null gres = [DodgyImport (DodgyImportsWildcard mod_name ns_spec)]\\n | otherwise = []\\n return ([(renamed_ie, gres)],\\n dodgy_warn)\\n\\n _other -> failLookupWith IllegalImport\\n -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed...\\n -- all of those constitute errors.\\n\\n where\\n mkIEThingAbs tc l gre\\n = (IEThingAbs Nothing (L l (replaceWrappedName tc n)) noDocstring, [gre])\\n where n = greName gre\\n\\n -- N.B. imports never have docstrings\\n noDocstring = Nothing\\n\\n handle_bad_import m = catchIELookup m $ \\\\case\\n BadImport ie sub -> do\\n ws <- bad_import_w ie sub\\n return ([], ws)\\n err -> failLookupWith err\\n\\n bad_import_w :: IE GhcPs -> IsSubordinateError -> IELookupM [IELookupWarning]\\n bad_import_w ie sub\\n | want_hiding == EverythingBut = return [BadImportW ie sub]\\n | otherwise = failLookupWith (BadImport ie sub)\\n\\n mk_depr_export_warning gre\\n = DeprecatedExport name <$> mi_export_warn_fn iface name\\n where\\n name = greName gre\\n\\n-- | Assuming a subordinate item could not be found, do another lookup for a\\n-- more specific error message.\\nmkBadExportSubordinate :: [GlobalRdrElt] -> LIEWrappedName GhcPs -> BadExportSubordinate\\nmkBadExportSubordinate child_gres n =\\n case lookupChildren child_gres [n] of\\n (LookupChildNonType {lce_nontype_item = g} : _, _) -> BadExportSubordinateNonType g\\n (LookupChildNonData {lce_nondata_item = g} : _, _) -> BadExportSubordinateNonData g\\n _ -> BadExportSubordinateNotFound n\\n\\ntype IELookupM = MaybeErr IELookupError\\n\\ndata IELookupWarning\\n = BadImportW (IE GhcPs) IsSubordinateError\\n | MissingImportList\\n | DodgyImport DodgyImportsReason\\n | DeprecatedExport Name (WarningTxt GhcRn)\\n\\n-- | Is this import/export item a subordinate or not?\\ndata IsSubordinateError\\n = IsSubordinateError { subordinate_err_parent :: !GlobalRdrElt\\n , subordinate_err_unavailable :: [FastString]\\n , subordinate_err_nontype :: [GlobalRdrElt]\\n , subordinate_err_nondata :: [GlobalRdrElt] }\\n | IsNotSubordinate\\n\\nmkSubordinateError :: GlobalRdrElt -> [LookupChildError] -> IsSubordinateError\\nmkSubordinateError gre children_errs = foldr add init_acc children_errs\\n where\\n init_acc :: IsSubordinateError\\n init_acc = IsSubordinateError gre [] [] []\\n\\n add :: LookupChildError -> IsSubordinateError -> IsSubordinateError\\n add children_err sub@IsSubordinateError{} =\\n case children_err of\\n LookupChildNonType{lce_nontype_item = g} ->\\n sub { subordinate_err_nontype = g : subordinate_err_nontype sub }\\n LookupChildNonData{lce_nondata_item = g} ->\\n sub { subordinate_err_nondata = g : subordinate_err_nondata sub }\\n LookupChildNotFound (L _ wname) ->\\n let fs = (occNameFS . rdrNameOcc . ieWrappedName) wname\\n in sub { subordinate_err_unavailable = fs : subordinate_err_unavailable sub }\\n add _ IsNotSubordinate = panic \\"mkSubordinateError: IsNotSubordinate\\"\\n\\ndata IELookupError\\n = QualImportError RdrName\\n | BadImport (IE GhcPs) IsSubordinateError\\n | IllegalImport\\n\\nfailLookupWith :: IELookupError -> IELookupM a\\nfailLookupWith err = Failed err\\n\\ncatchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a\\ncatchIELookup m h = case m of\\n Succeeded r -> return r\\n Failed err -> h err\\n\\ncatIELookupM :: [IELookupM a] -> [a]\\ncatIELookupM ms = [ a | Succeeded a <- ms ]\\n\\n-- | Information associated to an \'AvailInfo\' used in constructing\\n-- an \'OccEnv\' corresponding to imports.\\n--\\n-- See Note [Dealing with imports].\\ndata ImpOccItem\\n = ImpOccItem\\n { imp_item :: GlobalRdrElt\\n -- ^ The import item\\n , imp_bundled :: [GlobalRdrElt]\\n -- ^ Items bundled in the Avail this import item came from,\\n -- not including the import item itself if it is a parent.\\n , imp_is_parent :: Bool\\n -- ^ Is the import item a parent? See Note [Dealing with imports].\\n }\\n\\ninstance Outputable ImpOccItem where\\n ppr (ImpOccItem { imp_item = item, imp_bundled = bundled, imp_is_parent = is_par })\\n = braces $ hsep\\n [ text \\"ImpOccItem\\"\\n , if is_par then text \\"[is_par]\\" else empty\\n , ppr (greName item) <+> ppr (greParent item)\\n , braces $ text \\"bundled:\\" <+> ppr (map greName bundled) ]\\n\\n-- | Make an \'OccEnv\' of all the imports.\\n--\\n-- Complicated by the fact that associated data types and pattern synonyms\\n-- can appear twice. See Note [Dealing with imports].\\nmkImportOccEnv :: HscEnv -> ImpDeclSpec -> [IfaceExport] -> OccEnv (NameEnv ImpOccItem)\\nmkImportOccEnv hsc_env decl_spec all_avails =\\n mkOccEnv_C (plusNameEnv_C combine)\\n [ (occ, mkNameEnv [(nm, item)])\\n | avail <- all_avails\\n , let gres = gresFromAvail hsc_env (Just hiding_spec) avail\\n , gre <- gres\\n , let nm = greName gre\\n occ = greOccName gre\\n (is_parent, bundled) = case avail of\\n AvailTC c _\\n | c == nm -- (Recall the AvailTC invariant from GHC.Types.AvailInfo)\\n -> ( True, drop 1 gres ) -- \\"drop 1\\": don\'t include the parent itself.\\n | otherwise\\n -> ( False, gres )\\n _ -> ( False, [] )\\n item = ImpOccItem\\n { imp_item = gre\\n , imp_bundled = bundled\\n , imp_is_parent = is_parent }\\n ]\\n where\\n\\n hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\n -- See Note [Dealing with imports]\\n -- \'combine\' may be called for associated data types which appear\\n -- twice in the all_avails. In the example, we have two Avails for T,\\n -- namely T(T,T1,T2,T3) and C(C,T), and we combine them by dropping the\\n -- latter, in which T is not the parent.\\n combine :: ImpOccItem -> ImpOccItem -> ImpOccItem\\n combine item1@(ImpOccItem { imp_item = gre1, imp_is_parent = is_parent1 })\\n item2@(ImpOccItem { imp_item = gre2, imp_is_parent = is_parent2 })\\n | is_parent1 || is_parent2\\n , not (isRecFldGRE gre1 || isRecFldGRE gre2) -- NB: does not force GREInfo.\\n , let name1 = greName gre1\\n name2 = greName gre2\\n gre = gre1 `plusGRE` gre2\\n -- See Note [Preserve parent information when combining import OccEnvs]\\n = assertPpr (name1 == name2)\\n (ppr name1 <+> ppr name2) $\\n if is_parent1\\n then item1 { imp_item = gre }\\n else item2 { imp_item = gre }\\n -- Discard C(C,T) in favour of T(T, T1, T2, T3).\\n\\n -- \'combine\' may also be called for pattern synonyms which appear both\\n -- unassociated and associated (see Note [Importing PatternSynonyms]).\\n combine item1@(ImpOccItem { imp_item = c1, imp_bundled = kids1 })\\n item2@(ImpOccItem { imp_item = c2, imp_bundled = kids2 })\\n = assertPpr (greName c1 == greName c2\\n && (not (null kids1 && null kids2)))\\n (ppr c1 <+> ppr c2 <+> ppr kids1 <+> ppr kids2) $\\n if null kids1\\n then item2\\n else item1\\n -- Discard standalone pattern P in favour of T(P).\\n\\n-- | Essentially like @lookupGRE env (LookupOccName occ which_gres)@,\\n-- but working with \'ImpOccItem\'s instead of \'GlobalRdrElt\'s.\\nlookupImpOccEnv :: WhichGREs GREInfo\\n -> OccEnv (NameEnv ImpOccItem) -> OccName -> [NameEnv ImpOccItem]\\nlookupImpOccEnv which_gres env occ =\\n mapMaybe relevant_items $ lookupOccEnv_AllNameSpaces env occ\\n where\\n is_relevant :: ImpOccItem -> Bool\\n is_relevant (ImpOccItem { imp_item = gre }) =\\n greIsRelevant which_gres (occNameSpace occ) gre\\n relevant_items :: NameEnv ImpOccItem -> Maybe (NameEnv ImpOccItem)\\n relevant_items nms\\n | let nms\' = filterNameEnv is_relevant nms\\n = if isEmptyNameEnv nms\'\\n then Nothing\\n else Just nms\'\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{Import/Export Utils}\\n* *\\n************************************************************************\\n-}\\n\\n-- | Given an import\\\\/export spec, appropriately set the @gre_imp@ field\\n-- for the \'GlobalRdrElt\'s.\\ngresFromIE :: ImpDeclSpec -> (LIE GhcRn, [GlobalRdrElt]) -> [GlobalRdrElt]\\ngresFromIE decl_spec (L loc ie, gres)\\n = map set_gre_imp gres\\n where\\n is_explicit = case ie of\\n IEThingAll _ _ name _ -> \\\\n -> n == lieWrappedName name\\n IEWholeNamespace _ _ -> \\\\_ -> False\\n _ -> \\\\_ -> True\\n prov_fn name\\n = ImpSpec { is_decl = decl_spec, is_item = item_spec }\\n where\\n item_spec = ImpSome { is_explicit = is_explicit name\\n , is_iloc = locA loc }\\n set_gre_imp gre@( GRE { gre_name = nm } )\\n = gre { gre_imp = unitBag $ prov_fn nm }\\n\\nparentOfImplicitlyImportedGRE :: Outputable info => GlobalRdrEltX info -> Maybe Name\\nparentOfImplicitlyImportedGRE gre =\\n if any (explicit_import . is_item) $ gre_imp gre\\n then Nothing\\n else greParent_maybe gre\\n where\\n explicit_import :: ImpItemSpec -> Bool\\n explicit_import (ImpAll {}) =\\n pprPanic \\"parentOfImplicitlyImportedGRE: ImpAll\\" (ppr gre)\\n explicit_import (ImpSome { is_explicit }) = is_explicit\\n\\n{- Note [Children for duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider the module\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (F(foo, MkFInt, MkFBool)) where\\n data family F a\\n data instance F Int = MkFInt { foo :: Int }\\n data instance F Bool = MkFBool { foo :: Bool }\\n\\nThe `foo` in the export list refers to *both* selectors! For this\\nreason, lookupChildren builds an environment that maps the FastString\\nto a list of items, rather than a single item.\\n-}\\n\\nmkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]\\nmkChildEnv gres = foldr add emptyNameEnv gres\\n where\\n add gre env = case greParent gre of\\n ParentIs p -> extendNameEnv_Acc (:) Utils.singleton env p gre\\n NoParent -> env\\n\\nfindChildren :: NameEnv [a] -> Name -> [a]\\nfindChildren env n = lookupNameEnv env n `orElse` []\\n\\ndata LookupChildError\\n = LookupChildNotFound { lce_wrapped_name :: !(LIEWrappedName GhcPs) }\\n | LookupChildNonType { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nontype_item :: !GlobalRdrElt }\\n | LookupChildNonData { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nondata_item :: !GlobalRdrElt }\\n\\nlookupChildren :: [GlobalRdrElt]\\n -> [LIEWrappedName GhcPs]\\n -> ( [LookupChildError] -- The ones for which the lookup failed\\n , [LocatedA GlobalRdrElt] )\\n-- (lookupChildren all_kids rdr_items) maps each rdr_item to its\\n-- corresponding Name in all_kids, if the former exists\\n-- The matching is done by FastString, not OccName, so that\\n-- Cls( meth, AssocTy )\\n-- will correctly find AssocTy among the all_kids of Cls, even though\\n-- the RdrName for AssocTy may have a (bogus) DataName namespace\\n-- (Really the rdr_items should be FastStrings in the first place.)\\nlookupChildren all_kids rdr_items = (fails, successes)\\n where\\n mb_xs = map do_one rdr_items\\n fails = [ err | Failed err <- mb_xs ]\\n successes = [ ok | Succeeded oks <- mb_xs, ok <- NE.toList oks ]\\n\\n do_one :: LIEWrappedName GhcPs -> MaybeErr LookupChildError (NonEmpty (LocatedA GlobalRdrElt))\\n do_one item@(L l r) =\\n case r of\\n IEName{}\\n -- IEName (unadorned name) places no restriction on the namespace of\\n -- the imported entity, so we look in both `val_gres` and `typ_gres`.\\n -- In case of conflict (punning), the value namespace takes priority.\\n -- See Note [Prioritise the value namespace in subordinate import lists]\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEType{}\\n -- IEType (\'type\' namespace specifier) restricts the lookup to the\\n -- type namespace, i.e. to `typ_gres`. In case of failure, we check\\n -- `val_gres` to produce a more helpful error message.\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- val_gres -> Failed $ LookupChildNonType item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEData{}\\n -- IEData (\'data\' namespace specifier) restricts the lookup to the\\n -- data namespace, i.e. to `val_gres`. In case of failure, we check\\n -- `typ_gres` to produce a more helpful error message.\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- typ_gres -> Failed $ LookupChildNonData item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEPattern{} -> panic \\"lookupChildren: IEPattern\\" -- Never happens (invalid syntax)\\n IEDefault{} -> panic \\"lookupChildren: IEDefault\\" -- Never happens (invalid syntax)\\n where\\n fs = (occNameFS . rdrNameOcc . ieWrappedName) r\\n gres = fromMaybe [] (lookupFsEnv kid_env fs)\\n (val_gres, typ_gres) = partition (isValNameSpace . greNameSpace) gres\\n\\n -- See Note [Children for duplicate record fields]\\n kid_env :: FastStringEnv [GlobalRdrElt]\\n kid_env = extendFsEnvList_C (++) emptyFsEnv\\n [(occNameFS (occName x), [x]) | x <- all_kids]\\n\\n\\n{- Note [Prioritise the value namespace in subordinate import lists]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider this program that defines a class that has both an associated type\\nnamed (#) and a method named (#)\\n\\n module M_assoc where\\n class C a b where\\n type a # b\\n (#) :: a -> b -> ()\\n module N_assoc where\\n import M_assoc( C((#)) )\\n\\nIn the import declaration, when we see the unadorned name (#) in the subordinate\\nimport list of C, which children should we bring into scope? Our options are:\\n\\n a) only the method (#)\\n b) only the associated type (#)\\n c) both the method and the associated type\\n\\nTo follow the precedent established by top-level items, we go with option (a).\\nIndeed, consider a slightly different program\\n\\n module M_top where\\n type family a # b\\n a # b = ()\\n module N_top where\\n import M_top( (#) )\\n\\nHere the import brings only the function (#) into scope, and one has to say\\n`type (#)` to get the type family.\\n-}\\n\\n-------------------------------\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused names}\\n* *\\n*********************************************************\\n-}\\n\\nreportUnusedNames :: TcGblEnv -> HscSource -> RnM ()\\nreportUnusedNames gbl_env hsc_src\\n = do { keep <- readTcRef (tcg_keep gbl_env)\\n ; traceRn \\"RUN\\" (ppr (tcg_dus gbl_env))\\n ; warnUnusedImportDecls gbl_env hsc_src\\n ; warnUnusedTopBinds $ unused_locals keep\\n ; warnMissingSignatures gbl_env\\n ; warnMissingKindSignatures gbl_env }\\n where\\n used_names :: NameSet -> NameSet\\n used_names keep = findUses (tcg_dus gbl_env) emptyNameSet `unionNameSet` keep\\n -- NB: currently, if f x = g, we only treat \'g\' as used if \'f\' is used\\n -- Hence findUses\\n\\n -- Collect the defined names from the in-scope environment\\n defined_names :: [GlobalRdrElt]\\n defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)\\n\\n kids_env = mkChildEnv defined_names\\n -- This is done in mkExports too; duplicated work\\n\\n gre_is_used :: NameSet -> GlobalRdrElt -> Bool\\n gre_is_used used_names gre0\\n = name `elemNameSet` used_names\\n || any (\\\\ gre -> greName gre `elemNameSet` used_names) (findChildren kids_env name)\\n -- A use of C implies a use of T,\\n -- if C was brought into scope by T(..) or T(C)\\n where\\n name = greName gre0\\n\\n -- Filter out the ones that are\\n -- (a) defined in this module, and\\n -- (b) not defined by a \'deriving\' clause\\n -- The latter have an Internal Name, so we can filter them out easily\\n unused_locals :: NameSet -> [GlobalRdrElt]\\n unused_locals keep =\\n let -- Note that defined_and_used, defined_but_not_used\\n -- are both [GRE]; that\'s why we need defined_and_used\\n -- rather than just used_names\\n _defined_and_used, defined_but_not_used :: [GlobalRdrElt]\\n (_defined_and_used, defined_but_not_used)\\n = partition (gre_is_used (used_names keep)) defined_names\\n\\n in filter is_unused_local defined_but_not_used\\n is_unused_local :: GlobalRdrElt -> Bool\\n is_unused_local gre = isLocalGRE gre\\n && isExternalName (greName gre)\\n\\n{- *********************************************************************\\n* *\\n Missing signatures\\n* *\\n********************************************************************* -}\\n\\n{-\\nNote [Missing signatures]\\n~~~~~~~~~~~~~~~~~~~~~~~~~\\nThere are four warning flags in play:\\n\\n * -Wmissing-exported-signatures\\n Warn about any exported top-level function/value without a type signature.\\n Does not include pattern synonyms.\\n\\n * -Wmissing-signatures\\n Warn about any top-level function/value without a type signature. Does not\\n include pattern synonyms. Takes priority over -Wmissing-exported-signatures.\\n\\n * -Wmissing-exported-pattern-synonym-signatures\\n Warn about any exported pattern synonym without a type signature.\\n\\n * -Wmissing-pattern-synonym-signatures\\n Warn about any pattern synonym without a type signature. Takes priority over\\n -Wmissing-exported-pattern-synonym-signatures.\\n\\n-}\\n\\n-- | Warn the user about top level binders that lack type signatures.\\n-- Called /after/ type inference, so that we can report the\\n-- inferred type of the function\\nwarnMissingSignatures :: TcGblEnv -> RnM ()\\nwarnMissingSignatures gbl_env\\n = do { let exports = availsToNameSet (tcg_exports gbl_env)\\n sig_ns = tcg_sigs gbl_env\\n -- We use sig_ns to exclude top-level bindings that are generated by GHC\\n binds = collectHsBindsBinders CollNoDictBinders $ tcg_binds gbl_env\\n pat_syns = tcg_patsyns gbl_env\\n\\n not_ghc_generated :: Name -> Bool\\n not_ghc_generated name = name `elemNameSet` sig_ns\\n\\n add_binding_warn :: Id -> RnM ()\\n add_binding_warn id =\\n when (not_ghc_generated name) $\\n do { env <- liftZonkM $ tcInitTidyEnv -- Why not use emptyTidyEnv?\\n ; let ty = tidyOpenType env (idType id)\\n missing = MissingTopLevelBindingSig name ty\\n diag = TcRnMissingSignature missing exported\\n ; addDiagnosticAt (getSrcSpan name) diag }\\n where\\n name = idName id\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n add_patsyn_warn :: PatSyn -> RnM ()\\n add_patsyn_warn ps =\\n when (not_ghc_generated name) $\\n addDiagnosticAt (getSrcSpan name)\\n (TcRnMissingSignature missing exported)\\n where\\n name = patSynName ps\\n missing = MissingPatSynSig ps\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n -- Warn about missing signatures\\n -- Do this only when we have a type to offer\\n -- See Note [Missing signatures]\\n ; mapM_ add_binding_warn binds\\n ; mapM_ add_patsyn_warn pat_syns\\n }\\n\\n-- | Warn the user about tycons that lack kind signatures.\\n-- Called /after/ type (and kind) inference, so that we can report the\\n-- inferred kinds.\\nwarnMissingKindSignatures :: TcGblEnv -> RnM ()\\nwarnMissingKindSignatures gbl_env\\n = do { cusks_enabled <- xoptM LangExt.CUSKs\\n ; mapM_ (add_ty_warn cusks_enabled) tcs\\n }\\n where\\n tcs = tcg_tcs gbl_env\\n ksig_ns = tcg_ksigs gbl_env\\n exports = availsToNameSet (tcg_exports gbl_env)\\n\\n has_kind_signature :: Name -> Bool\\n has_kind_signature name = name `elemNameSet` ksig_ns\\n\\n add_ty_warn :: Bool -> TyCon -> RnM ()\\n add_ty_warn cusks_enabled tyCon =\\n when (has_kind_signature name) $\\n addDiagnosticAt (getSrcSpan name) diag\\n where\\n name = tyConName tyCon\\n diag = TcRnMissingSignature missing exported\\n missing = MissingTyConKindSig tyCon cusks_enabled\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused imports}\\n* *\\n*********************************************************\\n\\nThis code finds which import declarations are unused. The\\nspecification and implementation notes are here:\\n https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/unused-imports\\n\\nSee also Note [Choosing the best import declaration] in GHC.Types.Name.Reader\\n-}\\n\\ntype ImportDeclUsage\\n = ( LImportDecl GhcRn -- The import declaration\\n , [GlobalRdrElt] -- What *is* used (normalised)\\n , [Name] -- What is imported but *not* used\\n , [NamespaceSpecifier GhcRn] ) -- Unused wildcards\\n\\nwarnUnusedImportDecls :: TcGblEnv -> HscSource -> RnM ()\\nwarnUnusedImportDecls gbl_env hsc_src\\n = do { uses <- readMutVar (tcg_used_gres gbl_env)\\n ; let imports = tcg_rn_imports gbl_env\\n rdr_env = tcg_rdr_env gbl_env\\n\\n -- We should only warn for unnecessary *user* imports, but deciding\\n -- minimal imports should take generated imports into account\\n ; let usageUserImports = findImportUsage (excludeGenerated imports) uses\\n usageAllImports = findImportUsage imports uses\\n\\n ; traceRn \\"warnUnusedImportDecls\\" $\\n (vcat [ text \\"Uses:\\" <+> ppr uses\\n , text \\"Usage all user imports: \\" <+> ppr usageUserImports\\n , text \\"Usage all imports: \\" <+> ppr usageAllImports])\\n\\n ; mapM_ (warnUnusedImport rdr_env) usageUserImports\\n\\n ; whenGOptM Opt_D_dump_minimal_imports $\\n printMinimalImports hsc_src usageAllImports }\\n\\n-- | Exclude generated imports\\nexcludeGenerated :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\nexcludeGenerated = filterOut (isGeneratedImport . ideclOrigin . ideclExt . unLoc)\\n\\nfindImportUsage :: [LImportDecl GhcRn]\\n -> [GlobalRdrElt]\\n -> [ImportDeclUsage]\\n\\nfindImportUsage imports used_gres\\n = map unused_decl imports\\n where\\n import_usage :: ImportMap\\n import_usage = mkImportMap used_gres\\n\\n unused_decl :: LImportDecl GhcRn -> ImportDeclUsage\\n unused_decl decl@(L _ (ImportDecl { ideclImportList = imps }))\\n = -- pprTrace \\"unused_decl\\" (vcat [ ppr decl\\n -- , text \\"used\\" <+> ppr used_gres\\n -- , text \\"unused\\" <+> ppr unused_names ]) $\\n (decl, used_gres, unused_names, unused_wcs)\\n where\\n used_gres = lookupImportMap decl import_usage\\n\\n used_gre_env = mkGlobalRdrEnv used_gres\\n used_parents = mkNameSet (mapMaybe greParent_maybe used_gres)\\n\\n (unused_names, unused_wcs) -- Not trivial; see eg #7454\\n = case imps of\\n Just (Exactly, imp_ies) ->\\n let unused = foldr (add_unused . unLoc) emptyUnusedNames imp_ies\\n nms = nameSetElemsStable (collectUnusedNames unused)\\n wcs = collectUnusedWildcards unused\\n in (nms, wcs)\\n _other -> ([], []) -- No explicit import list => no unused-name list\\n\\n add_unused :: IE GhcRn -> UnusedNames -> UnusedNames\\n add_unused (IEVar _ n _) acc = add_unused_name (lieWrappedName n) True acc\\n add_unused (IEThingAbs _ n _) acc = add_unused_name (lieWrappedName n) False acc\\n add_unused (IEThingAll _ _ n _) acc = add_unused_all (lieWrappedName n) acc\\n add_unused (IEThingWith _ p wc ns _) acc = add_wc_all (add_unused_with pn xs acc)\\n where pn = lieWrappedName p\\n xs = map lieWrappedName ns\\n add_wc_all = case wc of\\n NoIEWildcard -> id\\n IEWildcard _ -> add_unused_all pn\\n add_unused (IEWholeNamespace x ns_spec) acc = add_unused_wildcard ns_spec (iewn_names x) acc\\n add_unused _ acc = acc\\n\\n add_unused_name :: Name -> Bool -> UnusedNames -> UnusedNames\\n add_unused_name n is_ie_var acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | is_ie_var\\n , isFieldName n\\n -- See Note [Reporting unused imported duplicate record fields]\\n = let\\n fs = getOccFS n\\n (flds, flds_used) = lookupFsEnv acc_fs fs `orElse` (emptyNameSet, Any False)\\n acc_fs\' = extendFsEnv acc_fs fs (extendNameSet flds n, Any used S.<> flds_used)\\n in UnusedNames acc_ns acc_wcs acc_fs\'\\n\\n | used\\n = acc\\n\\n | otherwise\\n = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n where\\n used = isJust $ lookupGRE_Name used_gre_env n\\n\\n add_unused_all :: Name -> UnusedNames -> UnusedNames\\n add_unused_all n acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | Just {} <- lookupGRE_Name used_gre_env n = acc\\n | n `elemNameSet` used_parents = acc\\n | otherwise = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n\\n add_unused_with :: Name -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_with p ns acc\\n | all (`elemNameSet` acc1_ns) ns = add_unused_name p False acc1\\n | otherwise = acc1\\n where\\n acc1@(UnusedNames acc1_ns _ _) = foldr (\\\\n acc\' -> add_unused_name n False acc\') acc ns\\n -- If you use \'signum\' from Num, then the user may well have\\n -- imported Num(signum). We don\'t want to complain that\\n -- Num is not itself mentioned. Hence the two cases in add_unused_with.\\n\\n add_unused_wildcard :: NamespaceSpecifier GhcRn -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_wildcard ns_spec names acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | any_used = acc\\n | otherwise = UnusedNames acc_ns (ns_spec : acc_wcs) acc_fs\\n where\\n -- A wildcard `type ..` or `data ..` is used if at least one of\\n -- the names it expands to is used\\n any_used = any (isJust . lookupGRE_Name used_gre_env) names\\n\\n\\n-- | An accumulator for unused names in an import list.\\n--\\n-- See Note [Reporting unused imported duplicate record fields].\\ndata UnusedNames =\\n UnusedNames\\n { unused_names :: NameSet\\n -- ^ Unused \'Name\'s in an import list, not including record fields\\n -- that are plain \'IEVar\' imports (tracked by \'rec_fld_uses\')\\n -- or wildcard imports (tracked by \'unused_wildcards\').\\n , unused_wildcards :: [NamespaceSpecifier GhcRn]\\n -- ^ Unused wildcards @type ..@ or @data ..@ in an import list.\\n , rec_fld_uses :: FastStringEnv (NameSet, Any)\\n -- ^ Record fields imported without a parent (i.e. an \'IEVar\' import).\\n --\\n -- The \'Any\' value records whether any of the record fields\\n -- sharing the same underlying \'FastString\' have been used.\\n }\\n\\nemptyUnusedNames :: UnusedNames\\nemptyUnusedNames = UnusedNames emptyNameSet [] emptyFsEnv\\n\\ninstance Outputable UnusedNames where\\n ppr (UnusedNames nms wcs flds) =\\n text \\"UnusedNames\\" <+>\\n braces (ppr nms <+> ppr wcs <+> ppr (fmap (second getAny) flds))\\n\\n-- | Collect all unused names from a \'UnusedNames\' value.\\ncollectUnusedNames :: UnusedNames -> NameSet\\ncollectUnusedNames (UnusedNames { unused_names = nms, rec_fld_uses = flds })\\n = nms S.<> unused_flds\\n where\\n unused_flds = nonDetFoldFsEnv collect_unused emptyNameSet flds\\n collect_unused :: (NameSet, Any) -> NameSet -> NameSet\\n collect_unused (nms, Any at_least_one_name_is_used) acc\\n | at_least_one_name_is_used = acc\\n | otherwise = unionNameSet nms acc\\n\\ncollectUnusedWildcards :: UnusedNames -> [NamespaceSpecifier GhcRn]\\ncollectUnusedWildcards = unused_wildcards\\n\\n{- Note [Reporting unused imported duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have (#24035):\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M1 (R1(..), R2(..)) where\\n data R1 = MkR1 { fld :: Int }\\n data R2 = MkR2 { fld :: Int }\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M2 where\\n import M1 (R1(MkR1), R2, fld)\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nIn the import of \'M1\' in \'M2\', the \'fld\' import resolves to two separate GREs,\\nnamely R1(fld) and R2(fld). From the perspective of the renamer, and in particular\\nthe \'findImportUsage\' function, it\'s as if the user had imported the two names\\nseparately (even though no source syntax allows that).\\n\\nThis means that we need to be careful when reporting unused imports: the R2(fld)\\nimport is indeed unused, but because R1(fld) is used, we should not report\\nfld as unused altogether.\\n\\nTo achieve this, we keep track of record field imports without a parent (i.e.\\nusing the IEVar constructor) separately from other import items, using the\\nUnusedNames datatype.\\nOnce we have accumulated usages, we emit warnings for unused record fields\\nwithout parents one whole group (of record fields sharing the same textual name)\\nat a time, and only if *all* of the record fields in the group are unused;\\nsee \'collectUnusedNames\'.\\n\\nNote that this only applies to record fields imported without a parent. If we\\nhad:\\n\\n import M1 (R1(MkR1, fld), R2(fld))\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nthen of course we should report the second \'fld\' as unused.\\n-}\\n\\n\\n{- Note [The ImportMap]\\n~~~~~~~~~~~~~~~~~~~~~~~\\nThe ImportMap is a short-lived intermediate data structure records, for\\neach import declaration, what stuff brought into scope by that\\ndeclaration is actually used in the module.\\n\\nThe [GlobalRdrElt] are the things imported from that decl.\\n-}\\n\\ndata ImportMap = ImportMap\\n { im_imports :: Map RealSrcSpan [GlobalRdrElt]\\n -- ^ See [The ImportMap]\\n -- If loc :-> gres, then\\n -- \'loc\' = the end loc of the bestImport of each GRE in \'gres\'\\n , im_generatedImports :: Map ModuleName [GlobalRdrElt]\\n }\\n\\nmkImportMap :: [GlobalRdrElt] -> ImportMap\\n-- For each of a list of used GREs, find all the import decls that brought\\n-- it into scope; choose one of them (bestImport), and record\\n-- the RdrName in that import decl\'s entry in the ImportMap\\nmkImportMap = foldr insertImportMap $ ImportMap Map.empty Map.empty\\n\\ninsertImportMap :: GlobalRdrElt -> ImportMap -> ImportMap\\ninsertImportMap gre@(GRE { gre_imp = imp_specs }) importMap\\n | RealSrcSpan importSpan _ <- is_dloc best_imp_spec =\\n importMap{im_imports = insertElem importSpan gre $ im_imports importMap}\\n | GeneratedSrcSpan{} <- is_dloc best_imp_spec =\\n importMap{im_generatedImports = insertElem (moduleName $ is_mod best_imp_spec) gre $ im_generatedImports importMap}\\n | otherwise = importMap\\n where\\n best_imp_spec =\\n case bagToList imp_specs of\\n [] -> pprPanic \\"mkImportMap: GRE with no ImportSpecs\\" (ppr gre)\\n is:iss -> is_decl $ bestImport (is NE.:| iss)\\n\\n -- https://github.com/haskell/containers/issues/784\\n insertElem :: Ord k => k -> v -> Map k [v] -> Map k [v]\\n insertElem k v = flip Map.alter k $ \\\\case\\n Just vs -> Just (v : vs)\\n Nothing -> Just [v]\\n\\nlookupImportMap :: LImportDecl GhcRn -> ImportMap -> [GlobalRdrElt]\\nlookupImportMap (L srcSpan ImportDecl{ideclName = L _ modName}) importMap =\\n fromMaybe [] $\\n -- should match logic in insertImportMap\\n case locA srcSpan of\\n RealSrcSpan realSrcSpan _ -> realSrcSpan `Map.lookup` im_imports importMap\\n GeneratedSrcSpan{} -> modName `Map.lookup` im_generatedImports importMap\\n _ -> Nothing\\n\\nlieNames :: LIE (GhcPass p) -> [Located (IdP (GhcPass p))]\\nlieNames = _\\n\\nwarnUnusedImport :: GlobalRdrEnv -> ImportDeclUsage -> RnM ()\\nwarnUnusedImport rdr_env (L loc decl, used, unused, unused_wcs)\\n\\n -- Do not warn for \'import M()\'\\n -- See (UI1) in Note [Unused imports]\\n | Just (Exactly, _) <- ideclImportList decl\\n , null unused && null unused_wcs\\n = return ()\\n\\n -- Note [Do not warn about Prelude hiding]\\n | Just (EverythingBut, hides) <- ideclImportList decl\\n , not (null hides)\\n , pRELUDE_NAME == unLoc (ideclName decl)\\n = return ()\\n\\n -- Do not warn about import X as Rebindable\\n -- See (UI2) in Note [Unused imports]\\n | Just (L _ mod) <- ideclAs decl\\n , mod == rEBINDABLE_MOD_NAME\\n = return ()\\n\\n -- Nothing used; drop entire declaration\\n | null used\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl UnusedImportNone)\\n\\n -- Everything imported is used; nop\\n | null unused && null unused_wcs\\n = return ()\\n\\n -- Some imports are unused: make the `SrcSpan` cover only the unused\\n -- items instead of the whole import statement\\n | Just (_, imports) <- ideclImportList decl\\n , let unused_locs = [ locA loc | L loc ie <- imports\\n , name <- ieNames ie\\n , name `elem` unused ]\\n , loc1 : locs <- unused_locs\\n , let span = foldr1 combineSrcSpans ( loc1 NE.:| locs )\\n = addDiagnosticAt span (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n -- Some imports are unused\\n | otherwise\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n where\\n -- In warning message, pretty-print identifiers unqualified unconditionally\\n -- to improve the consistent for ambiguous/unambiguous identifiers.\\n -- See #14881.\\n possible_field n =\\n case lookupGRE_Name rdr_env n of\\n Just (GRE { gre_par = par, gre_info = IAmRecField info }) ->\\n let fld_occ :: OccName\\n fld_occ = nameOccName $ flSelector $ recFieldLabel info\\n in UnusedImportNameRecField par fld_occ\\n _ -> UnusedImportNameRegular n\\n\\n -- Print unused names in a deterministic (lexicographic) order\\n sort_unused :: [UnusedImportName]\\n sort_unused =\\n [ UnusedImportWildcard wc | wc <- unused_wcs ] ++\\n [ possible_field nm | nm <- sortBy (comparing nameOccName) unused ]\\n\\ngetMinimalImports :: [ImportDeclUsage] -> RnM [LImportDecl GhcRn]\\ngetMinimalImports ie_decls\\n = do { rdr_env <- getGlobalRdrEnv\\n ; fmap combine $ mapM (mk_minimal rdr_env) ie_decls }\\n where\\n mk_minimal rdr_env (L l decl, used_gres, unused, unused_wcs)\\n | null unused && null unused_wcs\\n , Just (Exactly, _) <- ideclImportList decl\\n = return (L l decl)\\n | otherwise\\n = do { let ImportDecl { ideclName = L _ mod_name\\n , ideclSource = is_boot\\n , ideclPkgQual = pkg_qual\\n , ideclExt = XImportDeclPass { ideclOrigin = origin } } = decl\\n ; iface <- loadSrcInterface doc (importDeclLookupScope origin)\\n mod_name is_boot pkg_qual\\n ; let used_avails = gresToAvailInfo used_gres\\n ; lies <- map (L l) <$> concatMapM (to_ie rdr_env iface) used_avails\\n ; return (L l (decl { ideclImportList = Just (Exactly, lies) })) }\\n where\\n doc = text \\"Compute minimal imports for\\" <+> ppr decl\\n\\n to_ie :: GlobalRdrEnv -> ModIface -> AvailInfo -> RnM [IE GhcRn]\\n -- The main trick here is that if we\'re importing all the constructors\\n -- we want to say \\"T(..)\\", but if we\'re importing only a subset we want\\n -- to say \\"T(A,B,C)\\". So we have to find out what the module exports.\\n to_ie rdr_env _ (Avail c) -- Note [Overloaded field import]\\n = do { let\\n gre = expectJust $ lookupGRE_Name rdr_env c\\n ; return $ [IEVar Nothing (to_ie_post_rn $ noLocA $ greName gre) Nothing] }\\n to_ie _ _ avail@(AvailTC n [_]) -- Exporting the main decl and nothing else\\n | availExportsDecl avail\\n = return [IEThingAbs Nothing (to_ie_post_rn $ noLocA n) Nothing]\\n to_ie rdr_env iface (AvailTC n cs) =\\n case [ xs | avail@(AvailTC x xs) <- mi_exports iface\\n , x == n\\n , availExportsDecl avail -- Note [Partial export]\\n ] of\\n [xs]\\n | all_used xs\\n -> return [IEThingAll (IEThingAllExt Nothing noAnn noAnn noAnn)\\n (NoNamespaceSpecifier noExtField)\\n (to_ie_post_rn $ noLocA n)\\n Nothing]\\n | otherwise\\n -> do { let ns_gres = map (expectJust . lookupGRE_Name rdr_env) cs\\n ns = map greName ns_gres\\n ; return [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n -- Note [Overloaded field import]\\n _other\\n -> do { let infos = map (expectJust . lookupGRE_Name rdr_env) cs\\n (ns_gres,fs_gres) = classifyGREs infos\\n ns = map greName (ns_gres ++ fs_gres)\\n fs = map fieldGREInfo fs_gres\\n ; return $\\n if all_non_overloaded fs\\n then map (\\\\nm -> IEVar Nothing (to_ie_post_rn_var $ noLocA nm) Nothing) ns\\n else [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n where\\n\\n all_used avail_cs = all (`elem` cs) avail_cs\\n\\n all_non_overloaded = all (not . flIsOverloaded . recFieldLabel)\\n\\n combine :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\n combine = map merge . NE.groupAllWith getKey\\n\\n getKey :: LImportDecl GhcRn -> (Bool, Maybe ModuleName, ModuleName)\\n getKey decl =\\n ( isImportDeclQualified . ideclQualified $ idecl -- is this qualified? (important that this be first)\\n , unLoc <$> ideclAs idecl -- what is the qualifier (inside Maybe monad)\\n , unLoc . ideclName $ idecl -- Module Name\\n )\\n where\\n idecl :: ImportDecl GhcRn\\n idecl = unLoc decl\\n\\n merge :: NonEmpty (LImportDecl GhcRn) -> LImportDecl GhcRn\\n merge decls@((L l decl) :| _) = L l (decl { ideclImportList = Just (Exactly, lies) })\\n where lies = concatMap snd $ mapMaybe (ideclImportList . unLoc) $ NE.toList decls\\n\\nclassifyGREs :: [GlobalRdrElt] -> ([GlobalRdrElt], [FieldGlobalRdrElt])\\nclassifyGREs = partition (not . isRecFldGRE)\\n\\nprintMinimalImports :: HscSource -> [ImportDeclUsage] -> RnM ()\\n-- See Note [Printing minimal imports]\\nprintMinimalImports hsc_src imports_w_usage\\n = do { imports\' <- excludeGenerated <$> getMinimalImports imports_w_usage\\n ; this_mod <- getModule\\n ; dflags <- getDynFlags\\n ; liftIO $ withFile (mkFilename dflags this_mod) WriteMode $ \\\\h ->\\n printForUser dflags h neverQualify AllTheWay (vcat (map ppr imports\'))\\n -- The neverQualify is important. We are printing Names\\n -- but they are in the context of an \'import\' decl, and\\n -- we never qualify things inside there\\n -- E.g. import Blag( f, b )\\n -- not import Blag( Blag.f, Blag.g )!\\n }\\n where\\n mkFilename dflags this_mod\\n | Just d <- dumpDir dflags = d basefn\\n | otherwise = basefn\\n where\\n suffix = case hsc_src of\\n HsBootFile -> \\".imports-boot\\"\\n HsSrcFile -> \\".imports\\"\\n HsigFile -> \\".imports\\"\\n basefn = moduleNameString (moduleName this_mod) ++ suffix\\n\\n\\nto_ie_post_rn_var :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn_var (L l n)\\n | isDataOcc $ occName n = L l (IEPattern noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n\\n\\nto_ie_post_rn :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn (L l n)\\n | isTcOcc occ && isSymOcc occ = L l (IEType noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n where occ = occName n\\n\\n{- Note [Do not warn about Prelude hiding]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWe do not warn about\\n import Prelude hiding( x, y )\\nbecause even if nothing else from Prelude is used, it may be essential to hide\\nx,y to avoid name-shadowing warnings. Example (#9061)\\n import Prelude hiding( log )\\n f x = log where log = ()\\n\\nNote [Unused imports]\\n~~~~~~~~~~~~~~~~~~~~~\\nIn `warnUnusedImport`, if we see an import with an explicit list imports, thus\\n import M( a, b )\\nand neither `a` nor `b` is used, we report the entire import decl as unused. We\\ncheck this by looking at the names that it brings into scope scope; if there are\\nno ununused names, don\'t report.\\n\\n(UI1) We don\'t want to complain about `import M()`, because that is often used to bring\\n M\'s /instances/ into scope. That is neatly dealt with by the \\"no unused\\n names\\" (nor unused wildcard imports) criterion.\\n\\n(UI2) We don\'t report a decl as unused if it has an `as Rebindable` qualifier.\\n See (KN1) in Note [Overview of known entities] in GHC.Builtin\\n\\n\\nNote [Printing minimal imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nTo print the minimal imports we walk over all import decls (both user-supplied\\nand generated), trim their import lists, then filter out generated decls.\\n\\nNB that\\n\\n * We do *not* change the \'qualified\' or \'as\' parts!\\n\\n * We do not discard a decl altogether; we might need instances\\n from it. Instead we just trim to an empty import list\\n\\nNote [Partial export]\\n~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have\\n\\n module A( op ) where\\n class C a where\\n op :: a -> a\\n\\n module B where\\n import A\\n f = ..op...\\n\\nThen the minimal import for module B is\\n import A( op )\\nnot\\n import A( C( op ) )\\nwhich we would usually generate if C was exported from B. Hence\\nthe availExportsDecl test when deciding what to generate.\\n\\n\\nNote [Overloaded field import]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nOn the other hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n data T = MkT { foo :: Int }\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( T(foo) )\\nbecause when DuplicateRecordFields is enabled, field selectors are\\nnot in scope without their enclosing datatype.\\n\\nOn the third hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n pattern MkT { foo } = Just foo\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( foo )\\nbecause foo doesn\'t have a parent. This might actually be ambiguous if A\\nexports another field called foo, but there is no good answer to return and this\\nis a very obscure corner, so it seems to be the best we can do. See\\nDRFPatSynExport for a test of this.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Errors}\\n* *\\n************************************************************************\\n-}\\n\\nbadImportItemErr\\n :: ModIface -> ImpDeclSpec -> IE GhcPs\\n -> IsSubordinateError\\n -> [AvailInfo]\\n -> TcRn (NonEmpty ImportLookupReason)\\nbadImportItemErr iface decl_spec ie sub avails = do\\n exts <- importLookupExtensions\\n let import_lookup_bad :: BadImportKind -> ImportLookupReason\\n import_lookup_bad k = ImportLookupBad k iface decl_spec ie exts\\n dflags <- getDynFlags\\n hsc_env <- getTopEnv\\n let rdr_env = mkGlobalRdrEnv\\n $ gresFromAvails hsc_env (Just imp_spec) all_avails\\n pure $ fmap import_lookup_bad (importErrorKind dflags rdr_env)\\n where\\n importErrorKind :: DynFlags -> GlobalRdrEnv -> NonEmpty BadImportKind\\n importErrorKind dflags rdr_env\\n | any checkIfTyCon avails = case sub of\\n IsNotSubordinate -> NE.singleton BadImportAvailTyCon\\n IsSubordinateError { subordinate_err_parent = gre\\n , subordinate_err_unavailable = unavailable\\n , subordinate_err_nontype = nontype\\n , subordinate_err_nondata = nondata }\\n -> NE.fromList $ catMaybes $\\n [ fmap (BadImportNotExportedSubordinates gre) (NE.nonEmpty unavailable)\\n , fmap (BadImportNonTypeSubordinates gre) (NE.nonEmpty nontype)\\n , fmap (BadImportNonDataSubordinates gre) (NE.nonEmpty nondata) ]\\n | any checkIfVarName avails = NE.singleton BadImportAvailVar\\n | Just con <- find checkIfDataCon avails = NE.singleton (BadImportAvailDataCon (availOccName con))\\n | otherwise = NE.singleton (BadImportNotExported suggs)\\n where\\n suggs = similar_suggs ++ fieldSelectorSuggestions rdr_env rdr\\n what_look = case sub of\\n IsNotSubordinate -> WL_TyCon_or_TermVar\\n IsSubordinateError { subordinate_err_parent = gre } ->\\n case greInfo gre of\\n IAmTyCon ClassFlavour\\n -> WL_TyCon_or_TermVar\\n _ -> WL_Term\\n similar_names =\\n similarNameSuggestions (Unbound.LF what_look WL_Global)\\n dflags rdr_env emptyLocalRdrEnv rdr\\n similar_suggs =\\n case NE.nonEmpty $ mapMaybe imported_item $ similar_names of\\n Just similar -> [ SuggestSimilarNames rdr similar ]\\n Nothing -> [ ]\\n\\n -- Only keep imported items, and set the \\"HowInScope\\" to\\n -- \\"Nothing\\" to avoid printing \\"imported from...\\" in the suggestion\\n -- error message.\\n imported_item (SimilarRdrName rdr_name gre (Just (ImportedBy {})))\\n = Just (SimilarRdrName rdr_name gre Nothing)\\n imported_item _ = Nothing\\n\\n checkIfDataCon = checkIfAvailMatches isDataConName\\n checkIfTyCon = checkIfAvailMatches isTyConName\\n checkIfVarName =\\n \\\\case\\n AvailTC{} -> False\\n Avail n -> importedFS == occNameFS (occName n)\\n && (isVarOcc <||> isFieldOcc) (occName n)\\n checkIfAvailMatches namePred =\\n \\\\case\\n AvailTC _ ns ->\\n case find (\\\\n -> importedFS == occNameFS (occName n)) ns of\\n Just n -> namePred n\\n Nothing -> False\\n Avail{} -> False\\n availOccName = occName . availName\\n rdr = ieName ie\\n importedFS = occNameFS $ rdrNameOcc rdr\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n all_avails = mi_exports iface\\n\\nimportLookupExtensions :: TcRn ImportLookupExtensions\\nimportLookupExtensions = do\\n ile_pattern_synonyms <- xoptM LangExt.PatternSynonyms\\n ile_explicit_namespaces <- xoptM LangExt.ExplicitNamespaces\\n return ImportLookupExtensions{ile_pattern_synonyms, ile_explicit_namespaces}\\n\\naddDupDeclErr :: NonEmpty GlobalRdrElt -> TcRn ()\\naddDupDeclErr gres@(gre :| _)\\n -- Report the error at the later location\\n = addErrAt (getSrcSpan (NE.last sorted_names)) $ (TcRnDuplicateDecls (greOccName gre) sorted_names)\\n where\\n sorted_names =\\n NE.sortBy (SrcLoc.leftmost_smallest `on` nameSrcSpan)\\n (fmap greName gres)\\n\\n-- This data decl will parse OK\\n-- data T = a Int\\n-- treating \\"a\\" as the constructor.\\n-- It is really hard to make the parser spot this malformation.\\n-- So the renamer has to check that the constructor is legal\\n--\\n-- We can get an operator as the constructor, even in the prefix form:\\n-- data T = :% Int Int\\n-- from interface files, which always print in prefix form\\n--\\n-- We also allow type constructor names, which are defined by \\"type data\\"\\n-- declarations. See Note [Type data declarations] in GHC.Rename.Module.\\n\\ncheckConName :: RdrName -> TcRn ()\\ncheckConName name\\n = checkErr (isRdrDataCon name || isRdrTc name) (TcRnIllegalDataCon name)\\n", "filetypes": ["haskell"]}}}' 2026-10-16 14:46:03,626 - DEBUG - Server exception: {'exception': {'TYPE': 'ResponseTimeoutException'}, 'message': 'Response Timeout', 'traceback': 'Traceback (most recent call last):\n File "/home/enrico/.vim/plugged/YouCompleteMe/third_party/ycmd/ycmd/web_plumbing.py", line 213, in __call__\n out = callback( request, response )\n File "/home/enrico/.vim/plugged/YouCompleteMe/third_party/ycmd/ycmd/watchdog_plugin.py", line 97, in wrapper\n return callback( *args, **kwargs )\n File "/home/enrico/.vim/plugged/YouCompleteMe/third_party/ycmd/ycmd/hmac_plugin.py", line 64, in wrapper\n body = callback( request, response )\n File "/home/enrico/.vim/plugged/YouCompleteMe/third_party/ycmd/ycmd/handlers.py", line 89, in RunCompleterCommand\n return _JsonResponse( completer.OnUserCommand(\n ~~~~~~~~~~~~~~~~~~~~~~~^\n request_data[ \'command_arguments\' ],\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n request_data ), response )\n ^^^^^^^^^^^^^^\n File "/home/enrico/.vim/plugged/YouCompleteMe/third_party/ycmd/ycmd/completers/completer.py", line 481, in OnUserCommand\n return command( self, request_data, arguments[ 1: ] )\n File "/home/enrico/.vim/plugged/YouCompleteMe/third_party/ycmd/ycmd/completers/language_server/generic_lsp_completer.py", line 86, in \n self._GetHover( request_data ) }\n ~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^\n File "/home/enrico/.vim/plugged/YouCompleteMe/third_party/ycmd/ycmd/completers/language_server/generic_lsp_completer.py", line 90, in _GetHover\n raw_hover = self.GetHoverResponse( request_data )\n File "/home/enrico/.vim/plugged/YouCompleteMe/third_party/ycmd/ycmd/completers/language_server/language_server_completer.py", line 2583, in GetHoverResponse\n response = self.GetConnection().GetResponse(\n request_id,\n lsp.Hover( request_id, request_data ),\n REQUEST_TIMEOUT_COMMAND )\n File "/home/enrico/.vim/plugged/YouCompleteMe/third_party/ycmd/ycmd/completers/language_server/language_server_completer.py", line 443, in GetResponse\n return response.AwaitResponse( timeout )\n ~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^\n File "/home/enrico/.vim/plugged/YouCompleteMe/third_party/ycmd/ycmd/completers/language_server/language_server_completer.py", line 213, in AwaitResponse\n raise ResponseTimeoutException( \'Response Timeout\' )\nycmd.completers.language_server.language_server_completer.ResponseTimeoutException: Response Timeout\n'} 2026-10-16 14:46:03,626 - ERROR - Error while handling server response Traceback (most recent call last): File "/home/enrico/.vim/plugged/YouCompleteMe/python/ycm/client/base_request.py", line 274, in _JsonFromFuture response = future.result() File "/usr/lib/python3.14/concurrent/futures/_base.py", line 447, in result return self.__get_result() ~~~~~~~~~~~~~~~~~^^ File "/usr/lib/python3.14/concurrent/futures/_base.py", line 396, in __get_result raise self._exception File "/home/enrico/.vim/plugged/YouCompleteMe/python/ycm/unsafe_thread_pool_executor.py", line 42, in run result = self.fn( *self.args, **self.kwargs ) File "/home/enrico/.vim/plugged/YouCompleteMe/python/ycm/client/base_request.py", line 173, in _MakeRequest return urlopen( Request( ...<3 lines>... method = method ), timeout = max( _CONNECT_TIMEOUT_SEC, timeout ) ) File "/usr/lib/python3.14/urllib/request.py", line 187, in urlopen return opener.open(url, data, timeout) ~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.14/urllib/request.py", line 493, in open response = meth(req, response) File "/usr/lib/python3.14/urllib/request.py", line 602, in http_response response = self.parent.error( 'http', request, response, code, msg, hdrs) File "/usr/lib/python3.14/urllib/request.py", line 531, in error return self._call_chain(*args) ~~~~~~~~~~~~~~~~^^^^^^^ File "/usr/lib/python3.14/urllib/request.py", line 464, in _call_chain result = func(*args) File "/usr/lib/python3.14/urllib/request.py", line 611, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 500: Internal Server Error During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/enrico/.vim/plugged/YouCompleteMe/python/ycm/client/base_request.py", line 77, in HandleFuture return _JsonFromFuture( future ) File "/home/enrico/.vim/plugged/YouCompleteMe/python/ycm/client/base_request.py", line 287, in _JsonFromFuture raise MakeServerException( json.loads( response_text ) ) ycmd.responses.ServerError: ResponseTimeoutException: Response Timeout 2026-10-16 14:46:10,633 - DEBUG - POST b'http://127.0.0.1:37093/receive_messages' {'content-type': 'application/json', 'x-ycm-hmac': b'Rga7Yd4l4fgfufwYw+0sxzurvznImlBO0MPmgAlS4EY='} b'{"filepath": "/home/enrico/ghc/compiler/GHC/Rename/Names.hs", "line_num": 1, "column_num": 1, "working_dir": "/home/enrico/ghc", "file_data": {"/home/enrico/ghc/compiler/GHC/Rename/Names.hs": {"contents": "{-\\n(c) The GRASP/AQUA Project, Glasgow University, 1992-1998\\n\\nExtracting imported and top-level names in scope\\n-}\\n\\n{-# LANGUAGE NondecreasingIndentation #-}\\n{-# LANGUAGE TypeFamilies #-}\\n\\nmodule GHC.Rename.Names (\\n rnImports, getLocalNonValBinders, newRecordFieldLabel,\\n importsFromIface,\\n ImportUserSpec(..),\\n extendGlobalRdrEnvRn,\\n gresFromAvails,\\n calculateAvails,\\n reportUnusedNames,\\n checkConName,\\n mkChildEnv,\\n findChildren,\\n mkBadExportSubordinate,\\n findImportUsage,\\n getMinimalImports,\\n printMinimalImports,\\n renamePkgQual, renameRawPkgQual,\\n classifyGREs,\\n ImportDeclUsage,\\n rnNamespaceSpecifier\\n ) where\\n\\nimport GHC.Prelude hiding ( head, init, last, tail )\\n\\nimport GHC.Driver.Env\\nimport GHC.Driver.Session\\nimport GHC.Driver.Ppr\\n\\nimport GHC.Rename.Env\\nimport GHC.Rename.Fixity\\nimport GHC.Rename.Utils ( warnUnusedTopBinds )\\nimport GHC.Rename.Unbound\\nimport qualified GHC.Rename.Unbound as Unbound\\n\\nimport GHC.Tc.Errors.Types\\nimport GHC.Tc.Utils.Env\\nimport GHC.Tc.Utils.Monad\\nimport GHC.Tc.Types.LclEnv\\nimport GHC.Tc.Zonk.TcType ( tcInitTidyEnv )\\n\\nimport GHC.Hs\\nimport GHC.Iface.Load ( loadSrcInterface, loadSrcInterface_maybe )\\nimport GHC.Iface.Errors.Types\\n ( IfaceMessage(..), MissingInterfaceError, InterfaceLookingFor(..)\\n , LoadEssentialsReason(..) )\\nimport GHC.Iface.Syntax ( fromIfaceWarnings )\\nimport GHC.Builtin.Modules( pRELUDE_NAME, rEBINDABLE_MOD_NAME )\\nimport GHC.Parser.PostProcess ( setRdrNameSpace )\\nimport GHC.Core.TyCo.Tidy\\nimport GHC.Core.PatSyn\\nimport GHC.Core.TyCon ( TyCon, tyConName )\\nimport qualified GHC.LanguageExtensions as LangExt\\n\\nimport GHC.Utils.Outputable as Outputable\\nimport GHC.Utils.Misc as Utils\\nimport GHC.Utils.Panic\\n\\nimport GHC.Types.Fixity.Env\\nimport GHC.Types.SafeHaskell\\nimport GHC.Types.Name\\nimport GHC.Types.Name.Env\\nimport GHC.Types.Name.Set\\nimport GHC.Types.Name.Reader\\nimport GHC.Types.Avail\\nimport GHC.Types.FieldLabel\\nimport GHC.Types.Hint\\nimport GHC.Types.SourceFile\\nimport GHC.Types.SrcLoc as SrcLoc\\nimport GHC.Types.Basic (TyConFlavour (..), convImportLevel, VisArity)\\nimport GHC.Types.UnresolvedImport\\nimport GHC.Types.Id\\nimport GHC.Types.PkgQual\\nimport GHC.Types.GREInfo (ConInfo(..), ConFieldInfo (..), ConLikeInfo (ConIsData))\\n\\nimport GHC.Unit\\nimport GHC.Unit.Module.Warnings\\nimport GHC.Unit.Module.ModIface\\nimport GHC.Unit.Module.Imported\\nimport GHC.Unit.Module.Deps\\nimport GHC.Unit.Env\\n\\nimport GHC.Data.Bag\\nimport GHC.Data.FastString\\nimport GHC.Data.FastString.Env\\nimport GHC.Data.Maybe\\nimport GHC.Data.List.SetOps ( removeDups )\\n\\nimport Control.Arrow ( second )\\nimport Control.Monad\\nimport Data.Foldable ( for_ )\\nimport Data.IntMap ( IntMap )\\nimport qualified Data.IntMap as IntMap\\nimport Data.Map ( Map )\\nimport qualified Data.Map as Map\\nimport Data.Ord ( comparing )\\nimport Data.Semigroup ( Any(..) )\\nimport qualified Data.Semigroup as S\\nimport Data.List ( partition, find, sortBy )\\nimport Data.List.NonEmpty (NonEmpty(..))\\nimport qualified Data.List.NonEmpty as NE\\nimport Data.Function ( on )\\nimport qualified Data.Set as S\\nimport System.FilePath (())\\nimport System.IO\\n\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{rnImports}\\n* *\\n************************************************************************\\n\\nNote [Tracking Trust Transitively]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen we import a package as well as checking that the direct imports are safe\\naccording to the rules outlined in the Note [Safe Haskell Trust Check] in GHC.Driver.Main\\nwe must also check that these rules hold transitively for all dependent modules\\nand packages. Doing this without caching any trust information would be very\\nslow as we would need to touch all packages and interface files a module depends\\non. To avoid this we make use of the property that if a modules Safe Haskell\\nmode changes, this triggers a recompilation from that module in the dependency\\ngraph. So we can just worry mostly about direct imports.\\n\\nThere is one trust property that can change for a package though without\\nrecompilation being triggered: package trust. So we must check that all\\npackages a module transitively depends on to be trusted are still trusted when\\nwe are compiling this module (as due to recompilation avoidance some modules\\nbelow may not be considered trusted any more without recompilation being\\ntriggered).\\n\\nWe handle this by augmenting the existing transitive list of packages a module M\\ndepends on with a bool for each package that says if it must be trusted when the\\nmodule M is being checked for trust. This list of trust required packages for a\\nsingle import is gathered in the rnImportDecl function and stored in an\\nImportAvails data structure. The union of these trust required packages for all\\nimports is done by the rnImports function using the combine function which calls\\nthe plusImportAvails function that is a union operation for the ImportAvails\\ntype. This gives us in an ImportAvails structure all packages required to be\\ntrusted for the module we are currently compiling. Checking that these packages\\nare still trusted (and that direct imports are trusted) is done in\\nGHC.Driver.Main.checkSafeImports.\\n\\nSee the note below, [Trust Own Package] for a corner case in this method and\\nhow its handled.\\n\\n\\nNote [Trust Own Package]\\n~~~~~~~~~~~~~~~~~~~~~~~~\\nThere is a corner case of package trust checking that the usual transitive check\\ndoesn\'t cover. (For how the usual check operates see the Note [Tracking Trust\\nTransitively] below). The case is when you import a -XSafe module M and M\\nimports a -XTrustworthy module N. If N resides in a different package than M,\\nthen the usual check works as M will record a package dependency on N\'s package\\nand mark it as required to be trusted. If N resides in the same package as M\\nthough, then importing M should require its own package be trusted due to N\\n(since M is -XSafe so doesn\'t create this requirement by itself). The usual\\ncheck fails as a module doesn\'t record a package dependency of its own package.\\nSo instead we now have a bool field in a modules interface file that simply\\nstates if the module requires its own package to be trusted. This field avoids\\nus having to load all interface files that the module depends on to see if one\\nis trustworthy.\\n\\n\\nNote [Trust Transitive Property]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSo there is an interesting design question in regards to transitive trust\\nchecking. Say I have a module B compiled with -XSafe. B is dependent on a bunch\\nof modules and packages, some packages it requires to be trusted as its using\\n-XTrustworthy modules from them. Now if I have a module A that doesn\'t use safe\\nhaskell at all and simply imports B, should A inherit all the trust\\nrequirements from B? Should A now also require that a package p is trusted since\\nB required it?\\n\\nWe currently say no but saying yes also makes sense. The difference is, if a\\nmodule M that doesn\'t use Safe Haskell imports a module N that does, should all\\nthe trusted package requirements be dropped since M didn\'t declare that it cares\\nabout Safe Haskell (so -XSafe is more strongly associated with the module doing\\nthe importing) or should it be done still since the author of the module N that\\nuses Safe Haskell said they cared (so -XSafe is more strongly associated with\\nthe module that was compiled that used it).\\n\\nGoing with yes is a simpler semantics we think and harder for the user to stuff\\nup but it does mean that Safe Haskell will affect users who don\'t care about\\nSafe Haskell as they might grab a package from Cabal which uses safe haskell (say\\nnetwork) and that packages imports -XTrustworthy modules from another package\\n(say bytestring), so requires that package is trusted. The user may now get\\ncompilation errors in code that doesn\'t do anything with Safe Haskell simply\\nbecause they are using the network package. They will have to call \'ghc-pkg\\ntrust network\' to get everything working. Due to this invasive nature of going\\nwith yes we have gone with no for now.\\n-}\\n\\n-- | Process Import Decls. See \'rnImportDecl\' for a description of what\\n-- the return types represent.\\n-- Note: Do the non SOURCE ones first, so that we get a helpful warning\\n-- for SOURCE ones that are unnecessary\\nrnImports :: [(LImportDecl GhcPs, SDoc)]\\n -> RnM ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\nrnImports imports = do\\n tcg_env <- getGblEnv\\n -- NB: want an identity module here, because it\'s OK for a signature\\n -- module to import from its implementor\\n let this_mod = tcg_mod tcg_env\\n let (source, ordinary) = partition (is_source_import . fst) imports\\n is_source_import (d::LImportDecl GhcPs) = ideclSource (unLoc d) == IsBoot\\n stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary\\n stuff2 <- mapAndReportM (rnImportDecl this_mod) source\\n -- Safe Haskell: See Note [Tracking Trust Transitively]\\n let (decls, imp_user_spec, rdr_env, imp_avails) = combine (stuff1 ++ stuff2)\\n -- Update imp_boot_mods if imp_direct_mods mentions any of them\\n let merged_import_avail = clobberSourceImports imp_avails\\n return (decls, imp_user_spec, rdr_env, merged_import_avail)\\n\\n where\\n clobberSourceImports imp_avails =\\n imp_avails { imp_boot_mods = imp_boot_mods\' }\\n where\\n imp_boot_mods\' = mergeInstalledModuleEnv combJ id (const emptyInstalledModuleEnv)\\n (imp_boot_mods imp_avails)\\n (imp_direct_dep_mods imp_avails)\\n\\n combJ (GWIB _ IsBoot) (_, x) = Just x\\n combJ r _ = Just r\\n -- See Note [Combining ImportAvails]\\n combine :: [(LImportDecl GhcRn, ImportUserSpec, GlobalRdrEnv, ImportAvails)]\\n -> ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\n combine ss =\\n let (decls, imp_user_spec, rdr_env, imp_avails, finsts) = foldr\\n plus\\n ([], [], emptyGlobalRdrEnv, emptyImportAvails, emptyModuleSet)\\n ss\\n in (decls, imp_user_spec, rdr_env, imp_avails { imp_finsts = moduleSetElts finsts })\\n\\n plus (decl, us, gbl_env1, imp_avails1)\\n (decls, uss, gbl_env2, imp_avails2, finsts_set)\\n = ( decl:decls,\\n us:uss,\\n gbl_env1 `plusGlobalRdrEnv` gbl_env2,\\n imp_avails1\' `plusImportAvails` imp_avails2,\\n extendModuleSetList finsts_set new_finsts )\\n where\\n imp_avails1\' = imp_avails1 { imp_finsts = [] }\\n new_finsts = imp_finsts imp_avails1\\n\\n{-\\nNote [Combining ImportAvails]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nimp_finsts in ImportAvails is a list of family instance modules\\ntransitively depended on by an import. imp_finsts for a currently\\ncompiled module is a union of all the imp_finsts of imports.\\nComputing the union of two lists of size N is O(N^2) and if we\\ndo it to M imports we end up with O(M*N^2). That can get very\\nexpensive for bigger module hierarchies.\\n\\nUnion can be optimized to O(N log N) if we use a Set.\\nimp_finsts is converted back and forth between dep_finsts, so\\nchanging a type of imp_finsts means either paying for the conversions\\nor changing the type of dep_finsts as well.\\n\\nI\'ve measured that the conversions would cost 20% of allocations on my\\ntest case, so that can be ruled out.\\n\\nChanging the type of dep_finsts forces checkFamInsts to\\nget the module lists in non-deterministic order. If we wanted to restore\\nthe deterministic order, we\'d have to sort there, which is an additional\\ncost. As far as I can tell, using a non-deterministic order is fine there,\\nbut that\'s a brittle nonlocal property which I\'d like to avoid.\\n\\nAdditionally, dep_finsts is read from an interface file, so its \\"natural\\"\\ntype is a list. Which makes it a natural type for imp_finsts.\\n\\nSince rnImports.combine is really the only place that would benefit from\\nit being a Set, it makes sense to optimize the hot loop in rnImports.combine\\nwithout changing the representation.\\n\\nSo here\'s what we do: instead of naively merging ImportAvails with\\nplusImportAvails in a loop, we make plusImportAvails merge empty imp_finsts\\nand compute the union on the side using Sets. When we\'re done, we can\\nconvert it back to a list. One nice side effect of this approach is that\\nif there\'s a lot of overlap in the imp_finsts of imports, the\\nSet doesn\'t really need to grow and we don\'t need to allocate.\\n\\nRunning generateModules from #14693 with DEPTH=16, WIDTH=30 finishes in\\n23s before, and 11s after.\\n-}\\n\\n-- | Given a located import declaration @decl@ from @this_mod@,\\n-- calculate the following pieces of information:\\n--\\n-- 1. An updated \'LImportDecl\', where all unresolved \'RdrName\' in\\n-- the entity lists have been resolved into \'Name\'s,\\n--\\n-- 2. A \'GlobalRdrEnv\' representing the new identifiers that were\\n-- brought into scope (taking into account module qualification\\n-- and hiding),\\n--\\n-- 3. \'ImportAvails\' summarizing the identifiers that were imported\\n-- by this declaration, and\\n--\\n-- 4. A boolean \'AnyHpcUsage\' which is true if the imported module\\n-- used HPC.\\nrnImportDecl :: Module -> (LImportDecl GhcPs, SDoc)\\n -> RnM (LImportDecl GhcRn, ImportUserSpec , GlobalRdrEnv, ImportAvails)\\nrnImportDecl this_mod\\n (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name\\n , ideclPkgQual = raw_pkg_qual\\n , ideclSource = want_boot\\n , ideclSafe = mod_safe\\n , ideclLevelSpec = import_level\\n , ideclQualified = qual_style\\n , ideclExt = XImportDeclPass { ideclOrigin = origin }\\n , ideclAs = as_mod, ideclImportList = imp_details }), import_reason)\\n = setSrcSpanA loc $ do\\n\\n case raw_pkg_qual of\\n NoRawPkgQual -> pure ()\\n RawPkgQual {} -> do\\n pkg_imports <- xoptM LangExt.PackageImports\\n when (not pkg_imports) $ addErr TcRnPackageImportsDisabled\\n\\n let qual_only = isImportDeclQualified qual_style\\n generated = isGeneratedImport origin\\n\\n lookup_scope = importDeclLookupScope origin\\n\\n -- If there\'s an error in loadInterface, (e.g. interface\\n -- file not found) we get lots of spurious errors from \'filterImports\'\\n let imp_mod_name = unLoc loc_imp_mod_name\\n doc = ppr imp_mod_name <+> import_reason\\n\\n hsc_env <- getTopEnv\\n unit_env <- hsc_unit_env <$> getTopEnv\\n let pkg_qual = renameRawPkgQual unit_env imp_mod_name raw_pkg_qual\\n\\n -- Check for self-import, which confuses the typechecker (#9032)\\n -- ghc --make rejects self-import cycles already, but batch-mode may not\\n -- at least not until GHC.IfaceToCore.tcHiBootIface, which is too late to avoid\\n -- typechecker crashes. (Indirect self imports are not caught until\\n -- GHC.IfaceToCore, see #10337 tracking how to make this error better.)\\n --\\n -- Originally, we also allowed \'import {-# SOURCE #-} M\', but this\\n -- caused bug #10182: in one-shot mode, we should never load an hs-boot\\n -- file for the module we are compiling into the EPS. In principle,\\n -- it should be possible to support this mode of use, but we would have to\\n -- extend Provenance to support a local definition in a qualified location.\\n -- For now, we don\'t support it, but see #10336\\n when (imp_mod_name == moduleName this_mod &&\\n (case pkg_qual of -- If we have import \\"\\" M, then we should\\n -- check that \\"\\" is \\"this\\" (which is magic)\\n -- or the name of this_mod\'s package. Yurgh!\\n -- c.f. GHC.findModule, and #9997\\n NoPkgQual -> True\\n ThisPkg uid -> uid == homeUnitId_ (hsc_dflags hsc_env)\\n OtherPkg _ -> False))\\n (addErr (TcRnSelfImport imp_mod_name))\\n\\n -- Check for a missing import list (Opt_WarnMissingImportList also\\n -- checks for T(..) items but that is done in checkDodgyImport below)\\n case imp_details of\\n Just (Exactly, _) -> return () -- Explicit import list\\n _ | generated -> return () -- Do not bleat for generated imports\\n | qual_only -> return ()\\n | otherwise -> addDiagnostic (TcRnNoExplicitImportList imp_mod_name)\\n\\n\\n mb_iface <- loadSrcInterface_maybe doc lookup_scope imp_mod_name want_boot pkg_qual\\n iface <- case mb_iface of\\n Succeeded iface -> return iface\\n Failed err -> failWithTc $\\n importDeclLoadFailure origin imp_mod_name want_boot err\\n\\n -- Compiler sanity check: if the import didn\'t say\\n -- {-# SOURCE #-} we should not get a hi-boot file\\n warnPprTrace ((want_boot == NotBoot) && (mi_boot iface == IsBoot)) \\"rnImportDecl\\" (ppr imp_mod_name) $ do\\n\\n -- Issue a user warning for a redundant {- SOURCE -} import\\n -- NB that we arrange to read all the ordinary imports before\\n -- any of the {- SOURCE -} imports.\\n --\\n -- in --make and GHCi, the compilation manager checks for this,\\n -- and indeed we shouldn\'t do it here because the existence of\\n -- the non-boot module depends on the compilation order, which\\n -- is not deterministic. The hs-boot test can show this up.\\n dflags <- getDynFlags\\n warnIf ((want_boot == IsBoot) && (mi_boot iface == NotBoot) && isOneShot (ghcMode dflags))\\n (TcRnRedundantSourceImport imp_mod_name)\\n when (mod_safe && not (safeImportsOn dflags)) $\\n addErr (TcRnSafeImportsDisabled imp_mod_name)\\n\\n let imp_mod = mi_module iface\\n qual_mod_name = fmap unLoc as_mod `orElse` imp_mod_name\\n imp_spec = ImpDeclSpec { is_mod = imp_mod, is_qual = qual_only,\\n is_dloc = locA loc, is_as = qual_mod_name,\\n is_pkg_qual = pkg_qual, is_isboot = want_boot,\\n is_level = convImportLevel import_level }\\n\\n let filter_imports = do\\n -- filter the imports according to the import declaration\\n (new_imp_details, imp_user_list, gbl_env)\\n <- filterImports hsc_env iface imp_spec imp_details\\n -- for certain error messages, we\\u2019d like to know what could be\\n -- imported here, if everything were imported\\n potential_gres <- (\\\\(_,_,x) -> x) <$> filterImports hsc_env iface imp_spec Nothing\\n return (new_imp_details, imp_user_list, gbl_env, potential_gres)\\n\\n (new_imp_details, imp_user_list, gbl_env, potential_gres) <-\\n case origin of\\n ImplicitEssentialsImport ->\\n -- The implicit GHC.Essentials import does not bring anything into scope.\\n -- See Note [Finding GHC.Essentials] in GHC.Builtin.\\n return (Nothing, ImpUserDependOnly, emptyGlobalRdrEnv, emptyGlobalRdrEnv)\\n UserWrittenImport -> filter_imports\\n ImplicitPreludeImport -> filter_imports\\n PluginImport -> filter_imports\\n\\n let is_hiding | Just (EverythingBut,_) <- imp_details = True\\n | otherwise = False\\n\\n -- should the import be safe?\\n mod_safe\' = mod_safe\\n || (not generated && safeDirectImpsReq dflags)\\n || (generated && safeImplicitImpsReq dflags)\\n\\n hsc_env <- getTopEnv\\n let home_unit = hsc_home_unit hsc_env\\n other_home_units = hsc_all_home_unit_ids hsc_env\\n\\n imported_by\\n | isDependOnlyImport imp_user_list\\n = ImportedBySystem\\n | otherwise\\n = ImportedByUser $ ImportedModsVal\\n { imv_name = is_as imp_spec\\n , imv_span = locA loc\\n , imv_is_safe = mod_safe\'\\n , imv_is_hiding = is_hiding\\n , imv_all_exports = potential_gres\\n , imv_qualified = qual_only\\n , imv_is_level = convImportLevel import_level\\n }\\n imports = calculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by\\n\\n -- Complain if we import a deprecated module\\n case fromIfaceWarnings (mi_warns iface) of\\n WarnAll txt -> addDiagnostic (TcRnDeprecatedModule imp_mod_name txt)\\n _ -> return ()\\n\\n let new_imp_decl = ImportDecl\\n { ideclExt = ideclExt decl\\n , ideclName = ideclName decl\\n , ideclPkgQual = pkg_qual\\n , ideclSource = ideclSource decl\\n , ideclSafe = mod_safe\'\\n , ideclQualified = ideclQualified decl\\n , ideclAs = ideclAs decl\\n , ideclImportList = new_imp_details\\n , ideclLevelSpec = ideclLevelSpec decl\\n }\\n\\n return (L loc new_imp_decl, ImpUserSpec imp_spec imp_user_list, gbl_env, imports)\\n\\n-- | The error message to emit when we failed to load an interface.\\nimportDeclLoadFailure :: ImportDeclOrigin -> ModuleName -> IsBootInterface\\n -> MissingInterfaceError -> TcRnMessage\\nimportDeclLoadFailure ImplicitEssentialsImport _ _ err\\n = TcRnInterfaceError $ CantFindEssentials err LookingForEssentialsModule\\nimportDeclLoadFailure _ mod_name want_boot err\\n = TcRnInterfaceError $ Can\'tFindInterface err $ LookingForModule mod_name want_boot\\n\\n-- | Rename raw package imports\\nrenameRawPkgQual :: UnitEnv -> ModuleName -> RawPkgQual -> PkgQual\\nrenameRawPkgQual unit_env mn = \\\\case\\n NoRawPkgQual -> NoPkgQual\\n RawPkgQual _ fs -> renamePkgQual unit_env mn $ Just fs\\n\\n-- | Rename raw package imports\\nrenamePkgQual :: UnitEnv -> ModuleName -> Maybe FastString -> PkgQual\\nrenamePkgQual unit_env mn mb_pkg = case mb_pkg of\\n Nothing -> NoPkgQual\\n Just pkg_fs\\n | Just uid <- homeUnitId <$> ue_homeUnit unit_env\\n , pkg_fs == fsLit \\"this\\"\\n -> ThisPkg uid\\n\\n | Just (uid, _) <- find (fromMaybe False . fmap (== pkg_fs) . snd) home_names\\n -> ThisPkg uid\\n\\n | Just uid <- resolvePackageImport unit_state mn (PackageName pkg_fs)\\n -> OtherPkg uid\\n\\n | otherwise\\n -> OtherPkg (UnitId pkg_fs)\\n -- not really correct as pkg_fs is unlikely to be a valid unit-id but\\n -- we will report the failure later...\\n where\\n home_names =\\n [ (uid, mkFastString <$> thisPackageName (homeUnitEnv_dflags (ue_findHomeUnitEnv uid unit_env)))\\n | uid <- S.toList hpt_deps\\n ]\\n\\n unit_state = ue_homeUnitState unit_env\\n\\n hpt_deps :: S.Set UnitId\\n hpt_deps = homeUnitDepends unit_state\\n\\n\\n-- | Calculate the \'ImportAvails\' induced by an import of a particular\\n-- interface, but without \'imp_mods\'.\\ncalculateAvails :: HomeUnit\\n -> S.Set UnitId\\n -> ModIface\\n -> IsSafeImport\\n -> IsBootInterface\\n -> ImportedBy\\n -> ImportAvails\\ncalculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by =\\n let imp_mod = mi_module iface\\n imp_sem_mod= mi_semantic_module iface\\n orph_iface = mi_orphan iface\\n has_finsts = mi_finsts iface\\n deps = mi_deps iface\\n trust = getSafeMode $ mi_trust iface\\n trust_pkg = mi_trust_pkg iface\\n is_sig = mi_hsc_src iface == HsigFile\\n\\n -- If the module exports anything defined in this module, just\\n -- ignore it. Reason: otherwise it looks as if there are two\\n -- local definition sites for the thing, and an error gets\\n -- reported. Easiest thing is just to filter them out up\\n -- front. This situation only arises if a module imports\\n -- itself, or another module that imported it. (Necessarily,\\n -- this involves a loop.)\\n --\\n -- We do this *after* filterImports, so that if you say\\n -- module A where\\n -- import B( AType )\\n -- type AType = ...\\n --\\n -- module B( AType ) where\\n -- import {-# SOURCE #-} A( AType )\\n --\\n -- then you won\'t get a \'B does not export AType\' message.\\n\\n\\n -- Compute new transitive dependencies\\n --\\n -- \'dep_orphs\' and \'dep_finsts\' do NOT include the imported module\\n -- itself, but we DO need to include this module in \'imp_orphs\' and\\n -- \'imp_finsts\' if it defines an orphan or instance family; thus the\\n -- orph_iface/has_iface tests.\\n\\n deporphs = dep_orphs deps\\n depfinsts = dep_finsts deps\\n\\n orphans | orph_iface = assertPpr (not (imp_sem_mod `elem` deporphs)) (ppr imp_sem_mod <+> ppr deporphs) $\\n imp_sem_mod : deporphs\\n | otherwise = deporphs\\n\\n finsts | has_finsts = assertPpr (not (imp_sem_mod `elem` depfinsts)) (ppr imp_sem_mod <+> ppr depfinsts) $\\n imp_sem_mod : depfinsts\\n | otherwise = depfinsts\\n\\n -- Trusted packages are a lot like orphans.\\n trusted_pkgs | mod_safe\' = dep_trusted_pkgs deps\\n | otherwise = S.empty\\n\\n\\n pkg = moduleUnit (mi_module iface)\\n ipkg = toUnitId pkg\\n\\n -- Does this import mean we now require our own pkg\\n -- to be trusted? See Note [Trust Own Package]\\n ptrust = trust == Sf_Trustworthy || trust_pkg\\n pkg_trust_req\\n | isHomeUnit home_unit pkg = ptrust\\n | otherwise = False\\n\\n dependent_pkgs = if toUnitId pkg `S.member` other_home_units\\n then S.empty\\n else S.singleton (lvl, ipkg)\\n\\n lvl = case imported_by of\\n ImportedByUser imv -> imv_is_level imv\\n ImportedBySystem -> NormalLevel\\n\\n\\n direct_mods = if toUnitId pkg `S.member` other_home_units\\n then mkPlusModDeps (moduleUnitId imp_mod) lvl (GWIB (moduleName imp_mod) want_boot)\\n else emptyInstalledModuleEnv\\n\\n dep_boot_mods_map = mkModDeps (dep_boot_mods deps)\\n\\n\\n boot_mods\\n -- If we are looking for a boot module, it must be HPT\\n | IsBoot <- want_boot = extendInstalledModuleEnv dep_boot_mods_map (toUnitId <$> imp_mod) (GWIB (moduleName imp_mod) IsBoot)\\n -- Now we are importing A properly, so don\'t go looking for\\n -- A.hs-boot\\n | isHomeUnit home_unit pkg = dep_boot_mods_map\\n -- There\'s no boot files to find in external imports\\n | otherwise = emptyInstalledModuleEnv\\n\\n sig_mods =\\n if is_sig\\n then moduleName imp_mod : dep_sig_mods deps\\n else dep_sig_mods deps\\n\\n\\n in ImportAvails {\\n imp_mods = Map.singleton (mi_module iface) [imported_by],\\n imp_orphs = orphans,\\n imp_finsts = finsts,\\n imp_sig_mods = sig_mods,\\n imp_direct_dep_mods = direct_mods,\\n imp_dep_direct_pkgs = dependent_pkgs,\\n imp_boot_mods = boot_mods,\\n\\n -- Add in the imported modules trusted package\\n -- requirements. ONLY do this though if we import the\\n -- module as a safe import.\\n -- See Note [Tracking Trust Transitively]\\n -- and Note [Trust Transitive Property]\\n imp_trust_pkgs = trusted_pkgs,\\n -- Do we require our own pkg to be trusted?\\n -- See Note [Trust Own Package]\\n imp_trust_own_pkg = pkg_trust_req\\n }\\n\\nmkPlusModDeps :: UnitId -> ImportLevel -> ModuleNameWithIsBoot\\n -> InstalledModuleEnv (S.Set ImportLevel, ModuleNameWithIsBoot)\\nmkPlusModDeps uid st elt = extendInstalledModuleEnv emptyInstalledModuleEnv (mkModule uid (gwib_mod elt)) (S.singleton st, elt)\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{importsFromLocalDecls}\\n* *\\n************************************************************************\\n\\nFrom the top-level declarations of this module produce\\n * the lexical environment\\n * the ImportAvails\\ncreated by its bindings.\\n\\nNote [Top-level Names in Template Haskell decl quotes]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSee also: Note [Interactively-bound Ids in GHCi] in GHC.Driver.Env\\n Note [Looking up Exact RdrNames] in GHC.Rename.Env\\n\\nConsider a Template Haskell declaration quotation like this:\\n module M where\\n f x = h [d| f = 3 |]\\nWhen renaming the declarations inside [d| ...|], we treat the\\ntop level binders specially in two ways\\n\\n1. We give them an Internal Name, not (as usual) an External one.\\n This is done by GHC.Rename.Env.newTopSrcBinder.\\n\\n2. We make them *shadow* the outer bindings.\\n See Note [GlobalRdrEnv shadowing]\\n\\n3. We find out whether we are inside a [d| ... |] by testing the TH\\n level. This is a slight hack, because the level field was really\\n meant for the type checker, and here we are not interested in the\\n fields of Brack, hence the error thunks in thRnBrack.\\n-}\\n\\nextendGlobalRdrEnvRn :: [GlobalRdrElt]\\n -> MiniFixityEnv\\n -> RnM (TcGblEnv, TcLclEnv)\\n-- Updates both the GlobalRdrEnv and the FixityEnv\\n-- We return a new TcLclEnv only because we might have to\\n-- delete some bindings from it;\\n-- see Note [Top-level Names in Template Haskell decl quotes]\\n\\nextendGlobalRdrEnvRn new_gres new_fixities\\n = checkNoErrs $ -- See Note [Fail fast on duplicate definitions]\\n do { (gbl_env, lcl_env) <- getEnvs\\n ; level <- getThLevel\\n ; isGHCi <- getIsGHCi\\n ; let rdr_env = tcg_rdr_env gbl_env\\n fix_env = tcg_fix_env gbl_env\\n th_bndrs = getLclEnvThBndrs lcl_env\\n th_lvl = thLevelIndex level\\n\\n -- Delete new_occs from global and local envs\\n -- If we are in a TemplateHaskell decl bracket,\\n -- we are going to shadow them\\n -- See Note [GlobalRdrEnv shadowing]\\n inBracket = isBrackLevel level\\n\\n lcl_env_TH = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_rdr = minusLocalRdrEnv (tcl_rdr lcl_env) new_gres_env }) lcl_env\\n -- See Note [GlobalRdrEnv shadowing]\\n\\n lcl_env2 | inBracket = lcl_env_TH\\n | otherwise = lcl_env\\n\\n -- Deal with shadowing: see Note [GlobalRdrEnv shadowing]\\n want_shadowing = isGHCi || inBracket\\n rdr_env1 | want_shadowing = shadowNames False rdr_env new_gres_env\\n | otherwise = rdr_env\\n\\n lcl_env3 = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_th_bndrs = extendNameEnvList th_bndrs\\n [ ( n, (TopLevel, th_lvl) )\\n | n <- new_names ] }) lcl_env2\\n\\n ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres\\n\\n ; let fix_env\' = foldl\' extend_fix_env fix_env new_gres\\n gbl_env\' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env\' }\\n\\n ; traceRn \\"extendGlobalRdrEnvRn 2\\" (pprGlobalRdrEnv True rdr_env2)\\n ; return (gbl_env\', lcl_env3) }\\n where\\n new_names = map greName new_gres\\n new_gres_env = mkGlobalRdrEnv new_gres\\n\\n -- If there is a fixity decl for the gre, add it to the fixity env\\n extend_fix_env fix_env gre\\n | Just (L _ fi) <- lookupMiniFixityEnv new_fixities name\\n = extendNameEnv fix_env name (FixItem occ fi)\\n | otherwise\\n = fix_env\\n where\\n name = greName gre\\n occ = greOccName gre\\n\\n add_gre :: GlobalRdrEnv -> GlobalRdrElt -> RnM GlobalRdrEnv\\n -- Extend the GlobalRdrEnv with a LocalDef GRE\\n -- If there is already a LocalDef GRE with the same OccName,\\n -- report an error and discard the new GRE\\n -- This establishes INVARIANT 1 of GlobalRdrEnvs\\n add_gre env gre\\n | not (null dups) -- Same OccName defined twice\\n = do { addDupDeclErr (gre :| dups); return env }\\n\\n | otherwise\\n = return (extendGlobalRdrEnv env gre)\\n where\\n -- See Note [Reporting duplicate local declarations]\\n dups = filter isBadDupGRE\\n $ lookupGRE env (LookupOccName (greOccName gre) (RelevantGREsFOS WantBoth))\\n isBadDupGRE old_gre = isLocalGRE old_gre && greClashesWith gre old_gre\\n\\n{- Note [Fail fast on duplicate definitions]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIf there are duplicate bindings for the same thing, we want to fail\\nfast. Having two bindings for the same thing can cause follow-on errors.\\nExample (test T9975a):\\n data Test = Test { x :: Int }\\n pattern Test wat = Test { x = wat }\\nThis defines \'Test\' twice. The second defn has no field-names; and then\\nwe get an error from Test { x=wat }, saying \\"Test has no field \'x\'\\".\\n\\nEasiest thing is to bale out fast on duplicate definitions, which\\nwe do via `checkNoErrs` on `extendGlobalRdrEnvRn`.\\n\\nNote [Reporting duplicate local declarations]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn general, a single module may not define the same OccName multiple times. This\\nis checked in extendGlobalRdrEnvRn: when adding a new locally-defined GRE to the\\nGlobalRdrEnv we report an error if there are already duplicates in the\\nenvironment. This establishes INVARIANT 1 (see comments on GlobalRdrEnv in\\nGHC.Types.Name.Reader), which says that for a given OccName, all the\\nGlobalRdrElts to which it maps must have distinct \'greName\'s.\\n\\nFor example, the following will be rejected:\\n\\n f x = x\\n g x = x\\n f x = x -- Duplicate!\\n\\nUsers are allowed to introduce new GREs with the same OccName as an imported GRE,\\nas disambiguation is possible through the module system, e.g.:\\n\\n module M where\\n import N (f)\\n f x = x\\n g x = M.f x + N.f x\\n\\nIf both GREs are local, the general rule is that two GREs clash if they have\\nthe same OccName, i.e. they share a textual name and live in the same namespace.\\nHowever, there are additional clashes due to record fields:\\n\\n - a new variable clashes with previously defined record fields\\n which define field selectors,\\n\\n - a new record field shadows:\\n\\n - previously defined variables, if it defines a field selector,\\n - previously defined record fields, unless it is a duplicate record field.\\n\\nThis logic is implemented in the function \'GHC.Types.Name.Reader.greClashesWith\'.\\n\\nSee also Note [Skipping ambiguity errors at use sites of local declarations] in\\nGHC.Rename.Utils.\\n-}\\n\\n\\n{- *********************************************************************\\n* *\\n getLocalDeclBindersd@ returns the names for an HsDecl\\n It\'s used for source code.\\n\\n *** See Note [The Naming story] in GHC.Hs.Decls ****\\n* *\\n********************************************************************* -}\\n\\ngetLocalNonValBinders :: MiniFixityEnv -> HsGroup GhcPs\\n -> RnM ((TcGblEnv, TcLclEnv), NameSet)\\n-- Get all the top-level binders bound the group *except*\\n-- for value bindings, which are treated separately\\n-- Specifically we return AvailInfo for\\n-- * type decls (incl constructors and record selectors)\\n-- * class decls (including class ops)\\n-- * associated types\\n-- * foreign imports\\n-- * value signatures (in hs-boot files only)\\n\\ngetLocalNonValBinders fixity_env\\n (HsGroup { hs_valds = binds,\\n hs_tyclds = tycl_decls,\\n hs_fords = foreign_decls })\\n = do { -- Process all type/class decls *except* family instances\\n ; let inst_decls = tycl_decls >>= group_instds\\n ; dup_fields_ok <- xopt_DuplicateRecordFields <$> getDynFlags\\n ; has_sel <- xopt_FieldSelectors <$> getDynFlags\\n ; tc_gres\\n <- concatMapM\\n (new_tc dup_fields_ok has_sel)\\n (tyClGroupTyClDecls tycl_decls)\\n ; traceRn \\"getLocalNonValBinders 1\\" (ppr tc_gres)\\n ; envs <- extendGlobalRdrEnvRn tc_gres fixity_env\\n ; restoreEnvs envs $ do {\\n -- Bring these things into scope first\\n -- See Note [Looking up family names in family instances]\\n\\n -- Process all family instances\\n -- to bring new data constructors into scope\\n ; nti_gress <- mapM (new_assoc dup_fields_ok has_sel) inst_decls\\n\\n -- Finish off with value binders:\\n -- foreign decls and pattern synonyms for an ordinary module\\n -- type sigs in case of a hs-boot file only\\n ; is_boot <- tcIsHsBootOrSig\\n ; let val_bndrs\\n | is_boot = case binds of\\n ValBinds _ val_binds ->\\n -- In a hs-boot file, the value binders come from the\\n -- *signatures*, and there should be no foreign binders\\n [ L (l2l decl_loc) (unLoc n)\\n | L decl_loc (TypeSig _ _ ns _) <- (val_sigs val_binds), n <- ns]\\n _ -> panic \\"Non-ValBinds in hs-boot group\\"\\n | otherwise = for_hs_bndrs\\n ; val_gres <- mapM new_simple val_bndrs\\n\\n ; let avails = concat nti_gress ++ val_gres\\n new_bndrs = gresToNameSet avails `unionNameSet`\\n gresToNameSet tc_gres\\n ; traceRn \\"getLocalNonValBinders 2\\" (ppr avails)\\n ; envs <- extendGlobalRdrEnvRn avails fixity_env\\n ; return (envs, new_bndrs) } }\\n where\\n for_hs_bndrs :: [LocatedN RdrName]\\n for_hs_bndrs = hsForeignDeclsBinders foreign_decls\\n\\n -- the SrcSpan attached to the input should be the span of the\\n -- declaration, not just the name\\n new_simple :: LocatedN RdrName -> RnM GlobalRdrElt\\n new_simple rdr_name = do { nm <- newTopSrcBinder rdr_name\\n ; return (mkLocalVanillaGRE NoParent nm) }\\n\\n new_tc :: DuplicateRecordFields -> FieldSelectors -> LTyClDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_tc dup_fields_ok has_sel tc_decl -- NOT for type/data instances\\n = do { let TyDeclBinders (main_bndr, tc_flav) at_bndrs sig_bndrs\\n (LConsWithFields cons_with_flds flds) = hsLTyClDeclBinders tc_decl\\n ; tycon_name <- newTopSrcBinder $ la2la main_bndr\\n ; at_names <- mapM (newTopSrcBinder . la2la . fst) at_bndrs\\n ; sig_names <- mapM (newTopSrcBinder . la2la) sig_bndrs\\n ; con_names_with_flds <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst con_names_with_flds) flds\\n ; mapM_ (add_dup_fld_errs flds\') con_names_with_flds\\n ; let tc_gre = mkLocalTyConGRE (fmap (const tycon_name) tc_flav) tycon_name\\n fld_env = mk_fld_env con_names_with_flds flds\'\\n at_gres = zipWith (\\\\ (_, at_flav) at_nm -> mkLocalTyConGRE (fmap (const tycon_name) at_flav) at_nm)\\n at_bndrs at_names\\n sig_gres = map (mkLocalVanillaGRE (ParentIs tycon_name)) sig_names\\n con_gres = map (mkLocalConLikeGRE (ParentIs tycon_name)) fld_env\\n fld_gres = mkLocalFieldGREs (ParentIs tycon_name) fld_env\\n sub_gres = at_gres ++ sig_gres ++ con_gres ++ fld_gres\\n ; traceRn \\"getLocalNonValBinders new_tc\\" $\\n vcat [ text \\"tycon:\\" <+> ppr tycon_name\\n , text \\"tc_gre:\\" <+> ppr tc_gre\\n , text \\"sub_gres:\\" <+> ppr sub_gres ]\\n ; return $ tc_gre : sub_gres }\\n\\n -- Calculate the record field information, which feeds into the GlobalRdrElts\\n -- for DataCons and their fields. It\'s convenient to do this here where\\n -- we are working with a single datatype definition.\\n --\\n -- The information we needed was all set up for us:\\n -- see Note [Collecting record fields in data declarations] in GHC.Hs.Utils.\\n mk_fld_env :: [(Name, Either VisArity [Located Int])] -> IntMap FieldLabel\\n -> [(ConLikeName, ConInfo)]\\n mk_fld_env names flds =\\n [ (DataConName con, ConInfo (ConIsData (map fst names)) fld_info)\\n | (con, con_fl_indxs) <- names\\n , let fld_info = case fmap (map ((flds IntMap.!) . unLoc)) con_fl_indxs of\\n Left 0 -> ConIsNullary\\n Left arity -> ConHasPositionalArgs arity\\n Right [] -> ConIsNullary\\n Right (fld:flds) -> ConHasRecordFields $ fld NE.:| flds ]\\n\\n new_assoc :: DuplicateRecordFields -> FieldSelectors -> LInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_assoc _ _ (L _ (TyFamInstD {})) = return []\\n -- type instances don\'t bind new names\\n\\n new_assoc dup_fields_ok has_sel (L _ (DataFamInstD _ d))\\n = new_di dup_fields_ok has_sel Nothing d\\n new_assoc dup_fields_ok has_sel\\n (L _ (ClsInstD _ (ClsInstDecl { cid_poly_ty = inst_ty\\n , cid_decls = decls })))\\n = do -- First, attempt to grab the name of the class from the instance.\\n -- This step could fail if the instance is not headed by a class,\\n -- such as in the following examples:\\n --\\n -- (1) The class is headed by a bang pattern, such as in\\n -- `instance !Show Int` (#3811c)\\n -- (2) The class is headed by a type variable, such as in\\n -- `instance c` (#16385)\\n --\\n -- If looking up the class name fails, then mb_cls_gre will\\n -- be Nothing.\\n mb_cls_gre <- runMaybeT $ do\\n -- See (1) above\\n L loc cls_rdr <- MaybeT $ pure $ getLHsInstDeclClass_maybe inst_ty\\n -- See (2) above\\n MaybeT $ setSrcSpan (locA loc) $ lookupGlobalOccRn_maybe SameNameSpace cls_rdr\\n -- Assuming the previous step succeeded, process any associated data\\n -- family instances. If the previous step failed, bail out.\\n case mb_cls_gre of\\n Nothing\\n -> pure []\\n Just cls_gre\\n -> let cls_nm = greName cls_gre\\n in concatMapM (new_di dup_fields_ok has_sel (Just cls_nm) . unLoc) (data_fam_insts decls)\\n\\n data_fam_insts decls = concatMap get decls\\n where\\n get (L l (InstD _ (DataFamInstD { dfid_inst = d}))) = [L l d]\\n get _ = []\\n\\n new_di :: DuplicateRecordFields -> FieldSelectors\\n -> Maybe Name -- class name\\n -> DataFamInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_di dup_fields_ok has_sel mb_cls dfid@(DataFamInstDecl { dfid_eqn = ti_decl })\\n = do { main_name <- unLoc <$> lookupFamInstName mb_cls (feqn_tycon ti_decl)\\n ; let LConsWithFields cons_with_flds flds = hsDataFamInstBinders dfid\\n ; sub_names <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst sub_names) flds\\n ; mapM_ (add_dup_fld_errs flds\') sub_names\\n ; let fld_env = mk_fld_env sub_names flds\'\\n con_gres = map (mkLocalConLikeGRE (ParentIs main_name)) fld_env\\n field_gres = mkLocalFieldGREs (ParentIs main_name) fld_env\\n -- NB: the data family name is not bound here,\\n -- so we don\'t return a GlobalRdrElt for it here!\\n ; return $ con_gres ++ field_gres }\\n\\n -- Add errors if a constructor has a duplicate record field.\\n add_dup_fld_errs :: IntMap FieldLabel\\n -> (Name, Either VisArity [Located Int])\\n -> IOEnv (Env TcGblEnv TcLclEnv) ()\\n add_dup_fld_errs all_flds (con, con_flds_or_arity)\\n | Right con_flds <- con_flds_or_arity\\n , let (_, dups) = removeDups (comparing unLoc) con_flds\\n = for_ dups $ \\\\ dup_flds ->\\n -- Report the error at the location of the second occurrence\\n -- of the duplicate field.\\n let loc =\\n case dup_flds of\\n _ :| ( L loc _ : _) -> loc\\n L loc _ :| _ -> loc\\n dup_rdrs = fmap (nameRdrName . flSelector . (all_flds IntMap.!) . unLoc) dup_flds\\n in addErrAt loc $ TcRnDuplicateFieldName (RecordFieldDecl con) dup_rdrs\\n | otherwise\\n = return ()\\n\\nnewRecordFieldLabel :: DuplicateRecordFields -> FieldSelectors -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel\\nnewRecordFieldLabel _ _ [] _ = error \\"newRecordFieldLabel: datatype has no constructors!\\"\\nnewRecordFieldLabel dup_fields_ok has_sel (dc:_) (L loc (FieldOcc _ (L _ fld)))\\n = do { selName <- newTopSrcBinder $ L (l2l loc) $ field\\n ; return $ FieldLabel { flHasDuplicateRecordFields = dup_fields_ok\\n , flHasFieldSelector = has_sel\\n , flSelector = selName } }\\n where\\n fld_occ = rdrNameOcc fld\\n dc_fs = occNameFS $ nameOccName dc\\n field\\n -- Use an Exact RdrName as-is, to preserve the bindings\\n -- of an already renamer-resolved field and its use\\n -- sites. This is needed to correctly support record\\n -- selectors in Template Haskell. See Note [Binders in\\n -- Template Haskell] in \\"GHC.ThToHs\\" and Note [Looking up\\n -- Exact RdrNames] in \\"GHC.Rename.Env\\".\\n | isExact fld\\n = assertPpr (fieldOcc_maybe fld_occ == Just dc_fs)\\n (vcat [ text \\"newRecordFieldLabel: incorrect namespace for exact Name\\" <+> quotes (ppr fld)\\n , text \\"expected namespace:\\" <+> pprNameSpace (fieldName dc_fs)\\n , text \\" actual namespace:\\" <+> pprNameSpace (occNameSpace fld_occ) ])\\n fld\\n\\n -- Field names produced by the parser are namespaced with VarName.\\n -- Here we namespace them according to the first constructor.\\n -- See Note [Record field namespacing] in GHC.Types.Name.Occurrence.\\n | otherwise\\n = mkRdrUnqual $ varToRecFieldOcc dc_fs fld_occ\\n\\n{-\\nNote [Looking up family names in family instances]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider\\n\\n module M where\\n type family T a :: *\\n type instance M.T Int = Bool\\n\\nWe might think that we can simply use \'lookupOccRn\' when processing the type\\ninstance to look up \'M.T\'. Alas, we can\'t! The type family declaration is in\\nthe *same* HsGroup as the type instance declaration. Hence, as we are\\ncurrently collecting the binders declared in that HsGroup, these binders will\\nnot have been added to the global environment yet.\\n\\nSolution is simple: process the type family declarations first, extend\\nthe environment, and then process the type instances.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Filtering imports}\\n* *\\n************************************************************************\\n\\n@filterImports@ takes the @ExportEnv@ telling what the imported module makes\\navailable, and filters it through the import spec (if any).\\n\\nNote [Dealing with imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nFor import M( ies ), we take each AvailInfo from the mi_exports of M, and make\\n\\n imp_occ_env :: OccEnv (NameEnv ImpOccItem)\\n\\nThis map contains one entry for each OccName that M exports, mapping each OccName\\nto the following information:\\n\\n 1. the GlobalRdrElt corresponding to the OccName,\\n 2. whether this GlobalRdrElt was the parent in the AvailInfo we found\\n the OccName in.\\n 3. the GlobalRdrElts that were bundled together in the AvailInfo we found\\n this OccName in (not including the parent),\\n\\nWe need (2) and (3) during the construction of the OccEnv because of associated\\ntypes and bundled pattern synonyms, respectively.\\n(3) is explained in Note [Importing PatternSynonyms].\\n\\nTo explain (2), consider for example:\\n\\n module M where\\n class C a where { data T a }\\n instance C Int where { data T Int = T1 | T2 }\\n instance C Bool where { data T Int = T3 }\\n\\nHere, M\'s exports avails are (recalling the AvailTC invariant from GHC.Types.Avail)\\n\\n C(C,T), T(T,T1,T2,T3)\\n\\nNotice that T appears *twice*, once as a child and once as a parent. From\\nthese two exports, respectively, during construction of the imp_occ_env, we begin\\nby associating the following two elements with the key T:\\n\\n T -> ImpOccItem { imp_item = gre1, imp_bundled = [C,T] , imp_is_parent = False }\\n T -> ImpOccItem { imp_item = gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nwhere `gre1`, `gre2` are two GlobalRdrElts with greName T.\\nWe combine these (in function \'combine\' in \'mkImportOccEnv\') by discarding the\\nnon-parent item, thusly:\\n\\n T -> IE_ITem { imp_item = gre1 `plusGRE` gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nNote the `plusGRE`: this ensures we don\'t drop parent information;\\nsee Note [Preserve parent information when combining import OccEnvs].\\n\\nSo the overall imp_occ_env is:\\n\\n C -> ImpOccItem { imp_item = C, imp_bundled = [T ], imp_is_parent = True }\\n T -> ImpOccItem { imp_item = T , imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n T1 -> ImpOccItem { imp_item = T1, imp_bundled = [T1,T2,T3], imp_is_parent = False }\\n -- similarly for T2, T3\\n\\nNote that the imp_occ_env will have entries for data constructors too,\\nalthough we never look up data constructors.\\n\\nNote [Importing PatternSynonyms]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nAs described in Note [Dealing with imports], associated types can lead to the\\nsame Name appearing twice, both as a child and once as a parent, when\\nconstructing the imp_occ_env. The same thing can happen with pattern synonyms\\nif they are exported bundled with a type.\\n\\nA simplified example, based on #11959:\\n\\n {-# LANGUAGE PatternSynonyms #-}\\n module M (T(P), pattern P) where -- Duplicate export warning, but allowed\\n data T = MkT\\n pattern P = MkT\\n\\nHere we have T(P) and P in export_avails, and respectively construct both\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n P -> ImpOccItem { imp_item = P, imp_bundled = [] , imp_is_parent = False }\\n\\nWe combine these by dropping the one with no siblings, leaving us with:\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n\\nThat is, we simply discard the non-bundled Avail.\\n\\nNote [Importing DuplicateRecordFields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn filterImports, another complicating factor is DuplicateRecordFields.\\nSuppose we have:\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (S(foo), T(foo)) where\\n data S = MkS { foo :: Int }\\n data T = MkT { foo :: Int }\\n\\n module N where\\n import M (foo) -- this is allowed (A)\\n import M (S(foo)) -- this is allowed (B)\\n\\nHere M exports \'foo\' at two different OccNames, with different namespaces for\\nthe two construtors MkS and MkT. Then, when we look up \'foo\' in lookup_names\\nfor case (A), we have a variable foo but must look in all the record field\\nnamespaces to find the two fields (and hence two different Avails).\\nWhereas in case (B) we reach the lookup_ie case for IEThingWith,\\nwhich looks up \'S\' and then finds the unique \'foo\' amongst its children.\\n\\nSee T16745 for a test of this.\\n\\nNote [Preserve parent information when combining import OccEnvs]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen discarding one ImpOccItem in favour of another, as described in\\nNote [Dealing with imports], we must make sure to combine the GREs so that\\nwe don\'t lose information.\\n\\nConsider for example #24084:\\n\\n module M1 where { class C a where { type T a } }\\n module M2 ( module M1 ) where { import M1 }\\n module M3 where { import M2 ( C, T ); instance C () where T () = () }\\n\\nWhen processing the import list of `M3`, we will have two `Avail`s attached\\nto `T`, namely `C(C, T)` and `T(T)`. We combine them in the `combine` function\\nof `mkImportOccEnv`; as described in Note [Dealing with imports] we discard\\n`C(C, T)` in favour of `T(T)`. However, in doing so, we **must not**\\ndiscard the information want that `C` is the parent of `T`. Indeed,\\nlosing track of this information can cause errors when importing,\\nas we could get an error of the form\\n\\n \\u2018T\\u2019 is not a (visible) associated type of class \\u2018C\\u2019\\n\\nThis explains why we use `plusGRE` when combining the two ImpOccItems, even\\nthough we are discarding one in favour of the other.\\n-}\\n\\n-- | All the \'GlobalRdrElt\'s associated with an \'AvailInfo\'.\\ngresFromAvail :: HasDebugCallStack\\n => HscEnv -> Maybe ImportSpec -> AvailInfo -> [GlobalRdrElt]\\ngresFromAvail hsc_env prov avail =\\n [ mk_gre nm info\\n | nm <- availNames avail\\n , let info = lookupGREInfo hsc_env nm ]\\n where\\n\\n mk_gre n info\\n = case prov of\\n -- Nothing => bound locally\\n -- Just is => imported from \'is\'\\n Nothing -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = True, gre_imp = emptyBag\\n , gre_info = info }\\n Just is -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = False, gre_imp = unitBag is\\n , gre_info = info }\\n\\n-- | All the \'GlobalRdrElt\'s associated with a collection of \'AvailInfo\'s.\\ngresFromAvails :: HscEnv -> Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]\\ngresFromAvails hsc_env prov = concatMap (gresFromAvail hsc_env prov)\\n\\nimportsFromIface :: HscEnv -> ModIface -> ImpDeclSpec -> Maybe NameSet -> GlobalRdrEnv\\nimportsFromIface hsc_env iface decl_spec hidden = mkGlobalRdrEnv $ case hidden of\\n Nothing -> all_gres\\n Just hidden_names -> filter (not . (`elemNameSet` hidden_names) . greName) all_gres\\n where\\n all_gres = gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\nrnNamespaceSpecifier :: NamespaceSpecifier GhcPs -> NamespaceSpecifier GhcRn\\nrnNamespaceSpecifier (NoNamespaceSpecifier _) = NoNamespaceSpecifier noExtField\\nrnNamespaceSpecifier (TypeNamespaceSpecifier x) = TypeNamespaceSpecifier x\\nrnNamespaceSpecifier (DataNamespaceSpecifier x) = DataNamespaceSpecifier x\\n\\nfilterImports\\n :: HasDebugCallStack\\n => HscEnv\\n -> ModIface\\n -> ImpDeclSpec\\n -- ^ Import spec\\n -> Maybe (ImportListInterpretation, [LIE GhcPs])\\n -- ^ Whether this is a \\"hiding\\" import list\\n -> RnM (Maybe (ImportListInterpretation, [LIE GhcRn]), -- Import spec w/ Names\\n ImpUserList, -- same, but designed for storage in interfaces\\n GlobalRdrEnv) -- Same again, but in GRE form\\nfilterImports hsc_env iface decl_spec Nothing\\n = return (Nothing, ImpUserAll, importsFromIface hsc_env iface decl_spec Nothing)\\nfilterImports hsc_env iface decl_spec (Just (want_hiding, import_items))\\n = do -- check for errors, convert RdrNames to Names\\n items1 <- mapM lookup_lie import_items\\n\\n let items2 :: [(LIE GhcRn, [GlobalRdrElt])]\\n items2 = concat items1\\n -- NB we may have duplicates, and several items\\n -- for the same parent; e.g N(x) and N(y)\\n\\n (gres, imp_user_list) = case want_hiding of\\n Exactly ->\\n let gres = concatMap (gresFromIE decl_spec) items2\\n gre_env = mkGlobalRdrEnv gres\\n implicit_parents = mkNameSet $ mapMaybe parentOfImplicitlyImportedGRE gres\\n in (gre_env, ImpUserExplicit (gresToAvailInfo $ globalRdrEnvElts $ gre_env) implicit_parents)\\n EverythingBut ->\\n let hidden_names = mkNameSet $ concatMap (map greName . snd) items2\\n in (importsFromIface hsc_env iface decl_spec (Just hidden_names), ImpUserEverythingBut hidden_names)\\n\\n return (Just (want_hiding, map fst items2), imp_user_list, gres)\\n where\\n import_mod = mi_module iface\\n all_avails = mi_exports iface\\n imp_occ_env = mkImportOccEnv hsc_env decl_spec all_avails\\n\\n -- Look up a parent (type constructor, class or data constructor)\\n -- in an import.\\n lookup_parent :: IE GhcPs -> RdrName -> IELookupM ImpOccItem\\n lookup_parent ie rdr =\\n assertPpr (not $ isVarNameSpace ns)\\n (vcat [ text \\"filterImports lookup_parent: unexpected variable\\"\\n , text \\"rdr:\\" <+> ppr rdr\\n , text \\"namespace:\\" <+> pprNameSpace ns ]) $\\n do { xs <- lookup_names ie rdr\\n ; case xs of\\n cax :| [] -> return cax\\n _ -> pprPanic \\"filter_imports lookup_parent ambiguous\\" $\\n vcat [ text \\"rdr:\\" <+> ppr rdr\\n , text \\"lookups:\\" <+> ppr (fmap imp_item xs) ] }\\n -- Looking up non-variables is always unambiguous,\\n -- as there can be at most one corresponding item\\n -- in the imp_occ_env.\\n -- See item (1) of Note [Exporting duplicate declarations]\\n -- in GHC.Tc.Gen.Export.\\n where\\n occ = rdrNameOcc rdr\\n ns = occNameSpace occ\\n\\n -- Look up a RdrName used in an import, returning multiple values if there\\n -- are several fields with the same name exposed by the module\\n lookup_names :: IE GhcPs -> RdrName -> IELookupM (NonEmpty ImpOccItem)\\n lookup_names ie rdr\\n | isQual rdr\\n = failLookupWith (QualImportError rdr)\\n | otherwise\\n = case lookups of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n item:items -> return $ item :| items\\n where\\n lookups = concatMap nonDetNameEnvElts\\n $ lookupImpOccEnv (RelevantGREsFOS WantNormal) imp_occ_env (rdrNameOcc rdr)\\n\\n lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, [GlobalRdrElt])]\\n lookup_lie (L loc ieRdr)\\n = setSrcSpanA loc $\\n do (stuff, warns) <- run_lookup ([],[]) (lookup_ie ieRdr)\\n mapM_ (addTcRnDiagnostic <=< warning_msg) warns\\n return [ (L loc ie, gres) | (ie,gres) <- stuff ]\\n where\\n\\n -- Warn when importing T(..) and no children are brought in scope\\n warning_msg (DodgyImport reason) =\\n pure (TcRnDodgyImports reason)\\n warning_msg MissingImportList =\\n pure (TcRnMissingImportList ieRdr)\\n warning_msg (BadImportW ie sub) = do\\n -- \'BadImportW\' is only constructed below in \'bad_import_w\', in\\n -- the \'EverythingBut\' case, so here we assume a \'hiding\' clause.\\n (reason :| _) <- badImportItemErr iface decl_spec ie sub all_avails\\n pure (TcRnDodgyImports (DodgyImportsHiding reason))\\n warning_msg (DeprecatedExport n w) =\\n pure $ TcRnPragmaWarning\\n PragmaWarningExport\\n { pwarn_occname = occName n\\n , pwarn_impmod = moduleName import_mod }\\n w\\n\\n run_lookup :: a -> IELookupM a -> TcRn a\\n run_lookup def m = case m of\\n Failed err -> do\\n msgs <- lookup_err_msgs err\\n forM_ msgs $ \\\\msg -> addErr (TcRnImportLookup msg)\\n return def\\n Succeeded a -> return a\\n\\n lookup_err_msgs err = case err of\\n BadImport ie sub -> badImportItemErr iface decl_spec ie sub all_avails\\n IllegalImport -> pure $ NE.singleton ImportLookupIllegal\\n QualImportError rdr -> pure $ NE.singleton (ImportLookupQualified rdr)\\n\\n -- For each import item, we convert its RdrNames to Names,\\n -- and at the same time compute all the GlobalRdrElt corresponding\\n -- to what is actually imported by this item.\\n -- Returns Nothing on error.\\n --\\n -- Returns a list because, with DuplicateRecordFields, a naked\\n -- import/export of a record field can correspond to multiple\\n -- different GlobalRdrElts. See Note [Importing DuplicateRecordFields].\\n lookup_ie :: IE GhcPs\\n -> IELookupM ([(IE GhcRn, [GlobalRdrElt])], [IELookupWarning])\\n lookup_ie ie = handle_bad_import $\\n case ie of\\n IEVar _ (L l n) _ -> do\\n -- See Note [Importing DuplicateRecordFields]\\n xs <- lookup_names ie (ieWrappedName n)\\n let gres = map imp_item $ NE.toList xs\\n export_depr_warns\\n | want_hiding == Exactly\\n = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ( [ (IEVar Nothing (L l (replaceWrappedName n name)) noDocstring, [gre])\\n | gre <- gres\\n , let name = greName gre ]\\n , export_depr_warns )\\n\\n IEThingAll x ns_spec (L l tc) _ -> do\\n ImpOccItem { imp_item = gre\\n , imp_bundled = bundled_gres\\n , imp_is_parent = is_par\\n }\\n <- lookup_parent ie $ ieWrappedName tc\\n let name = greName gre\\n\\n child_gres :: [GlobalRdrElt]\\n child_gres\\n | is_par = filterByNamespaceSpecifierGREs ns_spec bundled_gres\\n | otherwise = []\\n\\n imp_list_warn\\n\\n | null child_gres\\n -- e.g. f(..) or T(..) where T is a type synonym\\n = [DodgyImport (DodgyImportsEmptyParent ie ns_spec gre)]\\n\\n -- e.g. import M( T(..) )\\n | not (is_qual decl_spec)\\n = [MissingImportList]\\n\\n | otherwise\\n = []\\n\\n renamed_ie = IEThingAll (x { ieta_warning = Nothing })\\n (rnNamespaceSpecifier ns_spec)\\n (L l (replaceWrappedName tc name))\\n noDocstring\\n export_depr_warn\\n | want_hiding == Exactly\\n = maybeToList $ mk_depr_export_warning gre\\n -- We don\'t want to warn about the children as they\\n -- are not explicitly mentioned; the warning will\\n -- be emitted later on if they are used\\n | otherwise = []\\n\\n return ( [(renamed_ie, gre:child_gres)]\\n , imp_list_warn ++ export_depr_warn)\\n\\n\\n IEThingAbs _ (L l tc\') _\\n | want_hiding == EverythingBut -- hiding ( C )\\n -- Here the \'C\' can be a data constructor\\n -- *or* a type/class, or even both\\n -> let tc = ieWrappedName tc\'\\n tc_name = lookup_parent ie tc\\n dc_name = lookup_parent ie (setRdrNameSpace tc srcDataName)\\n in\\n case catIELookupM [ tc_name, dc_name ] of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n names -> return ( [mkIEThingAbs tc\' l (imp_item name) | name <- names], [])\\n | otherwise\\n -> do ImpOccItem { imp_item = gre } <- lookup_parent ie (ieWrappedName tc\')\\n return ( [mkIEThingAbs tc\' l gre]\\n , maybeToList $ mk_depr_export_warning gre)\\n\\n IEThingWith (deprecation, ann) ltc@(L l rdr_tc) wc rdr_ns _ -> do\\n ImpOccItem { imp_item = gre, imp_bundled = subnames }\\n <- lookup_parent (IEThingAbs Nothing ltc noDocstring) (ieWrappedName rdr_tc)\\n let name = greName gre\\n\\n -- Look up the children in the sub-names of the parent\\n -- See Note [Importing DuplicateRecordFields]\\n let (children_errs, childnames) = lookupChildren subnames rdr_ns\\n\\n bad_import_warns <-\\n if null children_errs then return [] else\\n let items = map lce_wrapped_name children_errs\\n ie = IEThingWith (deprecation, ann) ltc wc items noDocstring\\n -- We are trying to import T( a,b,c,d ), and failed\\n -- to find \'b\' and \'d\'. So we make up an import item\\n -- to report as failing, namely T( b, d ).\\n -- c.f. #15413\\n subordinate_err = mkSubordinateError gre children_errs\\n in bad_import_w ie subordinate_err\\n\\n let name\' = replaceWrappedName rdr_tc name\\n childnames\' = map (to_ie_post_rn . fmap greName) childnames\\n gres = gre : map unLoc childnames\\n export_depr_warns\\n | want_hiding == Exactly = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ([ (IEThingWith (Nothing, ann) (L l name\') wc childnames\' noDocstring\\n ,gres)]\\n , bad_import_warns ++ export_depr_warns)\\n\\n IEWholeNamespace x ns_spec -> do\\n let mod_name = moduleName import_mod\\n names = map greName gres\\n renamed_ie = IEWholeNamespace x { iewn_warning = Nothing\\n , iewn_names = names }\\n (rnNamespaceSpecifier ns_spec)\\n gres = filterByNamespaceSpecifierGREs ns_spec $\\n gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n dodgy_warn\\n | null gres = [DodgyImport (DodgyImportsWildcard mod_name ns_spec)]\\n | otherwise = []\\n return ([(renamed_ie, gres)],\\n dodgy_warn)\\n\\n _other -> failLookupWith IllegalImport\\n -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed...\\n -- all of those constitute errors.\\n\\n where\\n mkIEThingAbs tc l gre\\n = (IEThingAbs Nothing (L l (replaceWrappedName tc n)) noDocstring, [gre])\\n where n = greName gre\\n\\n -- N.B. imports never have docstrings\\n noDocstring = Nothing\\n\\n handle_bad_import m = catchIELookup m $ \\\\case\\n BadImport ie sub -> do\\n ws <- bad_import_w ie sub\\n return ([], ws)\\n err -> failLookupWith err\\n\\n bad_import_w :: IE GhcPs -> IsSubordinateError -> IELookupM [IELookupWarning]\\n bad_import_w ie sub\\n | want_hiding == EverythingBut = return [BadImportW ie sub]\\n | otherwise = failLookupWith (BadImport ie sub)\\n\\n mk_depr_export_warning gre\\n = DeprecatedExport name <$> mi_export_warn_fn iface name\\n where\\n name = greName gre\\n\\n-- | Assuming a subordinate item could not be found, do another lookup for a\\n-- more specific error message.\\nmkBadExportSubordinate :: [GlobalRdrElt] -> LIEWrappedName GhcPs -> BadExportSubordinate\\nmkBadExportSubordinate child_gres n =\\n case lookupChildren child_gres [n] of\\n (LookupChildNonType {lce_nontype_item = g} : _, _) -> BadExportSubordinateNonType g\\n (LookupChildNonData {lce_nondata_item = g} : _, _) -> BadExportSubordinateNonData g\\n _ -> BadExportSubordinateNotFound n\\n\\ntype IELookupM = MaybeErr IELookupError\\n\\ndata IELookupWarning\\n = BadImportW (IE GhcPs) IsSubordinateError\\n | MissingImportList\\n | DodgyImport DodgyImportsReason\\n | DeprecatedExport Name (WarningTxt GhcRn)\\n\\n-- | Is this import/export item a subordinate or not?\\ndata IsSubordinateError\\n = IsSubordinateError { subordinate_err_parent :: !GlobalRdrElt\\n , subordinate_err_unavailable :: [FastString]\\n , subordinate_err_nontype :: [GlobalRdrElt]\\n , subordinate_err_nondata :: [GlobalRdrElt] }\\n | IsNotSubordinate\\n\\nmkSubordinateError :: GlobalRdrElt -> [LookupChildError] -> IsSubordinateError\\nmkSubordinateError gre children_errs = foldr add init_acc children_errs\\n where\\n init_acc :: IsSubordinateError\\n init_acc = IsSubordinateError gre [] [] []\\n\\n add :: LookupChildError -> IsSubordinateError -> IsSubordinateError\\n add children_err sub@IsSubordinateError{} =\\n case children_err of\\n LookupChildNonType{lce_nontype_item = g} ->\\n sub { subordinate_err_nontype = g : subordinate_err_nontype sub }\\n LookupChildNonData{lce_nondata_item = g} ->\\n sub { subordinate_err_nondata = g : subordinate_err_nondata sub }\\n LookupChildNotFound (L _ wname) ->\\n let fs = (occNameFS . rdrNameOcc . ieWrappedName) wname\\n in sub { subordinate_err_unavailable = fs : subordinate_err_unavailable sub }\\n add _ IsNotSubordinate = panic \\"mkSubordinateError: IsNotSubordinate\\"\\n\\ndata IELookupError\\n = QualImportError RdrName\\n | BadImport (IE GhcPs) IsSubordinateError\\n | IllegalImport\\n\\nfailLookupWith :: IELookupError -> IELookupM a\\nfailLookupWith err = Failed err\\n\\ncatchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a\\ncatchIELookup m h = case m of\\n Succeeded r -> return r\\n Failed err -> h err\\n\\ncatIELookupM :: [IELookupM a] -> [a]\\ncatIELookupM ms = [ a | Succeeded a <- ms ]\\n\\n-- | Information associated to an \'AvailInfo\' used in constructing\\n-- an \'OccEnv\' corresponding to imports.\\n--\\n-- See Note [Dealing with imports].\\ndata ImpOccItem\\n = ImpOccItem\\n { imp_item :: GlobalRdrElt\\n -- ^ The import item\\n , imp_bundled :: [GlobalRdrElt]\\n -- ^ Items bundled in the Avail this import item came from,\\n -- not including the import item itself if it is a parent.\\n , imp_is_parent :: Bool\\n -- ^ Is the import item a parent? See Note [Dealing with imports].\\n }\\n\\ninstance Outputable ImpOccItem where\\n ppr (ImpOccItem { imp_item = item, imp_bundled = bundled, imp_is_parent = is_par })\\n = braces $ hsep\\n [ text \\"ImpOccItem\\"\\n , if is_par then text \\"[is_par]\\" else empty\\n , ppr (greName item) <+> ppr (greParent item)\\n , braces $ text \\"bundled:\\" <+> ppr (map greName bundled) ]\\n\\n-- | Make an \'OccEnv\' of all the imports.\\n--\\n-- Complicated by the fact that associated data types and pattern synonyms\\n-- can appear twice. See Note [Dealing with imports].\\nmkImportOccEnv :: HscEnv -> ImpDeclSpec -> [IfaceExport] -> OccEnv (NameEnv ImpOccItem)\\nmkImportOccEnv hsc_env decl_spec all_avails =\\n mkOccEnv_C (plusNameEnv_C combine)\\n [ (occ, mkNameEnv [(nm, item)])\\n | avail <- all_avails\\n , let gres = gresFromAvail hsc_env (Just hiding_spec) avail\\n , gre <- gres\\n , let nm = greName gre\\n occ = greOccName gre\\n (is_parent, bundled) = case avail of\\n AvailTC c _\\n | c == nm -- (Recall the AvailTC invariant from GHC.Types.AvailInfo)\\n -> ( True, drop 1 gres ) -- \\"drop 1\\": don\'t include the parent itself.\\n | otherwise\\n -> ( False, gres )\\n _ -> ( False, [] )\\n item = ImpOccItem\\n { imp_item = gre\\n , imp_bundled = bundled\\n , imp_is_parent = is_parent }\\n ]\\n where\\n\\n hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\n -- See Note [Dealing with imports]\\n -- \'combine\' may be called for associated data types which appear\\n -- twice in the all_avails. In the example, we have two Avails for T,\\n -- namely T(T,T1,T2,T3) and C(C,T), and we combine them by dropping the\\n -- latter, in which T is not the parent.\\n combine :: ImpOccItem -> ImpOccItem -> ImpOccItem\\n combine item1@(ImpOccItem { imp_item = gre1, imp_is_parent = is_parent1 })\\n item2@(ImpOccItem { imp_item = gre2, imp_is_parent = is_parent2 })\\n | is_parent1 || is_parent2\\n , not (isRecFldGRE gre1 || isRecFldGRE gre2) -- NB: does not force GREInfo.\\n , let name1 = greName gre1\\n name2 = greName gre2\\n gre = gre1 `plusGRE` gre2\\n -- See Note [Preserve parent information when combining import OccEnvs]\\n = assertPpr (name1 == name2)\\n (ppr name1 <+> ppr name2) $\\n if is_parent1\\n then item1 { imp_item = gre }\\n else item2 { imp_item = gre }\\n -- Discard C(C,T) in favour of T(T, T1, T2, T3).\\n\\n -- \'combine\' may also be called for pattern synonyms which appear both\\n -- unassociated and associated (see Note [Importing PatternSynonyms]).\\n combine item1@(ImpOccItem { imp_item = c1, imp_bundled = kids1 })\\n item2@(ImpOccItem { imp_item = c2, imp_bundled = kids2 })\\n = assertPpr (greName c1 == greName c2\\n && (not (null kids1 && null kids2)))\\n (ppr c1 <+> ppr c2 <+> ppr kids1 <+> ppr kids2) $\\n if null kids1\\n then item2\\n else item1\\n -- Discard standalone pattern P in favour of T(P).\\n\\n-- | Essentially like @lookupGRE env (LookupOccName occ which_gres)@,\\n-- but working with \'ImpOccItem\'s instead of \'GlobalRdrElt\'s.\\nlookupImpOccEnv :: WhichGREs GREInfo\\n -> OccEnv (NameEnv ImpOccItem) -> OccName -> [NameEnv ImpOccItem]\\nlookupImpOccEnv which_gres env occ =\\n mapMaybe relevant_items $ lookupOccEnv_AllNameSpaces env occ\\n where\\n is_relevant :: ImpOccItem -> Bool\\n is_relevant (ImpOccItem { imp_item = gre }) =\\n greIsRelevant which_gres (occNameSpace occ) gre\\n relevant_items :: NameEnv ImpOccItem -> Maybe (NameEnv ImpOccItem)\\n relevant_items nms\\n | let nms\' = filterNameEnv is_relevant nms\\n = if isEmptyNameEnv nms\'\\n then Nothing\\n else Just nms\'\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{Import/Export Utils}\\n* *\\n************************************************************************\\n-}\\n\\n-- | Given an import\\\\/export spec, appropriately set the @gre_imp@ field\\n-- for the \'GlobalRdrElt\'s.\\ngresFromIE :: ImpDeclSpec -> (LIE GhcRn, [GlobalRdrElt]) -> [GlobalRdrElt]\\ngresFromIE decl_spec (L loc ie, gres)\\n = map set_gre_imp gres\\n where\\n is_explicit = case ie of\\n IEThingAll _ _ name _ -> \\\\n -> n == lieWrappedName name\\n IEWholeNamespace _ _ -> \\\\_ -> False\\n _ -> \\\\_ -> True\\n prov_fn name\\n = ImpSpec { is_decl = decl_spec, is_item = item_spec }\\n where\\n item_spec = ImpSome { is_explicit = is_explicit name\\n , is_iloc = locA loc }\\n set_gre_imp gre@( GRE { gre_name = nm } )\\n = gre { gre_imp = unitBag $ prov_fn nm }\\n\\nparentOfImplicitlyImportedGRE :: Outputable info => GlobalRdrEltX info -> Maybe Name\\nparentOfImplicitlyImportedGRE gre =\\n if any (explicit_import . is_item) $ gre_imp gre\\n then Nothing\\n else greParent_maybe gre\\n where\\n explicit_import :: ImpItemSpec -> Bool\\n explicit_import (ImpAll {}) =\\n pprPanic \\"parentOfImplicitlyImportedGRE: ImpAll\\" (ppr gre)\\n explicit_import (ImpSome { is_explicit }) = is_explicit\\n\\n{- Note [Children for duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider the module\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (F(foo, MkFInt, MkFBool)) where\\n data family F a\\n data instance F Int = MkFInt { foo :: Int }\\n data instance F Bool = MkFBool { foo :: Bool }\\n\\nThe `foo` in the export list refers to *both* selectors! For this\\nreason, lookupChildren builds an environment that maps the FastString\\nto a list of items, rather than a single item.\\n-}\\n\\nmkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]\\nmkChildEnv gres = foldr add emptyNameEnv gres\\n where\\n add gre env = case greParent gre of\\n ParentIs p -> extendNameEnv_Acc (:) Utils.singleton env p gre\\n NoParent -> env\\n\\nfindChildren :: NameEnv [a] -> Name -> [a]\\nfindChildren env n = lookupNameEnv env n `orElse` []\\n\\ndata LookupChildError\\n = LookupChildNotFound { lce_wrapped_name :: !(LIEWrappedName GhcPs) }\\n | LookupChildNonType { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nontype_item :: !GlobalRdrElt }\\n | LookupChildNonData { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nondata_item :: !GlobalRdrElt }\\n\\nlookupChildren :: [GlobalRdrElt]\\n -> [LIEWrappedName GhcPs]\\n -> ( [LookupChildError] -- The ones for which the lookup failed\\n , [LocatedA GlobalRdrElt] )\\n-- (lookupChildren all_kids rdr_items) maps each rdr_item to its\\n-- corresponding Name in all_kids, if the former exists\\n-- The matching is done by FastString, not OccName, so that\\n-- Cls( meth, AssocTy )\\n-- will correctly find AssocTy among the all_kids of Cls, even though\\n-- the RdrName for AssocTy may have a (bogus) DataName namespace\\n-- (Really the rdr_items should be FastStrings in the first place.)\\nlookupChildren all_kids rdr_items = (fails, successes)\\n where\\n mb_xs = map do_one rdr_items\\n fails = [ err | Failed err <- mb_xs ]\\n successes = [ ok | Succeeded oks <- mb_xs, ok <- NE.toList oks ]\\n\\n do_one :: LIEWrappedName GhcPs -> MaybeErr LookupChildError (NonEmpty (LocatedA GlobalRdrElt))\\n do_one item@(L l r) =\\n case r of\\n IEName{}\\n -- IEName (unadorned name) places no restriction on the namespace of\\n -- the imported entity, so we look in both `val_gres` and `typ_gres`.\\n -- In case of conflict (punning), the value namespace takes priority.\\n -- See Note [Prioritise the value namespace in subordinate import lists]\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEType{}\\n -- IEType (\'type\' namespace specifier) restricts the lookup to the\\n -- type namespace, i.e. to `typ_gres`. In case of failure, we check\\n -- `val_gres` to produce a more helpful error message.\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- val_gres -> Failed $ LookupChildNonType item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEData{}\\n -- IEData (\'data\' namespace specifier) restricts the lookup to the\\n -- data namespace, i.e. to `val_gres`. In case of failure, we check\\n -- `typ_gres` to produce a more helpful error message.\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- typ_gres -> Failed $ LookupChildNonData item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEPattern{} -> panic \\"lookupChildren: IEPattern\\" -- Never happens (invalid syntax)\\n IEDefault{} -> panic \\"lookupChildren: IEDefault\\" -- Never happens (invalid syntax)\\n where\\n fs = (occNameFS . rdrNameOcc . ieWrappedName) r\\n gres = fromMaybe [] (lookupFsEnv kid_env fs)\\n (val_gres, typ_gres) = partition (isValNameSpace . greNameSpace) gres\\n\\n -- See Note [Children for duplicate record fields]\\n kid_env :: FastStringEnv [GlobalRdrElt]\\n kid_env = extendFsEnvList_C (++) emptyFsEnv\\n [(occNameFS (occName x), [x]) | x <- all_kids]\\n\\n\\n{- Note [Prioritise the value namespace in subordinate import lists]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider this program that defines a class that has both an associated type\\nnamed (#) and a method named (#)\\n\\n module M_assoc where\\n class C a b where\\n type a # b\\n (#) :: a -> b -> ()\\n module N_assoc where\\n import M_assoc( C((#)) )\\n\\nIn the import declaration, when we see the unadorned name (#) in the subordinate\\nimport list of C, which children should we bring into scope? Our options are:\\n\\n a) only the method (#)\\n b) only the associated type (#)\\n c) both the method and the associated type\\n\\nTo follow the precedent established by top-level items, we go with option (a).\\nIndeed, consider a slightly different program\\n\\n module M_top where\\n type family a # b\\n a # b = ()\\n module N_top where\\n import M_top( (#) )\\n\\nHere the import brings only the function (#) into scope, and one has to say\\n`type (#)` to get the type family.\\n-}\\n\\n-------------------------------\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused names}\\n* *\\n*********************************************************\\n-}\\n\\nreportUnusedNames :: TcGblEnv -> HscSource -> RnM ()\\nreportUnusedNames gbl_env hsc_src\\n = do { keep <- readTcRef (tcg_keep gbl_env)\\n ; traceRn \\"RUN\\" (ppr (tcg_dus gbl_env))\\n ; warnUnusedImportDecls gbl_env hsc_src\\n ; warnUnusedTopBinds $ unused_locals keep\\n ; warnMissingSignatures gbl_env\\n ; warnMissingKindSignatures gbl_env }\\n where\\n used_names :: NameSet -> NameSet\\n used_names keep = findUses (tcg_dus gbl_env) emptyNameSet `unionNameSet` keep\\n -- NB: currently, if f x = g, we only treat \'g\' as used if \'f\' is used\\n -- Hence findUses\\n\\n -- Collect the defined names from the in-scope environment\\n defined_names :: [GlobalRdrElt]\\n defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)\\n\\n kids_env = mkChildEnv defined_names\\n -- This is done in mkExports too; duplicated work\\n\\n gre_is_used :: NameSet -> GlobalRdrElt -> Bool\\n gre_is_used used_names gre0\\n = name `elemNameSet` used_names\\n || any (\\\\ gre -> greName gre `elemNameSet` used_names) (findChildren kids_env name)\\n -- A use of C implies a use of T,\\n -- if C was brought into scope by T(..) or T(C)\\n where\\n name = greName gre0\\n\\n -- Filter out the ones that are\\n -- (a) defined in this module, and\\n -- (b) not defined by a \'deriving\' clause\\n -- The latter have an Internal Name, so we can filter them out easily\\n unused_locals :: NameSet -> [GlobalRdrElt]\\n unused_locals keep =\\n let -- Note that defined_and_used, defined_but_not_used\\n -- are both [GRE]; that\'s why we need defined_and_used\\n -- rather than just used_names\\n _defined_and_used, defined_but_not_used :: [GlobalRdrElt]\\n (_defined_and_used, defined_but_not_used)\\n = partition (gre_is_used (used_names keep)) defined_names\\n\\n in filter is_unused_local defined_but_not_used\\n is_unused_local :: GlobalRdrElt -> Bool\\n is_unused_local gre = isLocalGRE gre\\n && isExternalName (greName gre)\\n\\n{- *********************************************************************\\n* *\\n Missing signatures\\n* *\\n********************************************************************* -}\\n\\n{-\\nNote [Missing signatures]\\n~~~~~~~~~~~~~~~~~~~~~~~~~\\nThere are four warning flags in play:\\n\\n * -Wmissing-exported-signatures\\n Warn about any exported top-level function/value without a type signature.\\n Does not include pattern synonyms.\\n\\n * -Wmissing-signatures\\n Warn about any top-level function/value without a type signature. Does not\\n include pattern synonyms. Takes priority over -Wmissing-exported-signatures.\\n\\n * -Wmissing-exported-pattern-synonym-signatures\\n Warn about any exported pattern synonym without a type signature.\\n\\n * -Wmissing-pattern-synonym-signatures\\n Warn about any pattern synonym without a type signature. Takes priority over\\n -Wmissing-exported-pattern-synonym-signatures.\\n\\n-}\\n\\n-- | Warn the user about top level binders that lack type signatures.\\n-- Called /after/ type inference, so that we can report the\\n-- inferred type of the function\\nwarnMissingSignatures :: TcGblEnv -> RnM ()\\nwarnMissingSignatures gbl_env\\n = do { let exports = availsToNameSet (tcg_exports gbl_env)\\n sig_ns = tcg_sigs gbl_env\\n -- We use sig_ns to exclude top-level bindings that are generated by GHC\\n binds = collectHsBindsBinders CollNoDictBinders $ tcg_binds gbl_env\\n pat_syns = tcg_patsyns gbl_env\\n\\n not_ghc_generated :: Name -> Bool\\n not_ghc_generated name = name `elemNameSet` sig_ns\\n\\n add_binding_warn :: Id -> RnM ()\\n add_binding_warn id =\\n when (not_ghc_generated name) $\\n do { env <- liftZonkM $ tcInitTidyEnv -- Why not use emptyTidyEnv?\\n ; let ty = tidyOpenType env (idType id)\\n missing = MissingTopLevelBindingSig name ty\\n diag = TcRnMissingSignature missing exported\\n ; addDiagnosticAt (getSrcSpan name) diag }\\n where\\n name = idName id\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n add_patsyn_warn :: PatSyn -> RnM ()\\n add_patsyn_warn ps =\\n when (not_ghc_generated name) $\\n addDiagnosticAt (getSrcSpan name)\\n (TcRnMissingSignature missing exported)\\n where\\n name = patSynName ps\\n missing = MissingPatSynSig ps\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n -- Warn about missing signatures\\n -- Do this only when we have a type to offer\\n -- See Note [Missing signatures]\\n ; mapM_ add_binding_warn binds\\n ; mapM_ add_patsyn_warn pat_syns\\n }\\n\\n-- | Warn the user about tycons that lack kind signatures.\\n-- Called /after/ type (and kind) inference, so that we can report the\\n-- inferred kinds.\\nwarnMissingKindSignatures :: TcGblEnv -> RnM ()\\nwarnMissingKindSignatures gbl_env\\n = do { cusks_enabled <- xoptM LangExt.CUSKs\\n ; mapM_ (add_ty_warn cusks_enabled) tcs\\n }\\n where\\n tcs = tcg_tcs gbl_env\\n ksig_ns = tcg_ksigs gbl_env\\n exports = availsToNameSet (tcg_exports gbl_env)\\n\\n has_kind_signature :: Name -> Bool\\n has_kind_signature name = name `elemNameSet` ksig_ns\\n\\n add_ty_warn :: Bool -> TyCon -> RnM ()\\n add_ty_warn cusks_enabled tyCon =\\n when (has_kind_signature name) $\\n addDiagnosticAt (getSrcSpan name) diag\\n where\\n name = tyConName tyCon\\n diag = TcRnMissingSignature missing exported\\n missing = MissingTyConKindSig tyCon cusks_enabled\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused imports}\\n* *\\n*********************************************************\\n\\nThis code finds which import declarations are unused. The\\nspecification and implementation notes are here:\\n https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/unused-imports\\n\\nSee also Note [Choosing the best import declaration] in GHC.Types.Name.Reader\\n-}\\n\\ntype ImportDeclUsage\\n = ( LImportDecl GhcRn -- The import declaration\\n , [GlobalRdrElt] -- What *is* used (normalised)\\n , [Name] -- What is imported but *not* used\\n , [NamespaceSpecifier GhcRn] ) -- Unused wildcards\\n\\nwarnUnusedImportDecls :: TcGblEnv -> HscSource -> RnM ()\\nwarnUnusedImportDecls gbl_env hsc_src\\n = do { uses <- readMutVar (tcg_used_gres gbl_env)\\n ; let imports = tcg_rn_imports gbl_env\\n rdr_env = tcg_rdr_env gbl_env\\n\\n -- We should only warn for unnecessary *user* imports, but deciding\\n -- minimal imports should take generated imports into account\\n ; let usageUserImports = findImportUsage (excludeGenerated imports) uses\\n usageAllImports = findImportUsage imports uses\\n\\n ; traceRn \\"warnUnusedImportDecls\\" $\\n (vcat [ text \\"Uses:\\" <+> ppr uses\\n , text \\"Usage all user imports: \\" <+> ppr usageUserImports\\n , text \\"Usage all imports: \\" <+> ppr usageAllImports])\\n\\n ; mapM_ (warnUnusedImport rdr_env) usageUserImports\\n\\n ; whenGOptM Opt_D_dump_minimal_imports $\\n printMinimalImports hsc_src usageAllImports }\\n\\n-- | Exclude generated imports\\nexcludeGenerated :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\nexcludeGenerated = filterOut (isGeneratedImport . ideclOrigin . ideclExt . unLoc)\\n\\nfindImportUsage :: [LImportDecl GhcRn]\\n -> [GlobalRdrElt]\\n -> [ImportDeclUsage]\\n\\nfindImportUsage imports used_gres\\n = map unused_decl imports\\n where\\n import_usage :: ImportMap\\n import_usage = mkImportMap used_gres\\n\\n unused_decl :: LImportDecl GhcRn -> ImportDeclUsage\\n unused_decl decl@(L _ (ImportDecl { ideclImportList = imps }))\\n = -- pprTrace \\"unused_decl\\" (vcat [ ppr decl\\n -- , text \\"used\\" <+> ppr used_gres\\n -- , text \\"unused\\" <+> ppr unused_names ]) $\\n (decl, used_gres, unused_names, unused_wcs)\\n where\\n used_gres = lookupImportMap decl import_usage\\n\\n used_gre_env = mkGlobalRdrEnv used_gres\\n used_parents = mkNameSet (mapMaybe greParent_maybe used_gres)\\n\\n (unused_names, unused_wcs) -- Not trivial; see eg #7454\\n = case imps of\\n Just (Exactly, imp_ies) ->\\n let unused = foldr (add_unused . unLoc) emptyUnusedNames imp_ies\\n nms = nameSetElemsStable (collectUnusedNames unused)\\n wcs = collectUnusedWildcards unused\\n in (nms, wcs)\\n _other -> ([], []) -- No explicit import list => no unused-name list\\n\\n add_unused :: IE GhcRn -> UnusedNames -> UnusedNames\\n add_unused (IEVar _ n _) acc = add_unused_name (lieWrappedName n) True acc\\n add_unused (IEThingAbs _ n _) acc = add_unused_name (lieWrappedName n) False acc\\n add_unused (IEThingAll _ _ n _) acc = add_unused_all (lieWrappedName n) acc\\n add_unused (IEThingWith _ p wc ns _) acc = add_wc_all (add_unused_with pn xs acc)\\n where pn = lieWrappedName p\\n xs = map lieWrappedName ns\\n add_wc_all = case wc of\\n NoIEWildcard -> id\\n IEWildcard _ -> add_unused_all pn\\n add_unused (IEWholeNamespace x ns_spec) acc = add_unused_wildcard ns_spec (iewn_names x) acc\\n add_unused _ acc = acc\\n\\n add_unused_name :: Name -> Bool -> UnusedNames -> UnusedNames\\n add_unused_name n is_ie_var acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | is_ie_var\\n , isFieldName n\\n -- See Note [Reporting unused imported duplicate record fields]\\n = let\\n fs = getOccFS n\\n (flds, flds_used) = lookupFsEnv acc_fs fs `orElse` (emptyNameSet, Any False)\\n acc_fs\' = extendFsEnv acc_fs fs (extendNameSet flds n, Any used S.<> flds_used)\\n in UnusedNames acc_ns acc_wcs acc_fs\'\\n\\n | used\\n = acc\\n\\n | otherwise\\n = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n where\\n used = isJust $ lookupGRE_Name used_gre_env n\\n\\n add_unused_all :: Name -> UnusedNames -> UnusedNames\\n add_unused_all n acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | Just {} <- lookupGRE_Name used_gre_env n = acc\\n | n `elemNameSet` used_parents = acc\\n | otherwise = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n\\n add_unused_with :: Name -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_with p ns acc\\n | all (`elemNameSet` acc1_ns) ns = add_unused_name p False acc1\\n | otherwise = acc1\\n where\\n acc1@(UnusedNames acc1_ns _ _) = foldr (\\\\n acc\' -> add_unused_name n False acc\') acc ns\\n -- If you use \'signum\' from Num, then the user may well have\\n -- imported Num(signum). We don\'t want to complain that\\n -- Num is not itself mentioned. Hence the two cases in add_unused_with.\\n\\n add_unused_wildcard :: NamespaceSpecifier GhcRn -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_wildcard ns_spec names acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | any_used = acc\\n | otherwise = UnusedNames acc_ns (ns_spec : acc_wcs) acc_fs\\n where\\n -- A wildcard `type ..` or `data ..` is used if at least one of\\n -- the names it expands to is used\\n any_used = any (isJust . lookupGRE_Name used_gre_env) names\\n\\n\\n-- | An accumulator for unused names in an import list.\\n--\\n-- See Note [Reporting unused imported duplicate record fields].\\ndata UnusedNames =\\n UnusedNames\\n { unused_names :: NameSet\\n -- ^ Unused \'Name\'s in an import list, not including record fields\\n -- that are plain \'IEVar\' imports (tracked by \'rec_fld_uses\')\\n -- or wildcard imports (tracked by \'unused_wildcards\').\\n , unused_wildcards :: [NamespaceSpecifier GhcRn]\\n -- ^ Unused wildcards @type ..@ or @data ..@ in an import list.\\n , rec_fld_uses :: FastStringEnv (NameSet, Any)\\n -- ^ Record fields imported without a parent (i.e. an \'IEVar\' import).\\n --\\n -- The \'Any\' value records whether any of the record fields\\n -- sharing the same underlying \'FastString\' have been used.\\n }\\n\\nemptyUnusedNames :: UnusedNames\\nemptyUnusedNames = UnusedNames emptyNameSet [] emptyFsEnv\\n\\ninstance Outputable UnusedNames where\\n ppr (UnusedNames nms wcs flds) =\\n text \\"UnusedNames\\" <+>\\n braces (ppr nms <+> ppr wcs <+> ppr (fmap (second getAny) flds))\\n\\n-- | Collect all unused names from a \'UnusedNames\' value.\\ncollectUnusedNames :: UnusedNames -> NameSet\\ncollectUnusedNames (UnusedNames { unused_names = nms, rec_fld_uses = flds })\\n = nms S.<> unused_flds\\n where\\n unused_flds = nonDetFoldFsEnv collect_unused emptyNameSet flds\\n collect_unused :: (NameSet, Any) -> NameSet -> NameSet\\n collect_unused (nms, Any at_least_one_name_is_used) acc\\n | at_least_one_name_is_used = acc\\n | otherwise = unionNameSet nms acc\\n\\ncollectUnusedWildcards :: UnusedNames -> [NamespaceSpecifier GhcRn]\\ncollectUnusedWildcards = unused_wildcards\\n\\n{- Note [Reporting unused imported duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have (#24035):\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M1 (R1(..), R2(..)) where\\n data R1 = MkR1 { fld :: Int }\\n data R2 = MkR2 { fld :: Int }\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M2 where\\n import M1 (R1(MkR1), R2, fld)\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nIn the import of \'M1\' in \'M2\', the \'fld\' import resolves to two separate GREs,\\nnamely R1(fld) and R2(fld). From the perspective of the renamer, and in particular\\nthe \'findImportUsage\' function, it\'s as if the user had imported the two names\\nseparately (even though no source syntax allows that).\\n\\nThis means that we need to be careful when reporting unused imports: the R2(fld)\\nimport is indeed unused, but because R1(fld) is used, we should not report\\nfld as unused altogether.\\n\\nTo achieve this, we keep track of record field imports without a parent (i.e.\\nusing the IEVar constructor) separately from other import items, using the\\nUnusedNames datatype.\\nOnce we have accumulated usages, we emit warnings for unused record fields\\nwithout parents one whole group (of record fields sharing the same textual name)\\nat a time, and only if *all* of the record fields in the group are unused;\\nsee \'collectUnusedNames\'.\\n\\nNote that this only applies to record fields imported without a parent. If we\\nhad:\\n\\n import M1 (R1(MkR1, fld), R2(fld))\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nthen of course we should report the second \'fld\' as unused.\\n-}\\n\\n\\n{- Note [The ImportMap]\\n~~~~~~~~~~~~~~~~~~~~~~~\\nThe ImportMap is a short-lived intermediate data structure records, for\\neach import declaration, what stuff brought into scope by that\\ndeclaration is actually used in the module.\\n\\nThe [GlobalRdrElt] are the things imported from that decl.\\n-}\\n\\ndata ImportMap = ImportMap\\n { im_imports :: Map RealSrcSpan [GlobalRdrElt]\\n -- ^ See [The ImportMap]\\n -- If loc :-> gres, then\\n -- \'loc\' = the end loc of the bestImport of each GRE in \'gres\'\\n , im_generatedImports :: Map ModuleName [GlobalRdrElt]\\n }\\n\\nmkImportMap :: [GlobalRdrElt] -> ImportMap\\n-- For each of a list of used GREs, find all the import decls that brought\\n-- it into scope; choose one of them (bestImport), and record\\n-- the RdrName in that import decl\'s entry in the ImportMap\\nmkImportMap = foldr insertImportMap $ ImportMap Map.empty Map.empty\\n\\ninsertImportMap :: GlobalRdrElt -> ImportMap -> ImportMap\\ninsertImportMap gre@(GRE { gre_imp = imp_specs }) importMap\\n | RealSrcSpan importSpan _ <- is_dloc best_imp_spec =\\n importMap{im_imports = insertElem importSpan gre $ im_imports importMap}\\n | GeneratedSrcSpan{} <- is_dloc best_imp_spec =\\n importMap{im_generatedImports = insertElem (moduleName $ is_mod best_imp_spec) gre $ im_generatedImports importMap}\\n | otherwise = importMap\\n where\\n best_imp_spec =\\n case bagToList imp_specs of\\n [] -> pprPanic \\"mkImportMap: GRE with no ImportSpecs\\" (ppr gre)\\n is:iss -> is_decl $ bestImport (is NE.:| iss)\\n\\n -- https://github.com/haskell/containers/issues/784\\n insertElem :: Ord k => k -> v -> Map k [v] -> Map k [v]\\n insertElem k v = flip Map.alter k $ \\\\case\\n Just vs -> Just (v : vs)\\n Nothing -> Just [v]\\n\\nlookupImportMap :: LImportDecl GhcRn -> ImportMap -> [GlobalRdrElt]\\nlookupImportMap (L srcSpan ImportDecl{ideclName = L _ modName}) importMap =\\n fromMaybe [] $\\n -- should match logic in insertImportMap\\n case locA srcSpan of\\n RealSrcSpan realSrcSpan _ -> realSrcSpan `Map.lookup` im_imports importMap\\n GeneratedSrcSpan{} -> modName `Map.lookup` im_generatedImports importMap\\n _ -> Nothing\\n\\nlieNames :: LIE (GhcPass p) -> [Located (IdP (GhcPass p))]\\nlieNames = _\\n\\nwarnUnusedImport :: GlobalRdrEnv -> ImportDeclUsage -> RnM ()\\nwarnUnusedImport rdr_env (L loc decl, used, unused, unused_wcs)\\n\\n -- Do not warn for \'import M()\'\\n -- See (UI1) in Note [Unused imports]\\n | Just (Exactly, _) <- ideclImportList decl\\n , null unused && null unused_wcs\\n = return ()\\n\\n -- Note [Do not warn about Prelude hiding]\\n | Just (EverythingBut, hides) <- ideclImportList decl\\n , not (null hides)\\n , pRELUDE_NAME == unLoc (ideclName decl)\\n = return ()\\n\\n -- Do not warn about import X as Rebindable\\n -- See (UI2) in Note [Unused imports]\\n | Just (L _ mod) <- ideclAs decl\\n , mod == rEBINDABLE_MOD_NAME\\n = return ()\\n\\n -- Nothing used; drop entire declaration\\n | null used\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl UnusedImportNone)\\n\\n -- Everything imported is used; nop\\n | null unused && null unused_wcs\\n = return ()\\n\\n -- Some imports are unused: make the `SrcSpan` cover only the unused\\n -- items instead of the whole import statement\\n | Just (_, imports) <- ideclImportList decl\\n , let unused_locs = [ locA loc | L loc ie <- imports\\n , name <- ieNames ie\\n , name `elem` unused ]\\n , loc1 : locs <- unused_locs\\n , let span = foldr1 combineSrcSpans ( loc1 NE.:| locs )\\n = addDiagnosticAt span (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n -- Some imports are unused\\n | otherwise\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n where\\n -- In warning message, pretty-print identifiers unqualified unconditionally\\n -- to improve the consistent for ambiguous/unambiguous identifiers.\\n -- See #14881.\\n possible_field n =\\n case lookupGRE_Name rdr_env n of\\n Just (GRE { gre_par = par, gre_info = IAmRecField info }) ->\\n let fld_occ :: OccName\\n fld_occ = nameOccName $ flSelector $ recFieldLabel info\\n in UnusedImportNameRecField par fld_occ\\n _ -> UnusedImportNameRegular n\\n\\n -- Print unused names in a deterministic (lexicographic) order\\n sort_unused :: [UnusedImportName]\\n sort_unused =\\n [ UnusedImportWildcard wc | wc <- unused_wcs ] ++\\n [ possible_field nm | nm <- sortBy (comparing nameOccName) unused ]\\n\\ngetMinimalImports :: [ImportDeclUsage] -> RnM [LImportDecl GhcRn]\\ngetMinimalImports ie_decls\\n = do { rdr_env <- getGlobalRdrEnv\\n ; fmap combine $ mapM (mk_minimal rdr_env) ie_decls }\\n where\\n mk_minimal rdr_env (L l decl, used_gres, unused, unused_wcs)\\n | null unused && null unused_wcs\\n , Just (Exactly, _) <- ideclImportList decl\\n = return (L l decl)\\n | otherwise\\n = do { let ImportDecl { ideclName = L _ mod_name\\n , ideclSource = is_boot\\n , ideclPkgQual = pkg_qual\\n , ideclExt = XImportDeclPass { ideclOrigin = origin } } = decl\\n ; iface <- loadSrcInterface doc (importDeclLookupScope origin)\\n mod_name is_boot pkg_qual\\n ; let used_avails = gresToAvailInfo used_gres\\n ; lies <- map (L l) <$> concatMapM (to_ie rdr_env iface) used_avails\\n ; return (L l (decl { ideclImportList = Just (Exactly, lies) })) }\\n where\\n doc = text \\"Compute minimal imports for\\" <+> ppr decl\\n\\n to_ie :: GlobalRdrEnv -> ModIface -> AvailInfo -> RnM [IE GhcRn]\\n -- The main trick here is that if we\'re importing all the constructors\\n -- we want to say \\"T(..)\\", but if we\'re importing only a subset we want\\n -- to say \\"T(A,B,C)\\". So we have to find out what the module exports.\\n to_ie rdr_env _ (Avail c) -- Note [Overloaded field import]\\n = do { let\\n gre = expectJust $ lookupGRE_Name rdr_env c\\n ; return $ [IEVar Nothing (to_ie_post_rn $ noLocA $ greName gre) Nothing] }\\n to_ie _ _ avail@(AvailTC n [_]) -- Exporting the main decl and nothing else\\n | availExportsDecl avail\\n = return [IEThingAbs Nothing (to_ie_post_rn $ noLocA n) Nothing]\\n to_ie rdr_env iface (AvailTC n cs) =\\n case [ xs | avail@(AvailTC x xs) <- mi_exports iface\\n , x == n\\n , availExportsDecl avail -- Note [Partial export]\\n ] of\\n [xs]\\n | all_used xs\\n -> return [IEThingAll (IEThingAllExt Nothing noAnn noAnn noAnn)\\n (NoNamespaceSpecifier noExtField)\\n (to_ie_post_rn $ noLocA n)\\n Nothing]\\n | otherwise\\n -> do { let ns_gres = map (expectJust . lookupGRE_Name rdr_env) cs\\n ns = map greName ns_gres\\n ; return [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n -- Note [Overloaded field import]\\n _other\\n -> do { let infos = map (expectJust . lookupGRE_Name rdr_env) cs\\n (ns_gres,fs_gres) = classifyGREs infos\\n ns = map greName (ns_gres ++ fs_gres)\\n fs = map fieldGREInfo fs_gres\\n ; return $\\n if all_non_overloaded fs\\n then map (\\\\nm -> IEVar Nothing (to_ie_post_rn_var $ noLocA nm) Nothing) ns\\n else [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n where\\n\\n all_used avail_cs = all (`elem` cs) avail_cs\\n\\n all_non_overloaded = all (not . flIsOverloaded . recFieldLabel)\\n\\n combine :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\n combine = map merge . NE.groupAllWith getKey\\n\\n getKey :: LImportDecl GhcRn -> (Bool, Maybe ModuleName, ModuleName)\\n getKey decl =\\n ( isImportDeclQualified . ideclQualified $ idecl -- is this qualified? (important that this be first)\\n , unLoc <$> ideclAs idecl -- what is the qualifier (inside Maybe monad)\\n , unLoc . ideclName $ idecl -- Module Name\\n )\\n where\\n idecl :: ImportDecl GhcRn\\n idecl = unLoc decl\\n\\n merge :: NonEmpty (LImportDecl GhcRn) -> LImportDecl GhcRn\\n merge decls@((L l decl) :| _) = L l (decl { ideclImportList = Just (Exactly, lies) })\\n where lies = concatMap snd $ mapMaybe (ideclImportList . unLoc) $ NE.toList decls\\n\\nclassifyGREs :: [GlobalRdrElt] -> ([GlobalRdrElt], [FieldGlobalRdrElt])\\nclassifyGREs = partition (not . isRecFldGRE)\\n\\nprintMinimalImports :: HscSource -> [ImportDeclUsage] -> RnM ()\\n-- See Note [Printing minimal imports]\\nprintMinimalImports hsc_src imports_w_usage\\n = do { imports\' <- excludeGenerated <$> getMinimalImports imports_w_usage\\n ; this_mod <- getModule\\n ; dflags <- getDynFlags\\n ; liftIO $ withFile (mkFilename dflags this_mod) WriteMode $ \\\\h ->\\n printForUser dflags h neverQualify AllTheWay (vcat (map ppr imports\'))\\n -- The neverQualify is important. We are printing Names\\n -- but they are in the context of an \'import\' decl, and\\n -- we never qualify things inside there\\n -- E.g. import Blag( f, b )\\n -- not import Blag( Blag.f, Blag.g )!\\n }\\n where\\n mkFilename dflags this_mod\\n | Just d <- dumpDir dflags = d basefn\\n | otherwise = basefn\\n where\\n suffix = case hsc_src of\\n HsBootFile -> \\".imports-boot\\"\\n HsSrcFile -> \\".imports\\"\\n HsigFile -> \\".imports\\"\\n basefn = moduleNameString (moduleName this_mod) ++ suffix\\n\\n\\nto_ie_post_rn_var :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn_var (L l n)\\n | isDataOcc $ occName n = L l (IEPattern noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n\\n\\nto_ie_post_rn :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn (L l n)\\n | isTcOcc occ && isSymOcc occ = L l (IEType noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n where occ = occName n\\n\\n{- Note [Do not warn about Prelude hiding]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWe do not warn about\\n import Prelude hiding( x, y )\\nbecause even if nothing else from Prelude is used, it may be essential to hide\\nx,y to avoid name-shadowing warnings. Example (#9061)\\n import Prelude hiding( log )\\n f x = log where log = ()\\n\\nNote [Unused imports]\\n~~~~~~~~~~~~~~~~~~~~~\\nIn `warnUnusedImport`, if we see an import with an explicit list imports, thus\\n import M( a, b )\\nand neither `a` nor `b` is used, we report the entire import decl as unused. We\\ncheck this by looking at the names that it brings into scope scope; if there are\\nno ununused names, don\'t report.\\n\\n(UI1) We don\'t want to complain about `import M()`, because that is often used to bring\\n M\'s /instances/ into scope. That is neatly dealt with by the \\"no unused\\n names\\" (nor unused wildcard imports) criterion.\\n\\n(UI2) We don\'t report a decl as unused if it has an `as Rebindable` qualifier.\\n See (KN1) in Note [Overview of known entities] in GHC.Builtin\\n\\n\\nNote [Printing minimal imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nTo print the minimal imports we walk over all import decls (both user-supplied\\nand generated), trim their import lists, then filter out generated decls.\\n\\nNB that\\n\\n * We do *not* change the \'qualified\' or \'as\' parts!\\n\\n * We do not discard a decl altogether; we might need instances\\n from it. Instead we just trim to an empty import list\\n\\nNote [Partial export]\\n~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have\\n\\n module A( op ) where\\n class C a where\\n op :: a -> a\\n\\n module B where\\n import A\\n f = ..op...\\n\\nThen the minimal import for module B is\\n import A( op )\\nnot\\n import A( C( op ) )\\nwhich we would usually generate if C was exported from B. Hence\\nthe availExportsDecl test when deciding what to generate.\\n\\n\\nNote [Overloaded field import]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nOn the other hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n data T = MkT { foo :: Int }\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( T(foo) )\\nbecause when DuplicateRecordFields is enabled, field selectors are\\nnot in scope without their enclosing datatype.\\n\\nOn the third hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n pattern MkT { foo } = Just foo\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( foo )\\nbecause foo doesn\'t have a parent. This might actually be ambiguous if A\\nexports another field called foo, but there is no good answer to return and this\\nis a very obscure corner, so it seems to be the best we can do. See\\nDRFPatSynExport for a test of this.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Errors}\\n* *\\n************************************************************************\\n-}\\n\\nbadImportItemErr\\n :: ModIface -> ImpDeclSpec -> IE GhcPs\\n -> IsSubordinateError\\n -> [AvailInfo]\\n -> TcRn (NonEmpty ImportLookupReason)\\nbadImportItemErr iface decl_spec ie sub avails = do\\n exts <- importLookupExtensions\\n let import_lookup_bad :: BadImportKind -> ImportLookupReason\\n import_lookup_bad k = ImportLookupBad k iface decl_spec ie exts\\n dflags <- getDynFlags\\n hsc_env <- getTopEnv\\n let rdr_env = mkGlobalRdrEnv\\n $ gresFromAvails hsc_env (Just imp_spec) all_avails\\n pure $ fmap import_lookup_bad (importErrorKind dflags rdr_env)\\n where\\n importErrorKind :: DynFlags -> GlobalRdrEnv -> NonEmpty BadImportKind\\n importErrorKind dflags rdr_env\\n | any checkIfTyCon avails = case sub of\\n IsNotSubordinate -> NE.singleton BadImportAvailTyCon\\n IsSubordinateError { subordinate_err_parent = gre\\n , subordinate_err_unavailable = unavailable\\n , subordinate_err_nontype = nontype\\n , subordinate_err_nondata = nondata }\\n -> NE.fromList $ catMaybes $\\n [ fmap (BadImportNotExportedSubordinates gre) (NE.nonEmpty unavailable)\\n , fmap (BadImportNonTypeSubordinates gre) (NE.nonEmpty nontype)\\n , fmap (BadImportNonDataSubordinates gre) (NE.nonEmpty nondata) ]\\n | any checkIfVarName avails = NE.singleton BadImportAvailVar\\n | Just con <- find checkIfDataCon avails = NE.singleton (BadImportAvailDataCon (availOccName con))\\n | otherwise = NE.singleton (BadImportNotExported suggs)\\n where\\n suggs = similar_suggs ++ fieldSelectorSuggestions rdr_env rdr\\n what_look = case sub of\\n IsNotSubordinate -> WL_TyCon_or_TermVar\\n IsSubordinateError { subordinate_err_parent = gre } ->\\n case greInfo gre of\\n IAmTyCon ClassFlavour\\n -> WL_TyCon_or_TermVar\\n _ -> WL_Term\\n similar_names =\\n similarNameSuggestions (Unbound.LF what_look WL_Global)\\n dflags rdr_env emptyLocalRdrEnv rdr\\n similar_suggs =\\n case NE.nonEmpty $ mapMaybe imported_item $ similar_names of\\n Just similar -> [ SuggestSimilarNames rdr similar ]\\n Nothing -> [ ]\\n\\n -- Only keep imported items, and set the \\"HowInScope\\" to\\n -- \\"Nothing\\" to avoid printing \\"imported from...\\" in the suggestion\\n -- error message.\\n imported_item (SimilarRdrName rdr_name gre (Just (ImportedBy {})))\\n = Just (SimilarRdrName rdr_name gre Nothing)\\n imported_item _ = Nothing\\n\\n checkIfDataCon = checkIfAvailMatches isDataConName\\n checkIfTyCon = checkIfAvailMatches isTyConName\\n checkIfVarName =\\n \\\\case\\n AvailTC{} -> False\\n Avail n -> importedFS == occNameFS (occName n)\\n && (isVarOcc <||> isFieldOcc) (occName n)\\n checkIfAvailMatches namePred =\\n \\\\case\\n AvailTC _ ns ->\\n case find (\\\\n -> importedFS == occNameFS (occName n)) ns of\\n Just n -> namePred n\\n Nothing -> False\\n Avail{} -> False\\n availOccName = occName . availName\\n rdr = ieName ie\\n importedFS = occNameFS $ rdrNameOcc rdr\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n all_avails = mi_exports iface\\n\\nimportLookupExtensions :: TcRn ImportLookupExtensions\\nimportLookupExtensions = do\\n ile_pattern_synonyms <- xoptM LangExt.PatternSynonyms\\n ile_explicit_namespaces <- xoptM LangExt.ExplicitNamespaces\\n return ImportLookupExtensions{ile_pattern_synonyms, ile_explicit_namespaces}\\n\\naddDupDeclErr :: NonEmpty GlobalRdrElt -> TcRn ()\\naddDupDeclErr gres@(gre :| _)\\n -- Report the error at the later location\\n = addErrAt (getSrcSpan (NE.last sorted_names)) $ (TcRnDuplicateDecls (greOccName gre) sorted_names)\\n where\\n sorted_names =\\n NE.sortBy (SrcLoc.leftmost_smallest `on` nameSrcSpan)\\n (fmap greName gres)\\n\\n-- This data decl will parse OK\\n-- data T = a Int\\n-- treating \\"a\\" as the constructor.\\n-- It is really hard to make the parser spot this malformation.\\n-- So the renamer has to check that the constructor is legal\\n--\\n-- We can get an operator as the constructor, even in the prefix form:\\n-- data T = :% Int Int\\n-- from interface files, which always print in prefix form\\n--\\n-- We also allow type constructor names, which are defined by \\"type data\\"\\n-- declarations. See Note [Type data declarations] in GHC.Rename.Module.\\n\\ncheckConName :: RdrName -> TcRn ()\\ncheckConName name\\n = checkErr (isRdrDataCon name || isRdrTc name) (TcRnIllegalDataCon name)\\n", "filetypes": ["haskell"]}}}' 2026-10-16 14:46:20,700 - DEBUG - POST b'http://127.0.0.1:37093/receive_messages' {'content-type': 'application/json', 'x-ycm-hmac': b'Rga7Yd4l4fgfufwYw+0sxzurvznImlBO0MPmgAlS4EY='} b'{"filepath": "/home/enrico/ghc/compiler/GHC/Rename/Names.hs", "line_num": 1, "column_num": 1, "working_dir": "/home/enrico/ghc", "file_data": {"/home/enrico/ghc/compiler/GHC/Rename/Names.hs": {"contents": "{-\\n(c) The GRASP/AQUA Project, Glasgow University, 1992-1998\\n\\nExtracting imported and top-level names in scope\\n-}\\n\\n{-# LANGUAGE NondecreasingIndentation #-}\\n{-# LANGUAGE TypeFamilies #-}\\n\\nmodule GHC.Rename.Names (\\n rnImports, getLocalNonValBinders, newRecordFieldLabel,\\n importsFromIface,\\n ImportUserSpec(..),\\n extendGlobalRdrEnvRn,\\n gresFromAvails,\\n calculateAvails,\\n reportUnusedNames,\\n checkConName,\\n mkChildEnv,\\n findChildren,\\n mkBadExportSubordinate,\\n findImportUsage,\\n getMinimalImports,\\n printMinimalImports,\\n renamePkgQual, renameRawPkgQual,\\n classifyGREs,\\n ImportDeclUsage,\\n rnNamespaceSpecifier\\n ) where\\n\\nimport GHC.Prelude hiding ( head, init, last, tail )\\n\\nimport GHC.Driver.Env\\nimport GHC.Driver.Session\\nimport GHC.Driver.Ppr\\n\\nimport GHC.Rename.Env\\nimport GHC.Rename.Fixity\\nimport GHC.Rename.Utils ( warnUnusedTopBinds )\\nimport GHC.Rename.Unbound\\nimport qualified GHC.Rename.Unbound as Unbound\\n\\nimport GHC.Tc.Errors.Types\\nimport GHC.Tc.Utils.Env\\nimport GHC.Tc.Utils.Monad\\nimport GHC.Tc.Types.LclEnv\\nimport GHC.Tc.Zonk.TcType ( tcInitTidyEnv )\\n\\nimport GHC.Hs\\nimport GHC.Iface.Load ( loadSrcInterface, loadSrcInterface_maybe )\\nimport GHC.Iface.Errors.Types\\n ( IfaceMessage(..), MissingInterfaceError, InterfaceLookingFor(..)\\n , LoadEssentialsReason(..) )\\nimport GHC.Iface.Syntax ( fromIfaceWarnings )\\nimport GHC.Builtin.Modules( pRELUDE_NAME, rEBINDABLE_MOD_NAME )\\nimport GHC.Parser.PostProcess ( setRdrNameSpace )\\nimport GHC.Core.TyCo.Tidy\\nimport GHC.Core.PatSyn\\nimport GHC.Core.TyCon ( TyCon, tyConName )\\nimport qualified GHC.LanguageExtensions as LangExt\\n\\nimport GHC.Utils.Outputable as Outputable\\nimport GHC.Utils.Misc as Utils\\nimport GHC.Utils.Panic\\n\\nimport GHC.Types.Fixity.Env\\nimport GHC.Types.SafeHaskell\\nimport GHC.Types.Name\\nimport GHC.Types.Name.Env\\nimport GHC.Types.Name.Set\\nimport GHC.Types.Name.Reader\\nimport GHC.Types.Avail\\nimport GHC.Types.FieldLabel\\nimport GHC.Types.Hint\\nimport GHC.Types.SourceFile\\nimport GHC.Types.SrcLoc as SrcLoc\\nimport GHC.Types.Basic (TyConFlavour (..), convImportLevel, VisArity)\\nimport GHC.Types.UnresolvedImport\\nimport GHC.Types.Id\\nimport GHC.Types.PkgQual\\nimport GHC.Types.GREInfo (ConInfo(..), ConFieldInfo (..), ConLikeInfo (ConIsData))\\n\\nimport GHC.Unit\\nimport GHC.Unit.Module.Warnings\\nimport GHC.Unit.Module.ModIface\\nimport GHC.Unit.Module.Imported\\nimport GHC.Unit.Module.Deps\\nimport GHC.Unit.Env\\n\\nimport GHC.Data.Bag\\nimport GHC.Data.FastString\\nimport GHC.Data.FastString.Env\\nimport GHC.Data.Maybe\\nimport GHC.Data.List.SetOps ( removeDups )\\n\\nimport Control.Arrow ( second )\\nimport Control.Monad\\nimport Data.Foldable ( for_ )\\nimport Data.IntMap ( IntMap )\\nimport qualified Data.IntMap as IntMap\\nimport Data.Map ( Map )\\nimport qualified Data.Map as Map\\nimport Data.Ord ( comparing )\\nimport Data.Semigroup ( Any(..) )\\nimport qualified Data.Semigroup as S\\nimport Data.List ( partition, find, sortBy )\\nimport Data.List.NonEmpty (NonEmpty(..))\\nimport qualified Data.List.NonEmpty as NE\\nimport Data.Function ( on )\\nimport qualified Data.Set as S\\nimport System.FilePath (())\\nimport System.IO\\n\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{rnImports}\\n* *\\n************************************************************************\\n\\nNote [Tracking Trust Transitively]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen we import a package as well as checking that the direct imports are safe\\naccording to the rules outlined in the Note [Safe Haskell Trust Check] in GHC.Driver.Main\\nwe must also check that these rules hold transitively for all dependent modules\\nand packages. Doing this without caching any trust information would be very\\nslow as we would need to touch all packages and interface files a module depends\\non. To avoid this we make use of the property that if a modules Safe Haskell\\nmode changes, this triggers a recompilation from that module in the dependency\\ngraph. So we can just worry mostly about direct imports.\\n\\nThere is one trust property that can change for a package though without\\nrecompilation being triggered: package trust. So we must check that all\\npackages a module transitively depends on to be trusted are still trusted when\\nwe are compiling this module (as due to recompilation avoidance some modules\\nbelow may not be considered trusted any more without recompilation being\\ntriggered).\\n\\nWe handle this by augmenting the existing transitive list of packages a module M\\ndepends on with a bool for each package that says if it must be trusted when the\\nmodule M is being checked for trust. This list of trust required packages for a\\nsingle import is gathered in the rnImportDecl function and stored in an\\nImportAvails data structure. The union of these trust required packages for all\\nimports is done by the rnImports function using the combine function which calls\\nthe plusImportAvails function that is a union operation for the ImportAvails\\ntype. This gives us in an ImportAvails structure all packages required to be\\ntrusted for the module we are currently compiling. Checking that these packages\\nare still trusted (and that direct imports are trusted) is done in\\nGHC.Driver.Main.checkSafeImports.\\n\\nSee the note below, [Trust Own Package] for a corner case in this method and\\nhow its handled.\\n\\n\\nNote [Trust Own Package]\\n~~~~~~~~~~~~~~~~~~~~~~~~\\nThere is a corner case of package trust checking that the usual transitive check\\ndoesn\'t cover. (For how the usual check operates see the Note [Tracking Trust\\nTransitively] below). The case is when you import a -XSafe module M and M\\nimports a -XTrustworthy module N. If N resides in a different package than M,\\nthen the usual check works as M will record a package dependency on N\'s package\\nand mark it as required to be trusted. If N resides in the same package as M\\nthough, then importing M should require its own package be trusted due to N\\n(since M is -XSafe so doesn\'t create this requirement by itself). The usual\\ncheck fails as a module doesn\'t record a package dependency of its own package.\\nSo instead we now have a bool field in a modules interface file that simply\\nstates if the module requires its own package to be trusted. This field avoids\\nus having to load all interface files that the module depends on to see if one\\nis trustworthy.\\n\\n\\nNote [Trust Transitive Property]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSo there is an interesting design question in regards to transitive trust\\nchecking. Say I have a module B compiled with -XSafe. B is dependent on a bunch\\nof modules and packages, some packages it requires to be trusted as its using\\n-XTrustworthy modules from them. Now if I have a module A that doesn\'t use safe\\nhaskell at all and simply imports B, should A inherit all the trust\\nrequirements from B? Should A now also require that a package p is trusted since\\nB required it?\\n\\nWe currently say no but saying yes also makes sense. The difference is, if a\\nmodule M that doesn\'t use Safe Haskell imports a module N that does, should all\\nthe trusted package requirements be dropped since M didn\'t declare that it cares\\nabout Safe Haskell (so -XSafe is more strongly associated with the module doing\\nthe importing) or should it be done still since the author of the module N that\\nuses Safe Haskell said they cared (so -XSafe is more strongly associated with\\nthe module that was compiled that used it).\\n\\nGoing with yes is a simpler semantics we think and harder for the user to stuff\\nup but it does mean that Safe Haskell will affect users who don\'t care about\\nSafe Haskell as they might grab a package from Cabal which uses safe haskell (say\\nnetwork) and that packages imports -XTrustworthy modules from another package\\n(say bytestring), so requires that package is trusted. The user may now get\\ncompilation errors in code that doesn\'t do anything with Safe Haskell simply\\nbecause they are using the network package. They will have to call \'ghc-pkg\\ntrust network\' to get everything working. Due to this invasive nature of going\\nwith yes we have gone with no for now.\\n-}\\n\\n-- | Process Import Decls. See \'rnImportDecl\' for a description of what\\n-- the return types represent.\\n-- Note: Do the non SOURCE ones first, so that we get a helpful warning\\n-- for SOURCE ones that are unnecessary\\nrnImports :: [(LImportDecl GhcPs, SDoc)]\\n -> RnM ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\nrnImports imports = do\\n tcg_env <- getGblEnv\\n -- NB: want an identity module here, because it\'s OK for a signature\\n -- module to import from its implementor\\n let this_mod = tcg_mod tcg_env\\n let (source, ordinary) = partition (is_source_import . fst) imports\\n is_source_import (d::LImportDecl GhcPs) = ideclSource (unLoc d) == IsBoot\\n stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary\\n stuff2 <- mapAndReportM (rnImportDecl this_mod) source\\n -- Safe Haskell: See Note [Tracking Trust Transitively]\\n let (decls, imp_user_spec, rdr_env, imp_avails) = combine (stuff1 ++ stuff2)\\n -- Update imp_boot_mods if imp_direct_mods mentions any of them\\n let merged_import_avail = clobberSourceImports imp_avails\\n return (decls, imp_user_spec, rdr_env, merged_import_avail)\\n\\n where\\n clobberSourceImports imp_avails =\\n imp_avails { imp_boot_mods = imp_boot_mods\' }\\n where\\n imp_boot_mods\' = mergeInstalledModuleEnv combJ id (const emptyInstalledModuleEnv)\\n (imp_boot_mods imp_avails)\\n (imp_direct_dep_mods imp_avails)\\n\\n combJ (GWIB _ IsBoot) (_, x) = Just x\\n combJ r _ = Just r\\n -- See Note [Combining ImportAvails]\\n combine :: [(LImportDecl GhcRn, ImportUserSpec, GlobalRdrEnv, ImportAvails)]\\n -> ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\n combine ss =\\n let (decls, imp_user_spec, rdr_env, imp_avails, finsts) = foldr\\n plus\\n ([], [], emptyGlobalRdrEnv, emptyImportAvails, emptyModuleSet)\\n ss\\n in (decls, imp_user_spec, rdr_env, imp_avails { imp_finsts = moduleSetElts finsts })\\n\\n plus (decl, us, gbl_env1, imp_avails1)\\n (decls, uss, gbl_env2, imp_avails2, finsts_set)\\n = ( decl:decls,\\n us:uss,\\n gbl_env1 `plusGlobalRdrEnv` gbl_env2,\\n imp_avails1\' `plusImportAvails` imp_avails2,\\n extendModuleSetList finsts_set new_finsts )\\n where\\n imp_avails1\' = imp_avails1 { imp_finsts = [] }\\n new_finsts = imp_finsts imp_avails1\\n\\n{-\\nNote [Combining ImportAvails]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nimp_finsts in ImportAvails is a list of family instance modules\\ntransitively depended on by an import. imp_finsts for a currently\\ncompiled module is a union of all the imp_finsts of imports.\\nComputing the union of two lists of size N is O(N^2) and if we\\ndo it to M imports we end up with O(M*N^2). That can get very\\nexpensive for bigger module hierarchies.\\n\\nUnion can be optimized to O(N log N) if we use a Set.\\nimp_finsts is converted back and forth between dep_finsts, so\\nchanging a type of imp_finsts means either paying for the conversions\\nor changing the type of dep_finsts as well.\\n\\nI\'ve measured that the conversions would cost 20% of allocations on my\\ntest case, so that can be ruled out.\\n\\nChanging the type of dep_finsts forces checkFamInsts to\\nget the module lists in non-deterministic order. If we wanted to restore\\nthe deterministic order, we\'d have to sort there, which is an additional\\ncost. As far as I can tell, using a non-deterministic order is fine there,\\nbut that\'s a brittle nonlocal property which I\'d like to avoid.\\n\\nAdditionally, dep_finsts is read from an interface file, so its \\"natural\\"\\ntype is a list. Which makes it a natural type for imp_finsts.\\n\\nSince rnImports.combine is really the only place that would benefit from\\nit being a Set, it makes sense to optimize the hot loop in rnImports.combine\\nwithout changing the representation.\\n\\nSo here\'s what we do: instead of naively merging ImportAvails with\\nplusImportAvails in a loop, we make plusImportAvails merge empty imp_finsts\\nand compute the union on the side using Sets. When we\'re done, we can\\nconvert it back to a list. One nice side effect of this approach is that\\nif there\'s a lot of overlap in the imp_finsts of imports, the\\nSet doesn\'t really need to grow and we don\'t need to allocate.\\n\\nRunning generateModules from #14693 with DEPTH=16, WIDTH=30 finishes in\\n23s before, and 11s after.\\n-}\\n\\n-- | Given a located import declaration @decl@ from @this_mod@,\\n-- calculate the following pieces of information:\\n--\\n-- 1. An updated \'LImportDecl\', where all unresolved \'RdrName\' in\\n-- the entity lists have been resolved into \'Name\'s,\\n--\\n-- 2. A \'GlobalRdrEnv\' representing the new identifiers that were\\n-- brought into scope (taking into account module qualification\\n-- and hiding),\\n--\\n-- 3. \'ImportAvails\' summarizing the identifiers that were imported\\n-- by this declaration, and\\n--\\n-- 4. A boolean \'AnyHpcUsage\' which is true if the imported module\\n-- used HPC.\\nrnImportDecl :: Module -> (LImportDecl GhcPs, SDoc)\\n -> RnM (LImportDecl GhcRn, ImportUserSpec , GlobalRdrEnv, ImportAvails)\\nrnImportDecl this_mod\\n (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name\\n , ideclPkgQual = raw_pkg_qual\\n , ideclSource = want_boot\\n , ideclSafe = mod_safe\\n , ideclLevelSpec = import_level\\n , ideclQualified = qual_style\\n , ideclExt = XImportDeclPass { ideclOrigin = origin }\\n , ideclAs = as_mod, ideclImportList = imp_details }), import_reason)\\n = setSrcSpanA loc $ do\\n\\n case raw_pkg_qual of\\n NoRawPkgQual -> pure ()\\n RawPkgQual {} -> do\\n pkg_imports <- xoptM LangExt.PackageImports\\n when (not pkg_imports) $ addErr TcRnPackageImportsDisabled\\n\\n let qual_only = isImportDeclQualified qual_style\\n generated = isGeneratedImport origin\\n\\n lookup_scope = importDeclLookupScope origin\\n\\n -- If there\'s an error in loadInterface, (e.g. interface\\n -- file not found) we get lots of spurious errors from \'filterImports\'\\n let imp_mod_name = unLoc loc_imp_mod_name\\n doc = ppr imp_mod_name <+> import_reason\\n\\n hsc_env <- getTopEnv\\n unit_env <- hsc_unit_env <$> getTopEnv\\n let pkg_qual = renameRawPkgQual unit_env imp_mod_name raw_pkg_qual\\n\\n -- Check for self-import, which confuses the typechecker (#9032)\\n -- ghc --make rejects self-import cycles already, but batch-mode may not\\n -- at least not until GHC.IfaceToCore.tcHiBootIface, which is too late to avoid\\n -- typechecker crashes. (Indirect self imports are not caught until\\n -- GHC.IfaceToCore, see #10337 tracking how to make this error better.)\\n --\\n -- Originally, we also allowed \'import {-# SOURCE #-} M\', but this\\n -- caused bug #10182: in one-shot mode, we should never load an hs-boot\\n -- file for the module we are compiling into the EPS. In principle,\\n -- it should be possible to support this mode of use, but we would have to\\n -- extend Provenance to support a local definition in a qualified location.\\n -- For now, we don\'t support it, but see #10336\\n when (imp_mod_name == moduleName this_mod &&\\n (case pkg_qual of -- If we have import \\"\\" M, then we should\\n -- check that \\"\\" is \\"this\\" (which is magic)\\n -- or the name of this_mod\'s package. Yurgh!\\n -- c.f. GHC.findModule, and #9997\\n NoPkgQual -> True\\n ThisPkg uid -> uid == homeUnitId_ (hsc_dflags hsc_env)\\n OtherPkg _ -> False))\\n (addErr (TcRnSelfImport imp_mod_name))\\n\\n -- Check for a missing import list (Opt_WarnMissingImportList also\\n -- checks for T(..) items but that is done in checkDodgyImport below)\\n case imp_details of\\n Just (Exactly, _) -> return () -- Explicit import list\\n _ | generated -> return () -- Do not bleat for generated imports\\n | qual_only -> return ()\\n | otherwise -> addDiagnostic (TcRnNoExplicitImportList imp_mod_name)\\n\\n\\n mb_iface <- loadSrcInterface_maybe doc lookup_scope imp_mod_name want_boot pkg_qual\\n iface <- case mb_iface of\\n Succeeded iface -> return iface\\n Failed err -> failWithTc $\\n importDeclLoadFailure origin imp_mod_name want_boot err\\n\\n -- Compiler sanity check: if the import didn\'t say\\n -- {-# SOURCE #-} we should not get a hi-boot file\\n warnPprTrace ((want_boot == NotBoot) && (mi_boot iface == IsBoot)) \\"rnImportDecl\\" (ppr imp_mod_name) $ do\\n\\n -- Issue a user warning for a redundant {- SOURCE -} import\\n -- NB that we arrange to read all the ordinary imports before\\n -- any of the {- SOURCE -} imports.\\n --\\n -- in --make and GHCi, the compilation manager checks for this,\\n -- and indeed we shouldn\'t do it here because the existence of\\n -- the non-boot module depends on the compilation order, which\\n -- is not deterministic. The hs-boot test can show this up.\\n dflags <- getDynFlags\\n warnIf ((want_boot == IsBoot) && (mi_boot iface == NotBoot) && isOneShot (ghcMode dflags))\\n (TcRnRedundantSourceImport imp_mod_name)\\n when (mod_safe && not (safeImportsOn dflags)) $\\n addErr (TcRnSafeImportsDisabled imp_mod_name)\\n\\n let imp_mod = mi_module iface\\n qual_mod_name = fmap unLoc as_mod `orElse` imp_mod_name\\n imp_spec = ImpDeclSpec { is_mod = imp_mod, is_qual = qual_only,\\n is_dloc = locA loc, is_as = qual_mod_name,\\n is_pkg_qual = pkg_qual, is_isboot = want_boot,\\n is_level = convImportLevel import_level }\\n\\n let filter_imports = do\\n -- filter the imports according to the import declaration\\n (new_imp_details, imp_user_list, gbl_env)\\n <- filterImports hsc_env iface imp_spec imp_details\\n -- for certain error messages, we\\u2019d like to know what could be\\n -- imported here, if everything were imported\\n potential_gres <- (\\\\(_,_,x) -> x) <$> filterImports hsc_env iface imp_spec Nothing\\n return (new_imp_details, imp_user_list, gbl_env, potential_gres)\\n\\n (new_imp_details, imp_user_list, gbl_env, potential_gres) <-\\n case origin of\\n ImplicitEssentialsImport ->\\n -- The implicit GHC.Essentials import does not bring anything into scope.\\n -- See Note [Finding GHC.Essentials] in GHC.Builtin.\\n return (Nothing, ImpUserDependOnly, emptyGlobalRdrEnv, emptyGlobalRdrEnv)\\n UserWrittenImport -> filter_imports\\n ImplicitPreludeImport -> filter_imports\\n PluginImport -> filter_imports\\n\\n let is_hiding | Just (EverythingBut,_) <- imp_details = True\\n | otherwise = False\\n\\n -- should the import be safe?\\n mod_safe\' = mod_safe\\n || (not generated && safeDirectImpsReq dflags)\\n || (generated && safeImplicitImpsReq dflags)\\n\\n hsc_env <- getTopEnv\\n let home_unit = hsc_home_unit hsc_env\\n other_home_units = hsc_all_home_unit_ids hsc_env\\n\\n imported_by\\n | isDependOnlyImport imp_user_list\\n = ImportedBySystem\\n | otherwise\\n = ImportedByUser $ ImportedModsVal\\n { imv_name = is_as imp_spec\\n , imv_span = locA loc\\n , imv_is_safe = mod_safe\'\\n , imv_is_hiding = is_hiding\\n , imv_all_exports = potential_gres\\n , imv_qualified = qual_only\\n , imv_is_level = convImportLevel import_level\\n }\\n imports = calculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by\\n\\n -- Complain if we import a deprecated module\\n case fromIfaceWarnings (mi_warns iface) of\\n WarnAll txt -> addDiagnostic (TcRnDeprecatedModule imp_mod_name txt)\\n _ -> return ()\\n\\n let new_imp_decl = ImportDecl\\n { ideclExt = ideclExt decl\\n , ideclName = ideclName decl\\n , ideclPkgQual = pkg_qual\\n , ideclSource = ideclSource decl\\n , ideclSafe = mod_safe\'\\n , ideclQualified = ideclQualified decl\\n , ideclAs = ideclAs decl\\n , ideclImportList = new_imp_details\\n , ideclLevelSpec = ideclLevelSpec decl\\n }\\n\\n return (L loc new_imp_decl, ImpUserSpec imp_spec imp_user_list, gbl_env, imports)\\n\\n-- | The error message to emit when we failed to load an interface.\\nimportDeclLoadFailure :: ImportDeclOrigin -> ModuleName -> IsBootInterface\\n -> MissingInterfaceError -> TcRnMessage\\nimportDeclLoadFailure ImplicitEssentialsImport _ _ err\\n = TcRnInterfaceError $ CantFindEssentials err LookingForEssentialsModule\\nimportDeclLoadFailure _ mod_name want_boot err\\n = TcRnInterfaceError $ Can\'tFindInterface err $ LookingForModule mod_name want_boot\\n\\n-- | Rename raw package imports\\nrenameRawPkgQual :: UnitEnv -> ModuleName -> RawPkgQual -> PkgQual\\nrenameRawPkgQual unit_env mn = \\\\case\\n NoRawPkgQual -> NoPkgQual\\n RawPkgQual _ fs -> renamePkgQual unit_env mn $ Just fs\\n\\n-- | Rename raw package imports\\nrenamePkgQual :: UnitEnv -> ModuleName -> Maybe FastString -> PkgQual\\nrenamePkgQual unit_env mn mb_pkg = case mb_pkg of\\n Nothing -> NoPkgQual\\n Just pkg_fs\\n | Just uid <- homeUnitId <$> ue_homeUnit unit_env\\n , pkg_fs == fsLit \\"this\\"\\n -> ThisPkg uid\\n\\n | Just (uid, _) <- find (fromMaybe False . fmap (== pkg_fs) . snd) home_names\\n -> ThisPkg uid\\n\\n | Just uid <- resolvePackageImport unit_state mn (PackageName pkg_fs)\\n -> OtherPkg uid\\n\\n | otherwise\\n -> OtherPkg (UnitId pkg_fs)\\n -- not really correct as pkg_fs is unlikely to be a valid unit-id but\\n -- we will report the failure later...\\n where\\n home_names =\\n [ (uid, mkFastString <$> thisPackageName (homeUnitEnv_dflags (ue_findHomeUnitEnv uid unit_env)))\\n | uid <- S.toList hpt_deps\\n ]\\n\\n unit_state = ue_homeUnitState unit_env\\n\\n hpt_deps :: S.Set UnitId\\n hpt_deps = homeUnitDepends unit_state\\n\\n\\n-- | Calculate the \'ImportAvails\' induced by an import of a particular\\n-- interface, but without \'imp_mods\'.\\ncalculateAvails :: HomeUnit\\n -> S.Set UnitId\\n -> ModIface\\n -> IsSafeImport\\n -> IsBootInterface\\n -> ImportedBy\\n -> ImportAvails\\ncalculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by =\\n let imp_mod = mi_module iface\\n imp_sem_mod= mi_semantic_module iface\\n orph_iface = mi_orphan iface\\n has_finsts = mi_finsts iface\\n deps = mi_deps iface\\n trust = getSafeMode $ mi_trust iface\\n trust_pkg = mi_trust_pkg iface\\n is_sig = mi_hsc_src iface == HsigFile\\n\\n -- If the module exports anything defined in this module, just\\n -- ignore it. Reason: otherwise it looks as if there are two\\n -- local definition sites for the thing, and an error gets\\n -- reported. Easiest thing is just to filter them out up\\n -- front. This situation only arises if a module imports\\n -- itself, or another module that imported it. (Necessarily,\\n -- this involves a loop.)\\n --\\n -- We do this *after* filterImports, so that if you say\\n -- module A where\\n -- import B( AType )\\n -- type AType = ...\\n --\\n -- module B( AType ) where\\n -- import {-# SOURCE #-} A( AType )\\n --\\n -- then you won\'t get a \'B does not export AType\' message.\\n\\n\\n -- Compute new transitive dependencies\\n --\\n -- \'dep_orphs\' and \'dep_finsts\' do NOT include the imported module\\n -- itself, but we DO need to include this module in \'imp_orphs\' and\\n -- \'imp_finsts\' if it defines an orphan or instance family; thus the\\n -- orph_iface/has_iface tests.\\n\\n deporphs = dep_orphs deps\\n depfinsts = dep_finsts deps\\n\\n orphans | orph_iface = assertPpr (not (imp_sem_mod `elem` deporphs)) (ppr imp_sem_mod <+> ppr deporphs) $\\n imp_sem_mod : deporphs\\n | otherwise = deporphs\\n\\n finsts | has_finsts = assertPpr (not (imp_sem_mod `elem` depfinsts)) (ppr imp_sem_mod <+> ppr depfinsts) $\\n imp_sem_mod : depfinsts\\n | otherwise = depfinsts\\n\\n -- Trusted packages are a lot like orphans.\\n trusted_pkgs | mod_safe\' = dep_trusted_pkgs deps\\n | otherwise = S.empty\\n\\n\\n pkg = moduleUnit (mi_module iface)\\n ipkg = toUnitId pkg\\n\\n -- Does this import mean we now require our own pkg\\n -- to be trusted? See Note [Trust Own Package]\\n ptrust = trust == Sf_Trustworthy || trust_pkg\\n pkg_trust_req\\n | isHomeUnit home_unit pkg = ptrust\\n | otherwise = False\\n\\n dependent_pkgs = if toUnitId pkg `S.member` other_home_units\\n then S.empty\\n else S.singleton (lvl, ipkg)\\n\\n lvl = case imported_by of\\n ImportedByUser imv -> imv_is_level imv\\n ImportedBySystem -> NormalLevel\\n\\n\\n direct_mods = if toUnitId pkg `S.member` other_home_units\\n then mkPlusModDeps (moduleUnitId imp_mod) lvl (GWIB (moduleName imp_mod) want_boot)\\n else emptyInstalledModuleEnv\\n\\n dep_boot_mods_map = mkModDeps (dep_boot_mods deps)\\n\\n\\n boot_mods\\n -- If we are looking for a boot module, it must be HPT\\n | IsBoot <- want_boot = extendInstalledModuleEnv dep_boot_mods_map (toUnitId <$> imp_mod) (GWIB (moduleName imp_mod) IsBoot)\\n -- Now we are importing A properly, so don\'t go looking for\\n -- A.hs-boot\\n | isHomeUnit home_unit pkg = dep_boot_mods_map\\n -- There\'s no boot files to find in external imports\\n | otherwise = emptyInstalledModuleEnv\\n\\n sig_mods =\\n if is_sig\\n then moduleName imp_mod : dep_sig_mods deps\\n else dep_sig_mods deps\\n\\n\\n in ImportAvails {\\n imp_mods = Map.singleton (mi_module iface) [imported_by],\\n imp_orphs = orphans,\\n imp_finsts = finsts,\\n imp_sig_mods = sig_mods,\\n imp_direct_dep_mods = direct_mods,\\n imp_dep_direct_pkgs = dependent_pkgs,\\n imp_boot_mods = boot_mods,\\n\\n -- Add in the imported modules trusted package\\n -- requirements. ONLY do this though if we import the\\n -- module as a safe import.\\n -- See Note [Tracking Trust Transitively]\\n -- and Note [Trust Transitive Property]\\n imp_trust_pkgs = trusted_pkgs,\\n -- Do we require our own pkg to be trusted?\\n -- See Note [Trust Own Package]\\n imp_trust_own_pkg = pkg_trust_req\\n }\\n\\nmkPlusModDeps :: UnitId -> ImportLevel -> ModuleNameWithIsBoot\\n -> InstalledModuleEnv (S.Set ImportLevel, ModuleNameWithIsBoot)\\nmkPlusModDeps uid st elt = extendInstalledModuleEnv emptyInstalledModuleEnv (mkModule uid (gwib_mod elt)) (S.singleton st, elt)\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{importsFromLocalDecls}\\n* *\\n************************************************************************\\n\\nFrom the top-level declarations of this module produce\\n * the lexical environment\\n * the ImportAvails\\ncreated by its bindings.\\n\\nNote [Top-level Names in Template Haskell decl quotes]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSee also: Note [Interactively-bound Ids in GHCi] in GHC.Driver.Env\\n Note [Looking up Exact RdrNames] in GHC.Rename.Env\\n\\nConsider a Template Haskell declaration quotation like this:\\n module M where\\n f x = h [d| f = 3 |]\\nWhen renaming the declarations inside [d| ...|], we treat the\\ntop level binders specially in two ways\\n\\n1. We give them an Internal Name, not (as usual) an External one.\\n This is done by GHC.Rename.Env.newTopSrcBinder.\\n\\n2. We make them *shadow* the outer bindings.\\n See Note [GlobalRdrEnv shadowing]\\n\\n3. We find out whether we are inside a [d| ... |] by testing the TH\\n level. This is a slight hack, because the level field was really\\n meant for the type checker, and here we are not interested in the\\n fields of Brack, hence the error thunks in thRnBrack.\\n-}\\n\\nextendGlobalRdrEnvRn :: [GlobalRdrElt]\\n -> MiniFixityEnv\\n -> RnM (TcGblEnv, TcLclEnv)\\n-- Updates both the GlobalRdrEnv and the FixityEnv\\n-- We return a new TcLclEnv only because we might have to\\n-- delete some bindings from it;\\n-- see Note [Top-level Names in Template Haskell decl quotes]\\n\\nextendGlobalRdrEnvRn new_gres new_fixities\\n = checkNoErrs $ -- See Note [Fail fast on duplicate definitions]\\n do { (gbl_env, lcl_env) <- getEnvs\\n ; level <- getThLevel\\n ; isGHCi <- getIsGHCi\\n ; let rdr_env = tcg_rdr_env gbl_env\\n fix_env = tcg_fix_env gbl_env\\n th_bndrs = getLclEnvThBndrs lcl_env\\n th_lvl = thLevelIndex level\\n\\n -- Delete new_occs from global and local envs\\n -- If we are in a TemplateHaskell decl bracket,\\n -- we are going to shadow them\\n -- See Note [GlobalRdrEnv shadowing]\\n inBracket = isBrackLevel level\\n\\n lcl_env_TH = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_rdr = minusLocalRdrEnv (tcl_rdr lcl_env) new_gres_env }) lcl_env\\n -- See Note [GlobalRdrEnv shadowing]\\n\\n lcl_env2 | inBracket = lcl_env_TH\\n | otherwise = lcl_env\\n\\n -- Deal with shadowing: see Note [GlobalRdrEnv shadowing]\\n want_shadowing = isGHCi || inBracket\\n rdr_env1 | want_shadowing = shadowNames False rdr_env new_gres_env\\n | otherwise = rdr_env\\n\\n lcl_env3 = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_th_bndrs = extendNameEnvList th_bndrs\\n [ ( n, (TopLevel, th_lvl) )\\n | n <- new_names ] }) lcl_env2\\n\\n ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres\\n\\n ; let fix_env\' = foldl\' extend_fix_env fix_env new_gres\\n gbl_env\' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env\' }\\n\\n ; traceRn \\"extendGlobalRdrEnvRn 2\\" (pprGlobalRdrEnv True rdr_env2)\\n ; return (gbl_env\', lcl_env3) }\\n where\\n new_names = map greName new_gres\\n new_gres_env = mkGlobalRdrEnv new_gres\\n\\n -- If there is a fixity decl for the gre, add it to the fixity env\\n extend_fix_env fix_env gre\\n | Just (L _ fi) <- lookupMiniFixityEnv new_fixities name\\n = extendNameEnv fix_env name (FixItem occ fi)\\n | otherwise\\n = fix_env\\n where\\n name = greName gre\\n occ = greOccName gre\\n\\n add_gre :: GlobalRdrEnv -> GlobalRdrElt -> RnM GlobalRdrEnv\\n -- Extend the GlobalRdrEnv with a LocalDef GRE\\n -- If there is already a LocalDef GRE with the same OccName,\\n -- report an error and discard the new GRE\\n -- This establishes INVARIANT 1 of GlobalRdrEnvs\\n add_gre env gre\\n | not (null dups) -- Same OccName defined twice\\n = do { addDupDeclErr (gre :| dups); return env }\\n\\n | otherwise\\n = return (extendGlobalRdrEnv env gre)\\n where\\n -- See Note [Reporting duplicate local declarations]\\n dups = filter isBadDupGRE\\n $ lookupGRE env (LookupOccName (greOccName gre) (RelevantGREsFOS WantBoth))\\n isBadDupGRE old_gre = isLocalGRE old_gre && greClashesWith gre old_gre\\n\\n{- Note [Fail fast on duplicate definitions]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIf there are duplicate bindings for the same thing, we want to fail\\nfast. Having two bindings for the same thing can cause follow-on errors.\\nExample (test T9975a):\\n data Test = Test { x :: Int }\\n pattern Test wat = Test { x = wat }\\nThis defines \'Test\' twice. The second defn has no field-names; and then\\nwe get an error from Test { x=wat }, saying \\"Test has no field \'x\'\\".\\n\\nEasiest thing is to bale out fast on duplicate definitions, which\\nwe do via `checkNoErrs` on `extendGlobalRdrEnvRn`.\\n\\nNote [Reporting duplicate local declarations]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn general, a single module may not define the same OccName multiple times. This\\nis checked in extendGlobalRdrEnvRn: when adding a new locally-defined GRE to the\\nGlobalRdrEnv we report an error if there are already duplicates in the\\nenvironment. This establishes INVARIANT 1 (see comments on GlobalRdrEnv in\\nGHC.Types.Name.Reader), which says that for a given OccName, all the\\nGlobalRdrElts to which it maps must have distinct \'greName\'s.\\n\\nFor example, the following will be rejected:\\n\\n f x = x\\n g x = x\\n f x = x -- Duplicate!\\n\\nUsers are allowed to introduce new GREs with the same OccName as an imported GRE,\\nas disambiguation is possible through the module system, e.g.:\\n\\n module M where\\n import N (f)\\n f x = x\\n g x = M.f x + N.f x\\n\\nIf both GREs are local, the general rule is that two GREs clash if they have\\nthe same OccName, i.e. they share a textual name and live in the same namespace.\\nHowever, there are additional clashes due to record fields:\\n\\n - a new variable clashes with previously defined record fields\\n which define field selectors,\\n\\n - a new record field shadows:\\n\\n - previously defined variables, if it defines a field selector,\\n - previously defined record fields, unless it is a duplicate record field.\\n\\nThis logic is implemented in the function \'GHC.Types.Name.Reader.greClashesWith\'.\\n\\nSee also Note [Skipping ambiguity errors at use sites of local declarations] in\\nGHC.Rename.Utils.\\n-}\\n\\n\\n{- *********************************************************************\\n* *\\n getLocalDeclBindersd@ returns the names for an HsDecl\\n It\'s used for source code.\\n\\n *** See Note [The Naming story] in GHC.Hs.Decls ****\\n* *\\n********************************************************************* -}\\n\\ngetLocalNonValBinders :: MiniFixityEnv -> HsGroup GhcPs\\n -> RnM ((TcGblEnv, TcLclEnv), NameSet)\\n-- Get all the top-level binders bound the group *except*\\n-- for value bindings, which are treated separately\\n-- Specifically we return AvailInfo for\\n-- * type decls (incl constructors and record selectors)\\n-- * class decls (including class ops)\\n-- * associated types\\n-- * foreign imports\\n-- * value signatures (in hs-boot files only)\\n\\ngetLocalNonValBinders fixity_env\\n (HsGroup { hs_valds = binds,\\n hs_tyclds = tycl_decls,\\n hs_fords = foreign_decls })\\n = do { -- Process all type/class decls *except* family instances\\n ; let inst_decls = tycl_decls >>= group_instds\\n ; dup_fields_ok <- xopt_DuplicateRecordFields <$> getDynFlags\\n ; has_sel <- xopt_FieldSelectors <$> getDynFlags\\n ; tc_gres\\n <- concatMapM\\n (new_tc dup_fields_ok has_sel)\\n (tyClGroupTyClDecls tycl_decls)\\n ; traceRn \\"getLocalNonValBinders 1\\" (ppr tc_gres)\\n ; envs <- extendGlobalRdrEnvRn tc_gres fixity_env\\n ; restoreEnvs envs $ do {\\n -- Bring these things into scope first\\n -- See Note [Looking up family names in family instances]\\n\\n -- Process all family instances\\n -- to bring new data constructors into scope\\n ; nti_gress <- mapM (new_assoc dup_fields_ok has_sel) inst_decls\\n\\n -- Finish off with value binders:\\n -- foreign decls and pattern synonyms for an ordinary module\\n -- type sigs in case of a hs-boot file only\\n ; is_boot <- tcIsHsBootOrSig\\n ; let val_bndrs\\n | is_boot = case binds of\\n ValBinds _ val_binds ->\\n -- In a hs-boot file, the value binders come from the\\n -- *signatures*, and there should be no foreign binders\\n [ L (l2l decl_loc) (unLoc n)\\n | L decl_loc (TypeSig _ _ ns _) <- (val_sigs val_binds), n <- ns]\\n _ -> panic \\"Non-ValBinds in hs-boot group\\"\\n | otherwise = for_hs_bndrs\\n ; val_gres <- mapM new_simple val_bndrs\\n\\n ; let avails = concat nti_gress ++ val_gres\\n new_bndrs = gresToNameSet avails `unionNameSet`\\n gresToNameSet tc_gres\\n ; traceRn \\"getLocalNonValBinders 2\\" (ppr avails)\\n ; envs <- extendGlobalRdrEnvRn avails fixity_env\\n ; return (envs, new_bndrs) } }\\n where\\n for_hs_bndrs :: [LocatedN RdrName]\\n for_hs_bndrs = hsForeignDeclsBinders foreign_decls\\n\\n -- the SrcSpan attached to the input should be the span of the\\n -- declaration, not just the name\\n new_simple :: LocatedN RdrName -> RnM GlobalRdrElt\\n new_simple rdr_name = do { nm <- newTopSrcBinder rdr_name\\n ; return (mkLocalVanillaGRE NoParent nm) }\\n\\n new_tc :: DuplicateRecordFields -> FieldSelectors -> LTyClDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_tc dup_fields_ok has_sel tc_decl -- NOT for type/data instances\\n = do { let TyDeclBinders (main_bndr, tc_flav) at_bndrs sig_bndrs\\n (LConsWithFields cons_with_flds flds) = hsLTyClDeclBinders tc_decl\\n ; tycon_name <- newTopSrcBinder $ la2la main_bndr\\n ; at_names <- mapM (newTopSrcBinder . la2la . fst) at_bndrs\\n ; sig_names <- mapM (newTopSrcBinder . la2la) sig_bndrs\\n ; con_names_with_flds <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst con_names_with_flds) flds\\n ; mapM_ (add_dup_fld_errs flds\') con_names_with_flds\\n ; let tc_gre = mkLocalTyConGRE (fmap (const tycon_name) tc_flav) tycon_name\\n fld_env = mk_fld_env con_names_with_flds flds\'\\n at_gres = zipWith (\\\\ (_, at_flav) at_nm -> mkLocalTyConGRE (fmap (const tycon_name) at_flav) at_nm)\\n at_bndrs at_names\\n sig_gres = map (mkLocalVanillaGRE (ParentIs tycon_name)) sig_names\\n con_gres = map (mkLocalConLikeGRE (ParentIs tycon_name)) fld_env\\n fld_gres = mkLocalFieldGREs (ParentIs tycon_name) fld_env\\n sub_gres = at_gres ++ sig_gres ++ con_gres ++ fld_gres\\n ; traceRn \\"getLocalNonValBinders new_tc\\" $\\n vcat [ text \\"tycon:\\" <+> ppr tycon_name\\n , text \\"tc_gre:\\" <+> ppr tc_gre\\n , text \\"sub_gres:\\" <+> ppr sub_gres ]\\n ; return $ tc_gre : sub_gres }\\n\\n -- Calculate the record field information, which feeds into the GlobalRdrElts\\n -- for DataCons and their fields. It\'s convenient to do this here where\\n -- we are working with a single datatype definition.\\n --\\n -- The information we needed was all set up for us:\\n -- see Note [Collecting record fields in data declarations] in GHC.Hs.Utils.\\n mk_fld_env :: [(Name, Either VisArity [Located Int])] -> IntMap FieldLabel\\n -> [(ConLikeName, ConInfo)]\\n mk_fld_env names flds =\\n [ (DataConName con, ConInfo (ConIsData (map fst names)) fld_info)\\n | (con, con_fl_indxs) <- names\\n , let fld_info = case fmap (map ((flds IntMap.!) . unLoc)) con_fl_indxs of\\n Left 0 -> ConIsNullary\\n Left arity -> ConHasPositionalArgs arity\\n Right [] -> ConIsNullary\\n Right (fld:flds) -> ConHasRecordFields $ fld NE.:| flds ]\\n\\n new_assoc :: DuplicateRecordFields -> FieldSelectors -> LInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_assoc _ _ (L _ (TyFamInstD {})) = return []\\n -- type instances don\'t bind new names\\n\\n new_assoc dup_fields_ok has_sel (L _ (DataFamInstD _ d))\\n = new_di dup_fields_ok has_sel Nothing d\\n new_assoc dup_fields_ok has_sel\\n (L _ (ClsInstD _ (ClsInstDecl { cid_poly_ty = inst_ty\\n , cid_decls = decls })))\\n = do -- First, attempt to grab the name of the class from the instance.\\n -- This step could fail if the instance is not headed by a class,\\n -- such as in the following examples:\\n --\\n -- (1) The class is headed by a bang pattern, such as in\\n -- `instance !Show Int` (#3811c)\\n -- (2) The class is headed by a type variable, such as in\\n -- `instance c` (#16385)\\n --\\n -- If looking up the class name fails, then mb_cls_gre will\\n -- be Nothing.\\n mb_cls_gre <- runMaybeT $ do\\n -- See (1) above\\n L loc cls_rdr <- MaybeT $ pure $ getLHsInstDeclClass_maybe inst_ty\\n -- See (2) above\\n MaybeT $ setSrcSpan (locA loc) $ lookupGlobalOccRn_maybe SameNameSpace cls_rdr\\n -- Assuming the previous step succeeded, process any associated data\\n -- family instances. If the previous step failed, bail out.\\n case mb_cls_gre of\\n Nothing\\n -> pure []\\n Just cls_gre\\n -> let cls_nm = greName cls_gre\\n in concatMapM (new_di dup_fields_ok has_sel (Just cls_nm) . unLoc) (data_fam_insts decls)\\n\\n data_fam_insts decls = concatMap get decls\\n where\\n get (L l (InstD _ (DataFamInstD { dfid_inst = d}))) = [L l d]\\n get _ = []\\n\\n new_di :: DuplicateRecordFields -> FieldSelectors\\n -> Maybe Name -- class name\\n -> DataFamInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_di dup_fields_ok has_sel mb_cls dfid@(DataFamInstDecl { dfid_eqn = ti_decl })\\n = do { main_name <- unLoc <$> lookupFamInstName mb_cls (feqn_tycon ti_decl)\\n ; let LConsWithFields cons_with_flds flds = hsDataFamInstBinders dfid\\n ; sub_names <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst sub_names) flds\\n ; mapM_ (add_dup_fld_errs flds\') sub_names\\n ; let fld_env = mk_fld_env sub_names flds\'\\n con_gres = map (mkLocalConLikeGRE (ParentIs main_name)) fld_env\\n field_gres = mkLocalFieldGREs (ParentIs main_name) fld_env\\n -- NB: the data family name is not bound here,\\n -- so we don\'t return a GlobalRdrElt for it here!\\n ; return $ con_gres ++ field_gres }\\n\\n -- Add errors if a constructor has a duplicate record field.\\n add_dup_fld_errs :: IntMap FieldLabel\\n -> (Name, Either VisArity [Located Int])\\n -> IOEnv (Env TcGblEnv TcLclEnv) ()\\n add_dup_fld_errs all_flds (con, con_flds_or_arity)\\n | Right con_flds <- con_flds_or_arity\\n , let (_, dups) = removeDups (comparing unLoc) con_flds\\n = for_ dups $ \\\\ dup_flds ->\\n -- Report the error at the location of the second occurrence\\n -- of the duplicate field.\\n let loc =\\n case dup_flds of\\n _ :| ( L loc _ : _) -> loc\\n L loc _ :| _ -> loc\\n dup_rdrs = fmap (nameRdrName . flSelector . (all_flds IntMap.!) . unLoc) dup_flds\\n in addErrAt loc $ TcRnDuplicateFieldName (RecordFieldDecl con) dup_rdrs\\n | otherwise\\n = return ()\\n\\nnewRecordFieldLabel :: DuplicateRecordFields -> FieldSelectors -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel\\nnewRecordFieldLabel _ _ [] _ = error \\"newRecordFieldLabel: datatype has no constructors!\\"\\nnewRecordFieldLabel dup_fields_ok has_sel (dc:_) (L loc (FieldOcc _ (L _ fld)))\\n = do { selName <- newTopSrcBinder $ L (l2l loc) $ field\\n ; return $ FieldLabel { flHasDuplicateRecordFields = dup_fields_ok\\n , flHasFieldSelector = has_sel\\n , flSelector = selName } }\\n where\\n fld_occ = rdrNameOcc fld\\n dc_fs = occNameFS $ nameOccName dc\\n field\\n -- Use an Exact RdrName as-is, to preserve the bindings\\n -- of an already renamer-resolved field and its use\\n -- sites. This is needed to correctly support record\\n -- selectors in Template Haskell. See Note [Binders in\\n -- Template Haskell] in \\"GHC.ThToHs\\" and Note [Looking up\\n -- Exact RdrNames] in \\"GHC.Rename.Env\\".\\n | isExact fld\\n = assertPpr (fieldOcc_maybe fld_occ == Just dc_fs)\\n (vcat [ text \\"newRecordFieldLabel: incorrect namespace for exact Name\\" <+> quotes (ppr fld)\\n , text \\"expected namespace:\\" <+> pprNameSpace (fieldName dc_fs)\\n , text \\" actual namespace:\\" <+> pprNameSpace (occNameSpace fld_occ) ])\\n fld\\n\\n -- Field names produced by the parser are namespaced with VarName.\\n -- Here we namespace them according to the first constructor.\\n -- See Note [Record field namespacing] in GHC.Types.Name.Occurrence.\\n | otherwise\\n = mkRdrUnqual $ varToRecFieldOcc dc_fs fld_occ\\n\\n{-\\nNote [Looking up family names in family instances]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider\\n\\n module M where\\n type family T a :: *\\n type instance M.T Int = Bool\\n\\nWe might think that we can simply use \'lookupOccRn\' when processing the type\\ninstance to look up \'M.T\'. Alas, we can\'t! The type family declaration is in\\nthe *same* HsGroup as the type instance declaration. Hence, as we are\\ncurrently collecting the binders declared in that HsGroup, these binders will\\nnot have been added to the global environment yet.\\n\\nSolution is simple: process the type family declarations first, extend\\nthe environment, and then process the type instances.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Filtering imports}\\n* *\\n************************************************************************\\n\\n@filterImports@ takes the @ExportEnv@ telling what the imported module makes\\navailable, and filters it through the import spec (if any).\\n\\nNote [Dealing with imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nFor import M( ies ), we take each AvailInfo from the mi_exports of M, and make\\n\\n imp_occ_env :: OccEnv (NameEnv ImpOccItem)\\n\\nThis map contains one entry for each OccName that M exports, mapping each OccName\\nto the following information:\\n\\n 1. the GlobalRdrElt corresponding to the OccName,\\n 2. whether this GlobalRdrElt was the parent in the AvailInfo we found\\n the OccName in.\\n 3. the GlobalRdrElts that were bundled together in the AvailInfo we found\\n this OccName in (not including the parent),\\n\\nWe need (2) and (3) during the construction of the OccEnv because of associated\\ntypes and bundled pattern synonyms, respectively.\\n(3) is explained in Note [Importing PatternSynonyms].\\n\\nTo explain (2), consider for example:\\n\\n module M where\\n class C a where { data T a }\\n instance C Int where { data T Int = T1 | T2 }\\n instance C Bool where { data T Int = T3 }\\n\\nHere, M\'s exports avails are (recalling the AvailTC invariant from GHC.Types.Avail)\\n\\n C(C,T), T(T,T1,T2,T3)\\n\\nNotice that T appears *twice*, once as a child and once as a parent. From\\nthese two exports, respectively, during construction of the imp_occ_env, we begin\\nby associating the following two elements with the key T:\\n\\n T -> ImpOccItem { imp_item = gre1, imp_bundled = [C,T] , imp_is_parent = False }\\n T -> ImpOccItem { imp_item = gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nwhere `gre1`, `gre2` are two GlobalRdrElts with greName T.\\nWe combine these (in function \'combine\' in \'mkImportOccEnv\') by discarding the\\nnon-parent item, thusly:\\n\\n T -> IE_ITem { imp_item = gre1 `plusGRE` gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nNote the `plusGRE`: this ensures we don\'t drop parent information;\\nsee Note [Preserve parent information when combining import OccEnvs].\\n\\nSo the overall imp_occ_env is:\\n\\n C -> ImpOccItem { imp_item = C, imp_bundled = [T ], imp_is_parent = True }\\n T -> ImpOccItem { imp_item = T , imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n T1 -> ImpOccItem { imp_item = T1, imp_bundled = [T1,T2,T3], imp_is_parent = False }\\n -- similarly for T2, T3\\n\\nNote that the imp_occ_env will have entries for data constructors too,\\nalthough we never look up data constructors.\\n\\nNote [Importing PatternSynonyms]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nAs described in Note [Dealing with imports], associated types can lead to the\\nsame Name appearing twice, both as a child and once as a parent, when\\nconstructing the imp_occ_env. The same thing can happen with pattern synonyms\\nif they are exported bundled with a type.\\n\\nA simplified example, based on #11959:\\n\\n {-# LANGUAGE PatternSynonyms #-}\\n module M (T(P), pattern P) where -- Duplicate export warning, but allowed\\n data T = MkT\\n pattern P = MkT\\n\\nHere we have T(P) and P in export_avails, and respectively construct both\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n P -> ImpOccItem { imp_item = P, imp_bundled = [] , imp_is_parent = False }\\n\\nWe combine these by dropping the one with no siblings, leaving us with:\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n\\nThat is, we simply discard the non-bundled Avail.\\n\\nNote [Importing DuplicateRecordFields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn filterImports, another complicating factor is DuplicateRecordFields.\\nSuppose we have:\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (S(foo), T(foo)) where\\n data S = MkS { foo :: Int }\\n data T = MkT { foo :: Int }\\n\\n module N where\\n import M (foo) -- this is allowed (A)\\n import M (S(foo)) -- this is allowed (B)\\n\\nHere M exports \'foo\' at two different OccNames, with different namespaces for\\nthe two construtors MkS and MkT. Then, when we look up \'foo\' in lookup_names\\nfor case (A), we have a variable foo but must look in all the record field\\nnamespaces to find the two fields (and hence two different Avails).\\nWhereas in case (B) we reach the lookup_ie case for IEThingWith,\\nwhich looks up \'S\' and then finds the unique \'foo\' amongst its children.\\n\\nSee T16745 for a test of this.\\n\\nNote [Preserve parent information when combining import OccEnvs]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen discarding one ImpOccItem in favour of another, as described in\\nNote [Dealing with imports], we must make sure to combine the GREs so that\\nwe don\'t lose information.\\n\\nConsider for example #24084:\\n\\n module M1 where { class C a where { type T a } }\\n module M2 ( module M1 ) where { import M1 }\\n module M3 where { import M2 ( C, T ); instance C () where T () = () }\\n\\nWhen processing the import list of `M3`, we will have two `Avail`s attached\\nto `T`, namely `C(C, T)` and `T(T)`. We combine them in the `combine` function\\nof `mkImportOccEnv`; as described in Note [Dealing with imports] we discard\\n`C(C, T)` in favour of `T(T)`. However, in doing so, we **must not**\\ndiscard the information want that `C` is the parent of `T`. Indeed,\\nlosing track of this information can cause errors when importing,\\nas we could get an error of the form\\n\\n \\u2018T\\u2019 is not a (visible) associated type of class \\u2018C\\u2019\\n\\nThis explains why we use `plusGRE` when combining the two ImpOccItems, even\\nthough we are discarding one in favour of the other.\\n-}\\n\\n-- | All the \'GlobalRdrElt\'s associated with an \'AvailInfo\'.\\ngresFromAvail :: HasDebugCallStack\\n => HscEnv -> Maybe ImportSpec -> AvailInfo -> [GlobalRdrElt]\\ngresFromAvail hsc_env prov avail =\\n [ mk_gre nm info\\n | nm <- availNames avail\\n , let info = lookupGREInfo hsc_env nm ]\\n where\\n\\n mk_gre n info\\n = case prov of\\n -- Nothing => bound locally\\n -- Just is => imported from \'is\'\\n Nothing -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = True, gre_imp = emptyBag\\n , gre_info = info }\\n Just is -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = False, gre_imp = unitBag is\\n , gre_info = info }\\n\\n-- | All the \'GlobalRdrElt\'s associated with a collection of \'AvailInfo\'s.\\ngresFromAvails :: HscEnv -> Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]\\ngresFromAvails hsc_env prov = concatMap (gresFromAvail hsc_env prov)\\n\\nimportsFromIface :: HscEnv -> ModIface -> ImpDeclSpec -> Maybe NameSet -> GlobalRdrEnv\\nimportsFromIface hsc_env iface decl_spec hidden = mkGlobalRdrEnv $ case hidden of\\n Nothing -> all_gres\\n Just hidden_names -> filter (not . (`elemNameSet` hidden_names) . greName) all_gres\\n where\\n all_gres = gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\nrnNamespaceSpecifier :: NamespaceSpecifier GhcPs -> NamespaceSpecifier GhcRn\\nrnNamespaceSpecifier (NoNamespaceSpecifier _) = NoNamespaceSpecifier noExtField\\nrnNamespaceSpecifier (TypeNamespaceSpecifier x) = TypeNamespaceSpecifier x\\nrnNamespaceSpecifier (DataNamespaceSpecifier x) = DataNamespaceSpecifier x\\n\\nfilterImports\\n :: HasDebugCallStack\\n => HscEnv\\n -> ModIface\\n -> ImpDeclSpec\\n -- ^ Import spec\\n -> Maybe (ImportListInterpretation, [LIE GhcPs])\\n -- ^ Whether this is a \\"hiding\\" import list\\n -> RnM (Maybe (ImportListInterpretation, [LIE GhcRn]), -- Import spec w/ Names\\n ImpUserList, -- same, but designed for storage in interfaces\\n GlobalRdrEnv) -- Same again, but in GRE form\\nfilterImports hsc_env iface decl_spec Nothing\\n = return (Nothing, ImpUserAll, importsFromIface hsc_env iface decl_spec Nothing)\\nfilterImports hsc_env iface decl_spec (Just (want_hiding, import_items))\\n = do -- check for errors, convert RdrNames to Names\\n items1 <- mapM lookup_lie import_items\\n\\n let items2 :: [(LIE GhcRn, [GlobalRdrElt])]\\n items2 = concat items1\\n -- NB we may have duplicates, and several items\\n -- for the same parent; e.g N(x) and N(y)\\n\\n (gres, imp_user_list) = case want_hiding of\\n Exactly ->\\n let gres = concatMap (gresFromIE decl_spec) items2\\n gre_env = mkGlobalRdrEnv gres\\n implicit_parents = mkNameSet $ mapMaybe parentOfImplicitlyImportedGRE gres\\n in (gre_env, ImpUserExplicit (gresToAvailInfo $ globalRdrEnvElts $ gre_env) implicit_parents)\\n EverythingBut ->\\n let hidden_names = mkNameSet $ concatMap (map greName . snd) items2\\n in (importsFromIface hsc_env iface decl_spec (Just hidden_names), ImpUserEverythingBut hidden_names)\\n\\n return (Just (want_hiding, map fst items2), imp_user_list, gres)\\n where\\n import_mod = mi_module iface\\n all_avails = mi_exports iface\\n imp_occ_env = mkImportOccEnv hsc_env decl_spec all_avails\\n\\n -- Look up a parent (type constructor, class or data constructor)\\n -- in an import.\\n lookup_parent :: IE GhcPs -> RdrName -> IELookupM ImpOccItem\\n lookup_parent ie rdr =\\n assertPpr (not $ isVarNameSpace ns)\\n (vcat [ text \\"filterImports lookup_parent: unexpected variable\\"\\n , text \\"rdr:\\" <+> ppr rdr\\n , text \\"namespace:\\" <+> pprNameSpace ns ]) $\\n do { xs <- lookup_names ie rdr\\n ; case xs of\\n cax :| [] -> return cax\\n _ -> pprPanic \\"filter_imports lookup_parent ambiguous\\" $\\n vcat [ text \\"rdr:\\" <+> ppr rdr\\n , text \\"lookups:\\" <+> ppr (fmap imp_item xs) ] }\\n -- Looking up non-variables is always unambiguous,\\n -- as there can be at most one corresponding item\\n -- in the imp_occ_env.\\n -- See item (1) of Note [Exporting duplicate declarations]\\n -- in GHC.Tc.Gen.Export.\\n where\\n occ = rdrNameOcc rdr\\n ns = occNameSpace occ\\n\\n -- Look up a RdrName used in an import, returning multiple values if there\\n -- are several fields with the same name exposed by the module\\n lookup_names :: IE GhcPs -> RdrName -> IELookupM (NonEmpty ImpOccItem)\\n lookup_names ie rdr\\n | isQual rdr\\n = failLookupWith (QualImportError rdr)\\n | otherwise\\n = case lookups of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n item:items -> return $ item :| items\\n where\\n lookups = concatMap nonDetNameEnvElts\\n $ lookupImpOccEnv (RelevantGREsFOS WantNormal) imp_occ_env (rdrNameOcc rdr)\\n\\n lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, [GlobalRdrElt])]\\n lookup_lie (L loc ieRdr)\\n = setSrcSpanA loc $\\n do (stuff, warns) <- run_lookup ([],[]) (lookup_ie ieRdr)\\n mapM_ (addTcRnDiagnostic <=< warning_msg) warns\\n return [ (L loc ie, gres) | (ie,gres) <- stuff ]\\n where\\n\\n -- Warn when importing T(..) and no children are brought in scope\\n warning_msg (DodgyImport reason) =\\n pure (TcRnDodgyImports reason)\\n warning_msg MissingImportList =\\n pure (TcRnMissingImportList ieRdr)\\n warning_msg (BadImportW ie sub) = do\\n -- \'BadImportW\' is only constructed below in \'bad_import_w\', in\\n -- the \'EverythingBut\' case, so here we assume a \'hiding\' clause.\\n (reason :| _) <- badImportItemErr iface decl_spec ie sub all_avails\\n pure (TcRnDodgyImports (DodgyImportsHiding reason))\\n warning_msg (DeprecatedExport n w) =\\n pure $ TcRnPragmaWarning\\n PragmaWarningExport\\n { pwarn_occname = occName n\\n , pwarn_impmod = moduleName import_mod }\\n w\\n\\n run_lookup :: a -> IELookupM a -> TcRn a\\n run_lookup def m = case m of\\n Failed err -> do\\n msgs <- lookup_err_msgs err\\n forM_ msgs $ \\\\msg -> addErr (TcRnImportLookup msg)\\n return def\\n Succeeded a -> return a\\n\\n lookup_err_msgs err = case err of\\n BadImport ie sub -> badImportItemErr iface decl_spec ie sub all_avails\\n IllegalImport -> pure $ NE.singleton ImportLookupIllegal\\n QualImportError rdr -> pure $ NE.singleton (ImportLookupQualified rdr)\\n\\n -- For each import item, we convert its RdrNames to Names,\\n -- and at the same time compute all the GlobalRdrElt corresponding\\n -- to what is actually imported by this item.\\n -- Returns Nothing on error.\\n --\\n -- Returns a list because, with DuplicateRecordFields, a naked\\n -- import/export of a record field can correspond to multiple\\n -- different GlobalRdrElts. See Note [Importing DuplicateRecordFields].\\n lookup_ie :: IE GhcPs\\n -> IELookupM ([(IE GhcRn, [GlobalRdrElt])], [IELookupWarning])\\n lookup_ie ie = handle_bad_import $\\n case ie of\\n IEVar _ (L l n) _ -> do\\n -- See Note [Importing DuplicateRecordFields]\\n xs <- lookup_names ie (ieWrappedName n)\\n let gres = map imp_item $ NE.toList xs\\n export_depr_warns\\n | want_hiding == Exactly\\n = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ( [ (IEVar Nothing (L l (replaceWrappedName n name)) noDocstring, [gre])\\n | gre <- gres\\n , let name = greName gre ]\\n , export_depr_warns )\\n\\n IEThingAll x ns_spec (L l tc) _ -> do\\n ImpOccItem { imp_item = gre\\n , imp_bundled = bundled_gres\\n , imp_is_parent = is_par\\n }\\n <- lookup_parent ie $ ieWrappedName tc\\n let name = greName gre\\n\\n child_gres :: [GlobalRdrElt]\\n child_gres\\n | is_par = filterByNamespaceSpecifierGREs ns_spec bundled_gres\\n | otherwise = []\\n\\n imp_list_warn\\n\\n | null child_gres\\n -- e.g. f(..) or T(..) where T is a type synonym\\n = [DodgyImport (DodgyImportsEmptyParent ie ns_spec gre)]\\n\\n -- e.g. import M( T(..) )\\n | not (is_qual decl_spec)\\n = [MissingImportList]\\n\\n | otherwise\\n = []\\n\\n renamed_ie = IEThingAll (x { ieta_warning = Nothing })\\n (rnNamespaceSpecifier ns_spec)\\n (L l (replaceWrappedName tc name))\\n noDocstring\\n export_depr_warn\\n | want_hiding == Exactly\\n = maybeToList $ mk_depr_export_warning gre\\n -- We don\'t want to warn about the children as they\\n -- are not explicitly mentioned; the warning will\\n -- be emitted later on if they are used\\n | otherwise = []\\n\\n return ( [(renamed_ie, gre:child_gres)]\\n , imp_list_warn ++ export_depr_warn)\\n\\n\\n IEThingAbs _ (L l tc\') _\\n | want_hiding == EverythingBut -- hiding ( C )\\n -- Here the \'C\' can be a data constructor\\n -- *or* a type/class, or even both\\n -> let tc = ieWrappedName tc\'\\n tc_name = lookup_parent ie tc\\n dc_name = lookup_parent ie (setRdrNameSpace tc srcDataName)\\n in\\n case catIELookupM [ tc_name, dc_name ] of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n names -> return ( [mkIEThingAbs tc\' l (imp_item name) | name <- names], [])\\n | otherwise\\n -> do ImpOccItem { imp_item = gre } <- lookup_parent ie (ieWrappedName tc\')\\n return ( [mkIEThingAbs tc\' l gre]\\n , maybeToList $ mk_depr_export_warning gre)\\n\\n IEThingWith (deprecation, ann) ltc@(L l rdr_tc) wc rdr_ns _ -> do\\n ImpOccItem { imp_item = gre, imp_bundled = subnames }\\n <- lookup_parent (IEThingAbs Nothing ltc noDocstring) (ieWrappedName rdr_tc)\\n let name = greName gre\\n\\n -- Look up the children in the sub-names of the parent\\n -- See Note [Importing DuplicateRecordFields]\\n let (children_errs, childnames) = lookupChildren subnames rdr_ns\\n\\n bad_import_warns <-\\n if null children_errs then return [] else\\n let items = map lce_wrapped_name children_errs\\n ie = IEThingWith (deprecation, ann) ltc wc items noDocstring\\n -- We are trying to import T( a,b,c,d ), and failed\\n -- to find \'b\' and \'d\'. So we make up an import item\\n -- to report as failing, namely T( b, d ).\\n -- c.f. #15413\\n subordinate_err = mkSubordinateError gre children_errs\\n in bad_import_w ie subordinate_err\\n\\n let name\' = replaceWrappedName rdr_tc name\\n childnames\' = map (to_ie_post_rn . fmap greName) childnames\\n gres = gre : map unLoc childnames\\n export_depr_warns\\n | want_hiding == Exactly = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ([ (IEThingWith (Nothing, ann) (L l name\') wc childnames\' noDocstring\\n ,gres)]\\n , bad_import_warns ++ export_depr_warns)\\n\\n IEWholeNamespace x ns_spec -> do\\n let mod_name = moduleName import_mod\\n names = map greName gres\\n renamed_ie = IEWholeNamespace x { iewn_warning = Nothing\\n , iewn_names = names }\\n (rnNamespaceSpecifier ns_spec)\\n gres = filterByNamespaceSpecifierGREs ns_spec $\\n gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n dodgy_warn\\n | null gres = [DodgyImport (DodgyImportsWildcard mod_name ns_spec)]\\n | otherwise = []\\n return ([(renamed_ie, gres)],\\n dodgy_warn)\\n\\n _other -> failLookupWith IllegalImport\\n -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed...\\n -- all of those constitute errors.\\n\\n where\\n mkIEThingAbs tc l gre\\n = (IEThingAbs Nothing (L l (replaceWrappedName tc n)) noDocstring, [gre])\\n where n = greName gre\\n\\n -- N.B. imports never have docstrings\\n noDocstring = Nothing\\n\\n handle_bad_import m = catchIELookup m $ \\\\case\\n BadImport ie sub -> do\\n ws <- bad_import_w ie sub\\n return ([], ws)\\n err -> failLookupWith err\\n\\n bad_import_w :: IE GhcPs -> IsSubordinateError -> IELookupM [IELookupWarning]\\n bad_import_w ie sub\\n | want_hiding == EverythingBut = return [BadImportW ie sub]\\n | otherwise = failLookupWith (BadImport ie sub)\\n\\n mk_depr_export_warning gre\\n = DeprecatedExport name <$> mi_export_warn_fn iface name\\n where\\n name = greName gre\\n\\n-- | Assuming a subordinate item could not be found, do another lookup for a\\n-- more specific error message.\\nmkBadExportSubordinate :: [GlobalRdrElt] -> LIEWrappedName GhcPs -> BadExportSubordinate\\nmkBadExportSubordinate child_gres n =\\n case lookupChildren child_gres [n] of\\n (LookupChildNonType {lce_nontype_item = g} : _, _) -> BadExportSubordinateNonType g\\n (LookupChildNonData {lce_nondata_item = g} : _, _) -> BadExportSubordinateNonData g\\n _ -> BadExportSubordinateNotFound n\\n\\ntype IELookupM = MaybeErr IELookupError\\n\\ndata IELookupWarning\\n = BadImportW (IE GhcPs) IsSubordinateError\\n | MissingImportList\\n | DodgyImport DodgyImportsReason\\n | DeprecatedExport Name (WarningTxt GhcRn)\\n\\n-- | Is this import/export item a subordinate or not?\\ndata IsSubordinateError\\n = IsSubordinateError { subordinate_err_parent :: !GlobalRdrElt\\n , subordinate_err_unavailable :: [FastString]\\n , subordinate_err_nontype :: [GlobalRdrElt]\\n , subordinate_err_nondata :: [GlobalRdrElt] }\\n | IsNotSubordinate\\n\\nmkSubordinateError :: GlobalRdrElt -> [LookupChildError] -> IsSubordinateError\\nmkSubordinateError gre children_errs = foldr add init_acc children_errs\\n where\\n init_acc :: IsSubordinateError\\n init_acc = IsSubordinateError gre [] [] []\\n\\n add :: LookupChildError -> IsSubordinateError -> IsSubordinateError\\n add children_err sub@IsSubordinateError{} =\\n case children_err of\\n LookupChildNonType{lce_nontype_item = g} ->\\n sub { subordinate_err_nontype = g : subordinate_err_nontype sub }\\n LookupChildNonData{lce_nondata_item = g} ->\\n sub { subordinate_err_nondata = g : subordinate_err_nondata sub }\\n LookupChildNotFound (L _ wname) ->\\n let fs = (occNameFS . rdrNameOcc . ieWrappedName) wname\\n in sub { subordinate_err_unavailable = fs : subordinate_err_unavailable sub }\\n add _ IsNotSubordinate = panic \\"mkSubordinateError: IsNotSubordinate\\"\\n\\ndata IELookupError\\n = QualImportError RdrName\\n | BadImport (IE GhcPs) IsSubordinateError\\n | IllegalImport\\n\\nfailLookupWith :: IELookupError -> IELookupM a\\nfailLookupWith err = Failed err\\n\\ncatchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a\\ncatchIELookup m h = case m of\\n Succeeded r -> return r\\n Failed err -> h err\\n\\ncatIELookupM :: [IELookupM a] -> [a]\\ncatIELookupM ms = [ a | Succeeded a <- ms ]\\n\\n-- | Information associated to an \'AvailInfo\' used in constructing\\n-- an \'OccEnv\' corresponding to imports.\\n--\\n-- See Note [Dealing with imports].\\ndata ImpOccItem\\n = ImpOccItem\\n { imp_item :: GlobalRdrElt\\n -- ^ The import item\\n , imp_bundled :: [GlobalRdrElt]\\n -- ^ Items bundled in the Avail this import item came from,\\n -- not including the import item itself if it is a parent.\\n , imp_is_parent :: Bool\\n -- ^ Is the import item a parent? See Note [Dealing with imports].\\n }\\n\\ninstance Outputable ImpOccItem where\\n ppr (ImpOccItem { imp_item = item, imp_bundled = bundled, imp_is_parent = is_par })\\n = braces $ hsep\\n [ text \\"ImpOccItem\\"\\n , if is_par then text \\"[is_par]\\" else empty\\n , ppr (greName item) <+> ppr (greParent item)\\n , braces $ text \\"bundled:\\" <+> ppr (map greName bundled) ]\\n\\n-- | Make an \'OccEnv\' of all the imports.\\n--\\n-- Complicated by the fact that associated data types and pattern synonyms\\n-- can appear twice. See Note [Dealing with imports].\\nmkImportOccEnv :: HscEnv -> ImpDeclSpec -> [IfaceExport] -> OccEnv (NameEnv ImpOccItem)\\nmkImportOccEnv hsc_env decl_spec all_avails =\\n mkOccEnv_C (plusNameEnv_C combine)\\n [ (occ, mkNameEnv [(nm, item)])\\n | avail <- all_avails\\n , let gres = gresFromAvail hsc_env (Just hiding_spec) avail\\n , gre <- gres\\n , let nm = greName gre\\n occ = greOccName gre\\n (is_parent, bundled) = case avail of\\n AvailTC c _\\n | c == nm -- (Recall the AvailTC invariant from GHC.Types.AvailInfo)\\n -> ( True, drop 1 gres ) -- \\"drop 1\\": don\'t include the parent itself.\\n | otherwise\\n -> ( False, gres )\\n _ -> ( False, [] )\\n item = ImpOccItem\\n { imp_item = gre\\n , imp_bundled = bundled\\n , imp_is_parent = is_parent }\\n ]\\n where\\n\\n hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\n -- See Note [Dealing with imports]\\n -- \'combine\' may be called for associated data types which appear\\n -- twice in the all_avails. In the example, we have two Avails for T,\\n -- namely T(T,T1,T2,T3) and C(C,T), and we combine them by dropping the\\n -- latter, in which T is not the parent.\\n combine :: ImpOccItem -> ImpOccItem -> ImpOccItem\\n combine item1@(ImpOccItem { imp_item = gre1, imp_is_parent = is_parent1 })\\n item2@(ImpOccItem { imp_item = gre2, imp_is_parent = is_parent2 })\\n | is_parent1 || is_parent2\\n , not (isRecFldGRE gre1 || isRecFldGRE gre2) -- NB: does not force GREInfo.\\n , let name1 = greName gre1\\n name2 = greName gre2\\n gre = gre1 `plusGRE` gre2\\n -- See Note [Preserve parent information when combining import OccEnvs]\\n = assertPpr (name1 == name2)\\n (ppr name1 <+> ppr name2) $\\n if is_parent1\\n then item1 { imp_item = gre }\\n else item2 { imp_item = gre }\\n -- Discard C(C,T) in favour of T(T, T1, T2, T3).\\n\\n -- \'combine\' may also be called for pattern synonyms which appear both\\n -- unassociated and associated (see Note [Importing PatternSynonyms]).\\n combine item1@(ImpOccItem { imp_item = c1, imp_bundled = kids1 })\\n item2@(ImpOccItem { imp_item = c2, imp_bundled = kids2 })\\n = assertPpr (greName c1 == greName c2\\n && (not (null kids1 && null kids2)))\\n (ppr c1 <+> ppr c2 <+> ppr kids1 <+> ppr kids2) $\\n if null kids1\\n then item2\\n else item1\\n -- Discard standalone pattern P in favour of T(P).\\n\\n-- | Essentially like @lookupGRE env (LookupOccName occ which_gres)@,\\n-- but working with \'ImpOccItem\'s instead of \'GlobalRdrElt\'s.\\nlookupImpOccEnv :: WhichGREs GREInfo\\n -> OccEnv (NameEnv ImpOccItem) -> OccName -> [NameEnv ImpOccItem]\\nlookupImpOccEnv which_gres env occ =\\n mapMaybe relevant_items $ lookupOccEnv_AllNameSpaces env occ\\n where\\n is_relevant :: ImpOccItem -> Bool\\n is_relevant (ImpOccItem { imp_item = gre }) =\\n greIsRelevant which_gres (occNameSpace occ) gre\\n relevant_items :: NameEnv ImpOccItem -> Maybe (NameEnv ImpOccItem)\\n relevant_items nms\\n | let nms\' = filterNameEnv is_relevant nms\\n = if isEmptyNameEnv nms\'\\n then Nothing\\n else Just nms\'\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{Import/Export Utils}\\n* *\\n************************************************************************\\n-}\\n\\n-- | Given an import\\\\/export spec, appropriately set the @gre_imp@ field\\n-- for the \'GlobalRdrElt\'s.\\ngresFromIE :: ImpDeclSpec -> (LIE GhcRn, [GlobalRdrElt]) -> [GlobalRdrElt]\\ngresFromIE decl_spec (L loc ie, gres)\\n = map set_gre_imp gres\\n where\\n is_explicit = case ie of\\n IEThingAll _ _ name _ -> \\\\n -> n == lieWrappedName name\\n IEWholeNamespace _ _ -> \\\\_ -> False\\n _ -> \\\\_ -> True\\n prov_fn name\\n = ImpSpec { is_decl = decl_spec, is_item = item_spec }\\n where\\n item_spec = ImpSome { is_explicit = is_explicit name\\n , is_iloc = locA loc }\\n set_gre_imp gre@( GRE { gre_name = nm } )\\n = gre { gre_imp = unitBag $ prov_fn nm }\\n\\nparentOfImplicitlyImportedGRE :: Outputable info => GlobalRdrEltX info -> Maybe Name\\nparentOfImplicitlyImportedGRE gre =\\n if any (explicit_import . is_item) $ gre_imp gre\\n then Nothing\\n else greParent_maybe gre\\n where\\n explicit_import :: ImpItemSpec -> Bool\\n explicit_import (ImpAll {}) =\\n pprPanic \\"parentOfImplicitlyImportedGRE: ImpAll\\" (ppr gre)\\n explicit_import (ImpSome { is_explicit }) = is_explicit\\n\\n{- Note [Children for duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider the module\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (F(foo, MkFInt, MkFBool)) where\\n data family F a\\n data instance F Int = MkFInt { foo :: Int }\\n data instance F Bool = MkFBool { foo :: Bool }\\n\\nThe `foo` in the export list refers to *both* selectors! For this\\nreason, lookupChildren builds an environment that maps the FastString\\nto a list of items, rather than a single item.\\n-}\\n\\nmkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]\\nmkChildEnv gres = foldr add emptyNameEnv gres\\n where\\n add gre env = case greParent gre of\\n ParentIs p -> extendNameEnv_Acc (:) Utils.singleton env p gre\\n NoParent -> env\\n\\nfindChildren :: NameEnv [a] -> Name -> [a]\\nfindChildren env n = lookupNameEnv env n `orElse` []\\n\\ndata LookupChildError\\n = LookupChildNotFound { lce_wrapped_name :: !(LIEWrappedName GhcPs) }\\n | LookupChildNonType { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nontype_item :: !GlobalRdrElt }\\n | LookupChildNonData { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nondata_item :: !GlobalRdrElt }\\n\\nlookupChildren :: [GlobalRdrElt]\\n -> [LIEWrappedName GhcPs]\\n -> ( [LookupChildError] -- The ones for which the lookup failed\\n , [LocatedA GlobalRdrElt] )\\n-- (lookupChildren all_kids rdr_items) maps each rdr_item to its\\n-- corresponding Name in all_kids, if the former exists\\n-- The matching is done by FastString, not OccName, so that\\n-- Cls( meth, AssocTy )\\n-- will correctly find AssocTy among the all_kids of Cls, even though\\n-- the RdrName for AssocTy may have a (bogus) DataName namespace\\n-- (Really the rdr_items should be FastStrings in the first place.)\\nlookupChildren all_kids rdr_items = (fails, successes)\\n where\\n mb_xs = map do_one rdr_items\\n fails = [ err | Failed err <- mb_xs ]\\n successes = [ ok | Succeeded oks <- mb_xs, ok <- NE.toList oks ]\\n\\n do_one :: LIEWrappedName GhcPs -> MaybeErr LookupChildError (NonEmpty (LocatedA GlobalRdrElt))\\n do_one item@(L l r) =\\n case r of\\n IEName{}\\n -- IEName (unadorned name) places no restriction on the namespace of\\n -- the imported entity, so we look in both `val_gres` and `typ_gres`.\\n -- In case of conflict (punning), the value namespace takes priority.\\n -- See Note [Prioritise the value namespace in subordinate import lists]\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEType{}\\n -- IEType (\'type\' namespace specifier) restricts the lookup to the\\n -- type namespace, i.e. to `typ_gres`. In case of failure, we check\\n -- `val_gres` to produce a more helpful error message.\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- val_gres -> Failed $ LookupChildNonType item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEData{}\\n -- IEData (\'data\' namespace specifier) restricts the lookup to the\\n -- data namespace, i.e. to `val_gres`. In case of failure, we check\\n -- `typ_gres` to produce a more helpful error message.\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- typ_gres -> Failed $ LookupChildNonData item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEPattern{} -> panic \\"lookupChildren: IEPattern\\" -- Never happens (invalid syntax)\\n IEDefault{} -> panic \\"lookupChildren: IEDefault\\" -- Never happens (invalid syntax)\\n where\\n fs = (occNameFS . rdrNameOcc . ieWrappedName) r\\n gres = fromMaybe [] (lookupFsEnv kid_env fs)\\n (val_gres, typ_gres) = partition (isValNameSpace . greNameSpace) gres\\n\\n -- See Note [Children for duplicate record fields]\\n kid_env :: FastStringEnv [GlobalRdrElt]\\n kid_env = extendFsEnvList_C (++) emptyFsEnv\\n [(occNameFS (occName x), [x]) | x <- all_kids]\\n\\n\\n{- Note [Prioritise the value namespace in subordinate import lists]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider this program that defines a class that has both an associated type\\nnamed (#) and a method named (#)\\n\\n module M_assoc where\\n class C a b where\\n type a # b\\n (#) :: a -> b -> ()\\n module N_assoc where\\n import M_assoc( C((#)) )\\n\\nIn the import declaration, when we see the unadorned name (#) in the subordinate\\nimport list of C, which children should we bring into scope? Our options are:\\n\\n a) only the method (#)\\n b) only the associated type (#)\\n c) both the method and the associated type\\n\\nTo follow the precedent established by top-level items, we go with option (a).\\nIndeed, consider a slightly different program\\n\\n module M_top where\\n type family a # b\\n a # b = ()\\n module N_top where\\n import M_top( (#) )\\n\\nHere the import brings only the function (#) into scope, and one has to say\\n`type (#)` to get the type family.\\n-}\\n\\n-------------------------------\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused names}\\n* *\\n*********************************************************\\n-}\\n\\nreportUnusedNames :: TcGblEnv -> HscSource -> RnM ()\\nreportUnusedNames gbl_env hsc_src\\n = do { keep <- readTcRef (tcg_keep gbl_env)\\n ; traceRn \\"RUN\\" (ppr (tcg_dus gbl_env))\\n ; warnUnusedImportDecls gbl_env hsc_src\\n ; warnUnusedTopBinds $ unused_locals keep\\n ; warnMissingSignatures gbl_env\\n ; warnMissingKindSignatures gbl_env }\\n where\\n used_names :: NameSet -> NameSet\\n used_names keep = findUses (tcg_dus gbl_env) emptyNameSet `unionNameSet` keep\\n -- NB: currently, if f x = g, we only treat \'g\' as used if \'f\' is used\\n -- Hence findUses\\n\\n -- Collect the defined names from the in-scope environment\\n defined_names :: [GlobalRdrElt]\\n defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)\\n\\n kids_env = mkChildEnv defined_names\\n -- This is done in mkExports too; duplicated work\\n\\n gre_is_used :: NameSet -> GlobalRdrElt -> Bool\\n gre_is_used used_names gre0\\n = name `elemNameSet` used_names\\n || any (\\\\ gre -> greName gre `elemNameSet` used_names) (findChildren kids_env name)\\n -- A use of C implies a use of T,\\n -- if C was brought into scope by T(..) or T(C)\\n where\\n name = greName gre0\\n\\n -- Filter out the ones that are\\n -- (a) defined in this module, and\\n -- (b) not defined by a \'deriving\' clause\\n -- The latter have an Internal Name, so we can filter them out easily\\n unused_locals :: NameSet -> [GlobalRdrElt]\\n unused_locals keep =\\n let -- Note that defined_and_used, defined_but_not_used\\n -- are both [GRE]; that\'s why we need defined_and_used\\n -- rather than just used_names\\n _defined_and_used, defined_but_not_used :: [GlobalRdrElt]\\n (_defined_and_used, defined_but_not_used)\\n = partition (gre_is_used (used_names keep)) defined_names\\n\\n in filter is_unused_local defined_but_not_used\\n is_unused_local :: GlobalRdrElt -> Bool\\n is_unused_local gre = isLocalGRE gre\\n && isExternalName (greName gre)\\n\\n{- *********************************************************************\\n* *\\n Missing signatures\\n* *\\n********************************************************************* -}\\n\\n{-\\nNote [Missing signatures]\\n~~~~~~~~~~~~~~~~~~~~~~~~~\\nThere are four warning flags in play:\\n\\n * -Wmissing-exported-signatures\\n Warn about any exported top-level function/value without a type signature.\\n Does not include pattern synonyms.\\n\\n * -Wmissing-signatures\\n Warn about any top-level function/value without a type signature. Does not\\n include pattern synonyms. Takes priority over -Wmissing-exported-signatures.\\n\\n * -Wmissing-exported-pattern-synonym-signatures\\n Warn about any exported pattern synonym without a type signature.\\n\\n * -Wmissing-pattern-synonym-signatures\\n Warn about any pattern synonym without a type signature. Takes priority over\\n -Wmissing-exported-pattern-synonym-signatures.\\n\\n-}\\n\\n-- | Warn the user about top level binders that lack type signatures.\\n-- Called /after/ type inference, so that we can report the\\n-- inferred type of the function\\nwarnMissingSignatures :: TcGblEnv -> RnM ()\\nwarnMissingSignatures gbl_env\\n = do { let exports = availsToNameSet (tcg_exports gbl_env)\\n sig_ns = tcg_sigs gbl_env\\n -- We use sig_ns to exclude top-level bindings that are generated by GHC\\n binds = collectHsBindsBinders CollNoDictBinders $ tcg_binds gbl_env\\n pat_syns = tcg_patsyns gbl_env\\n\\n not_ghc_generated :: Name -> Bool\\n not_ghc_generated name = name `elemNameSet` sig_ns\\n\\n add_binding_warn :: Id -> RnM ()\\n add_binding_warn id =\\n when (not_ghc_generated name) $\\n do { env <- liftZonkM $ tcInitTidyEnv -- Why not use emptyTidyEnv?\\n ; let ty = tidyOpenType env (idType id)\\n missing = MissingTopLevelBindingSig name ty\\n diag = TcRnMissingSignature missing exported\\n ; addDiagnosticAt (getSrcSpan name) diag }\\n where\\n name = idName id\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n add_patsyn_warn :: PatSyn -> RnM ()\\n add_patsyn_warn ps =\\n when (not_ghc_generated name) $\\n addDiagnosticAt (getSrcSpan name)\\n (TcRnMissingSignature missing exported)\\n where\\n name = patSynName ps\\n missing = MissingPatSynSig ps\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n -- Warn about missing signatures\\n -- Do this only when we have a type to offer\\n -- See Note [Missing signatures]\\n ; mapM_ add_binding_warn binds\\n ; mapM_ add_patsyn_warn pat_syns\\n }\\n\\n-- | Warn the user about tycons that lack kind signatures.\\n-- Called /after/ type (and kind) inference, so that we can report the\\n-- inferred kinds.\\nwarnMissingKindSignatures :: TcGblEnv -> RnM ()\\nwarnMissingKindSignatures gbl_env\\n = do { cusks_enabled <- xoptM LangExt.CUSKs\\n ; mapM_ (add_ty_warn cusks_enabled) tcs\\n }\\n where\\n tcs = tcg_tcs gbl_env\\n ksig_ns = tcg_ksigs gbl_env\\n exports = availsToNameSet (tcg_exports gbl_env)\\n\\n has_kind_signature :: Name -> Bool\\n has_kind_signature name = name `elemNameSet` ksig_ns\\n\\n add_ty_warn :: Bool -> TyCon -> RnM ()\\n add_ty_warn cusks_enabled tyCon =\\n when (has_kind_signature name) $\\n addDiagnosticAt (getSrcSpan name) diag\\n where\\n name = tyConName tyCon\\n diag = TcRnMissingSignature missing exported\\n missing = MissingTyConKindSig tyCon cusks_enabled\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused imports}\\n* *\\n*********************************************************\\n\\nThis code finds which import declarations are unused. The\\nspecification and implementation notes are here:\\n https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/unused-imports\\n\\nSee also Note [Choosing the best import declaration] in GHC.Types.Name.Reader\\n-}\\n\\ntype ImportDeclUsage\\n = ( LImportDecl GhcRn -- The import declaration\\n , [GlobalRdrElt] -- What *is* used (normalised)\\n , [Name] -- What is imported but *not* used\\n , [NamespaceSpecifier GhcRn] ) -- Unused wildcards\\n\\nwarnUnusedImportDecls :: TcGblEnv -> HscSource -> RnM ()\\nwarnUnusedImportDecls gbl_env hsc_src\\n = do { uses <- readMutVar (tcg_used_gres gbl_env)\\n ; let imports = tcg_rn_imports gbl_env\\n rdr_env = tcg_rdr_env gbl_env\\n\\n -- We should only warn for unnecessary *user* imports, but deciding\\n -- minimal imports should take generated imports into account\\n ; let usageUserImports = findImportUsage (excludeGenerated imports) uses\\n usageAllImports = findImportUsage imports uses\\n\\n ; traceRn \\"warnUnusedImportDecls\\" $\\n (vcat [ text \\"Uses:\\" <+> ppr uses\\n , text \\"Usage all user imports: \\" <+> ppr usageUserImports\\n , text \\"Usage all imports: \\" <+> ppr usageAllImports])\\n\\n ; mapM_ (warnUnusedImport rdr_env) usageUserImports\\n\\n ; whenGOptM Opt_D_dump_minimal_imports $\\n printMinimalImports hsc_src usageAllImports }\\n\\n-- | Exclude generated imports\\nexcludeGenerated :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\nexcludeGenerated = filterOut (isGeneratedImport . ideclOrigin . ideclExt . unLoc)\\n\\nfindImportUsage :: [LImportDecl GhcRn]\\n -> [GlobalRdrElt]\\n -> [ImportDeclUsage]\\n\\nfindImportUsage imports used_gres\\n = map unused_decl imports\\n where\\n import_usage :: ImportMap\\n import_usage = mkImportMap used_gres\\n\\n unused_decl :: LImportDecl GhcRn -> ImportDeclUsage\\n unused_decl decl@(L _ (ImportDecl { ideclImportList = imps }))\\n = -- pprTrace \\"unused_decl\\" (vcat [ ppr decl\\n -- , text \\"used\\" <+> ppr used_gres\\n -- , text \\"unused\\" <+> ppr unused_names ]) $\\n (decl, used_gres, unused_names, unused_wcs)\\n where\\n used_gres = lookupImportMap decl import_usage\\n\\n used_gre_env = mkGlobalRdrEnv used_gres\\n used_parents = mkNameSet (mapMaybe greParent_maybe used_gres)\\n\\n (unused_names, unused_wcs) -- Not trivial; see eg #7454\\n = case imps of\\n Just (Exactly, imp_ies) ->\\n let unused = foldr (add_unused . unLoc) emptyUnusedNames imp_ies\\n nms = nameSetElemsStable (collectUnusedNames unused)\\n wcs = collectUnusedWildcards unused\\n in (nms, wcs)\\n _other -> ([], []) -- No explicit import list => no unused-name list\\n\\n add_unused :: IE GhcRn -> UnusedNames -> UnusedNames\\n add_unused (IEVar _ n _) acc = add_unused_name (lieWrappedName n) True acc\\n add_unused (IEThingAbs _ n _) acc = add_unused_name (lieWrappedName n) False acc\\n add_unused (IEThingAll _ _ n _) acc = add_unused_all (lieWrappedName n) acc\\n add_unused (IEThingWith _ p wc ns _) acc = add_wc_all (add_unused_with pn xs acc)\\n where pn = lieWrappedName p\\n xs = map lieWrappedName ns\\n add_wc_all = case wc of\\n NoIEWildcard -> id\\n IEWildcard _ -> add_unused_all pn\\n add_unused (IEWholeNamespace x ns_spec) acc = add_unused_wildcard ns_spec (iewn_names x) acc\\n add_unused _ acc = acc\\n\\n add_unused_name :: Name -> Bool -> UnusedNames -> UnusedNames\\n add_unused_name n is_ie_var acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | is_ie_var\\n , isFieldName n\\n -- See Note [Reporting unused imported duplicate record fields]\\n = let\\n fs = getOccFS n\\n (flds, flds_used) = lookupFsEnv acc_fs fs `orElse` (emptyNameSet, Any False)\\n acc_fs\' = extendFsEnv acc_fs fs (extendNameSet flds n, Any used S.<> flds_used)\\n in UnusedNames acc_ns acc_wcs acc_fs\'\\n\\n | used\\n = acc\\n\\n | otherwise\\n = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n where\\n used = isJust $ lookupGRE_Name used_gre_env n\\n\\n add_unused_all :: Name -> UnusedNames -> UnusedNames\\n add_unused_all n acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | Just {} <- lookupGRE_Name used_gre_env n = acc\\n | n `elemNameSet` used_parents = acc\\n | otherwise = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n\\n add_unused_with :: Name -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_with p ns acc\\n | all (`elemNameSet` acc1_ns) ns = add_unused_name p False acc1\\n | otherwise = acc1\\n where\\n acc1@(UnusedNames acc1_ns _ _) = foldr (\\\\n acc\' -> add_unused_name n False acc\') acc ns\\n -- If you use \'signum\' from Num, then the user may well have\\n -- imported Num(signum). We don\'t want to complain that\\n -- Num is not itself mentioned. Hence the two cases in add_unused_with.\\n\\n add_unused_wildcard :: NamespaceSpecifier GhcRn -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_wildcard ns_spec names acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | any_used = acc\\n | otherwise = UnusedNames acc_ns (ns_spec : acc_wcs) acc_fs\\n where\\n -- A wildcard `type ..` or `data ..` is used if at least one of\\n -- the names it expands to is used\\n any_used = any (isJust . lookupGRE_Name used_gre_env) names\\n\\n\\n-- | An accumulator for unused names in an import list.\\n--\\n-- See Note [Reporting unused imported duplicate record fields].\\ndata UnusedNames =\\n UnusedNames\\n { unused_names :: NameSet\\n -- ^ Unused \'Name\'s in an import list, not including record fields\\n -- that are plain \'IEVar\' imports (tracked by \'rec_fld_uses\')\\n -- or wildcard imports (tracked by \'unused_wildcards\').\\n , unused_wildcards :: [NamespaceSpecifier GhcRn]\\n -- ^ Unused wildcards @type ..@ or @data ..@ in an import list.\\n , rec_fld_uses :: FastStringEnv (NameSet, Any)\\n -- ^ Record fields imported without a parent (i.e. an \'IEVar\' import).\\n --\\n -- The \'Any\' value records whether any of the record fields\\n -- sharing the same underlying \'FastString\' have been used.\\n }\\n\\nemptyUnusedNames :: UnusedNames\\nemptyUnusedNames = UnusedNames emptyNameSet [] emptyFsEnv\\n\\ninstance Outputable UnusedNames where\\n ppr (UnusedNames nms wcs flds) =\\n text \\"UnusedNames\\" <+>\\n braces (ppr nms <+> ppr wcs <+> ppr (fmap (second getAny) flds))\\n\\n-- | Collect all unused names from a \'UnusedNames\' value.\\ncollectUnusedNames :: UnusedNames -> NameSet\\ncollectUnusedNames (UnusedNames { unused_names = nms, rec_fld_uses = flds })\\n = nms S.<> unused_flds\\n where\\n unused_flds = nonDetFoldFsEnv collect_unused emptyNameSet flds\\n collect_unused :: (NameSet, Any) -> NameSet -> NameSet\\n collect_unused (nms, Any at_least_one_name_is_used) acc\\n | at_least_one_name_is_used = acc\\n | otherwise = unionNameSet nms acc\\n\\ncollectUnusedWildcards :: UnusedNames -> [NamespaceSpecifier GhcRn]\\ncollectUnusedWildcards = unused_wildcards\\n\\n{- Note [Reporting unused imported duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have (#24035):\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M1 (R1(..), R2(..)) where\\n data R1 = MkR1 { fld :: Int }\\n data R2 = MkR2 { fld :: Int }\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M2 where\\n import M1 (R1(MkR1), R2, fld)\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nIn the import of \'M1\' in \'M2\', the \'fld\' import resolves to two separate GREs,\\nnamely R1(fld) and R2(fld). From the perspective of the renamer, and in particular\\nthe \'findImportUsage\' function, it\'s as if the user had imported the two names\\nseparately (even though no source syntax allows that).\\n\\nThis means that we need to be careful when reporting unused imports: the R2(fld)\\nimport is indeed unused, but because R1(fld) is used, we should not report\\nfld as unused altogether.\\n\\nTo achieve this, we keep track of record field imports without a parent (i.e.\\nusing the IEVar constructor) separately from other import items, using the\\nUnusedNames datatype.\\nOnce we have accumulated usages, we emit warnings for unused record fields\\nwithout parents one whole group (of record fields sharing the same textual name)\\nat a time, and only if *all* of the record fields in the group are unused;\\nsee \'collectUnusedNames\'.\\n\\nNote that this only applies to record fields imported without a parent. If we\\nhad:\\n\\n import M1 (R1(MkR1, fld), R2(fld))\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nthen of course we should report the second \'fld\' as unused.\\n-}\\n\\n\\n{- Note [The ImportMap]\\n~~~~~~~~~~~~~~~~~~~~~~~\\nThe ImportMap is a short-lived intermediate data structure records, for\\neach import declaration, what stuff brought into scope by that\\ndeclaration is actually used in the module.\\n\\nThe [GlobalRdrElt] are the things imported from that decl.\\n-}\\n\\ndata ImportMap = ImportMap\\n { im_imports :: Map RealSrcSpan [GlobalRdrElt]\\n -- ^ See [The ImportMap]\\n -- If loc :-> gres, then\\n -- \'loc\' = the end loc of the bestImport of each GRE in \'gres\'\\n , im_generatedImports :: Map ModuleName [GlobalRdrElt]\\n }\\n\\nmkImportMap :: [GlobalRdrElt] -> ImportMap\\n-- For each of a list of used GREs, find all the import decls that brought\\n-- it into scope; choose one of them (bestImport), and record\\n-- the RdrName in that import decl\'s entry in the ImportMap\\nmkImportMap = foldr insertImportMap $ ImportMap Map.empty Map.empty\\n\\ninsertImportMap :: GlobalRdrElt -> ImportMap -> ImportMap\\ninsertImportMap gre@(GRE { gre_imp = imp_specs }) importMap\\n | RealSrcSpan importSpan _ <- is_dloc best_imp_spec =\\n importMap{im_imports = insertElem importSpan gre $ im_imports importMap}\\n | GeneratedSrcSpan{} <- is_dloc best_imp_spec =\\n importMap{im_generatedImports = insertElem (moduleName $ is_mod best_imp_spec) gre $ im_generatedImports importMap}\\n | otherwise = importMap\\n where\\n best_imp_spec =\\n case bagToList imp_specs of\\n [] -> pprPanic \\"mkImportMap: GRE with no ImportSpecs\\" (ppr gre)\\n is:iss -> is_decl $ bestImport (is NE.:| iss)\\n\\n -- https://github.com/haskell/containers/issues/784\\n insertElem :: Ord k => k -> v -> Map k [v] -> Map k [v]\\n insertElem k v = flip Map.alter k $ \\\\case\\n Just vs -> Just (v : vs)\\n Nothing -> Just [v]\\n\\nlookupImportMap :: LImportDecl GhcRn -> ImportMap -> [GlobalRdrElt]\\nlookupImportMap (L srcSpan ImportDecl{ideclName = L _ modName}) importMap =\\n fromMaybe [] $\\n -- should match logic in insertImportMap\\n case locA srcSpan of\\n RealSrcSpan realSrcSpan _ -> realSrcSpan `Map.lookup` im_imports importMap\\n GeneratedSrcSpan{} -> modName `Map.lookup` im_generatedImports importMap\\n _ -> Nothing\\n\\nlieNames :: LIE (GhcPass p) -> [Located (IdP (GhcPass p))]\\nlieNames = _\\n\\nwarnUnusedImport :: GlobalRdrEnv -> ImportDeclUsage -> RnM ()\\nwarnUnusedImport rdr_env (L loc decl, used, unused, unused_wcs)\\n\\n -- Do not warn for \'import M()\'\\n -- See (UI1) in Note [Unused imports]\\n | Just (Exactly, _) <- ideclImportList decl\\n , null unused && null unused_wcs\\n = return ()\\n\\n -- Note [Do not warn about Prelude hiding]\\n | Just (EverythingBut, hides) <- ideclImportList decl\\n , not (null hides)\\n , pRELUDE_NAME == unLoc (ideclName decl)\\n = return ()\\n\\n -- Do not warn about import X as Rebindable\\n -- See (UI2) in Note [Unused imports]\\n | Just (L _ mod) <- ideclAs decl\\n , mod == rEBINDABLE_MOD_NAME\\n = return ()\\n\\n -- Nothing used; drop entire declaration\\n | null used\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl UnusedImportNone)\\n\\n -- Everything imported is used; nop\\n | null unused && null unused_wcs\\n = return ()\\n\\n -- Some imports are unused: make the `SrcSpan` cover only the unused\\n -- items instead of the whole import statement\\n | Just (_, imports) <- ideclImportList decl\\n , let unused_locs = [ locA loc | L loc ie <- imports\\n , name <- ieNames ie\\n , name `elem` unused ]\\n , loc1 : locs <- unused_locs\\n , let span = foldr1 combineSrcSpans ( loc1 NE.:| locs )\\n = addDiagnosticAt span (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n -- Some imports are unused\\n | otherwise\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n where\\n -- In warning message, pretty-print identifiers unqualified unconditionally\\n -- to improve the consistent for ambiguous/unambiguous identifiers.\\n -- See #14881.\\n possible_field n =\\n case lookupGRE_Name rdr_env n of\\n Just (GRE { gre_par = par, gre_info = IAmRecField info }) ->\\n let fld_occ :: OccName\\n fld_occ = nameOccName $ flSelector $ recFieldLabel info\\n in UnusedImportNameRecField par fld_occ\\n _ -> UnusedImportNameRegular n\\n\\n -- Print unused names in a deterministic (lexicographic) order\\n sort_unused :: [UnusedImportName]\\n sort_unused =\\n [ UnusedImportWildcard wc | wc <- unused_wcs ] ++\\n [ possible_field nm | nm <- sortBy (comparing nameOccName) unused ]\\n\\ngetMinimalImports :: [ImportDeclUsage] -> RnM [LImportDecl GhcRn]\\ngetMinimalImports ie_decls\\n = do { rdr_env <- getGlobalRdrEnv\\n ; fmap combine $ mapM (mk_minimal rdr_env) ie_decls }\\n where\\n mk_minimal rdr_env (L l decl, used_gres, unused, unused_wcs)\\n | null unused && null unused_wcs\\n , Just (Exactly, _) <- ideclImportList decl\\n = return (L l decl)\\n | otherwise\\n = do { let ImportDecl { ideclName = L _ mod_name\\n , ideclSource = is_boot\\n , ideclPkgQual = pkg_qual\\n , ideclExt = XImportDeclPass { ideclOrigin = origin } } = decl\\n ; iface <- loadSrcInterface doc (importDeclLookupScope origin)\\n mod_name is_boot pkg_qual\\n ; let used_avails = gresToAvailInfo used_gres\\n ; lies <- map (L l) <$> concatMapM (to_ie rdr_env iface) used_avails\\n ; return (L l (decl { ideclImportList = Just (Exactly, lies) })) }\\n where\\n doc = text \\"Compute minimal imports for\\" <+> ppr decl\\n\\n to_ie :: GlobalRdrEnv -> ModIface -> AvailInfo -> RnM [IE GhcRn]\\n -- The main trick here is that if we\'re importing all the constructors\\n -- we want to say \\"T(..)\\", but if we\'re importing only a subset we want\\n -- to say \\"T(A,B,C)\\". So we have to find out what the module exports.\\n to_ie rdr_env _ (Avail c) -- Note [Overloaded field import]\\n = do { let\\n gre = expectJust $ lookupGRE_Name rdr_env c\\n ; return $ [IEVar Nothing (to_ie_post_rn $ noLocA $ greName gre) Nothing] }\\n to_ie _ _ avail@(AvailTC n [_]) -- Exporting the main decl and nothing else\\n | availExportsDecl avail\\n = return [IEThingAbs Nothing (to_ie_post_rn $ noLocA n) Nothing]\\n to_ie rdr_env iface (AvailTC n cs) =\\n case [ xs | avail@(AvailTC x xs) <- mi_exports iface\\n , x == n\\n , availExportsDecl avail -- Note [Partial export]\\n ] of\\n [xs]\\n | all_used xs\\n -> return [IEThingAll (IEThingAllExt Nothing noAnn noAnn noAnn)\\n (NoNamespaceSpecifier noExtField)\\n (to_ie_post_rn $ noLocA n)\\n Nothing]\\n | otherwise\\n -> do { let ns_gres = map (expectJust . lookupGRE_Name rdr_env) cs\\n ns = map greName ns_gres\\n ; return [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n -- Note [Overloaded field import]\\n _other\\n -> do { let infos = map (expectJust . lookupGRE_Name rdr_env) cs\\n (ns_gres,fs_gres) = classifyGREs infos\\n ns = map greName (ns_gres ++ fs_gres)\\n fs = map fieldGREInfo fs_gres\\n ; return $\\n if all_non_overloaded fs\\n then map (\\\\nm -> IEVar Nothing (to_ie_post_rn_var $ noLocA nm) Nothing) ns\\n else [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n where\\n\\n all_used avail_cs = all (`elem` cs) avail_cs\\n\\n all_non_overloaded = all (not . flIsOverloaded . recFieldLabel)\\n\\n combine :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\n combine = map merge . NE.groupAllWith getKey\\n\\n getKey :: LImportDecl GhcRn -> (Bool, Maybe ModuleName, ModuleName)\\n getKey decl =\\n ( isImportDeclQualified . ideclQualified $ idecl -- is this qualified? (important that this be first)\\n , unLoc <$> ideclAs idecl -- what is the qualifier (inside Maybe monad)\\n , unLoc . ideclName $ idecl -- Module Name\\n )\\n where\\n idecl :: ImportDecl GhcRn\\n idecl = unLoc decl\\n\\n merge :: NonEmpty (LImportDecl GhcRn) -> LImportDecl GhcRn\\n merge decls@((L l decl) :| _) = L l (decl { ideclImportList = Just (Exactly, lies) })\\n where lies = concatMap snd $ mapMaybe (ideclImportList . unLoc) $ NE.toList decls\\n\\nclassifyGREs :: [GlobalRdrElt] -> ([GlobalRdrElt], [FieldGlobalRdrElt])\\nclassifyGREs = partition (not . isRecFldGRE)\\n\\nprintMinimalImports :: HscSource -> [ImportDeclUsage] -> RnM ()\\n-- See Note [Printing minimal imports]\\nprintMinimalImports hsc_src imports_w_usage\\n = do { imports\' <- excludeGenerated <$> getMinimalImports imports_w_usage\\n ; this_mod <- getModule\\n ; dflags <- getDynFlags\\n ; liftIO $ withFile (mkFilename dflags this_mod) WriteMode $ \\\\h ->\\n printForUser dflags h neverQualify AllTheWay (vcat (map ppr imports\'))\\n -- The neverQualify is important. We are printing Names\\n -- but they are in the context of an \'import\' decl, and\\n -- we never qualify things inside there\\n -- E.g. import Blag( f, b )\\n -- not import Blag( Blag.f, Blag.g )!\\n }\\n where\\n mkFilename dflags this_mod\\n | Just d <- dumpDir dflags = d basefn\\n | otherwise = basefn\\n where\\n suffix = case hsc_src of\\n HsBootFile -> \\".imports-boot\\"\\n HsSrcFile -> \\".imports\\"\\n HsigFile -> \\".imports\\"\\n basefn = moduleNameString (moduleName this_mod) ++ suffix\\n\\n\\nto_ie_post_rn_var :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn_var (L l n)\\n | isDataOcc $ occName n = L l (IEPattern noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n\\n\\nto_ie_post_rn :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn (L l n)\\n | isTcOcc occ && isSymOcc occ = L l (IEType noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n where occ = occName n\\n\\n{- Note [Do not warn about Prelude hiding]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWe do not warn about\\n import Prelude hiding( x, y )\\nbecause even if nothing else from Prelude is used, it may be essential to hide\\nx,y to avoid name-shadowing warnings. Example (#9061)\\n import Prelude hiding( log )\\n f x = log where log = ()\\n\\nNote [Unused imports]\\n~~~~~~~~~~~~~~~~~~~~~\\nIn `warnUnusedImport`, if we see an import with an explicit list imports, thus\\n import M( a, b )\\nand neither `a` nor `b` is used, we report the entire import decl as unused. We\\ncheck this by looking at the names that it brings into scope scope; if there are\\nno ununused names, don\'t report.\\n\\n(UI1) We don\'t want to complain about `import M()`, because that is often used to bring\\n M\'s /instances/ into scope. That is neatly dealt with by the \\"no unused\\n names\\" (nor unused wildcard imports) criterion.\\n\\n(UI2) We don\'t report a decl as unused if it has an `as Rebindable` qualifier.\\n See (KN1) in Note [Overview of known entities] in GHC.Builtin\\n\\n\\nNote [Printing minimal imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nTo print the minimal imports we walk over all import decls (both user-supplied\\nand generated), trim their import lists, then filter out generated decls.\\n\\nNB that\\n\\n * We do *not* change the \'qualified\' or \'as\' parts!\\n\\n * We do not discard a decl altogether; we might need instances\\n from it. Instead we just trim to an empty import list\\n\\nNote [Partial export]\\n~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have\\n\\n module A( op ) where\\n class C a where\\n op :: a -> a\\n\\n module B where\\n import A\\n f = ..op...\\n\\nThen the minimal import for module B is\\n import A( op )\\nnot\\n import A( C( op ) )\\nwhich we would usually generate if C was exported from B. Hence\\nthe availExportsDecl test when deciding what to generate.\\n\\n\\nNote [Overloaded field import]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nOn the other hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n data T = MkT { foo :: Int }\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( T(foo) )\\nbecause when DuplicateRecordFields is enabled, field selectors are\\nnot in scope without their enclosing datatype.\\n\\nOn the third hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n pattern MkT { foo } = Just foo\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( foo )\\nbecause foo doesn\'t have a parent. This might actually be ambiguous if A\\nexports another field called foo, but there is no good answer to return and this\\nis a very obscure corner, so it seems to be the best we can do. See\\nDRFPatSynExport for a test of this.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Errors}\\n* *\\n************************************************************************\\n-}\\n\\nbadImportItemErr\\n :: ModIface -> ImpDeclSpec -> IE GhcPs\\n -> IsSubordinateError\\n -> [AvailInfo]\\n -> TcRn (NonEmpty ImportLookupReason)\\nbadImportItemErr iface decl_spec ie sub avails = do\\n exts <- importLookupExtensions\\n let import_lookup_bad :: BadImportKind -> ImportLookupReason\\n import_lookup_bad k = ImportLookupBad k iface decl_spec ie exts\\n dflags <- getDynFlags\\n hsc_env <- getTopEnv\\n let rdr_env = mkGlobalRdrEnv\\n $ gresFromAvails hsc_env (Just imp_spec) all_avails\\n pure $ fmap import_lookup_bad (importErrorKind dflags rdr_env)\\n where\\n importErrorKind :: DynFlags -> GlobalRdrEnv -> NonEmpty BadImportKind\\n importErrorKind dflags rdr_env\\n | any checkIfTyCon avails = case sub of\\n IsNotSubordinate -> NE.singleton BadImportAvailTyCon\\n IsSubordinateError { subordinate_err_parent = gre\\n , subordinate_err_unavailable = unavailable\\n , subordinate_err_nontype = nontype\\n , subordinate_err_nondata = nondata }\\n -> NE.fromList $ catMaybes $\\n [ fmap (BadImportNotExportedSubordinates gre) (NE.nonEmpty unavailable)\\n , fmap (BadImportNonTypeSubordinates gre) (NE.nonEmpty nontype)\\n , fmap (BadImportNonDataSubordinates gre) (NE.nonEmpty nondata) ]\\n | any checkIfVarName avails = NE.singleton BadImportAvailVar\\n | Just con <- find checkIfDataCon avails = NE.singleton (BadImportAvailDataCon (availOccName con))\\n | otherwise = NE.singleton (BadImportNotExported suggs)\\n where\\n suggs = similar_suggs ++ fieldSelectorSuggestions rdr_env rdr\\n what_look = case sub of\\n IsNotSubordinate -> WL_TyCon_or_TermVar\\n IsSubordinateError { subordinate_err_parent = gre } ->\\n case greInfo gre of\\n IAmTyCon ClassFlavour\\n -> WL_TyCon_or_TermVar\\n _ -> WL_Term\\n similar_names =\\n similarNameSuggestions (Unbound.LF what_look WL_Global)\\n dflags rdr_env emptyLocalRdrEnv rdr\\n similar_suggs =\\n case NE.nonEmpty $ mapMaybe imported_item $ similar_names of\\n Just similar -> [ SuggestSimilarNames rdr similar ]\\n Nothing -> [ ]\\n\\n -- Only keep imported items, and set the \\"HowInScope\\" to\\n -- \\"Nothing\\" to avoid printing \\"imported from...\\" in the suggestion\\n -- error message.\\n imported_item (SimilarRdrName rdr_name gre (Just (ImportedBy {})))\\n = Just (SimilarRdrName rdr_name gre Nothing)\\n imported_item _ = Nothing\\n\\n checkIfDataCon = checkIfAvailMatches isDataConName\\n checkIfTyCon = checkIfAvailMatches isTyConName\\n checkIfVarName =\\n \\\\case\\n AvailTC{} -> False\\n Avail n -> importedFS == occNameFS (occName n)\\n && (isVarOcc <||> isFieldOcc) (occName n)\\n checkIfAvailMatches namePred =\\n \\\\case\\n AvailTC _ ns ->\\n case find (\\\\n -> importedFS == occNameFS (occName n)) ns of\\n Just n -> namePred n\\n Nothing -> False\\n Avail{} -> False\\n availOccName = occName . availName\\n rdr = ieName ie\\n importedFS = occNameFS $ rdrNameOcc rdr\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n all_avails = mi_exports iface\\n\\nimportLookupExtensions :: TcRn ImportLookupExtensions\\nimportLookupExtensions = do\\n ile_pattern_synonyms <- xoptM LangExt.PatternSynonyms\\n ile_explicit_namespaces <- xoptM LangExt.ExplicitNamespaces\\n return ImportLookupExtensions{ile_pattern_synonyms, ile_explicit_namespaces}\\n\\naddDupDeclErr :: NonEmpty GlobalRdrElt -> TcRn ()\\naddDupDeclErr gres@(gre :| _)\\n -- Report the error at the later location\\n = addErrAt (getSrcSpan (NE.last sorted_names)) $ (TcRnDuplicateDecls (greOccName gre) sorted_names)\\n where\\n sorted_names =\\n NE.sortBy (SrcLoc.leftmost_smallest `on` nameSrcSpan)\\n (fmap greName gres)\\n\\n-- This data decl will parse OK\\n-- data T = a Int\\n-- treating \\"a\\" as the constructor.\\n-- It is really hard to make the parser spot this malformation.\\n-- So the renamer has to check that the constructor is legal\\n--\\n-- We can get an operator as the constructor, even in the prefix form:\\n-- data T = :% Int Int\\n-- from interface files, which always print in prefix form\\n--\\n-- We also allow type constructor names, which are defined by \\"type data\\"\\n-- declarations. See Note [Type data declarations] in GHC.Rename.Module.\\n\\ncheckConName :: RdrName -> TcRn ()\\ncheckConName name\\n = checkErr (isRdrDataCon name || isRdrTc name) (TcRnIllegalDataCon name)\\n", "filetypes": ["haskell"]}}}' 2026-10-16 14:46:30,769 - DEBUG - POST b'http://127.0.0.1:37093/receive_messages' {'content-type': 'application/json', 'x-ycm-hmac': b'Rga7Yd4l4fgfufwYw+0sxzurvznImlBO0MPmgAlS4EY='} b'{"filepath": "/home/enrico/ghc/compiler/GHC/Rename/Names.hs", "line_num": 1, "column_num": 1, "working_dir": "/home/enrico/ghc", "file_data": {"/home/enrico/ghc/compiler/GHC/Rename/Names.hs": {"contents": "{-\\n(c) The GRASP/AQUA Project, Glasgow University, 1992-1998\\n\\nExtracting imported and top-level names in scope\\n-}\\n\\n{-# LANGUAGE NondecreasingIndentation #-}\\n{-# LANGUAGE TypeFamilies #-}\\n\\nmodule GHC.Rename.Names (\\n rnImports, getLocalNonValBinders, newRecordFieldLabel,\\n importsFromIface,\\n ImportUserSpec(..),\\n extendGlobalRdrEnvRn,\\n gresFromAvails,\\n calculateAvails,\\n reportUnusedNames,\\n checkConName,\\n mkChildEnv,\\n findChildren,\\n mkBadExportSubordinate,\\n findImportUsage,\\n getMinimalImports,\\n printMinimalImports,\\n renamePkgQual, renameRawPkgQual,\\n classifyGREs,\\n ImportDeclUsage,\\n rnNamespaceSpecifier\\n ) where\\n\\nimport GHC.Prelude hiding ( head, init, last, tail )\\n\\nimport GHC.Driver.Env\\nimport GHC.Driver.Session\\nimport GHC.Driver.Ppr\\n\\nimport GHC.Rename.Env\\nimport GHC.Rename.Fixity\\nimport GHC.Rename.Utils ( warnUnusedTopBinds )\\nimport GHC.Rename.Unbound\\nimport qualified GHC.Rename.Unbound as Unbound\\n\\nimport GHC.Tc.Errors.Types\\nimport GHC.Tc.Utils.Env\\nimport GHC.Tc.Utils.Monad\\nimport GHC.Tc.Types.LclEnv\\nimport GHC.Tc.Zonk.TcType ( tcInitTidyEnv )\\n\\nimport GHC.Hs\\nimport GHC.Iface.Load ( loadSrcInterface, loadSrcInterface_maybe )\\nimport GHC.Iface.Errors.Types\\n ( IfaceMessage(..), MissingInterfaceError, InterfaceLookingFor(..)\\n , LoadEssentialsReason(..) )\\nimport GHC.Iface.Syntax ( fromIfaceWarnings )\\nimport GHC.Builtin.Modules( pRELUDE_NAME, rEBINDABLE_MOD_NAME )\\nimport GHC.Parser.PostProcess ( setRdrNameSpace )\\nimport GHC.Core.TyCo.Tidy\\nimport GHC.Core.PatSyn\\nimport GHC.Core.TyCon ( TyCon, tyConName )\\nimport qualified GHC.LanguageExtensions as LangExt\\n\\nimport GHC.Utils.Outputable as Outputable\\nimport GHC.Utils.Misc as Utils\\nimport GHC.Utils.Panic\\n\\nimport GHC.Types.Fixity.Env\\nimport GHC.Types.SafeHaskell\\nimport GHC.Types.Name\\nimport GHC.Types.Name.Env\\nimport GHC.Types.Name.Set\\nimport GHC.Types.Name.Reader\\nimport GHC.Types.Avail\\nimport GHC.Types.FieldLabel\\nimport GHC.Types.Hint\\nimport GHC.Types.SourceFile\\nimport GHC.Types.SrcLoc as SrcLoc\\nimport GHC.Types.Basic (TyConFlavour (..), convImportLevel, VisArity)\\nimport GHC.Types.UnresolvedImport\\nimport GHC.Types.Id\\nimport GHC.Types.PkgQual\\nimport GHC.Types.GREInfo (ConInfo(..), ConFieldInfo (..), ConLikeInfo (ConIsData))\\n\\nimport GHC.Unit\\nimport GHC.Unit.Module.Warnings\\nimport GHC.Unit.Module.ModIface\\nimport GHC.Unit.Module.Imported\\nimport GHC.Unit.Module.Deps\\nimport GHC.Unit.Env\\n\\nimport GHC.Data.Bag\\nimport GHC.Data.FastString\\nimport GHC.Data.FastString.Env\\nimport GHC.Data.Maybe\\nimport GHC.Data.List.SetOps ( removeDups )\\n\\nimport Control.Arrow ( second )\\nimport Control.Monad\\nimport Data.Foldable ( for_ )\\nimport Data.IntMap ( IntMap )\\nimport qualified Data.IntMap as IntMap\\nimport Data.Map ( Map )\\nimport qualified Data.Map as Map\\nimport Data.Ord ( comparing )\\nimport Data.Semigroup ( Any(..) )\\nimport qualified Data.Semigroup as S\\nimport Data.List ( partition, find, sortBy )\\nimport Data.List.NonEmpty (NonEmpty(..))\\nimport qualified Data.List.NonEmpty as NE\\nimport Data.Function ( on )\\nimport qualified Data.Set as S\\nimport System.FilePath (())\\nimport System.IO\\n\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{rnImports}\\n* *\\n************************************************************************\\n\\nNote [Tracking Trust Transitively]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen we import a package as well as checking that the direct imports are safe\\naccording to the rules outlined in the Note [Safe Haskell Trust Check] in GHC.Driver.Main\\nwe must also check that these rules hold transitively for all dependent modules\\nand packages. Doing this without caching any trust information would be very\\nslow as we would need to touch all packages and interface files a module depends\\non. To avoid this we make use of the property that if a modules Safe Haskell\\nmode changes, this triggers a recompilation from that module in the dependency\\ngraph. So we can just worry mostly about direct imports.\\n\\nThere is one trust property that can change for a package though without\\nrecompilation being triggered: package trust. So we must check that all\\npackages a module transitively depends on to be trusted are still trusted when\\nwe are compiling this module (as due to recompilation avoidance some modules\\nbelow may not be considered trusted any more without recompilation being\\ntriggered).\\n\\nWe handle this by augmenting the existing transitive list of packages a module M\\ndepends on with a bool for each package that says if it must be trusted when the\\nmodule M is being checked for trust. This list of trust required packages for a\\nsingle import is gathered in the rnImportDecl function and stored in an\\nImportAvails data structure. The union of these trust required packages for all\\nimports is done by the rnImports function using the combine function which calls\\nthe plusImportAvails function that is a union operation for the ImportAvails\\ntype. This gives us in an ImportAvails structure all packages required to be\\ntrusted for the module we are currently compiling. Checking that these packages\\nare still trusted (and that direct imports are trusted) is done in\\nGHC.Driver.Main.checkSafeImports.\\n\\nSee the note below, [Trust Own Package] for a corner case in this method and\\nhow its handled.\\n\\n\\nNote [Trust Own Package]\\n~~~~~~~~~~~~~~~~~~~~~~~~\\nThere is a corner case of package trust checking that the usual transitive check\\ndoesn\'t cover. (For how the usual check operates see the Note [Tracking Trust\\nTransitively] below). The case is when you import a -XSafe module M and M\\nimports a -XTrustworthy module N. If N resides in a different package than M,\\nthen the usual check works as M will record a package dependency on N\'s package\\nand mark it as required to be trusted. If N resides in the same package as M\\nthough, then importing M should require its own package be trusted due to N\\n(since M is -XSafe so doesn\'t create this requirement by itself). The usual\\ncheck fails as a module doesn\'t record a package dependency of its own package.\\nSo instead we now have a bool field in a modules interface file that simply\\nstates if the module requires its own package to be trusted. This field avoids\\nus having to load all interface files that the module depends on to see if one\\nis trustworthy.\\n\\n\\nNote [Trust Transitive Property]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSo there is an interesting design question in regards to transitive trust\\nchecking. Say I have a module B compiled with -XSafe. B is dependent on a bunch\\nof modules and packages, some packages it requires to be trusted as its using\\n-XTrustworthy modules from them. Now if I have a module A that doesn\'t use safe\\nhaskell at all and simply imports B, should A inherit all the trust\\nrequirements from B? Should A now also require that a package p is trusted since\\nB required it?\\n\\nWe currently say no but saying yes also makes sense. The difference is, if a\\nmodule M that doesn\'t use Safe Haskell imports a module N that does, should all\\nthe trusted package requirements be dropped since M didn\'t declare that it cares\\nabout Safe Haskell (so -XSafe is more strongly associated with the module doing\\nthe importing) or should it be done still since the author of the module N that\\nuses Safe Haskell said they cared (so -XSafe is more strongly associated with\\nthe module that was compiled that used it).\\n\\nGoing with yes is a simpler semantics we think and harder for the user to stuff\\nup but it does mean that Safe Haskell will affect users who don\'t care about\\nSafe Haskell as they might grab a package from Cabal which uses safe haskell (say\\nnetwork) and that packages imports -XTrustworthy modules from another package\\n(say bytestring), so requires that package is trusted. The user may now get\\ncompilation errors in code that doesn\'t do anything with Safe Haskell simply\\nbecause they are using the network package. They will have to call \'ghc-pkg\\ntrust network\' to get everything working. Due to this invasive nature of going\\nwith yes we have gone with no for now.\\n-}\\n\\n-- | Process Import Decls. See \'rnImportDecl\' for a description of what\\n-- the return types represent.\\n-- Note: Do the non SOURCE ones first, so that we get a helpful warning\\n-- for SOURCE ones that are unnecessary\\nrnImports :: [(LImportDecl GhcPs, SDoc)]\\n -> RnM ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\nrnImports imports = do\\n tcg_env <- getGblEnv\\n -- NB: want an identity module here, because it\'s OK for a signature\\n -- module to import from its implementor\\n let this_mod = tcg_mod tcg_env\\n let (source, ordinary) = partition (is_source_import . fst) imports\\n is_source_import (d::LImportDecl GhcPs) = ideclSource (unLoc d) == IsBoot\\n stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary\\n stuff2 <- mapAndReportM (rnImportDecl this_mod) source\\n -- Safe Haskell: See Note [Tracking Trust Transitively]\\n let (decls, imp_user_spec, rdr_env, imp_avails) = combine (stuff1 ++ stuff2)\\n -- Update imp_boot_mods if imp_direct_mods mentions any of them\\n let merged_import_avail = clobberSourceImports imp_avails\\n return (decls, imp_user_spec, rdr_env, merged_import_avail)\\n\\n where\\n clobberSourceImports imp_avails =\\n imp_avails { imp_boot_mods = imp_boot_mods\' }\\n where\\n imp_boot_mods\' = mergeInstalledModuleEnv combJ id (const emptyInstalledModuleEnv)\\n (imp_boot_mods imp_avails)\\n (imp_direct_dep_mods imp_avails)\\n\\n combJ (GWIB _ IsBoot) (_, x) = Just x\\n combJ r _ = Just r\\n -- See Note [Combining ImportAvails]\\n combine :: [(LImportDecl GhcRn, ImportUserSpec, GlobalRdrEnv, ImportAvails)]\\n -> ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\n combine ss =\\n let (decls, imp_user_spec, rdr_env, imp_avails, finsts) = foldr\\n plus\\n ([], [], emptyGlobalRdrEnv, emptyImportAvails, emptyModuleSet)\\n ss\\n in (decls, imp_user_spec, rdr_env, imp_avails { imp_finsts = moduleSetElts finsts })\\n\\n plus (decl, us, gbl_env1, imp_avails1)\\n (decls, uss, gbl_env2, imp_avails2, finsts_set)\\n = ( decl:decls,\\n us:uss,\\n gbl_env1 `plusGlobalRdrEnv` gbl_env2,\\n imp_avails1\' `plusImportAvails` imp_avails2,\\n extendModuleSetList finsts_set new_finsts )\\n where\\n imp_avails1\' = imp_avails1 { imp_finsts = [] }\\n new_finsts = imp_finsts imp_avails1\\n\\n{-\\nNote [Combining ImportAvails]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nimp_finsts in ImportAvails is a list of family instance modules\\ntransitively depended on by an import. imp_finsts for a currently\\ncompiled module is a union of all the imp_finsts of imports.\\nComputing the union of two lists of size N is O(N^2) and if we\\ndo it to M imports we end up with O(M*N^2). That can get very\\nexpensive for bigger module hierarchies.\\n\\nUnion can be optimized to O(N log N) if we use a Set.\\nimp_finsts is converted back and forth between dep_finsts, so\\nchanging a type of imp_finsts means either paying for the conversions\\nor changing the type of dep_finsts as well.\\n\\nI\'ve measured that the conversions would cost 20% of allocations on my\\ntest case, so that can be ruled out.\\n\\nChanging the type of dep_finsts forces checkFamInsts to\\nget the module lists in non-deterministic order. If we wanted to restore\\nthe deterministic order, we\'d have to sort there, which is an additional\\ncost. As far as I can tell, using a non-deterministic order is fine there,\\nbut that\'s a brittle nonlocal property which I\'d like to avoid.\\n\\nAdditionally, dep_finsts is read from an interface file, so its \\"natural\\"\\ntype is a list. Which makes it a natural type for imp_finsts.\\n\\nSince rnImports.combine is really the only place that would benefit from\\nit being a Set, it makes sense to optimize the hot loop in rnImports.combine\\nwithout changing the representation.\\n\\nSo here\'s what we do: instead of naively merging ImportAvails with\\nplusImportAvails in a loop, we make plusImportAvails merge empty imp_finsts\\nand compute the union on the side using Sets. When we\'re done, we can\\nconvert it back to a list. One nice side effect of this approach is that\\nif there\'s a lot of overlap in the imp_finsts of imports, the\\nSet doesn\'t really need to grow and we don\'t need to allocate.\\n\\nRunning generateModules from #14693 with DEPTH=16, WIDTH=30 finishes in\\n23s before, and 11s after.\\n-}\\n\\n-- | Given a located import declaration @decl@ from @this_mod@,\\n-- calculate the following pieces of information:\\n--\\n-- 1. An updated \'LImportDecl\', where all unresolved \'RdrName\' in\\n-- the entity lists have been resolved into \'Name\'s,\\n--\\n-- 2. A \'GlobalRdrEnv\' representing the new identifiers that were\\n-- brought into scope (taking into account module qualification\\n-- and hiding),\\n--\\n-- 3. \'ImportAvails\' summarizing the identifiers that were imported\\n-- by this declaration, and\\n--\\n-- 4. A boolean \'AnyHpcUsage\' which is true if the imported module\\n-- used HPC.\\nrnImportDecl :: Module -> (LImportDecl GhcPs, SDoc)\\n -> RnM (LImportDecl GhcRn, ImportUserSpec , GlobalRdrEnv, ImportAvails)\\nrnImportDecl this_mod\\n (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name\\n , ideclPkgQual = raw_pkg_qual\\n , ideclSource = want_boot\\n , ideclSafe = mod_safe\\n , ideclLevelSpec = import_level\\n , ideclQualified = qual_style\\n , ideclExt = XImportDeclPass { ideclOrigin = origin }\\n , ideclAs = as_mod, ideclImportList = imp_details }), import_reason)\\n = setSrcSpanA loc $ do\\n\\n case raw_pkg_qual of\\n NoRawPkgQual -> pure ()\\n RawPkgQual {} -> do\\n pkg_imports <- xoptM LangExt.PackageImports\\n when (not pkg_imports) $ addErr TcRnPackageImportsDisabled\\n\\n let qual_only = isImportDeclQualified qual_style\\n generated = isGeneratedImport origin\\n\\n lookup_scope = importDeclLookupScope origin\\n\\n -- If there\'s an error in loadInterface, (e.g. interface\\n -- file not found) we get lots of spurious errors from \'filterImports\'\\n let imp_mod_name = unLoc loc_imp_mod_name\\n doc = ppr imp_mod_name <+> import_reason\\n\\n hsc_env <- getTopEnv\\n unit_env <- hsc_unit_env <$> getTopEnv\\n let pkg_qual = renameRawPkgQual unit_env imp_mod_name raw_pkg_qual\\n\\n -- Check for self-import, which confuses the typechecker (#9032)\\n -- ghc --make rejects self-import cycles already, but batch-mode may not\\n -- at least not until GHC.IfaceToCore.tcHiBootIface, which is too late to avoid\\n -- typechecker crashes. (Indirect self imports are not caught until\\n -- GHC.IfaceToCore, see #10337 tracking how to make this error better.)\\n --\\n -- Originally, we also allowed \'import {-# SOURCE #-} M\', but this\\n -- caused bug #10182: in one-shot mode, we should never load an hs-boot\\n -- file for the module we are compiling into the EPS. In principle,\\n -- it should be possible to support this mode of use, but we would have to\\n -- extend Provenance to support a local definition in a qualified location.\\n -- For now, we don\'t support it, but see #10336\\n when (imp_mod_name == moduleName this_mod &&\\n (case pkg_qual of -- If we have import \\"\\" M, then we should\\n -- check that \\"\\" is \\"this\\" (which is magic)\\n -- or the name of this_mod\'s package. Yurgh!\\n -- c.f. GHC.findModule, and #9997\\n NoPkgQual -> True\\n ThisPkg uid -> uid == homeUnitId_ (hsc_dflags hsc_env)\\n OtherPkg _ -> False))\\n (addErr (TcRnSelfImport imp_mod_name))\\n\\n -- Check for a missing import list (Opt_WarnMissingImportList also\\n -- checks for T(..) items but that is done in checkDodgyImport below)\\n case imp_details of\\n Just (Exactly, _) -> return () -- Explicit import list\\n _ | generated -> return () -- Do not bleat for generated imports\\n | qual_only -> return ()\\n | otherwise -> addDiagnostic (TcRnNoExplicitImportList imp_mod_name)\\n\\n\\n mb_iface <- loadSrcInterface_maybe doc lookup_scope imp_mod_name want_boot pkg_qual\\n iface <- case mb_iface of\\n Succeeded iface -> return iface\\n Failed err -> failWithTc $\\n importDeclLoadFailure origin imp_mod_name want_boot err\\n\\n -- Compiler sanity check: if the import didn\'t say\\n -- {-# SOURCE #-} we should not get a hi-boot file\\n warnPprTrace ((want_boot == NotBoot) && (mi_boot iface == IsBoot)) \\"rnImportDecl\\" (ppr imp_mod_name) $ do\\n\\n -- Issue a user warning for a redundant {- SOURCE -} import\\n -- NB that we arrange to read all the ordinary imports before\\n -- any of the {- SOURCE -} imports.\\n --\\n -- in --make and GHCi, the compilation manager checks for this,\\n -- and indeed we shouldn\'t do it here because the existence of\\n -- the non-boot module depends on the compilation order, which\\n -- is not deterministic. The hs-boot test can show this up.\\n dflags <- getDynFlags\\n warnIf ((want_boot == IsBoot) && (mi_boot iface == NotBoot) && isOneShot (ghcMode dflags))\\n (TcRnRedundantSourceImport imp_mod_name)\\n when (mod_safe && not (safeImportsOn dflags)) $\\n addErr (TcRnSafeImportsDisabled imp_mod_name)\\n\\n let imp_mod = mi_module iface\\n qual_mod_name = fmap unLoc as_mod `orElse` imp_mod_name\\n imp_spec = ImpDeclSpec { is_mod = imp_mod, is_qual = qual_only,\\n is_dloc = locA loc, is_as = qual_mod_name,\\n is_pkg_qual = pkg_qual, is_isboot = want_boot,\\n is_level = convImportLevel import_level }\\n\\n let filter_imports = do\\n -- filter the imports according to the import declaration\\n (new_imp_details, imp_user_list, gbl_env)\\n <- filterImports hsc_env iface imp_spec imp_details\\n -- for certain error messages, we\\u2019d like to know what could be\\n -- imported here, if everything were imported\\n potential_gres <- (\\\\(_,_,x) -> x) <$> filterImports hsc_env iface imp_spec Nothing\\n return (new_imp_details, imp_user_list, gbl_env, potential_gres)\\n\\n (new_imp_details, imp_user_list, gbl_env, potential_gres) <-\\n case origin of\\n ImplicitEssentialsImport ->\\n -- The implicit GHC.Essentials import does not bring anything into scope.\\n -- See Note [Finding GHC.Essentials] in GHC.Builtin.\\n return (Nothing, ImpUserDependOnly, emptyGlobalRdrEnv, emptyGlobalRdrEnv)\\n UserWrittenImport -> filter_imports\\n ImplicitPreludeImport -> filter_imports\\n PluginImport -> filter_imports\\n\\n let is_hiding | Just (EverythingBut,_) <- imp_details = True\\n | otherwise = False\\n\\n -- should the import be safe?\\n mod_safe\' = mod_safe\\n || (not generated && safeDirectImpsReq dflags)\\n || (generated && safeImplicitImpsReq dflags)\\n\\n hsc_env <- getTopEnv\\n let home_unit = hsc_home_unit hsc_env\\n other_home_units = hsc_all_home_unit_ids hsc_env\\n\\n imported_by\\n | isDependOnlyImport imp_user_list\\n = ImportedBySystem\\n | otherwise\\n = ImportedByUser $ ImportedModsVal\\n { imv_name = is_as imp_spec\\n , imv_span = locA loc\\n , imv_is_safe = mod_safe\'\\n , imv_is_hiding = is_hiding\\n , imv_all_exports = potential_gres\\n , imv_qualified = qual_only\\n , imv_is_level = convImportLevel import_level\\n }\\n imports = calculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by\\n\\n -- Complain if we import a deprecated module\\n case fromIfaceWarnings (mi_warns iface) of\\n WarnAll txt -> addDiagnostic (TcRnDeprecatedModule imp_mod_name txt)\\n _ -> return ()\\n\\n let new_imp_decl = ImportDecl\\n { ideclExt = ideclExt decl\\n , ideclName = ideclName decl\\n , ideclPkgQual = pkg_qual\\n , ideclSource = ideclSource decl\\n , ideclSafe = mod_safe\'\\n , ideclQualified = ideclQualified decl\\n , ideclAs = ideclAs decl\\n , ideclImportList = new_imp_details\\n , ideclLevelSpec = ideclLevelSpec decl\\n }\\n\\n return (L loc new_imp_decl, ImpUserSpec imp_spec imp_user_list, gbl_env, imports)\\n\\n-- | The error message to emit when we failed to load an interface.\\nimportDeclLoadFailure :: ImportDeclOrigin -> ModuleName -> IsBootInterface\\n -> MissingInterfaceError -> TcRnMessage\\nimportDeclLoadFailure ImplicitEssentialsImport _ _ err\\n = TcRnInterfaceError $ CantFindEssentials err LookingForEssentialsModule\\nimportDeclLoadFailure _ mod_name want_boot err\\n = TcRnInterfaceError $ Can\'tFindInterface err $ LookingForModule mod_name want_boot\\n\\n-- | Rename raw package imports\\nrenameRawPkgQual :: UnitEnv -> ModuleName -> RawPkgQual -> PkgQual\\nrenameRawPkgQual unit_env mn = \\\\case\\n NoRawPkgQual -> NoPkgQual\\n RawPkgQual _ fs -> renamePkgQual unit_env mn $ Just fs\\n\\n-- | Rename raw package imports\\nrenamePkgQual :: UnitEnv -> ModuleName -> Maybe FastString -> PkgQual\\nrenamePkgQual unit_env mn mb_pkg = case mb_pkg of\\n Nothing -> NoPkgQual\\n Just pkg_fs\\n | Just uid <- homeUnitId <$> ue_homeUnit unit_env\\n , pkg_fs == fsLit \\"this\\"\\n -> ThisPkg uid\\n\\n | Just (uid, _) <- find (fromMaybe False . fmap (== pkg_fs) . snd) home_names\\n -> ThisPkg uid\\n\\n | Just uid <- resolvePackageImport unit_state mn (PackageName pkg_fs)\\n -> OtherPkg uid\\n\\n | otherwise\\n -> OtherPkg (UnitId pkg_fs)\\n -- not really correct as pkg_fs is unlikely to be a valid unit-id but\\n -- we will report the failure later...\\n where\\n home_names =\\n [ (uid, mkFastString <$> thisPackageName (homeUnitEnv_dflags (ue_findHomeUnitEnv uid unit_env)))\\n | uid <- S.toList hpt_deps\\n ]\\n\\n unit_state = ue_homeUnitState unit_env\\n\\n hpt_deps :: S.Set UnitId\\n hpt_deps = homeUnitDepends unit_state\\n\\n\\n-- | Calculate the \'ImportAvails\' induced by an import of a particular\\n-- interface, but without \'imp_mods\'.\\ncalculateAvails :: HomeUnit\\n -> S.Set UnitId\\n -> ModIface\\n -> IsSafeImport\\n -> IsBootInterface\\n -> ImportedBy\\n -> ImportAvails\\ncalculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by =\\n let imp_mod = mi_module iface\\n imp_sem_mod= mi_semantic_module iface\\n orph_iface = mi_orphan iface\\n has_finsts = mi_finsts iface\\n deps = mi_deps iface\\n trust = getSafeMode $ mi_trust iface\\n trust_pkg = mi_trust_pkg iface\\n is_sig = mi_hsc_src iface == HsigFile\\n\\n -- If the module exports anything defined in this module, just\\n -- ignore it. Reason: otherwise it looks as if there are two\\n -- local definition sites for the thing, and an error gets\\n -- reported. Easiest thing is just to filter them out up\\n -- front. This situation only arises if a module imports\\n -- itself, or another module that imported it. (Necessarily,\\n -- this involves a loop.)\\n --\\n -- We do this *after* filterImports, so that if you say\\n -- module A where\\n -- import B( AType )\\n -- type AType = ...\\n --\\n -- module B( AType ) where\\n -- import {-# SOURCE #-} A( AType )\\n --\\n -- then you won\'t get a \'B does not export AType\' message.\\n\\n\\n -- Compute new transitive dependencies\\n --\\n -- \'dep_orphs\' and \'dep_finsts\' do NOT include the imported module\\n -- itself, but we DO need to include this module in \'imp_orphs\' and\\n -- \'imp_finsts\' if it defines an orphan or instance family; thus the\\n -- orph_iface/has_iface tests.\\n\\n deporphs = dep_orphs deps\\n depfinsts = dep_finsts deps\\n\\n orphans | orph_iface = assertPpr (not (imp_sem_mod `elem` deporphs)) (ppr imp_sem_mod <+> ppr deporphs) $\\n imp_sem_mod : deporphs\\n | otherwise = deporphs\\n\\n finsts | has_finsts = assertPpr (not (imp_sem_mod `elem` depfinsts)) (ppr imp_sem_mod <+> ppr depfinsts) $\\n imp_sem_mod : depfinsts\\n | otherwise = depfinsts\\n\\n -- Trusted packages are a lot like orphans.\\n trusted_pkgs | mod_safe\' = dep_trusted_pkgs deps\\n | otherwise = S.empty\\n\\n\\n pkg = moduleUnit (mi_module iface)\\n ipkg = toUnitId pkg\\n\\n -- Does this import mean we now require our own pkg\\n -- to be trusted? See Note [Trust Own Package]\\n ptrust = trust == Sf_Trustworthy || trust_pkg\\n pkg_trust_req\\n | isHomeUnit home_unit pkg = ptrust\\n | otherwise = False\\n\\n dependent_pkgs = if toUnitId pkg `S.member` other_home_units\\n then S.empty\\n else S.singleton (lvl, ipkg)\\n\\n lvl = case imported_by of\\n ImportedByUser imv -> imv_is_level imv\\n ImportedBySystem -> NormalLevel\\n\\n\\n direct_mods = if toUnitId pkg `S.member` other_home_units\\n then mkPlusModDeps (moduleUnitId imp_mod) lvl (GWIB (moduleName imp_mod) want_boot)\\n else emptyInstalledModuleEnv\\n\\n dep_boot_mods_map = mkModDeps (dep_boot_mods deps)\\n\\n\\n boot_mods\\n -- If we are looking for a boot module, it must be HPT\\n | IsBoot <- want_boot = extendInstalledModuleEnv dep_boot_mods_map (toUnitId <$> imp_mod) (GWIB (moduleName imp_mod) IsBoot)\\n -- Now we are importing A properly, so don\'t go looking for\\n -- A.hs-boot\\n | isHomeUnit home_unit pkg = dep_boot_mods_map\\n -- There\'s no boot files to find in external imports\\n | otherwise = emptyInstalledModuleEnv\\n\\n sig_mods =\\n if is_sig\\n then moduleName imp_mod : dep_sig_mods deps\\n else dep_sig_mods deps\\n\\n\\n in ImportAvails {\\n imp_mods = Map.singleton (mi_module iface) [imported_by],\\n imp_orphs = orphans,\\n imp_finsts = finsts,\\n imp_sig_mods = sig_mods,\\n imp_direct_dep_mods = direct_mods,\\n imp_dep_direct_pkgs = dependent_pkgs,\\n imp_boot_mods = boot_mods,\\n\\n -- Add in the imported modules trusted package\\n -- requirements. ONLY do this though if we import the\\n -- module as a safe import.\\n -- See Note [Tracking Trust Transitively]\\n -- and Note [Trust Transitive Property]\\n imp_trust_pkgs = trusted_pkgs,\\n -- Do we require our own pkg to be trusted?\\n -- See Note [Trust Own Package]\\n imp_trust_own_pkg = pkg_trust_req\\n }\\n\\nmkPlusModDeps :: UnitId -> ImportLevel -> ModuleNameWithIsBoot\\n -> InstalledModuleEnv (S.Set ImportLevel, ModuleNameWithIsBoot)\\nmkPlusModDeps uid st elt = extendInstalledModuleEnv emptyInstalledModuleEnv (mkModule uid (gwib_mod elt)) (S.singleton st, elt)\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{importsFromLocalDecls}\\n* *\\n************************************************************************\\n\\nFrom the top-level declarations of this module produce\\n * the lexical environment\\n * the ImportAvails\\ncreated by its bindings.\\n\\nNote [Top-level Names in Template Haskell decl quotes]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSee also: Note [Interactively-bound Ids in GHCi] in GHC.Driver.Env\\n Note [Looking up Exact RdrNames] in GHC.Rename.Env\\n\\nConsider a Template Haskell declaration quotation like this:\\n module M where\\n f x = h [d| f = 3 |]\\nWhen renaming the declarations inside [d| ...|], we treat the\\ntop level binders specially in two ways\\n\\n1. We give them an Internal Name, not (as usual) an External one.\\n This is done by GHC.Rename.Env.newTopSrcBinder.\\n\\n2. We make them *shadow* the outer bindings.\\n See Note [GlobalRdrEnv shadowing]\\n\\n3. We find out whether we are inside a [d| ... |] by testing the TH\\n level. This is a slight hack, because the level field was really\\n meant for the type checker, and here we are not interested in the\\n fields of Brack, hence the error thunks in thRnBrack.\\n-}\\n\\nextendGlobalRdrEnvRn :: [GlobalRdrElt]\\n -> MiniFixityEnv\\n -> RnM (TcGblEnv, TcLclEnv)\\n-- Updates both the GlobalRdrEnv and the FixityEnv\\n-- We return a new TcLclEnv only because we might have to\\n-- delete some bindings from it;\\n-- see Note [Top-level Names in Template Haskell decl quotes]\\n\\nextendGlobalRdrEnvRn new_gres new_fixities\\n = checkNoErrs $ -- See Note [Fail fast on duplicate definitions]\\n do { (gbl_env, lcl_env) <- getEnvs\\n ; level <- getThLevel\\n ; isGHCi <- getIsGHCi\\n ; let rdr_env = tcg_rdr_env gbl_env\\n fix_env = tcg_fix_env gbl_env\\n th_bndrs = getLclEnvThBndrs lcl_env\\n th_lvl = thLevelIndex level\\n\\n -- Delete new_occs from global and local envs\\n -- If we are in a TemplateHaskell decl bracket,\\n -- we are going to shadow them\\n -- See Note [GlobalRdrEnv shadowing]\\n inBracket = isBrackLevel level\\n\\n lcl_env_TH = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_rdr = minusLocalRdrEnv (tcl_rdr lcl_env) new_gres_env }) lcl_env\\n -- See Note [GlobalRdrEnv shadowing]\\n\\n lcl_env2 | inBracket = lcl_env_TH\\n | otherwise = lcl_env\\n\\n -- Deal with shadowing: see Note [GlobalRdrEnv shadowing]\\n want_shadowing = isGHCi || inBracket\\n rdr_env1 | want_shadowing = shadowNames False rdr_env new_gres_env\\n | otherwise = rdr_env\\n\\n lcl_env3 = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_th_bndrs = extendNameEnvList th_bndrs\\n [ ( n, (TopLevel, th_lvl) )\\n | n <- new_names ] }) lcl_env2\\n\\n ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres\\n\\n ; let fix_env\' = foldl\' extend_fix_env fix_env new_gres\\n gbl_env\' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env\' }\\n\\n ; traceRn \\"extendGlobalRdrEnvRn 2\\" (pprGlobalRdrEnv True rdr_env2)\\n ; return (gbl_env\', lcl_env3) }\\n where\\n new_names = map greName new_gres\\n new_gres_env = mkGlobalRdrEnv new_gres\\n\\n -- If there is a fixity decl for the gre, add it to the fixity env\\n extend_fix_env fix_env gre\\n | Just (L _ fi) <- lookupMiniFixityEnv new_fixities name\\n = extendNameEnv fix_env name (FixItem occ fi)\\n | otherwise\\n = fix_env\\n where\\n name = greName gre\\n occ = greOccName gre\\n\\n add_gre :: GlobalRdrEnv -> GlobalRdrElt -> RnM GlobalRdrEnv\\n -- Extend the GlobalRdrEnv with a LocalDef GRE\\n -- If there is already a LocalDef GRE with the same OccName,\\n -- report an error and discard the new GRE\\n -- This establishes INVARIANT 1 of GlobalRdrEnvs\\n add_gre env gre\\n | not (null dups) -- Same OccName defined twice\\n = do { addDupDeclErr (gre :| dups); return env }\\n\\n | otherwise\\n = return (extendGlobalRdrEnv env gre)\\n where\\n -- See Note [Reporting duplicate local declarations]\\n dups = filter isBadDupGRE\\n $ lookupGRE env (LookupOccName (greOccName gre) (RelevantGREsFOS WantBoth))\\n isBadDupGRE old_gre = isLocalGRE old_gre && greClashesWith gre old_gre\\n\\n{- Note [Fail fast on duplicate definitions]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIf there are duplicate bindings for the same thing, we want to fail\\nfast. Having two bindings for the same thing can cause follow-on errors.\\nExample (test T9975a):\\n data Test = Test { x :: Int }\\n pattern Test wat = Test { x = wat }\\nThis defines \'Test\' twice. The second defn has no field-names; and then\\nwe get an error from Test { x=wat }, saying \\"Test has no field \'x\'\\".\\n\\nEasiest thing is to bale out fast on duplicate definitions, which\\nwe do via `checkNoErrs` on `extendGlobalRdrEnvRn`.\\n\\nNote [Reporting duplicate local declarations]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn general, a single module may not define the same OccName multiple times. This\\nis checked in extendGlobalRdrEnvRn: when adding a new locally-defined GRE to the\\nGlobalRdrEnv we report an error if there are already duplicates in the\\nenvironment. This establishes INVARIANT 1 (see comments on GlobalRdrEnv in\\nGHC.Types.Name.Reader), which says that for a given OccName, all the\\nGlobalRdrElts to which it maps must have distinct \'greName\'s.\\n\\nFor example, the following will be rejected:\\n\\n f x = x\\n g x = x\\n f x = x -- Duplicate!\\n\\nUsers are allowed to introduce new GREs with the same OccName as an imported GRE,\\nas disambiguation is possible through the module system, e.g.:\\n\\n module M where\\n import N (f)\\n f x = x\\n g x = M.f x + N.f x\\n\\nIf both GREs are local, the general rule is that two GREs clash if they have\\nthe same OccName, i.e. they share a textual name and live in the same namespace.\\nHowever, there are additional clashes due to record fields:\\n\\n - a new variable clashes with previously defined record fields\\n which define field selectors,\\n\\n - a new record field shadows:\\n\\n - previously defined variables, if it defines a field selector,\\n - previously defined record fields, unless it is a duplicate record field.\\n\\nThis logic is implemented in the function \'GHC.Types.Name.Reader.greClashesWith\'.\\n\\nSee also Note [Skipping ambiguity errors at use sites of local declarations] in\\nGHC.Rename.Utils.\\n-}\\n\\n\\n{- *********************************************************************\\n* *\\n getLocalDeclBindersd@ returns the names for an HsDecl\\n It\'s used for source code.\\n\\n *** See Note [The Naming story] in GHC.Hs.Decls ****\\n* *\\n********************************************************************* -}\\n\\ngetLocalNonValBinders :: MiniFixityEnv -> HsGroup GhcPs\\n -> RnM ((TcGblEnv, TcLclEnv), NameSet)\\n-- Get all the top-level binders bound the group *except*\\n-- for value bindings, which are treated separately\\n-- Specifically we return AvailInfo for\\n-- * type decls (incl constructors and record selectors)\\n-- * class decls (including class ops)\\n-- * associated types\\n-- * foreign imports\\n-- * value signatures (in hs-boot files only)\\n\\ngetLocalNonValBinders fixity_env\\n (HsGroup { hs_valds = binds,\\n hs_tyclds = tycl_decls,\\n hs_fords = foreign_decls })\\n = do { -- Process all type/class decls *except* family instances\\n ; let inst_decls = tycl_decls >>= group_instds\\n ; dup_fields_ok <- xopt_DuplicateRecordFields <$> getDynFlags\\n ; has_sel <- xopt_FieldSelectors <$> getDynFlags\\n ; tc_gres\\n <- concatMapM\\n (new_tc dup_fields_ok has_sel)\\n (tyClGroupTyClDecls tycl_decls)\\n ; traceRn \\"getLocalNonValBinders 1\\" (ppr tc_gres)\\n ; envs <- extendGlobalRdrEnvRn tc_gres fixity_env\\n ; restoreEnvs envs $ do {\\n -- Bring these things into scope first\\n -- See Note [Looking up family names in family instances]\\n\\n -- Process all family instances\\n -- to bring new data constructors into scope\\n ; nti_gress <- mapM (new_assoc dup_fields_ok has_sel) inst_decls\\n\\n -- Finish off with value binders:\\n -- foreign decls and pattern synonyms for an ordinary module\\n -- type sigs in case of a hs-boot file only\\n ; is_boot <- tcIsHsBootOrSig\\n ; let val_bndrs\\n | is_boot = case binds of\\n ValBinds _ val_binds ->\\n -- In a hs-boot file, the value binders come from the\\n -- *signatures*, and there should be no foreign binders\\n [ L (l2l decl_loc) (unLoc n)\\n | L decl_loc (TypeSig _ _ ns _) <- (val_sigs val_binds), n <- ns]\\n _ -> panic \\"Non-ValBinds in hs-boot group\\"\\n | otherwise = for_hs_bndrs\\n ; val_gres <- mapM new_simple val_bndrs\\n\\n ; let avails = concat nti_gress ++ val_gres\\n new_bndrs = gresToNameSet avails `unionNameSet`\\n gresToNameSet tc_gres\\n ; traceRn \\"getLocalNonValBinders 2\\" (ppr avails)\\n ; envs <- extendGlobalRdrEnvRn avails fixity_env\\n ; return (envs, new_bndrs) } }\\n where\\n for_hs_bndrs :: [LocatedN RdrName]\\n for_hs_bndrs = hsForeignDeclsBinders foreign_decls\\n\\n -- the SrcSpan attached to the input should be the span of the\\n -- declaration, not just the name\\n new_simple :: LocatedN RdrName -> RnM GlobalRdrElt\\n new_simple rdr_name = do { nm <- newTopSrcBinder rdr_name\\n ; return (mkLocalVanillaGRE NoParent nm) }\\n\\n new_tc :: DuplicateRecordFields -> FieldSelectors -> LTyClDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_tc dup_fields_ok has_sel tc_decl -- NOT for type/data instances\\n = do { let TyDeclBinders (main_bndr, tc_flav) at_bndrs sig_bndrs\\n (LConsWithFields cons_with_flds flds) = hsLTyClDeclBinders tc_decl\\n ; tycon_name <- newTopSrcBinder $ la2la main_bndr\\n ; at_names <- mapM (newTopSrcBinder . la2la . fst) at_bndrs\\n ; sig_names <- mapM (newTopSrcBinder . la2la) sig_bndrs\\n ; con_names_with_flds <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst con_names_with_flds) flds\\n ; mapM_ (add_dup_fld_errs flds\') con_names_with_flds\\n ; let tc_gre = mkLocalTyConGRE (fmap (const tycon_name) tc_flav) tycon_name\\n fld_env = mk_fld_env con_names_with_flds flds\'\\n at_gres = zipWith (\\\\ (_, at_flav) at_nm -> mkLocalTyConGRE (fmap (const tycon_name) at_flav) at_nm)\\n at_bndrs at_names\\n sig_gres = map (mkLocalVanillaGRE (ParentIs tycon_name)) sig_names\\n con_gres = map (mkLocalConLikeGRE (ParentIs tycon_name)) fld_env\\n fld_gres = mkLocalFieldGREs (ParentIs tycon_name) fld_env\\n sub_gres = at_gres ++ sig_gres ++ con_gres ++ fld_gres\\n ; traceRn \\"getLocalNonValBinders new_tc\\" $\\n vcat [ text \\"tycon:\\" <+> ppr tycon_name\\n , text \\"tc_gre:\\" <+> ppr tc_gre\\n , text \\"sub_gres:\\" <+> ppr sub_gres ]\\n ; return $ tc_gre : sub_gres }\\n\\n -- Calculate the record field information, which feeds into the GlobalRdrElts\\n -- for DataCons and their fields. It\'s convenient to do this here where\\n -- we are working with a single datatype definition.\\n --\\n -- The information we needed was all set up for us:\\n -- see Note [Collecting record fields in data declarations] in GHC.Hs.Utils.\\n mk_fld_env :: [(Name, Either VisArity [Located Int])] -> IntMap FieldLabel\\n -> [(ConLikeName, ConInfo)]\\n mk_fld_env names flds =\\n [ (DataConName con, ConInfo (ConIsData (map fst names)) fld_info)\\n | (con, con_fl_indxs) <- names\\n , let fld_info = case fmap (map ((flds IntMap.!) . unLoc)) con_fl_indxs of\\n Left 0 -> ConIsNullary\\n Left arity -> ConHasPositionalArgs arity\\n Right [] -> ConIsNullary\\n Right (fld:flds) -> ConHasRecordFields $ fld NE.:| flds ]\\n\\n new_assoc :: DuplicateRecordFields -> FieldSelectors -> LInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_assoc _ _ (L _ (TyFamInstD {})) = return []\\n -- type instances don\'t bind new names\\n\\n new_assoc dup_fields_ok has_sel (L _ (DataFamInstD _ d))\\n = new_di dup_fields_ok has_sel Nothing d\\n new_assoc dup_fields_ok has_sel\\n (L _ (ClsInstD _ (ClsInstDecl { cid_poly_ty = inst_ty\\n , cid_decls = decls })))\\n = do -- First, attempt to grab the name of the class from the instance.\\n -- This step could fail if the instance is not headed by a class,\\n -- such as in the following examples:\\n --\\n -- (1) The class is headed by a bang pattern, such as in\\n -- `instance !Show Int` (#3811c)\\n -- (2) The class is headed by a type variable, such as in\\n -- `instance c` (#16385)\\n --\\n -- If looking up the class name fails, then mb_cls_gre will\\n -- be Nothing.\\n mb_cls_gre <- runMaybeT $ do\\n -- See (1) above\\n L loc cls_rdr <- MaybeT $ pure $ getLHsInstDeclClass_maybe inst_ty\\n -- See (2) above\\n MaybeT $ setSrcSpan (locA loc) $ lookupGlobalOccRn_maybe SameNameSpace cls_rdr\\n -- Assuming the previous step succeeded, process any associated data\\n -- family instances. If the previous step failed, bail out.\\n case mb_cls_gre of\\n Nothing\\n -> pure []\\n Just cls_gre\\n -> let cls_nm = greName cls_gre\\n in concatMapM (new_di dup_fields_ok has_sel (Just cls_nm) . unLoc) (data_fam_insts decls)\\n\\n data_fam_insts decls = concatMap get decls\\n where\\n get (L l (InstD _ (DataFamInstD { dfid_inst = d}))) = [L l d]\\n get _ = []\\n\\n new_di :: DuplicateRecordFields -> FieldSelectors\\n -> Maybe Name -- class name\\n -> DataFamInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_di dup_fields_ok has_sel mb_cls dfid@(DataFamInstDecl { dfid_eqn = ti_decl })\\n = do { main_name <- unLoc <$> lookupFamInstName mb_cls (feqn_tycon ti_decl)\\n ; let LConsWithFields cons_with_flds flds = hsDataFamInstBinders dfid\\n ; sub_names <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst sub_names) flds\\n ; mapM_ (add_dup_fld_errs flds\') sub_names\\n ; let fld_env = mk_fld_env sub_names flds\'\\n con_gres = map (mkLocalConLikeGRE (ParentIs main_name)) fld_env\\n field_gres = mkLocalFieldGREs (ParentIs main_name) fld_env\\n -- NB: the data family name is not bound here,\\n -- so we don\'t return a GlobalRdrElt for it here!\\n ; return $ con_gres ++ field_gres }\\n\\n -- Add errors if a constructor has a duplicate record field.\\n add_dup_fld_errs :: IntMap FieldLabel\\n -> (Name, Either VisArity [Located Int])\\n -> IOEnv (Env TcGblEnv TcLclEnv) ()\\n add_dup_fld_errs all_flds (con, con_flds_or_arity)\\n | Right con_flds <- con_flds_or_arity\\n , let (_, dups) = removeDups (comparing unLoc) con_flds\\n = for_ dups $ \\\\ dup_flds ->\\n -- Report the error at the location of the second occurrence\\n -- of the duplicate field.\\n let loc =\\n case dup_flds of\\n _ :| ( L loc _ : _) -> loc\\n L loc _ :| _ -> loc\\n dup_rdrs = fmap (nameRdrName . flSelector . (all_flds IntMap.!) . unLoc) dup_flds\\n in addErrAt loc $ TcRnDuplicateFieldName (RecordFieldDecl con) dup_rdrs\\n | otherwise\\n = return ()\\n\\nnewRecordFieldLabel :: DuplicateRecordFields -> FieldSelectors -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel\\nnewRecordFieldLabel _ _ [] _ = error \\"newRecordFieldLabel: datatype has no constructors!\\"\\nnewRecordFieldLabel dup_fields_ok has_sel (dc:_) (L loc (FieldOcc _ (L _ fld)))\\n = do { selName <- newTopSrcBinder $ L (l2l loc) $ field\\n ; return $ FieldLabel { flHasDuplicateRecordFields = dup_fields_ok\\n , flHasFieldSelector = has_sel\\n , flSelector = selName } }\\n where\\n fld_occ = rdrNameOcc fld\\n dc_fs = occNameFS $ nameOccName dc\\n field\\n -- Use an Exact RdrName as-is, to preserve the bindings\\n -- of an already renamer-resolved field and its use\\n -- sites. This is needed to correctly support record\\n -- selectors in Template Haskell. See Note [Binders in\\n -- Template Haskell] in \\"GHC.ThToHs\\" and Note [Looking up\\n -- Exact RdrNames] in \\"GHC.Rename.Env\\".\\n | isExact fld\\n = assertPpr (fieldOcc_maybe fld_occ == Just dc_fs)\\n (vcat [ text \\"newRecordFieldLabel: incorrect namespace for exact Name\\" <+> quotes (ppr fld)\\n , text \\"expected namespace:\\" <+> pprNameSpace (fieldName dc_fs)\\n , text \\" actual namespace:\\" <+> pprNameSpace (occNameSpace fld_occ) ])\\n fld\\n\\n -- Field names produced by the parser are namespaced with VarName.\\n -- Here we namespace them according to the first constructor.\\n -- See Note [Record field namespacing] in GHC.Types.Name.Occurrence.\\n | otherwise\\n = mkRdrUnqual $ varToRecFieldOcc dc_fs fld_occ\\n\\n{-\\nNote [Looking up family names in family instances]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider\\n\\n module M where\\n type family T a :: *\\n type instance M.T Int = Bool\\n\\nWe might think that we can simply use \'lookupOccRn\' when processing the type\\ninstance to look up \'M.T\'. Alas, we can\'t! The type family declaration is in\\nthe *same* HsGroup as the type instance declaration. Hence, as we are\\ncurrently collecting the binders declared in that HsGroup, these binders will\\nnot have been added to the global environment yet.\\n\\nSolution is simple: process the type family declarations first, extend\\nthe environment, and then process the type instances.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Filtering imports}\\n* *\\n************************************************************************\\n\\n@filterImports@ takes the @ExportEnv@ telling what the imported module makes\\navailable, and filters it through the import spec (if any).\\n\\nNote [Dealing with imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nFor import M( ies ), we take each AvailInfo from the mi_exports of M, and make\\n\\n imp_occ_env :: OccEnv (NameEnv ImpOccItem)\\n\\nThis map contains one entry for each OccName that M exports, mapping each OccName\\nto the following information:\\n\\n 1. the GlobalRdrElt corresponding to the OccName,\\n 2. whether this GlobalRdrElt was the parent in the AvailInfo we found\\n the OccName in.\\n 3. the GlobalRdrElts that were bundled together in the AvailInfo we found\\n this OccName in (not including the parent),\\n\\nWe need (2) and (3) during the construction of the OccEnv because of associated\\ntypes and bundled pattern synonyms, respectively.\\n(3) is explained in Note [Importing PatternSynonyms].\\n\\nTo explain (2), consider for example:\\n\\n module M where\\n class C a where { data T a }\\n instance C Int where { data T Int = T1 | T2 }\\n instance C Bool where { data T Int = T3 }\\n\\nHere, M\'s exports avails are (recalling the AvailTC invariant from GHC.Types.Avail)\\n\\n C(C,T), T(T,T1,T2,T3)\\n\\nNotice that T appears *twice*, once as a child and once as a parent. From\\nthese two exports, respectively, during construction of the imp_occ_env, we begin\\nby associating the following two elements with the key T:\\n\\n T -> ImpOccItem { imp_item = gre1, imp_bundled = [C,T] , imp_is_parent = False }\\n T -> ImpOccItem { imp_item = gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nwhere `gre1`, `gre2` are two GlobalRdrElts with greName T.\\nWe combine these (in function \'combine\' in \'mkImportOccEnv\') by discarding the\\nnon-parent item, thusly:\\n\\n T -> IE_ITem { imp_item = gre1 `plusGRE` gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nNote the `plusGRE`: this ensures we don\'t drop parent information;\\nsee Note [Preserve parent information when combining import OccEnvs].\\n\\nSo the overall imp_occ_env is:\\n\\n C -> ImpOccItem { imp_item = C, imp_bundled = [T ], imp_is_parent = True }\\n T -> ImpOccItem { imp_item = T , imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n T1 -> ImpOccItem { imp_item = T1, imp_bundled = [T1,T2,T3], imp_is_parent = False }\\n -- similarly for T2, T3\\n\\nNote that the imp_occ_env will have entries for data constructors too,\\nalthough we never look up data constructors.\\n\\nNote [Importing PatternSynonyms]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nAs described in Note [Dealing with imports], associated types can lead to the\\nsame Name appearing twice, both as a child and once as a parent, when\\nconstructing the imp_occ_env. The same thing can happen with pattern synonyms\\nif they are exported bundled with a type.\\n\\nA simplified example, based on #11959:\\n\\n {-# LANGUAGE PatternSynonyms #-}\\n module M (T(P), pattern P) where -- Duplicate export warning, but allowed\\n data T = MkT\\n pattern P = MkT\\n\\nHere we have T(P) and P in export_avails, and respectively construct both\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n P -> ImpOccItem { imp_item = P, imp_bundled = [] , imp_is_parent = False }\\n\\nWe combine these by dropping the one with no siblings, leaving us with:\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n\\nThat is, we simply discard the non-bundled Avail.\\n\\nNote [Importing DuplicateRecordFields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn filterImports, another complicating factor is DuplicateRecordFields.\\nSuppose we have:\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (S(foo), T(foo)) where\\n data S = MkS { foo :: Int }\\n data T = MkT { foo :: Int }\\n\\n module N where\\n import M (foo) -- this is allowed (A)\\n import M (S(foo)) -- this is allowed (B)\\n\\nHere M exports \'foo\' at two different OccNames, with different namespaces for\\nthe two construtors MkS and MkT. Then, when we look up \'foo\' in lookup_names\\nfor case (A), we have a variable foo but must look in all the record field\\nnamespaces to find the two fields (and hence two different Avails).\\nWhereas in case (B) we reach the lookup_ie case for IEThingWith,\\nwhich looks up \'S\' and then finds the unique \'foo\' amongst its children.\\n\\nSee T16745 for a test of this.\\n\\nNote [Preserve parent information when combining import OccEnvs]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen discarding one ImpOccItem in favour of another, as described in\\nNote [Dealing with imports], we must make sure to combine the GREs so that\\nwe don\'t lose information.\\n\\nConsider for example #24084:\\n\\n module M1 where { class C a where { type T a } }\\n module M2 ( module M1 ) where { import M1 }\\n module M3 where { import M2 ( C, T ); instance C () where T () = () }\\n\\nWhen processing the import list of `M3`, we will have two `Avail`s attached\\nto `T`, namely `C(C, T)` and `T(T)`. We combine them in the `combine` function\\nof `mkImportOccEnv`; as described in Note [Dealing with imports] we discard\\n`C(C, T)` in favour of `T(T)`. However, in doing so, we **must not**\\ndiscard the information want that `C` is the parent of `T`. Indeed,\\nlosing track of this information can cause errors when importing,\\nas we could get an error of the form\\n\\n \\u2018T\\u2019 is not a (visible) associated type of class \\u2018C\\u2019\\n\\nThis explains why we use `plusGRE` when combining the two ImpOccItems, even\\nthough we are discarding one in favour of the other.\\n-}\\n\\n-- | All the \'GlobalRdrElt\'s associated with an \'AvailInfo\'.\\ngresFromAvail :: HasDebugCallStack\\n => HscEnv -> Maybe ImportSpec -> AvailInfo -> [GlobalRdrElt]\\ngresFromAvail hsc_env prov avail =\\n [ mk_gre nm info\\n | nm <- availNames avail\\n , let info = lookupGREInfo hsc_env nm ]\\n where\\n\\n mk_gre n info\\n = case prov of\\n -- Nothing => bound locally\\n -- Just is => imported from \'is\'\\n Nothing -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = True, gre_imp = emptyBag\\n , gre_info = info }\\n Just is -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = False, gre_imp = unitBag is\\n , gre_info = info }\\n\\n-- | All the \'GlobalRdrElt\'s associated with a collection of \'AvailInfo\'s.\\ngresFromAvails :: HscEnv -> Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]\\ngresFromAvails hsc_env prov = concatMap (gresFromAvail hsc_env prov)\\n\\nimportsFromIface :: HscEnv -> ModIface -> ImpDeclSpec -> Maybe NameSet -> GlobalRdrEnv\\nimportsFromIface hsc_env iface decl_spec hidden = mkGlobalRdrEnv $ case hidden of\\n Nothing -> all_gres\\n Just hidden_names -> filter (not . (`elemNameSet` hidden_names) . greName) all_gres\\n where\\n all_gres = gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\nrnNamespaceSpecifier :: NamespaceSpecifier GhcPs -> NamespaceSpecifier GhcRn\\nrnNamespaceSpecifier (NoNamespaceSpecifier _) = NoNamespaceSpecifier noExtField\\nrnNamespaceSpecifier (TypeNamespaceSpecifier x) = TypeNamespaceSpecifier x\\nrnNamespaceSpecifier (DataNamespaceSpecifier x) = DataNamespaceSpecifier x\\n\\nfilterImports\\n :: HasDebugCallStack\\n => HscEnv\\n -> ModIface\\n -> ImpDeclSpec\\n -- ^ Import spec\\n -> Maybe (ImportListInterpretation, [LIE GhcPs])\\n -- ^ Whether this is a \\"hiding\\" import list\\n -> RnM (Maybe (ImportListInterpretation, [LIE GhcRn]), -- Import spec w/ Names\\n ImpUserList, -- same, but designed for storage in interfaces\\n GlobalRdrEnv) -- Same again, but in GRE form\\nfilterImports hsc_env iface decl_spec Nothing\\n = return (Nothing, ImpUserAll, importsFromIface hsc_env iface decl_spec Nothing)\\nfilterImports hsc_env iface decl_spec (Just (want_hiding, import_items))\\n = do -- check for errors, convert RdrNames to Names\\n items1 <- mapM lookup_lie import_items\\n\\n let items2 :: [(LIE GhcRn, [GlobalRdrElt])]\\n items2 = concat items1\\n -- NB we may have duplicates, and several items\\n -- for the same parent; e.g N(x) and N(y)\\n\\n (gres, imp_user_list) = case want_hiding of\\n Exactly ->\\n let gres = concatMap (gresFromIE decl_spec) items2\\n gre_env = mkGlobalRdrEnv gres\\n implicit_parents = mkNameSet $ mapMaybe parentOfImplicitlyImportedGRE gres\\n in (gre_env, ImpUserExplicit (gresToAvailInfo $ globalRdrEnvElts $ gre_env) implicit_parents)\\n EverythingBut ->\\n let hidden_names = mkNameSet $ concatMap (map greName . snd) items2\\n in (importsFromIface hsc_env iface decl_spec (Just hidden_names), ImpUserEverythingBut hidden_names)\\n\\n return (Just (want_hiding, map fst items2), imp_user_list, gres)\\n where\\n import_mod = mi_module iface\\n all_avails = mi_exports iface\\n imp_occ_env = mkImportOccEnv hsc_env decl_spec all_avails\\n\\n -- Look up a parent (type constructor, class or data constructor)\\n -- in an import.\\n lookup_parent :: IE GhcPs -> RdrName -> IELookupM ImpOccItem\\n lookup_parent ie rdr =\\n assertPpr (not $ isVarNameSpace ns)\\n (vcat [ text \\"filterImports lookup_parent: unexpected variable\\"\\n , text \\"rdr:\\" <+> ppr rdr\\n , text \\"namespace:\\" <+> pprNameSpace ns ]) $\\n do { xs <- lookup_names ie rdr\\n ; case xs of\\n cax :| [] -> return cax\\n _ -> pprPanic \\"filter_imports lookup_parent ambiguous\\" $\\n vcat [ text \\"rdr:\\" <+> ppr rdr\\n , text \\"lookups:\\" <+> ppr (fmap imp_item xs) ] }\\n -- Looking up non-variables is always unambiguous,\\n -- as there can be at most one corresponding item\\n -- in the imp_occ_env.\\n -- See item (1) of Note [Exporting duplicate declarations]\\n -- in GHC.Tc.Gen.Export.\\n where\\n occ = rdrNameOcc rdr\\n ns = occNameSpace occ\\n\\n -- Look up a RdrName used in an import, returning multiple values if there\\n -- are several fields with the same name exposed by the module\\n lookup_names :: IE GhcPs -> RdrName -> IELookupM (NonEmpty ImpOccItem)\\n lookup_names ie rdr\\n | isQual rdr\\n = failLookupWith (QualImportError rdr)\\n | otherwise\\n = case lookups of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n item:items -> return $ item :| items\\n where\\n lookups = concatMap nonDetNameEnvElts\\n $ lookupImpOccEnv (RelevantGREsFOS WantNormal) imp_occ_env (rdrNameOcc rdr)\\n\\n lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, [GlobalRdrElt])]\\n lookup_lie (L loc ieRdr)\\n = setSrcSpanA loc $\\n do (stuff, warns) <- run_lookup ([],[]) (lookup_ie ieRdr)\\n mapM_ (addTcRnDiagnostic <=< warning_msg) warns\\n return [ (L loc ie, gres) | (ie,gres) <- stuff ]\\n where\\n\\n -- Warn when importing T(..) and no children are brought in scope\\n warning_msg (DodgyImport reason) =\\n pure (TcRnDodgyImports reason)\\n warning_msg MissingImportList =\\n pure (TcRnMissingImportList ieRdr)\\n warning_msg (BadImportW ie sub) = do\\n -- \'BadImportW\' is only constructed below in \'bad_import_w\', in\\n -- the \'EverythingBut\' case, so here we assume a \'hiding\' clause.\\n (reason :| _) <- badImportItemErr iface decl_spec ie sub all_avails\\n pure (TcRnDodgyImports (DodgyImportsHiding reason))\\n warning_msg (DeprecatedExport n w) =\\n pure $ TcRnPragmaWarning\\n PragmaWarningExport\\n { pwarn_occname = occName n\\n , pwarn_impmod = moduleName import_mod }\\n w\\n\\n run_lookup :: a -> IELookupM a -> TcRn a\\n run_lookup def m = case m of\\n Failed err -> do\\n msgs <- lookup_err_msgs err\\n forM_ msgs $ \\\\msg -> addErr (TcRnImportLookup msg)\\n return def\\n Succeeded a -> return a\\n\\n lookup_err_msgs err = case err of\\n BadImport ie sub -> badImportItemErr iface decl_spec ie sub all_avails\\n IllegalImport -> pure $ NE.singleton ImportLookupIllegal\\n QualImportError rdr -> pure $ NE.singleton (ImportLookupQualified rdr)\\n\\n -- For each import item, we convert its RdrNames to Names,\\n -- and at the same time compute all the GlobalRdrElt corresponding\\n -- to what is actually imported by this item.\\n -- Returns Nothing on error.\\n --\\n -- Returns a list because, with DuplicateRecordFields, a naked\\n -- import/export of a record field can correspond to multiple\\n -- different GlobalRdrElts. See Note [Importing DuplicateRecordFields].\\n lookup_ie :: IE GhcPs\\n -> IELookupM ([(IE GhcRn, [GlobalRdrElt])], [IELookupWarning])\\n lookup_ie ie = handle_bad_import $\\n case ie of\\n IEVar _ (L l n) _ -> do\\n -- See Note [Importing DuplicateRecordFields]\\n xs <- lookup_names ie (ieWrappedName n)\\n let gres = map imp_item $ NE.toList xs\\n export_depr_warns\\n | want_hiding == Exactly\\n = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ( [ (IEVar Nothing (L l (replaceWrappedName n name)) noDocstring, [gre])\\n | gre <- gres\\n , let name = greName gre ]\\n , export_depr_warns )\\n\\n IEThingAll x ns_spec (L l tc) _ -> do\\n ImpOccItem { imp_item = gre\\n , imp_bundled = bundled_gres\\n , imp_is_parent = is_par\\n }\\n <- lookup_parent ie $ ieWrappedName tc\\n let name = greName gre\\n\\n child_gres :: [GlobalRdrElt]\\n child_gres\\n | is_par = filterByNamespaceSpecifierGREs ns_spec bundled_gres\\n | otherwise = []\\n\\n imp_list_warn\\n\\n | null child_gres\\n -- e.g. f(..) or T(..) where T is a type synonym\\n = [DodgyImport (DodgyImportsEmptyParent ie ns_spec gre)]\\n\\n -- e.g. import M( T(..) )\\n | not (is_qual decl_spec)\\n = [MissingImportList]\\n\\n | otherwise\\n = []\\n\\n renamed_ie = IEThingAll (x { ieta_warning = Nothing })\\n (rnNamespaceSpecifier ns_spec)\\n (L l (replaceWrappedName tc name))\\n noDocstring\\n export_depr_warn\\n | want_hiding == Exactly\\n = maybeToList $ mk_depr_export_warning gre\\n -- We don\'t want to warn about the children as they\\n -- are not explicitly mentioned; the warning will\\n -- be emitted later on if they are used\\n | otherwise = []\\n\\n return ( [(renamed_ie, gre:child_gres)]\\n , imp_list_warn ++ export_depr_warn)\\n\\n\\n IEThingAbs _ (L l tc\') _\\n | want_hiding == EverythingBut -- hiding ( C )\\n -- Here the \'C\' can be a data constructor\\n -- *or* a type/class, or even both\\n -> let tc = ieWrappedName tc\'\\n tc_name = lookup_parent ie tc\\n dc_name = lookup_parent ie (setRdrNameSpace tc srcDataName)\\n in\\n case catIELookupM [ tc_name, dc_name ] of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n names -> return ( [mkIEThingAbs tc\' l (imp_item name) | name <- names], [])\\n | otherwise\\n -> do ImpOccItem { imp_item = gre } <- lookup_parent ie (ieWrappedName tc\')\\n return ( [mkIEThingAbs tc\' l gre]\\n , maybeToList $ mk_depr_export_warning gre)\\n\\n IEThingWith (deprecation, ann) ltc@(L l rdr_tc) wc rdr_ns _ -> do\\n ImpOccItem { imp_item = gre, imp_bundled = subnames }\\n <- lookup_parent (IEThingAbs Nothing ltc noDocstring) (ieWrappedName rdr_tc)\\n let name = greName gre\\n\\n -- Look up the children in the sub-names of the parent\\n -- See Note [Importing DuplicateRecordFields]\\n let (children_errs, childnames) = lookupChildren subnames rdr_ns\\n\\n bad_import_warns <-\\n if null children_errs then return [] else\\n let items = map lce_wrapped_name children_errs\\n ie = IEThingWith (deprecation, ann) ltc wc items noDocstring\\n -- We are trying to import T( a,b,c,d ), and failed\\n -- to find \'b\' and \'d\'. So we make up an import item\\n -- to report as failing, namely T( b, d ).\\n -- c.f. #15413\\n subordinate_err = mkSubordinateError gre children_errs\\n in bad_import_w ie subordinate_err\\n\\n let name\' = replaceWrappedName rdr_tc name\\n childnames\' = map (to_ie_post_rn . fmap greName) childnames\\n gres = gre : map unLoc childnames\\n export_depr_warns\\n | want_hiding == Exactly = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ([ (IEThingWith (Nothing, ann) (L l name\') wc childnames\' noDocstring\\n ,gres)]\\n , bad_import_warns ++ export_depr_warns)\\n\\n IEWholeNamespace x ns_spec -> do\\n let mod_name = moduleName import_mod\\n names = map greName gres\\n renamed_ie = IEWholeNamespace x { iewn_warning = Nothing\\n , iewn_names = names }\\n (rnNamespaceSpecifier ns_spec)\\n gres = filterByNamespaceSpecifierGREs ns_spec $\\n gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n dodgy_warn\\n | null gres = [DodgyImport (DodgyImportsWildcard mod_name ns_spec)]\\n | otherwise = []\\n return ([(renamed_ie, gres)],\\n dodgy_warn)\\n\\n _other -> failLookupWith IllegalImport\\n -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed...\\n -- all of those constitute errors.\\n\\n where\\n mkIEThingAbs tc l gre\\n = (IEThingAbs Nothing (L l (replaceWrappedName tc n)) noDocstring, [gre])\\n where n = greName gre\\n\\n -- N.B. imports never have docstrings\\n noDocstring = Nothing\\n\\n handle_bad_import m = catchIELookup m $ \\\\case\\n BadImport ie sub -> do\\n ws <- bad_import_w ie sub\\n return ([], ws)\\n err -> failLookupWith err\\n\\n bad_import_w :: IE GhcPs -> IsSubordinateError -> IELookupM [IELookupWarning]\\n bad_import_w ie sub\\n | want_hiding == EverythingBut = return [BadImportW ie sub]\\n | otherwise = failLookupWith (BadImport ie sub)\\n\\n mk_depr_export_warning gre\\n = DeprecatedExport name <$> mi_export_warn_fn iface name\\n where\\n name = greName gre\\n\\n-- | Assuming a subordinate item could not be found, do another lookup for a\\n-- more specific error message.\\nmkBadExportSubordinate :: [GlobalRdrElt] -> LIEWrappedName GhcPs -> BadExportSubordinate\\nmkBadExportSubordinate child_gres n =\\n case lookupChildren child_gres [n] of\\n (LookupChildNonType {lce_nontype_item = g} : _, _) -> BadExportSubordinateNonType g\\n (LookupChildNonData {lce_nondata_item = g} : _, _) -> BadExportSubordinateNonData g\\n _ -> BadExportSubordinateNotFound n\\n\\ntype IELookupM = MaybeErr IELookupError\\n\\ndata IELookupWarning\\n = BadImportW (IE GhcPs) IsSubordinateError\\n | MissingImportList\\n | DodgyImport DodgyImportsReason\\n | DeprecatedExport Name (WarningTxt GhcRn)\\n\\n-- | Is this import/export item a subordinate or not?\\ndata IsSubordinateError\\n = IsSubordinateError { subordinate_err_parent :: !GlobalRdrElt\\n , subordinate_err_unavailable :: [FastString]\\n , subordinate_err_nontype :: [GlobalRdrElt]\\n , subordinate_err_nondata :: [GlobalRdrElt] }\\n | IsNotSubordinate\\n\\nmkSubordinateError :: GlobalRdrElt -> [LookupChildError] -> IsSubordinateError\\nmkSubordinateError gre children_errs = foldr add init_acc children_errs\\n where\\n init_acc :: IsSubordinateError\\n init_acc = IsSubordinateError gre [] [] []\\n\\n add :: LookupChildError -> IsSubordinateError -> IsSubordinateError\\n add children_err sub@IsSubordinateError{} =\\n case children_err of\\n LookupChildNonType{lce_nontype_item = g} ->\\n sub { subordinate_err_nontype = g : subordinate_err_nontype sub }\\n LookupChildNonData{lce_nondata_item = g} ->\\n sub { subordinate_err_nondata = g : subordinate_err_nondata sub }\\n LookupChildNotFound (L _ wname) ->\\n let fs = (occNameFS . rdrNameOcc . ieWrappedName) wname\\n in sub { subordinate_err_unavailable = fs : subordinate_err_unavailable sub }\\n add _ IsNotSubordinate = panic \\"mkSubordinateError: IsNotSubordinate\\"\\n\\ndata IELookupError\\n = QualImportError RdrName\\n | BadImport (IE GhcPs) IsSubordinateError\\n | IllegalImport\\n\\nfailLookupWith :: IELookupError -> IELookupM a\\nfailLookupWith err = Failed err\\n\\ncatchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a\\ncatchIELookup m h = case m of\\n Succeeded r -> return r\\n Failed err -> h err\\n\\ncatIELookupM :: [IELookupM a] -> [a]\\ncatIELookupM ms = [ a | Succeeded a <- ms ]\\n\\n-- | Information associated to an \'AvailInfo\' used in constructing\\n-- an \'OccEnv\' corresponding to imports.\\n--\\n-- See Note [Dealing with imports].\\ndata ImpOccItem\\n = ImpOccItem\\n { imp_item :: GlobalRdrElt\\n -- ^ The import item\\n , imp_bundled :: [GlobalRdrElt]\\n -- ^ Items bundled in the Avail this import item came from,\\n -- not including the import item itself if it is a parent.\\n , imp_is_parent :: Bool\\n -- ^ Is the import item a parent? See Note [Dealing with imports].\\n }\\n\\ninstance Outputable ImpOccItem where\\n ppr (ImpOccItem { imp_item = item, imp_bundled = bundled, imp_is_parent = is_par })\\n = braces $ hsep\\n [ text \\"ImpOccItem\\"\\n , if is_par then text \\"[is_par]\\" else empty\\n , ppr (greName item) <+> ppr (greParent item)\\n , braces $ text \\"bundled:\\" <+> ppr (map greName bundled) ]\\n\\n-- | Make an \'OccEnv\' of all the imports.\\n--\\n-- Complicated by the fact that associated data types and pattern synonyms\\n-- can appear twice. See Note [Dealing with imports].\\nmkImportOccEnv :: HscEnv -> ImpDeclSpec -> [IfaceExport] -> OccEnv (NameEnv ImpOccItem)\\nmkImportOccEnv hsc_env decl_spec all_avails =\\n mkOccEnv_C (plusNameEnv_C combine)\\n [ (occ, mkNameEnv [(nm, item)])\\n | avail <- all_avails\\n , let gres = gresFromAvail hsc_env (Just hiding_spec) avail\\n , gre <- gres\\n , let nm = greName gre\\n occ = greOccName gre\\n (is_parent, bundled) = case avail of\\n AvailTC c _\\n | c == nm -- (Recall the AvailTC invariant from GHC.Types.AvailInfo)\\n -> ( True, drop 1 gres ) -- \\"drop 1\\": don\'t include the parent itself.\\n | otherwise\\n -> ( False, gres )\\n _ -> ( False, [] )\\n item = ImpOccItem\\n { imp_item = gre\\n , imp_bundled = bundled\\n , imp_is_parent = is_parent }\\n ]\\n where\\n\\n hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\n -- See Note [Dealing with imports]\\n -- \'combine\' may be called for associated data types which appear\\n -- twice in the all_avails. In the example, we have two Avails for T,\\n -- namely T(T,T1,T2,T3) and C(C,T), and we combine them by dropping the\\n -- latter, in which T is not the parent.\\n combine :: ImpOccItem -> ImpOccItem -> ImpOccItem\\n combine item1@(ImpOccItem { imp_item = gre1, imp_is_parent = is_parent1 })\\n item2@(ImpOccItem { imp_item = gre2, imp_is_parent = is_parent2 })\\n | is_parent1 || is_parent2\\n , not (isRecFldGRE gre1 || isRecFldGRE gre2) -- NB: does not force GREInfo.\\n , let name1 = greName gre1\\n name2 = greName gre2\\n gre = gre1 `plusGRE` gre2\\n -- See Note [Preserve parent information when combining import OccEnvs]\\n = assertPpr (name1 == name2)\\n (ppr name1 <+> ppr name2) $\\n if is_parent1\\n then item1 { imp_item = gre }\\n else item2 { imp_item = gre }\\n -- Discard C(C,T) in favour of T(T, T1, T2, T3).\\n\\n -- \'combine\' may also be called for pattern synonyms which appear both\\n -- unassociated and associated (see Note [Importing PatternSynonyms]).\\n combine item1@(ImpOccItem { imp_item = c1, imp_bundled = kids1 })\\n item2@(ImpOccItem { imp_item = c2, imp_bundled = kids2 })\\n = assertPpr (greName c1 == greName c2\\n && (not (null kids1 && null kids2)))\\n (ppr c1 <+> ppr c2 <+> ppr kids1 <+> ppr kids2) $\\n if null kids1\\n then item2\\n else item1\\n -- Discard standalone pattern P in favour of T(P).\\n\\n-- | Essentially like @lookupGRE env (LookupOccName occ which_gres)@,\\n-- but working with \'ImpOccItem\'s instead of \'GlobalRdrElt\'s.\\nlookupImpOccEnv :: WhichGREs GREInfo\\n -> OccEnv (NameEnv ImpOccItem) -> OccName -> [NameEnv ImpOccItem]\\nlookupImpOccEnv which_gres env occ =\\n mapMaybe relevant_items $ lookupOccEnv_AllNameSpaces env occ\\n where\\n is_relevant :: ImpOccItem -> Bool\\n is_relevant (ImpOccItem { imp_item = gre }) =\\n greIsRelevant which_gres (occNameSpace occ) gre\\n relevant_items :: NameEnv ImpOccItem -> Maybe (NameEnv ImpOccItem)\\n relevant_items nms\\n | let nms\' = filterNameEnv is_relevant nms\\n = if isEmptyNameEnv nms\'\\n then Nothing\\n else Just nms\'\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{Import/Export Utils}\\n* *\\n************************************************************************\\n-}\\n\\n-- | Given an import\\\\/export spec, appropriately set the @gre_imp@ field\\n-- for the \'GlobalRdrElt\'s.\\ngresFromIE :: ImpDeclSpec -> (LIE GhcRn, [GlobalRdrElt]) -> [GlobalRdrElt]\\ngresFromIE decl_spec (L loc ie, gres)\\n = map set_gre_imp gres\\n where\\n is_explicit = case ie of\\n IEThingAll _ _ name _ -> \\\\n -> n == lieWrappedName name\\n IEWholeNamespace _ _ -> \\\\_ -> False\\n _ -> \\\\_ -> True\\n prov_fn name\\n = ImpSpec { is_decl = decl_spec, is_item = item_spec }\\n where\\n item_spec = ImpSome { is_explicit = is_explicit name\\n , is_iloc = locA loc }\\n set_gre_imp gre@( GRE { gre_name = nm } )\\n = gre { gre_imp = unitBag $ prov_fn nm }\\n\\nparentOfImplicitlyImportedGRE :: Outputable info => GlobalRdrEltX info -> Maybe Name\\nparentOfImplicitlyImportedGRE gre =\\n if any (explicit_import . is_item) $ gre_imp gre\\n then Nothing\\n else greParent_maybe gre\\n where\\n explicit_import :: ImpItemSpec -> Bool\\n explicit_import (ImpAll {}) =\\n pprPanic \\"parentOfImplicitlyImportedGRE: ImpAll\\" (ppr gre)\\n explicit_import (ImpSome { is_explicit }) = is_explicit\\n\\n{- Note [Children for duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider the module\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (F(foo, MkFInt, MkFBool)) where\\n data family F a\\n data instance F Int = MkFInt { foo :: Int }\\n data instance F Bool = MkFBool { foo :: Bool }\\n\\nThe `foo` in the export list refers to *both* selectors! For this\\nreason, lookupChildren builds an environment that maps the FastString\\nto a list of items, rather than a single item.\\n-}\\n\\nmkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]\\nmkChildEnv gres = foldr add emptyNameEnv gres\\n where\\n add gre env = case greParent gre of\\n ParentIs p -> extendNameEnv_Acc (:) Utils.singleton env p gre\\n NoParent -> env\\n\\nfindChildren :: NameEnv [a] -> Name -> [a]\\nfindChildren env n = lookupNameEnv env n `orElse` []\\n\\ndata LookupChildError\\n = LookupChildNotFound { lce_wrapped_name :: !(LIEWrappedName GhcPs) }\\n | LookupChildNonType { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nontype_item :: !GlobalRdrElt }\\n | LookupChildNonData { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nondata_item :: !GlobalRdrElt }\\n\\nlookupChildren :: [GlobalRdrElt]\\n -> [LIEWrappedName GhcPs]\\n -> ( [LookupChildError] -- The ones for which the lookup failed\\n , [LocatedA GlobalRdrElt] )\\n-- (lookupChildren all_kids rdr_items) maps each rdr_item to its\\n-- corresponding Name in all_kids, if the former exists\\n-- The matching is done by FastString, not OccName, so that\\n-- Cls( meth, AssocTy )\\n-- will correctly find AssocTy among the all_kids of Cls, even though\\n-- the RdrName for AssocTy may have a (bogus) DataName namespace\\n-- (Really the rdr_items should be FastStrings in the first place.)\\nlookupChildren all_kids rdr_items = (fails, successes)\\n where\\n mb_xs = map do_one rdr_items\\n fails = [ err | Failed err <- mb_xs ]\\n successes = [ ok | Succeeded oks <- mb_xs, ok <- NE.toList oks ]\\n\\n do_one :: LIEWrappedName GhcPs -> MaybeErr LookupChildError (NonEmpty (LocatedA GlobalRdrElt))\\n do_one item@(L l r) =\\n case r of\\n IEName{}\\n -- IEName (unadorned name) places no restriction on the namespace of\\n -- the imported entity, so we look in both `val_gres` and `typ_gres`.\\n -- In case of conflict (punning), the value namespace takes priority.\\n -- See Note [Prioritise the value namespace in subordinate import lists]\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEType{}\\n -- IEType (\'type\' namespace specifier) restricts the lookup to the\\n -- type namespace, i.e. to `typ_gres`. In case of failure, we check\\n -- `val_gres` to produce a more helpful error message.\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- val_gres -> Failed $ LookupChildNonType item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEData{}\\n -- IEData (\'data\' namespace specifier) restricts the lookup to the\\n -- data namespace, i.e. to `val_gres`. In case of failure, we check\\n -- `typ_gres` to produce a more helpful error message.\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- typ_gres -> Failed $ LookupChildNonData item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEPattern{} -> panic \\"lookupChildren: IEPattern\\" -- Never happens (invalid syntax)\\n IEDefault{} -> panic \\"lookupChildren: IEDefault\\" -- Never happens (invalid syntax)\\n where\\n fs = (occNameFS . rdrNameOcc . ieWrappedName) r\\n gres = fromMaybe [] (lookupFsEnv kid_env fs)\\n (val_gres, typ_gres) = partition (isValNameSpace . greNameSpace) gres\\n\\n -- See Note [Children for duplicate record fields]\\n kid_env :: FastStringEnv [GlobalRdrElt]\\n kid_env = extendFsEnvList_C (++) emptyFsEnv\\n [(occNameFS (occName x), [x]) | x <- all_kids]\\n\\n\\n{- Note [Prioritise the value namespace in subordinate import lists]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider this program that defines a class that has both an associated type\\nnamed (#) and a method named (#)\\n\\n module M_assoc where\\n class C a b where\\n type a # b\\n (#) :: a -> b -> ()\\n module N_assoc where\\n import M_assoc( C((#)) )\\n\\nIn the import declaration, when we see the unadorned name (#) in the subordinate\\nimport list of C, which children should we bring into scope? Our options are:\\n\\n a) only the method (#)\\n b) only the associated type (#)\\n c) both the method and the associated type\\n\\nTo follow the precedent established by top-level items, we go with option (a).\\nIndeed, consider a slightly different program\\n\\n module M_top where\\n type family a # b\\n a # b = ()\\n module N_top where\\n import M_top( (#) )\\n\\nHere the import brings only the function (#) into scope, and one has to say\\n`type (#)` to get the type family.\\n-}\\n\\n-------------------------------\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused names}\\n* *\\n*********************************************************\\n-}\\n\\nreportUnusedNames :: TcGblEnv -> HscSource -> RnM ()\\nreportUnusedNames gbl_env hsc_src\\n = do { keep <- readTcRef (tcg_keep gbl_env)\\n ; traceRn \\"RUN\\" (ppr (tcg_dus gbl_env))\\n ; warnUnusedImportDecls gbl_env hsc_src\\n ; warnUnusedTopBinds $ unused_locals keep\\n ; warnMissingSignatures gbl_env\\n ; warnMissingKindSignatures gbl_env }\\n where\\n used_names :: NameSet -> NameSet\\n used_names keep = findUses (tcg_dus gbl_env) emptyNameSet `unionNameSet` keep\\n -- NB: currently, if f x = g, we only treat \'g\' as used if \'f\' is used\\n -- Hence findUses\\n\\n -- Collect the defined names from the in-scope environment\\n defined_names :: [GlobalRdrElt]\\n defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)\\n\\n kids_env = mkChildEnv defined_names\\n -- This is done in mkExports too; duplicated work\\n\\n gre_is_used :: NameSet -> GlobalRdrElt -> Bool\\n gre_is_used used_names gre0\\n = name `elemNameSet` used_names\\n || any (\\\\ gre -> greName gre `elemNameSet` used_names) (findChildren kids_env name)\\n -- A use of C implies a use of T,\\n -- if C was brought into scope by T(..) or T(C)\\n where\\n name = greName gre0\\n\\n -- Filter out the ones that are\\n -- (a) defined in this module, and\\n -- (b) not defined by a \'deriving\' clause\\n -- The latter have an Internal Name, so we can filter them out easily\\n unused_locals :: NameSet -> [GlobalRdrElt]\\n unused_locals keep =\\n let -- Note that defined_and_used, defined_but_not_used\\n -- are both [GRE]; that\'s why we need defined_and_used\\n -- rather than just used_names\\n _defined_and_used, defined_but_not_used :: [GlobalRdrElt]\\n (_defined_and_used, defined_but_not_used)\\n = partition (gre_is_used (used_names keep)) defined_names\\n\\n in filter is_unused_local defined_but_not_used\\n is_unused_local :: GlobalRdrElt -> Bool\\n is_unused_local gre = isLocalGRE gre\\n && isExternalName (greName gre)\\n\\n{- *********************************************************************\\n* *\\n Missing signatures\\n* *\\n********************************************************************* -}\\n\\n{-\\nNote [Missing signatures]\\n~~~~~~~~~~~~~~~~~~~~~~~~~\\nThere are four warning flags in play:\\n\\n * -Wmissing-exported-signatures\\n Warn about any exported top-level function/value without a type signature.\\n Does not include pattern synonyms.\\n\\n * -Wmissing-signatures\\n Warn about any top-level function/value without a type signature. Does not\\n include pattern synonyms. Takes priority over -Wmissing-exported-signatures.\\n\\n * -Wmissing-exported-pattern-synonym-signatures\\n Warn about any exported pattern synonym without a type signature.\\n\\n * -Wmissing-pattern-synonym-signatures\\n Warn about any pattern synonym without a type signature. Takes priority over\\n -Wmissing-exported-pattern-synonym-signatures.\\n\\n-}\\n\\n-- | Warn the user about top level binders that lack type signatures.\\n-- Called /after/ type inference, so that we can report the\\n-- inferred type of the function\\nwarnMissingSignatures :: TcGblEnv -> RnM ()\\nwarnMissingSignatures gbl_env\\n = do { let exports = availsToNameSet (tcg_exports gbl_env)\\n sig_ns = tcg_sigs gbl_env\\n -- We use sig_ns to exclude top-level bindings that are generated by GHC\\n binds = collectHsBindsBinders CollNoDictBinders $ tcg_binds gbl_env\\n pat_syns = tcg_patsyns gbl_env\\n\\n not_ghc_generated :: Name -> Bool\\n not_ghc_generated name = name `elemNameSet` sig_ns\\n\\n add_binding_warn :: Id -> RnM ()\\n add_binding_warn id =\\n when (not_ghc_generated name) $\\n do { env <- liftZonkM $ tcInitTidyEnv -- Why not use emptyTidyEnv?\\n ; let ty = tidyOpenType env (idType id)\\n missing = MissingTopLevelBindingSig name ty\\n diag = TcRnMissingSignature missing exported\\n ; addDiagnosticAt (getSrcSpan name) diag }\\n where\\n name = idName id\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n add_patsyn_warn :: PatSyn -> RnM ()\\n add_patsyn_warn ps =\\n when (not_ghc_generated name) $\\n addDiagnosticAt (getSrcSpan name)\\n (TcRnMissingSignature missing exported)\\n where\\n name = patSynName ps\\n missing = MissingPatSynSig ps\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n -- Warn about missing signatures\\n -- Do this only when we have a type to offer\\n -- See Note [Missing signatures]\\n ; mapM_ add_binding_warn binds\\n ; mapM_ add_patsyn_warn pat_syns\\n }\\n\\n-- | Warn the user about tycons that lack kind signatures.\\n-- Called /after/ type (and kind) inference, so that we can report the\\n-- inferred kinds.\\nwarnMissingKindSignatures :: TcGblEnv -> RnM ()\\nwarnMissingKindSignatures gbl_env\\n = do { cusks_enabled <- xoptM LangExt.CUSKs\\n ; mapM_ (add_ty_warn cusks_enabled) tcs\\n }\\n where\\n tcs = tcg_tcs gbl_env\\n ksig_ns = tcg_ksigs gbl_env\\n exports = availsToNameSet (tcg_exports gbl_env)\\n\\n has_kind_signature :: Name -> Bool\\n has_kind_signature name = name `elemNameSet` ksig_ns\\n\\n add_ty_warn :: Bool -> TyCon -> RnM ()\\n add_ty_warn cusks_enabled tyCon =\\n when (has_kind_signature name) $\\n addDiagnosticAt (getSrcSpan name) diag\\n where\\n name = tyConName tyCon\\n diag = TcRnMissingSignature missing exported\\n missing = MissingTyConKindSig tyCon cusks_enabled\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused imports}\\n* *\\n*********************************************************\\n\\nThis code finds which import declarations are unused. The\\nspecification and implementation notes are here:\\n https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/unused-imports\\n\\nSee also Note [Choosing the best import declaration] in GHC.Types.Name.Reader\\n-}\\n\\ntype ImportDeclUsage\\n = ( LImportDecl GhcRn -- The import declaration\\n , [GlobalRdrElt] -- What *is* used (normalised)\\n , [Name] -- What is imported but *not* used\\n , [NamespaceSpecifier GhcRn] ) -- Unused wildcards\\n\\nwarnUnusedImportDecls :: TcGblEnv -> HscSource -> RnM ()\\nwarnUnusedImportDecls gbl_env hsc_src\\n = do { uses <- readMutVar (tcg_used_gres gbl_env)\\n ; let imports = tcg_rn_imports gbl_env\\n rdr_env = tcg_rdr_env gbl_env\\n\\n -- We should only warn for unnecessary *user* imports, but deciding\\n -- minimal imports should take generated imports into account\\n ; let usageUserImports = findImportUsage (excludeGenerated imports) uses\\n usageAllImports = findImportUsage imports uses\\n\\n ; traceRn \\"warnUnusedImportDecls\\" $\\n (vcat [ text \\"Uses:\\" <+> ppr uses\\n , text \\"Usage all user imports: \\" <+> ppr usageUserImports\\n , text \\"Usage all imports: \\" <+> ppr usageAllImports])\\n\\n ; mapM_ (warnUnusedImport rdr_env) usageUserImports\\n\\n ; whenGOptM Opt_D_dump_minimal_imports $\\n printMinimalImports hsc_src usageAllImports }\\n\\n-- | Exclude generated imports\\nexcludeGenerated :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\nexcludeGenerated = filterOut (isGeneratedImport . ideclOrigin . ideclExt . unLoc)\\n\\nfindImportUsage :: [LImportDecl GhcRn]\\n -> [GlobalRdrElt]\\n -> [ImportDeclUsage]\\n\\nfindImportUsage imports used_gres\\n = map unused_decl imports\\n where\\n import_usage :: ImportMap\\n import_usage = mkImportMap used_gres\\n\\n unused_decl :: LImportDecl GhcRn -> ImportDeclUsage\\n unused_decl decl@(L _ (ImportDecl { ideclImportList = imps }))\\n = -- pprTrace \\"unused_decl\\" (vcat [ ppr decl\\n -- , text \\"used\\" <+> ppr used_gres\\n -- , text \\"unused\\" <+> ppr unused_names ]) $\\n (decl, used_gres, unused_names, unused_wcs)\\n where\\n used_gres = lookupImportMap decl import_usage\\n\\n used_gre_env = mkGlobalRdrEnv used_gres\\n used_parents = mkNameSet (mapMaybe greParent_maybe used_gres)\\n\\n (unused_names, unused_wcs) -- Not trivial; see eg #7454\\n = case imps of\\n Just (Exactly, imp_ies) ->\\n let unused = foldr (add_unused . unLoc) emptyUnusedNames imp_ies\\n nms = nameSetElemsStable (collectUnusedNames unused)\\n wcs = collectUnusedWildcards unused\\n in (nms, wcs)\\n _other -> ([], []) -- No explicit import list => no unused-name list\\n\\n add_unused :: IE GhcRn -> UnusedNames -> UnusedNames\\n add_unused (IEVar _ n _) acc = add_unused_name (lieWrappedName n) True acc\\n add_unused (IEThingAbs _ n _) acc = add_unused_name (lieWrappedName n) False acc\\n add_unused (IEThingAll _ _ n _) acc = add_unused_all (lieWrappedName n) acc\\n add_unused (IEThingWith _ p wc ns _) acc = add_wc_all (add_unused_with pn xs acc)\\n where pn = lieWrappedName p\\n xs = map lieWrappedName ns\\n add_wc_all = case wc of\\n NoIEWildcard -> id\\n IEWildcard _ -> add_unused_all pn\\n add_unused (IEWholeNamespace x ns_spec) acc = add_unused_wildcard ns_spec (iewn_names x) acc\\n add_unused _ acc = acc\\n\\n add_unused_name :: Name -> Bool -> UnusedNames -> UnusedNames\\n add_unused_name n is_ie_var acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | is_ie_var\\n , isFieldName n\\n -- See Note [Reporting unused imported duplicate record fields]\\n = let\\n fs = getOccFS n\\n (flds, flds_used) = lookupFsEnv acc_fs fs `orElse` (emptyNameSet, Any False)\\n acc_fs\' = extendFsEnv acc_fs fs (extendNameSet flds n, Any used S.<> flds_used)\\n in UnusedNames acc_ns acc_wcs acc_fs\'\\n\\n | used\\n = acc\\n\\n | otherwise\\n = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n where\\n used = isJust $ lookupGRE_Name used_gre_env n\\n\\n add_unused_all :: Name -> UnusedNames -> UnusedNames\\n add_unused_all n acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | Just {} <- lookupGRE_Name used_gre_env n = acc\\n | n `elemNameSet` used_parents = acc\\n | otherwise = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n\\n add_unused_with :: Name -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_with p ns acc\\n | all (`elemNameSet` acc1_ns) ns = add_unused_name p False acc1\\n | otherwise = acc1\\n where\\n acc1@(UnusedNames acc1_ns _ _) = foldr (\\\\n acc\' -> add_unused_name n False acc\') acc ns\\n -- If you use \'signum\' from Num, then the user may well have\\n -- imported Num(signum). We don\'t want to complain that\\n -- Num is not itself mentioned. Hence the two cases in add_unused_with.\\n\\n add_unused_wildcard :: NamespaceSpecifier GhcRn -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_wildcard ns_spec names acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | any_used = acc\\n | otherwise = UnusedNames acc_ns (ns_spec : acc_wcs) acc_fs\\n where\\n -- A wildcard `type ..` or `data ..` is used if at least one of\\n -- the names it expands to is used\\n any_used = any (isJust . lookupGRE_Name used_gre_env) names\\n\\n\\n-- | An accumulator for unused names in an import list.\\n--\\n-- See Note [Reporting unused imported duplicate record fields].\\ndata UnusedNames =\\n UnusedNames\\n { unused_names :: NameSet\\n -- ^ Unused \'Name\'s in an import list, not including record fields\\n -- that are plain \'IEVar\' imports (tracked by \'rec_fld_uses\')\\n -- or wildcard imports (tracked by \'unused_wildcards\').\\n , unused_wildcards :: [NamespaceSpecifier GhcRn]\\n -- ^ Unused wildcards @type ..@ or @data ..@ in an import list.\\n , rec_fld_uses :: FastStringEnv (NameSet, Any)\\n -- ^ Record fields imported without a parent (i.e. an \'IEVar\' import).\\n --\\n -- The \'Any\' value records whether any of the record fields\\n -- sharing the same underlying \'FastString\' have been used.\\n }\\n\\nemptyUnusedNames :: UnusedNames\\nemptyUnusedNames = UnusedNames emptyNameSet [] emptyFsEnv\\n\\ninstance Outputable UnusedNames where\\n ppr (UnusedNames nms wcs flds) =\\n text \\"UnusedNames\\" <+>\\n braces (ppr nms <+> ppr wcs <+> ppr (fmap (second getAny) flds))\\n\\n-- | Collect all unused names from a \'UnusedNames\' value.\\ncollectUnusedNames :: UnusedNames -> NameSet\\ncollectUnusedNames (UnusedNames { unused_names = nms, rec_fld_uses = flds })\\n = nms S.<> unused_flds\\n where\\n unused_flds = nonDetFoldFsEnv collect_unused emptyNameSet flds\\n collect_unused :: (NameSet, Any) -> NameSet -> NameSet\\n collect_unused (nms, Any at_least_one_name_is_used) acc\\n | at_least_one_name_is_used = acc\\n | otherwise = unionNameSet nms acc\\n\\ncollectUnusedWildcards :: UnusedNames -> [NamespaceSpecifier GhcRn]\\ncollectUnusedWildcards = unused_wildcards\\n\\n{- Note [Reporting unused imported duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have (#24035):\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M1 (R1(..), R2(..)) where\\n data R1 = MkR1 { fld :: Int }\\n data R2 = MkR2 { fld :: Int }\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M2 where\\n import M1 (R1(MkR1), R2, fld)\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nIn the import of \'M1\' in \'M2\', the \'fld\' import resolves to two separate GREs,\\nnamely R1(fld) and R2(fld). From the perspective of the renamer, and in particular\\nthe \'findImportUsage\' function, it\'s as if the user had imported the two names\\nseparately (even though no source syntax allows that).\\n\\nThis means that we need to be careful when reporting unused imports: the R2(fld)\\nimport is indeed unused, but because R1(fld) is used, we should not report\\nfld as unused altogether.\\n\\nTo achieve this, we keep track of record field imports without a parent (i.e.\\nusing the IEVar constructor) separately from other import items, using the\\nUnusedNames datatype.\\nOnce we have accumulated usages, we emit warnings for unused record fields\\nwithout parents one whole group (of record fields sharing the same textual name)\\nat a time, and only if *all* of the record fields in the group are unused;\\nsee \'collectUnusedNames\'.\\n\\nNote that this only applies to record fields imported without a parent. If we\\nhad:\\n\\n import M1 (R1(MkR1, fld), R2(fld))\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nthen of course we should report the second \'fld\' as unused.\\n-}\\n\\n\\n{- Note [The ImportMap]\\n~~~~~~~~~~~~~~~~~~~~~~~\\nThe ImportMap is a short-lived intermediate data structure records, for\\neach import declaration, what stuff brought into scope by that\\ndeclaration is actually used in the module.\\n\\nThe [GlobalRdrElt] are the things imported from that decl.\\n-}\\n\\ndata ImportMap = ImportMap\\n { im_imports :: Map RealSrcSpan [GlobalRdrElt]\\n -- ^ See [The ImportMap]\\n -- If loc :-> gres, then\\n -- \'loc\' = the end loc of the bestImport of each GRE in \'gres\'\\n , im_generatedImports :: Map ModuleName [GlobalRdrElt]\\n }\\n\\nmkImportMap :: [GlobalRdrElt] -> ImportMap\\n-- For each of a list of used GREs, find all the import decls that brought\\n-- it into scope; choose one of them (bestImport), and record\\n-- the RdrName in that import decl\'s entry in the ImportMap\\nmkImportMap = foldr insertImportMap $ ImportMap Map.empty Map.empty\\n\\ninsertImportMap :: GlobalRdrElt -> ImportMap -> ImportMap\\ninsertImportMap gre@(GRE { gre_imp = imp_specs }) importMap\\n | RealSrcSpan importSpan _ <- is_dloc best_imp_spec =\\n importMap{im_imports = insertElem importSpan gre $ im_imports importMap}\\n | GeneratedSrcSpan{} <- is_dloc best_imp_spec =\\n importMap{im_generatedImports = insertElem (moduleName $ is_mod best_imp_spec) gre $ im_generatedImports importMap}\\n | otherwise = importMap\\n where\\n best_imp_spec =\\n case bagToList imp_specs of\\n [] -> pprPanic \\"mkImportMap: GRE with no ImportSpecs\\" (ppr gre)\\n is:iss -> is_decl $ bestImport (is NE.:| iss)\\n\\n -- https://github.com/haskell/containers/issues/784\\n insertElem :: Ord k => k -> v -> Map k [v] -> Map k [v]\\n insertElem k v = flip Map.alter k $ \\\\case\\n Just vs -> Just (v : vs)\\n Nothing -> Just [v]\\n\\nlookupImportMap :: LImportDecl GhcRn -> ImportMap -> [GlobalRdrElt]\\nlookupImportMap (L srcSpan ImportDecl{ideclName = L _ modName}) importMap =\\n fromMaybe [] $\\n -- should match logic in insertImportMap\\n case locA srcSpan of\\n RealSrcSpan realSrcSpan _ -> realSrcSpan `Map.lookup` im_imports importMap\\n GeneratedSrcSpan{} -> modName `Map.lookup` im_generatedImports importMap\\n _ -> Nothing\\n\\nlieNames :: LIE (GhcPass p) -> [Located (IdP (GhcPass p))]\\nlieNames = _\\n\\nwarnUnusedImport :: GlobalRdrEnv -> ImportDeclUsage -> RnM ()\\nwarnUnusedImport rdr_env (L loc decl, used, unused, unused_wcs)\\n\\n -- Do not warn for \'import M()\'\\n -- See (UI1) in Note [Unused imports]\\n | Just (Exactly, _) <- ideclImportList decl\\n , null unused && null unused_wcs\\n = return ()\\n\\n -- Note [Do not warn about Prelude hiding]\\n | Just (EverythingBut, hides) <- ideclImportList decl\\n , not (null hides)\\n , pRELUDE_NAME == unLoc (ideclName decl)\\n = return ()\\n\\n -- Do not warn about import X as Rebindable\\n -- See (UI2) in Note [Unused imports]\\n | Just (L _ mod) <- ideclAs decl\\n , mod == rEBINDABLE_MOD_NAME\\n = return ()\\n\\n -- Nothing used; drop entire declaration\\n | null used\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl UnusedImportNone)\\n\\n -- Everything imported is used; nop\\n | null unused && null unused_wcs\\n = return ()\\n\\n -- Some imports are unused: make the `SrcSpan` cover only the unused\\n -- items instead of the whole import statement\\n | Just (_, imports) <- ideclImportList decl\\n , let unused_locs = [ locA loc | L loc ie <- imports\\n , name <- ieNames ie\\n , name `elem` unused ]\\n , loc1 : locs <- unused_locs\\n , let span = foldr1 combineSrcSpans ( loc1 NE.:| locs )\\n = addDiagnosticAt span (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n -- Some imports are unused\\n | otherwise\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n where\\n -- In warning message, pretty-print identifiers unqualified unconditionally\\n -- to improve the consistent for ambiguous/unambiguous identifiers.\\n -- See #14881.\\n possible_field n =\\n case lookupGRE_Name rdr_env n of\\n Just (GRE { gre_par = par, gre_info = IAmRecField info }) ->\\n let fld_occ :: OccName\\n fld_occ = nameOccName $ flSelector $ recFieldLabel info\\n in UnusedImportNameRecField par fld_occ\\n _ -> UnusedImportNameRegular n\\n\\n -- Print unused names in a deterministic (lexicographic) order\\n sort_unused :: [UnusedImportName]\\n sort_unused =\\n [ UnusedImportWildcard wc | wc <- unused_wcs ] ++\\n [ possible_field nm | nm <- sortBy (comparing nameOccName) unused ]\\n\\ngetMinimalImports :: [ImportDeclUsage] -> RnM [LImportDecl GhcRn]\\ngetMinimalImports ie_decls\\n = do { rdr_env <- getGlobalRdrEnv\\n ; fmap combine $ mapM (mk_minimal rdr_env) ie_decls }\\n where\\n mk_minimal rdr_env (L l decl, used_gres, unused, unused_wcs)\\n | null unused && null unused_wcs\\n , Just (Exactly, _) <- ideclImportList decl\\n = return (L l decl)\\n | otherwise\\n = do { let ImportDecl { ideclName = L _ mod_name\\n , ideclSource = is_boot\\n , ideclPkgQual = pkg_qual\\n , ideclExt = XImportDeclPass { ideclOrigin = origin } } = decl\\n ; iface <- loadSrcInterface doc (importDeclLookupScope origin)\\n mod_name is_boot pkg_qual\\n ; let used_avails = gresToAvailInfo used_gres\\n ; lies <- map (L l) <$> concatMapM (to_ie rdr_env iface) used_avails\\n ; return (L l (decl { ideclImportList = Just (Exactly, lies) })) }\\n where\\n doc = text \\"Compute minimal imports for\\" <+> ppr decl\\n\\n to_ie :: GlobalRdrEnv -> ModIface -> AvailInfo -> RnM [IE GhcRn]\\n -- The main trick here is that if we\'re importing all the constructors\\n -- we want to say \\"T(..)\\", but if we\'re importing only a subset we want\\n -- to say \\"T(A,B,C)\\". So we have to find out what the module exports.\\n to_ie rdr_env _ (Avail c) -- Note [Overloaded field import]\\n = do { let\\n gre = expectJust $ lookupGRE_Name rdr_env c\\n ; return $ [IEVar Nothing (to_ie_post_rn $ noLocA $ greName gre) Nothing] }\\n to_ie _ _ avail@(AvailTC n [_]) -- Exporting the main decl and nothing else\\n | availExportsDecl avail\\n = return [IEThingAbs Nothing (to_ie_post_rn $ noLocA n) Nothing]\\n to_ie rdr_env iface (AvailTC n cs) =\\n case [ xs | avail@(AvailTC x xs) <- mi_exports iface\\n , x == n\\n , availExportsDecl avail -- Note [Partial export]\\n ] of\\n [xs]\\n | all_used xs\\n -> return [IEThingAll (IEThingAllExt Nothing noAnn noAnn noAnn)\\n (NoNamespaceSpecifier noExtField)\\n (to_ie_post_rn $ noLocA n)\\n Nothing]\\n | otherwise\\n -> do { let ns_gres = map (expectJust . lookupGRE_Name rdr_env) cs\\n ns = map greName ns_gres\\n ; return [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n -- Note [Overloaded field import]\\n _other\\n -> do { let infos = map (expectJust . lookupGRE_Name rdr_env) cs\\n (ns_gres,fs_gres) = classifyGREs infos\\n ns = map greName (ns_gres ++ fs_gres)\\n fs = map fieldGREInfo fs_gres\\n ; return $\\n if all_non_overloaded fs\\n then map (\\\\nm -> IEVar Nothing (to_ie_post_rn_var $ noLocA nm) Nothing) ns\\n else [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n where\\n\\n all_used avail_cs = all (`elem` cs) avail_cs\\n\\n all_non_overloaded = all (not . flIsOverloaded . recFieldLabel)\\n\\n combine :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\n combine = map merge . NE.groupAllWith getKey\\n\\n getKey :: LImportDecl GhcRn -> (Bool, Maybe ModuleName, ModuleName)\\n getKey decl =\\n ( isImportDeclQualified . ideclQualified $ idecl -- is this qualified? (important that this be first)\\n , unLoc <$> ideclAs idecl -- what is the qualifier (inside Maybe monad)\\n , unLoc . ideclName $ idecl -- Module Name\\n )\\n where\\n idecl :: ImportDecl GhcRn\\n idecl = unLoc decl\\n\\n merge :: NonEmpty (LImportDecl GhcRn) -> LImportDecl GhcRn\\n merge decls@((L l decl) :| _) = L l (decl { ideclImportList = Just (Exactly, lies) })\\n where lies = concatMap snd $ mapMaybe (ideclImportList . unLoc) $ NE.toList decls\\n\\nclassifyGREs :: [GlobalRdrElt] -> ([GlobalRdrElt], [FieldGlobalRdrElt])\\nclassifyGREs = partition (not . isRecFldGRE)\\n\\nprintMinimalImports :: HscSource -> [ImportDeclUsage] -> RnM ()\\n-- See Note [Printing minimal imports]\\nprintMinimalImports hsc_src imports_w_usage\\n = do { imports\' <- excludeGenerated <$> getMinimalImports imports_w_usage\\n ; this_mod <- getModule\\n ; dflags <- getDynFlags\\n ; liftIO $ withFile (mkFilename dflags this_mod) WriteMode $ \\\\h ->\\n printForUser dflags h neverQualify AllTheWay (vcat (map ppr imports\'))\\n -- The neverQualify is important. We are printing Names\\n -- but they are in the context of an \'import\' decl, and\\n -- we never qualify things inside there\\n -- E.g. import Blag( f, b )\\n -- not import Blag( Blag.f, Blag.g )!\\n }\\n where\\n mkFilename dflags this_mod\\n | Just d <- dumpDir dflags = d basefn\\n | otherwise = basefn\\n where\\n suffix = case hsc_src of\\n HsBootFile -> \\".imports-boot\\"\\n HsSrcFile -> \\".imports\\"\\n HsigFile -> \\".imports\\"\\n basefn = moduleNameString (moduleName this_mod) ++ suffix\\n\\n\\nto_ie_post_rn_var :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn_var (L l n)\\n | isDataOcc $ occName n = L l (IEPattern noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n\\n\\nto_ie_post_rn :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn (L l n)\\n | isTcOcc occ && isSymOcc occ = L l (IEType noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n where occ = occName n\\n\\n{- Note [Do not warn about Prelude hiding]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWe do not warn about\\n import Prelude hiding( x, y )\\nbecause even if nothing else from Prelude is used, it may be essential to hide\\nx,y to avoid name-shadowing warnings. Example (#9061)\\n import Prelude hiding( log )\\n f x = log where log = ()\\n\\nNote [Unused imports]\\n~~~~~~~~~~~~~~~~~~~~~\\nIn `warnUnusedImport`, if we see an import with an explicit list imports, thus\\n import M( a, b )\\nand neither `a` nor `b` is used, we report the entire import decl as unused. We\\ncheck this by looking at the names that it brings into scope scope; if there are\\nno ununused names, don\'t report.\\n\\n(UI1) We don\'t want to complain about `import M()`, because that is often used to bring\\n M\'s /instances/ into scope. That is neatly dealt with by the \\"no unused\\n names\\" (nor unused wildcard imports) criterion.\\n\\n(UI2) We don\'t report a decl as unused if it has an `as Rebindable` qualifier.\\n See (KN1) in Note [Overview of known entities] in GHC.Builtin\\n\\n\\nNote [Printing minimal imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nTo print the minimal imports we walk over all import decls (both user-supplied\\nand generated), trim their import lists, then filter out generated decls.\\n\\nNB that\\n\\n * We do *not* change the \'qualified\' or \'as\' parts!\\n\\n * We do not discard a decl altogether; we might need instances\\n from it. Instead we just trim to an empty import list\\n\\nNote [Partial export]\\n~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have\\n\\n module A( op ) where\\n class C a where\\n op :: a -> a\\n\\n module B where\\n import A\\n f = ..op...\\n\\nThen the minimal import for module B is\\n import A( op )\\nnot\\n import A( C( op ) )\\nwhich we would usually generate if C was exported from B. Hence\\nthe availExportsDecl test when deciding what to generate.\\n\\n\\nNote [Overloaded field import]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nOn the other hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n data T = MkT { foo :: Int }\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( T(foo) )\\nbecause when DuplicateRecordFields is enabled, field selectors are\\nnot in scope without their enclosing datatype.\\n\\nOn the third hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n pattern MkT { foo } = Just foo\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( foo )\\nbecause foo doesn\'t have a parent. This might actually be ambiguous if A\\nexports another field called foo, but there is no good answer to return and this\\nis a very obscure corner, so it seems to be the best we can do. See\\nDRFPatSynExport for a test of this.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Errors}\\n* *\\n************************************************************************\\n-}\\n\\nbadImportItemErr\\n :: ModIface -> ImpDeclSpec -> IE GhcPs\\n -> IsSubordinateError\\n -> [AvailInfo]\\n -> TcRn (NonEmpty ImportLookupReason)\\nbadImportItemErr iface decl_spec ie sub avails = do\\n exts <- importLookupExtensions\\n let import_lookup_bad :: BadImportKind -> ImportLookupReason\\n import_lookup_bad k = ImportLookupBad k iface decl_spec ie exts\\n dflags <- getDynFlags\\n hsc_env <- getTopEnv\\n let rdr_env = mkGlobalRdrEnv\\n $ gresFromAvails hsc_env (Just imp_spec) all_avails\\n pure $ fmap import_lookup_bad (importErrorKind dflags rdr_env)\\n where\\n importErrorKind :: DynFlags -> GlobalRdrEnv -> NonEmpty BadImportKind\\n importErrorKind dflags rdr_env\\n | any checkIfTyCon avails = case sub of\\n IsNotSubordinate -> NE.singleton BadImportAvailTyCon\\n IsSubordinateError { subordinate_err_parent = gre\\n , subordinate_err_unavailable = unavailable\\n , subordinate_err_nontype = nontype\\n , subordinate_err_nondata = nondata }\\n -> NE.fromList $ catMaybes $\\n [ fmap (BadImportNotExportedSubordinates gre) (NE.nonEmpty unavailable)\\n , fmap (BadImportNonTypeSubordinates gre) (NE.nonEmpty nontype)\\n , fmap (BadImportNonDataSubordinates gre) (NE.nonEmpty nondata) ]\\n | any checkIfVarName avails = NE.singleton BadImportAvailVar\\n | Just con <- find checkIfDataCon avails = NE.singleton (BadImportAvailDataCon (availOccName con))\\n | otherwise = NE.singleton (BadImportNotExported suggs)\\n where\\n suggs = similar_suggs ++ fieldSelectorSuggestions rdr_env rdr\\n what_look = case sub of\\n IsNotSubordinate -> WL_TyCon_or_TermVar\\n IsSubordinateError { subordinate_err_parent = gre } ->\\n case greInfo gre of\\n IAmTyCon ClassFlavour\\n -> WL_TyCon_or_TermVar\\n _ -> WL_Term\\n similar_names =\\n similarNameSuggestions (Unbound.LF what_look WL_Global)\\n dflags rdr_env emptyLocalRdrEnv rdr\\n similar_suggs =\\n case NE.nonEmpty $ mapMaybe imported_item $ similar_names of\\n Just similar -> [ SuggestSimilarNames rdr similar ]\\n Nothing -> [ ]\\n\\n -- Only keep imported items, and set the \\"HowInScope\\" to\\n -- \\"Nothing\\" to avoid printing \\"imported from...\\" in the suggestion\\n -- error message.\\n imported_item (SimilarRdrName rdr_name gre (Just (ImportedBy {})))\\n = Just (SimilarRdrName rdr_name gre Nothing)\\n imported_item _ = Nothing\\n\\n checkIfDataCon = checkIfAvailMatches isDataConName\\n checkIfTyCon = checkIfAvailMatches isTyConName\\n checkIfVarName =\\n \\\\case\\n AvailTC{} -> False\\n Avail n -> importedFS == occNameFS (occName n)\\n && (isVarOcc <||> isFieldOcc) (occName n)\\n checkIfAvailMatches namePred =\\n \\\\case\\n AvailTC _ ns ->\\n case find (\\\\n -> importedFS == occNameFS (occName n)) ns of\\n Just n -> namePred n\\n Nothing -> False\\n Avail{} -> False\\n availOccName = occName . availName\\n rdr = ieName ie\\n importedFS = occNameFS $ rdrNameOcc rdr\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n all_avails = mi_exports iface\\n\\nimportLookupExtensions :: TcRn ImportLookupExtensions\\nimportLookupExtensions = do\\n ile_pattern_synonyms <- xoptM LangExt.PatternSynonyms\\n ile_explicit_namespaces <- xoptM LangExt.ExplicitNamespaces\\n return ImportLookupExtensions{ile_pattern_synonyms, ile_explicit_namespaces}\\n\\naddDupDeclErr :: NonEmpty GlobalRdrElt -> TcRn ()\\naddDupDeclErr gres@(gre :| _)\\n -- Report the error at the later location\\n = addErrAt (getSrcSpan (NE.last sorted_names)) $ (TcRnDuplicateDecls (greOccName gre) sorted_names)\\n where\\n sorted_names =\\n NE.sortBy (SrcLoc.leftmost_smallest `on` nameSrcSpan)\\n (fmap greName gres)\\n\\n-- This data decl will parse OK\\n-- data T = a Int\\n-- treating \\"a\\" as the constructor.\\n-- It is really hard to make the parser spot this malformation.\\n-- So the renamer has to check that the constructor is legal\\n--\\n-- We can get an operator as the constructor, even in the prefix form:\\n-- data T = :% Int Int\\n-- from interface files, which always print in prefix form\\n--\\n-- We also allow type constructor names, which are defined by \\"type data\\"\\n-- declarations. See Note [Type data declarations] in GHC.Rename.Module.\\n\\ncheckConName :: RdrName -> TcRn ()\\ncheckConName name\\n = checkErr (isRdrDataCon name || isRdrTc name) (TcRnIllegalDataCon name)\\n", "filetypes": ["haskell"]}}}' 2026-10-16 14:46:40,837 - DEBUG - POST b'http://127.0.0.1:37093/receive_messages' {'content-type': 'application/json', 'x-ycm-hmac': b'Rga7Yd4l4fgfufwYw+0sxzurvznImlBO0MPmgAlS4EY='} b'{"filepath": "/home/enrico/ghc/compiler/GHC/Rename/Names.hs", "line_num": 1, "column_num": 1, "working_dir": "/home/enrico/ghc", "file_data": {"/home/enrico/ghc/compiler/GHC/Rename/Names.hs": {"contents": "{-\\n(c) The GRASP/AQUA Project, Glasgow University, 1992-1998\\n\\nExtracting imported and top-level names in scope\\n-}\\n\\n{-# LANGUAGE NondecreasingIndentation #-}\\n{-# LANGUAGE TypeFamilies #-}\\n\\nmodule GHC.Rename.Names (\\n rnImports, getLocalNonValBinders, newRecordFieldLabel,\\n importsFromIface,\\n ImportUserSpec(..),\\n extendGlobalRdrEnvRn,\\n gresFromAvails,\\n calculateAvails,\\n reportUnusedNames,\\n checkConName,\\n mkChildEnv,\\n findChildren,\\n mkBadExportSubordinate,\\n findImportUsage,\\n getMinimalImports,\\n printMinimalImports,\\n renamePkgQual, renameRawPkgQual,\\n classifyGREs,\\n ImportDeclUsage,\\n rnNamespaceSpecifier\\n ) where\\n\\nimport GHC.Prelude hiding ( head, init, last, tail )\\n\\nimport GHC.Driver.Env\\nimport GHC.Driver.Session\\nimport GHC.Driver.Ppr\\n\\nimport GHC.Rename.Env\\nimport GHC.Rename.Fixity\\nimport GHC.Rename.Utils ( warnUnusedTopBinds )\\nimport GHC.Rename.Unbound\\nimport qualified GHC.Rename.Unbound as Unbound\\n\\nimport GHC.Tc.Errors.Types\\nimport GHC.Tc.Utils.Env\\nimport GHC.Tc.Utils.Monad\\nimport GHC.Tc.Types.LclEnv\\nimport GHC.Tc.Zonk.TcType ( tcInitTidyEnv )\\n\\nimport GHC.Hs\\nimport GHC.Iface.Load ( loadSrcInterface, loadSrcInterface_maybe )\\nimport GHC.Iface.Errors.Types\\n ( IfaceMessage(..), MissingInterfaceError, InterfaceLookingFor(..)\\n , LoadEssentialsReason(..) )\\nimport GHC.Iface.Syntax ( fromIfaceWarnings )\\nimport GHC.Builtin.Modules( pRELUDE_NAME, rEBINDABLE_MOD_NAME )\\nimport GHC.Parser.PostProcess ( setRdrNameSpace )\\nimport GHC.Core.TyCo.Tidy\\nimport GHC.Core.PatSyn\\nimport GHC.Core.TyCon ( TyCon, tyConName )\\nimport qualified GHC.LanguageExtensions as LangExt\\n\\nimport GHC.Utils.Outputable as Outputable\\nimport GHC.Utils.Misc as Utils\\nimport GHC.Utils.Panic\\n\\nimport GHC.Types.Fixity.Env\\nimport GHC.Types.SafeHaskell\\nimport GHC.Types.Name\\nimport GHC.Types.Name.Env\\nimport GHC.Types.Name.Set\\nimport GHC.Types.Name.Reader\\nimport GHC.Types.Avail\\nimport GHC.Types.FieldLabel\\nimport GHC.Types.Hint\\nimport GHC.Types.SourceFile\\nimport GHC.Types.SrcLoc as SrcLoc\\nimport GHC.Types.Basic (TyConFlavour (..), convImportLevel, VisArity)\\nimport GHC.Types.UnresolvedImport\\nimport GHC.Types.Id\\nimport GHC.Types.PkgQual\\nimport GHC.Types.GREInfo (ConInfo(..), ConFieldInfo (..), ConLikeInfo (ConIsData))\\n\\nimport GHC.Unit\\nimport GHC.Unit.Module.Warnings\\nimport GHC.Unit.Module.ModIface\\nimport GHC.Unit.Module.Imported\\nimport GHC.Unit.Module.Deps\\nimport GHC.Unit.Env\\n\\nimport GHC.Data.Bag\\nimport GHC.Data.FastString\\nimport GHC.Data.FastString.Env\\nimport GHC.Data.Maybe\\nimport GHC.Data.List.SetOps ( removeDups )\\n\\nimport Control.Arrow ( second )\\nimport Control.Monad\\nimport Data.Foldable ( for_ )\\nimport Data.IntMap ( IntMap )\\nimport qualified Data.IntMap as IntMap\\nimport Data.Map ( Map )\\nimport qualified Data.Map as Map\\nimport Data.Ord ( comparing )\\nimport Data.Semigroup ( Any(..) )\\nimport qualified Data.Semigroup as S\\nimport Data.List ( partition, find, sortBy )\\nimport Data.List.NonEmpty (NonEmpty(..))\\nimport qualified Data.List.NonEmpty as NE\\nimport Data.Function ( on )\\nimport qualified Data.Set as S\\nimport System.FilePath (())\\nimport System.IO\\n\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{rnImports}\\n* *\\n************************************************************************\\n\\nNote [Tracking Trust Transitively]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen we import a package as well as checking that the direct imports are safe\\naccording to the rules outlined in the Note [Safe Haskell Trust Check] in GHC.Driver.Main\\nwe must also check that these rules hold transitively for all dependent modules\\nand packages. Doing this without caching any trust information would be very\\nslow as we would need to touch all packages and interface files a module depends\\non. To avoid this we make use of the property that if a modules Safe Haskell\\nmode changes, this triggers a recompilation from that module in the dependency\\ngraph. So we can just worry mostly about direct imports.\\n\\nThere is one trust property that can change for a package though without\\nrecompilation being triggered: package trust. So we must check that all\\npackages a module transitively depends on to be trusted are still trusted when\\nwe are compiling this module (as due to recompilation avoidance some modules\\nbelow may not be considered trusted any more without recompilation being\\ntriggered).\\n\\nWe handle this by augmenting the existing transitive list of packages a module M\\ndepends on with a bool for each package that says if it must be trusted when the\\nmodule M is being checked for trust. This list of trust required packages for a\\nsingle import is gathered in the rnImportDecl function and stored in an\\nImportAvails data structure. The union of these trust required packages for all\\nimports is done by the rnImports function using the combine function which calls\\nthe plusImportAvails function that is a union operation for the ImportAvails\\ntype. This gives us in an ImportAvails structure all packages required to be\\ntrusted for the module we are currently compiling. Checking that these packages\\nare still trusted (and that direct imports are trusted) is done in\\nGHC.Driver.Main.checkSafeImports.\\n\\nSee the note below, [Trust Own Package] for a corner case in this method and\\nhow its handled.\\n\\n\\nNote [Trust Own Package]\\n~~~~~~~~~~~~~~~~~~~~~~~~\\nThere is a corner case of package trust checking that the usual transitive check\\ndoesn\'t cover. (For how the usual check operates see the Note [Tracking Trust\\nTransitively] below). The case is when you import a -XSafe module M and M\\nimports a -XTrustworthy module N. If N resides in a different package than M,\\nthen the usual check works as M will record a package dependency on N\'s package\\nand mark it as required to be trusted. If N resides in the same package as M\\nthough, then importing M should require its own package be trusted due to N\\n(since M is -XSafe so doesn\'t create this requirement by itself). The usual\\ncheck fails as a module doesn\'t record a package dependency of its own package.\\nSo instead we now have a bool field in a modules interface file that simply\\nstates if the module requires its own package to be trusted. This field avoids\\nus having to load all interface files that the module depends on to see if one\\nis trustworthy.\\n\\n\\nNote [Trust Transitive Property]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSo there is an interesting design question in regards to transitive trust\\nchecking. Say I have a module B compiled with -XSafe. B is dependent on a bunch\\nof modules and packages, some packages it requires to be trusted as its using\\n-XTrustworthy modules from them. Now if I have a module A that doesn\'t use safe\\nhaskell at all and simply imports B, should A inherit all the trust\\nrequirements from B? Should A now also require that a package p is trusted since\\nB required it?\\n\\nWe currently say no but saying yes also makes sense. The difference is, if a\\nmodule M that doesn\'t use Safe Haskell imports a module N that does, should all\\nthe trusted package requirements be dropped since M didn\'t declare that it cares\\nabout Safe Haskell (so -XSafe is more strongly associated with the module doing\\nthe importing) or should it be done still since the author of the module N that\\nuses Safe Haskell said they cared (so -XSafe is more strongly associated with\\nthe module that was compiled that used it).\\n\\nGoing with yes is a simpler semantics we think and harder for the user to stuff\\nup but it does mean that Safe Haskell will affect users who don\'t care about\\nSafe Haskell as they might grab a package from Cabal which uses safe haskell (say\\nnetwork) and that packages imports -XTrustworthy modules from another package\\n(say bytestring), so requires that package is trusted. The user may now get\\ncompilation errors in code that doesn\'t do anything with Safe Haskell simply\\nbecause they are using the network package. They will have to call \'ghc-pkg\\ntrust network\' to get everything working. Due to this invasive nature of going\\nwith yes we have gone with no for now.\\n-}\\n\\n-- | Process Import Decls. See \'rnImportDecl\' for a description of what\\n-- the return types represent.\\n-- Note: Do the non SOURCE ones first, so that we get a helpful warning\\n-- for SOURCE ones that are unnecessary\\nrnImports :: [(LImportDecl GhcPs, SDoc)]\\n -> RnM ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\nrnImports imports = do\\n tcg_env <- getGblEnv\\n -- NB: want an identity module here, because it\'s OK for a signature\\n -- module to import from its implementor\\n let this_mod = tcg_mod tcg_env\\n let (source, ordinary) = partition (is_source_import . fst) imports\\n is_source_import (d::LImportDecl GhcPs) = ideclSource (unLoc d) == IsBoot\\n stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary\\n stuff2 <- mapAndReportM (rnImportDecl this_mod) source\\n -- Safe Haskell: See Note [Tracking Trust Transitively]\\n let (decls, imp_user_spec, rdr_env, imp_avails) = combine (stuff1 ++ stuff2)\\n -- Update imp_boot_mods if imp_direct_mods mentions any of them\\n let merged_import_avail = clobberSourceImports imp_avails\\n return (decls, imp_user_spec, rdr_env, merged_import_avail)\\n\\n where\\n clobberSourceImports imp_avails =\\n imp_avails { imp_boot_mods = imp_boot_mods\' }\\n where\\n imp_boot_mods\' = mergeInstalledModuleEnv combJ id (const emptyInstalledModuleEnv)\\n (imp_boot_mods imp_avails)\\n (imp_direct_dep_mods imp_avails)\\n\\n combJ (GWIB _ IsBoot) (_, x) = Just x\\n combJ r _ = Just r\\n -- See Note [Combining ImportAvails]\\n combine :: [(LImportDecl GhcRn, ImportUserSpec, GlobalRdrEnv, ImportAvails)]\\n -> ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\n combine ss =\\n let (decls, imp_user_spec, rdr_env, imp_avails, finsts) = foldr\\n plus\\n ([], [], emptyGlobalRdrEnv, emptyImportAvails, emptyModuleSet)\\n ss\\n in (decls, imp_user_spec, rdr_env, imp_avails { imp_finsts = moduleSetElts finsts })\\n\\n plus (decl, us, gbl_env1, imp_avails1)\\n (decls, uss, gbl_env2, imp_avails2, finsts_set)\\n = ( decl:decls,\\n us:uss,\\n gbl_env1 `plusGlobalRdrEnv` gbl_env2,\\n imp_avails1\' `plusImportAvails` imp_avails2,\\n extendModuleSetList finsts_set new_finsts )\\n where\\n imp_avails1\' = imp_avails1 { imp_finsts = [] }\\n new_finsts = imp_finsts imp_avails1\\n\\n{-\\nNote [Combining ImportAvails]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nimp_finsts in ImportAvails is a list of family instance modules\\ntransitively depended on by an import. imp_finsts for a currently\\ncompiled module is a union of all the imp_finsts of imports.\\nComputing the union of two lists of size N is O(N^2) and if we\\ndo it to M imports we end up with O(M*N^2). That can get very\\nexpensive for bigger module hierarchies.\\n\\nUnion can be optimized to O(N log N) if we use a Set.\\nimp_finsts is converted back and forth between dep_finsts, so\\nchanging a type of imp_finsts means either paying for the conversions\\nor changing the type of dep_finsts as well.\\n\\nI\'ve measured that the conversions would cost 20% of allocations on my\\ntest case, so that can be ruled out.\\n\\nChanging the type of dep_finsts forces checkFamInsts to\\nget the module lists in non-deterministic order. If we wanted to restore\\nthe deterministic order, we\'d have to sort there, which is an additional\\ncost. As far as I can tell, using a non-deterministic order is fine there,\\nbut that\'s a brittle nonlocal property which I\'d like to avoid.\\n\\nAdditionally, dep_finsts is read from an interface file, so its \\"natural\\"\\ntype is a list. Which makes it a natural type for imp_finsts.\\n\\nSince rnImports.combine is really the only place that would benefit from\\nit being a Set, it makes sense to optimize the hot loop in rnImports.combine\\nwithout changing the representation.\\n\\nSo here\'s what we do: instead of naively merging ImportAvails with\\nplusImportAvails in a loop, we make plusImportAvails merge empty imp_finsts\\nand compute the union on the side using Sets. When we\'re done, we can\\nconvert it back to a list. One nice side effect of this approach is that\\nif there\'s a lot of overlap in the imp_finsts of imports, the\\nSet doesn\'t really need to grow and we don\'t need to allocate.\\n\\nRunning generateModules from #14693 with DEPTH=16, WIDTH=30 finishes in\\n23s before, and 11s after.\\n-}\\n\\n-- | Given a located import declaration @decl@ from @this_mod@,\\n-- calculate the following pieces of information:\\n--\\n-- 1. An updated \'LImportDecl\', where all unresolved \'RdrName\' in\\n-- the entity lists have been resolved into \'Name\'s,\\n--\\n-- 2. A \'GlobalRdrEnv\' representing the new identifiers that were\\n-- brought into scope (taking into account module qualification\\n-- and hiding),\\n--\\n-- 3. \'ImportAvails\' summarizing the identifiers that were imported\\n-- by this declaration, and\\n--\\n-- 4. A boolean \'AnyHpcUsage\' which is true if the imported module\\n-- used HPC.\\nrnImportDecl :: Module -> (LImportDecl GhcPs, SDoc)\\n -> RnM (LImportDecl GhcRn, ImportUserSpec , GlobalRdrEnv, ImportAvails)\\nrnImportDecl this_mod\\n (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name\\n , ideclPkgQual = raw_pkg_qual\\n , ideclSource = want_boot\\n , ideclSafe = mod_safe\\n , ideclLevelSpec = import_level\\n , ideclQualified = qual_style\\n , ideclExt = XImportDeclPass { ideclOrigin = origin }\\n , ideclAs = as_mod, ideclImportList = imp_details }), import_reason)\\n = setSrcSpanA loc $ do\\n\\n case raw_pkg_qual of\\n NoRawPkgQual -> pure ()\\n RawPkgQual {} -> do\\n pkg_imports <- xoptM LangExt.PackageImports\\n when (not pkg_imports) $ addErr TcRnPackageImportsDisabled\\n\\n let qual_only = isImportDeclQualified qual_style\\n generated = isGeneratedImport origin\\n\\n lookup_scope = importDeclLookupScope origin\\n\\n -- If there\'s an error in loadInterface, (e.g. interface\\n -- file not found) we get lots of spurious errors from \'filterImports\'\\n let imp_mod_name = unLoc loc_imp_mod_name\\n doc = ppr imp_mod_name <+> import_reason\\n\\n hsc_env <- getTopEnv\\n unit_env <- hsc_unit_env <$> getTopEnv\\n let pkg_qual = renameRawPkgQual unit_env imp_mod_name raw_pkg_qual\\n\\n -- Check for self-import, which confuses the typechecker (#9032)\\n -- ghc --make rejects self-import cycles already, but batch-mode may not\\n -- at least not until GHC.IfaceToCore.tcHiBootIface, which is too late to avoid\\n -- typechecker crashes. (Indirect self imports are not caught until\\n -- GHC.IfaceToCore, see #10337 tracking how to make this error better.)\\n --\\n -- Originally, we also allowed \'import {-# SOURCE #-} M\', but this\\n -- caused bug #10182: in one-shot mode, we should never load an hs-boot\\n -- file for the module we are compiling into the EPS. In principle,\\n -- it should be possible to support this mode of use, but we would have to\\n -- extend Provenance to support a local definition in a qualified location.\\n -- For now, we don\'t support it, but see #10336\\n when (imp_mod_name == moduleName this_mod &&\\n (case pkg_qual of -- If we have import \\"\\" M, then we should\\n -- check that \\"\\" is \\"this\\" (which is magic)\\n -- or the name of this_mod\'s package. Yurgh!\\n -- c.f. GHC.findModule, and #9997\\n NoPkgQual -> True\\n ThisPkg uid -> uid == homeUnitId_ (hsc_dflags hsc_env)\\n OtherPkg _ -> False))\\n (addErr (TcRnSelfImport imp_mod_name))\\n\\n -- Check for a missing import list (Opt_WarnMissingImportList also\\n -- checks for T(..) items but that is done in checkDodgyImport below)\\n case imp_details of\\n Just (Exactly, _) -> return () -- Explicit import list\\n _ | generated -> return () -- Do not bleat for generated imports\\n | qual_only -> return ()\\n | otherwise -> addDiagnostic (TcRnNoExplicitImportList imp_mod_name)\\n\\n\\n mb_iface <- loadSrcInterface_maybe doc lookup_scope imp_mod_name want_boot pkg_qual\\n iface <- case mb_iface of\\n Succeeded iface -> return iface\\n Failed err -> failWithTc $\\n importDeclLoadFailure origin imp_mod_name want_boot err\\n\\n -- Compiler sanity check: if the import didn\'t say\\n -- {-# SOURCE #-} we should not get a hi-boot file\\n warnPprTrace ((want_boot == NotBoot) && (mi_boot iface == IsBoot)) \\"rnImportDecl\\" (ppr imp_mod_name) $ do\\n\\n -- Issue a user warning for a redundant {- SOURCE -} import\\n -- NB that we arrange to read all the ordinary imports before\\n -- any of the {- SOURCE -} imports.\\n --\\n -- in --make and GHCi, the compilation manager checks for this,\\n -- and indeed we shouldn\'t do it here because the existence of\\n -- the non-boot module depends on the compilation order, which\\n -- is not deterministic. The hs-boot test can show this up.\\n dflags <- getDynFlags\\n warnIf ((want_boot == IsBoot) && (mi_boot iface == NotBoot) && isOneShot (ghcMode dflags))\\n (TcRnRedundantSourceImport imp_mod_name)\\n when (mod_safe && not (safeImportsOn dflags)) $\\n addErr (TcRnSafeImportsDisabled imp_mod_name)\\n\\n let imp_mod = mi_module iface\\n qual_mod_name = fmap unLoc as_mod `orElse` imp_mod_name\\n imp_spec = ImpDeclSpec { is_mod = imp_mod, is_qual = qual_only,\\n is_dloc = locA loc, is_as = qual_mod_name,\\n is_pkg_qual = pkg_qual, is_isboot = want_boot,\\n is_level = convImportLevel import_level }\\n\\n let filter_imports = do\\n -- filter the imports according to the import declaration\\n (new_imp_details, imp_user_list, gbl_env)\\n <- filterImports hsc_env iface imp_spec imp_details\\n -- for certain error messages, we\\u2019d like to know what could be\\n -- imported here, if everything were imported\\n potential_gres <- (\\\\(_,_,x) -> x) <$> filterImports hsc_env iface imp_spec Nothing\\n return (new_imp_details, imp_user_list, gbl_env, potential_gres)\\n\\n (new_imp_details, imp_user_list, gbl_env, potential_gres) <-\\n case origin of\\n ImplicitEssentialsImport ->\\n -- The implicit GHC.Essentials import does not bring anything into scope.\\n -- See Note [Finding GHC.Essentials] in GHC.Builtin.\\n return (Nothing, ImpUserDependOnly, emptyGlobalRdrEnv, emptyGlobalRdrEnv)\\n UserWrittenImport -> filter_imports\\n ImplicitPreludeImport -> filter_imports\\n PluginImport -> filter_imports\\n\\n let is_hiding | Just (EverythingBut,_) <- imp_details = True\\n | otherwise = False\\n\\n -- should the import be safe?\\n mod_safe\' = mod_safe\\n || (not generated && safeDirectImpsReq dflags)\\n || (generated && safeImplicitImpsReq dflags)\\n\\n hsc_env <- getTopEnv\\n let home_unit = hsc_home_unit hsc_env\\n other_home_units = hsc_all_home_unit_ids hsc_env\\n\\n imported_by\\n | isDependOnlyImport imp_user_list\\n = ImportedBySystem\\n | otherwise\\n = ImportedByUser $ ImportedModsVal\\n { imv_name = is_as imp_spec\\n , imv_span = locA loc\\n , imv_is_safe = mod_safe\'\\n , imv_is_hiding = is_hiding\\n , imv_all_exports = potential_gres\\n , imv_qualified = qual_only\\n , imv_is_level = convImportLevel import_level\\n }\\n imports = calculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by\\n\\n -- Complain if we import a deprecated module\\n case fromIfaceWarnings (mi_warns iface) of\\n WarnAll txt -> addDiagnostic (TcRnDeprecatedModule imp_mod_name txt)\\n _ -> return ()\\n\\n let new_imp_decl = ImportDecl\\n { ideclExt = ideclExt decl\\n , ideclName = ideclName decl\\n , ideclPkgQual = pkg_qual\\n , ideclSource = ideclSource decl\\n , ideclSafe = mod_safe\'\\n , ideclQualified = ideclQualified decl\\n , ideclAs = ideclAs decl\\n , ideclImportList = new_imp_details\\n , ideclLevelSpec = ideclLevelSpec decl\\n }\\n\\n return (L loc new_imp_decl, ImpUserSpec imp_spec imp_user_list, gbl_env, imports)\\n\\n-- | The error message to emit when we failed to load an interface.\\nimportDeclLoadFailure :: ImportDeclOrigin -> ModuleName -> IsBootInterface\\n -> MissingInterfaceError -> TcRnMessage\\nimportDeclLoadFailure ImplicitEssentialsImport _ _ err\\n = TcRnInterfaceError $ CantFindEssentials err LookingForEssentialsModule\\nimportDeclLoadFailure _ mod_name want_boot err\\n = TcRnInterfaceError $ Can\'tFindInterface err $ LookingForModule mod_name want_boot\\n\\n-- | Rename raw package imports\\nrenameRawPkgQual :: UnitEnv -> ModuleName -> RawPkgQual -> PkgQual\\nrenameRawPkgQual unit_env mn = \\\\case\\n NoRawPkgQual -> NoPkgQual\\n RawPkgQual _ fs -> renamePkgQual unit_env mn $ Just fs\\n\\n-- | Rename raw package imports\\nrenamePkgQual :: UnitEnv -> ModuleName -> Maybe FastString -> PkgQual\\nrenamePkgQual unit_env mn mb_pkg = case mb_pkg of\\n Nothing -> NoPkgQual\\n Just pkg_fs\\n | Just uid <- homeUnitId <$> ue_homeUnit unit_env\\n , pkg_fs == fsLit \\"this\\"\\n -> ThisPkg uid\\n\\n | Just (uid, _) <- find (fromMaybe False . fmap (== pkg_fs) . snd) home_names\\n -> ThisPkg uid\\n\\n | Just uid <- resolvePackageImport unit_state mn (PackageName pkg_fs)\\n -> OtherPkg uid\\n\\n | otherwise\\n -> OtherPkg (UnitId pkg_fs)\\n -- not really correct as pkg_fs is unlikely to be a valid unit-id but\\n -- we will report the failure later...\\n where\\n home_names =\\n [ (uid, mkFastString <$> thisPackageName (homeUnitEnv_dflags (ue_findHomeUnitEnv uid unit_env)))\\n | uid <- S.toList hpt_deps\\n ]\\n\\n unit_state = ue_homeUnitState unit_env\\n\\n hpt_deps :: S.Set UnitId\\n hpt_deps = homeUnitDepends unit_state\\n\\n\\n-- | Calculate the \'ImportAvails\' induced by an import of a particular\\n-- interface, but without \'imp_mods\'.\\ncalculateAvails :: HomeUnit\\n -> S.Set UnitId\\n -> ModIface\\n -> IsSafeImport\\n -> IsBootInterface\\n -> ImportedBy\\n -> ImportAvails\\ncalculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by =\\n let imp_mod = mi_module iface\\n imp_sem_mod= mi_semantic_module iface\\n orph_iface = mi_orphan iface\\n has_finsts = mi_finsts iface\\n deps = mi_deps iface\\n trust = getSafeMode $ mi_trust iface\\n trust_pkg = mi_trust_pkg iface\\n is_sig = mi_hsc_src iface == HsigFile\\n\\n -- If the module exports anything defined in this module, just\\n -- ignore it. Reason: otherwise it looks as if there are two\\n -- local definition sites for the thing, and an error gets\\n -- reported. Easiest thing is just to filter them out up\\n -- front. This situation only arises if a module imports\\n -- itself, or another module that imported it. (Necessarily,\\n -- this involves a loop.)\\n --\\n -- We do this *after* filterImports, so that if you say\\n -- module A where\\n -- import B( AType )\\n -- type AType = ...\\n --\\n -- module B( AType ) where\\n -- import {-# SOURCE #-} A( AType )\\n --\\n -- then you won\'t get a \'B does not export AType\' message.\\n\\n\\n -- Compute new transitive dependencies\\n --\\n -- \'dep_orphs\' and \'dep_finsts\' do NOT include the imported module\\n -- itself, but we DO need to include this module in \'imp_orphs\' and\\n -- \'imp_finsts\' if it defines an orphan or instance family; thus the\\n -- orph_iface/has_iface tests.\\n\\n deporphs = dep_orphs deps\\n depfinsts = dep_finsts deps\\n\\n orphans | orph_iface = assertPpr (not (imp_sem_mod `elem` deporphs)) (ppr imp_sem_mod <+> ppr deporphs) $\\n imp_sem_mod : deporphs\\n | otherwise = deporphs\\n\\n finsts | has_finsts = assertPpr (not (imp_sem_mod `elem` depfinsts)) (ppr imp_sem_mod <+> ppr depfinsts) $\\n imp_sem_mod : depfinsts\\n | otherwise = depfinsts\\n\\n -- Trusted packages are a lot like orphans.\\n trusted_pkgs | mod_safe\' = dep_trusted_pkgs deps\\n | otherwise = S.empty\\n\\n\\n pkg = moduleUnit (mi_module iface)\\n ipkg = toUnitId pkg\\n\\n -- Does this import mean we now require our own pkg\\n -- to be trusted? See Note [Trust Own Package]\\n ptrust = trust == Sf_Trustworthy || trust_pkg\\n pkg_trust_req\\n | isHomeUnit home_unit pkg = ptrust\\n | otherwise = False\\n\\n dependent_pkgs = if toUnitId pkg `S.member` other_home_units\\n then S.empty\\n else S.singleton (lvl, ipkg)\\n\\n lvl = case imported_by of\\n ImportedByUser imv -> imv_is_level imv\\n ImportedBySystem -> NormalLevel\\n\\n\\n direct_mods = if toUnitId pkg `S.member` other_home_units\\n then mkPlusModDeps (moduleUnitId imp_mod) lvl (GWIB (moduleName imp_mod) want_boot)\\n else emptyInstalledModuleEnv\\n\\n dep_boot_mods_map = mkModDeps (dep_boot_mods deps)\\n\\n\\n boot_mods\\n -- If we are looking for a boot module, it must be HPT\\n | IsBoot <- want_boot = extendInstalledModuleEnv dep_boot_mods_map (toUnitId <$> imp_mod) (GWIB (moduleName imp_mod) IsBoot)\\n -- Now we are importing A properly, so don\'t go looking for\\n -- A.hs-boot\\n | isHomeUnit home_unit pkg = dep_boot_mods_map\\n -- There\'s no boot files to find in external imports\\n | otherwise = emptyInstalledModuleEnv\\n\\n sig_mods =\\n if is_sig\\n then moduleName imp_mod : dep_sig_mods deps\\n else dep_sig_mods deps\\n\\n\\n in ImportAvails {\\n imp_mods = Map.singleton (mi_module iface) [imported_by],\\n imp_orphs = orphans,\\n imp_finsts = finsts,\\n imp_sig_mods = sig_mods,\\n imp_direct_dep_mods = direct_mods,\\n imp_dep_direct_pkgs = dependent_pkgs,\\n imp_boot_mods = boot_mods,\\n\\n -- Add in the imported modules trusted package\\n -- requirements. ONLY do this though if we import the\\n -- module as a safe import.\\n -- See Note [Tracking Trust Transitively]\\n -- and Note [Trust Transitive Property]\\n imp_trust_pkgs = trusted_pkgs,\\n -- Do we require our own pkg to be trusted?\\n -- See Note [Trust Own Package]\\n imp_trust_own_pkg = pkg_trust_req\\n }\\n\\nmkPlusModDeps :: UnitId -> ImportLevel -> ModuleNameWithIsBoot\\n -> InstalledModuleEnv (S.Set ImportLevel, ModuleNameWithIsBoot)\\nmkPlusModDeps uid st elt = extendInstalledModuleEnv emptyInstalledModuleEnv (mkModule uid (gwib_mod elt)) (S.singleton st, elt)\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{importsFromLocalDecls}\\n* *\\n************************************************************************\\n\\nFrom the top-level declarations of this module produce\\n * the lexical environment\\n * the ImportAvails\\ncreated by its bindings.\\n\\nNote [Top-level Names in Template Haskell decl quotes]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSee also: Note [Interactively-bound Ids in GHCi] in GHC.Driver.Env\\n Note [Looking up Exact RdrNames] in GHC.Rename.Env\\n\\nConsider a Template Haskell declaration quotation like this:\\n module M where\\n f x = h [d| f = 3 |]\\nWhen renaming the declarations inside [d| ...|], we treat the\\ntop level binders specially in two ways\\n\\n1. We give them an Internal Name, not (as usual) an External one.\\n This is done by GHC.Rename.Env.newTopSrcBinder.\\n\\n2. We make them *shadow* the outer bindings.\\n See Note [GlobalRdrEnv shadowing]\\n\\n3. We find out whether we are inside a [d| ... |] by testing the TH\\n level. This is a slight hack, because the level field was really\\n meant for the type checker, and here we are not interested in the\\n fields of Brack, hence the error thunks in thRnBrack.\\n-}\\n\\nextendGlobalRdrEnvRn :: [GlobalRdrElt]\\n -> MiniFixityEnv\\n -> RnM (TcGblEnv, TcLclEnv)\\n-- Updates both the GlobalRdrEnv and the FixityEnv\\n-- We return a new TcLclEnv only because we might have to\\n-- delete some bindings from it;\\n-- see Note [Top-level Names in Template Haskell decl quotes]\\n\\nextendGlobalRdrEnvRn new_gres new_fixities\\n = checkNoErrs $ -- See Note [Fail fast on duplicate definitions]\\n do { (gbl_env, lcl_env) <- getEnvs\\n ; level <- getThLevel\\n ; isGHCi <- getIsGHCi\\n ; let rdr_env = tcg_rdr_env gbl_env\\n fix_env = tcg_fix_env gbl_env\\n th_bndrs = getLclEnvThBndrs lcl_env\\n th_lvl = thLevelIndex level\\n\\n -- Delete new_occs from global and local envs\\n -- If we are in a TemplateHaskell decl bracket,\\n -- we are going to shadow them\\n -- See Note [GlobalRdrEnv shadowing]\\n inBracket = isBrackLevel level\\n\\n lcl_env_TH = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_rdr = minusLocalRdrEnv (tcl_rdr lcl_env) new_gres_env }) lcl_env\\n -- See Note [GlobalRdrEnv shadowing]\\n\\n lcl_env2 | inBracket = lcl_env_TH\\n | otherwise = lcl_env\\n\\n -- Deal with shadowing: see Note [GlobalRdrEnv shadowing]\\n want_shadowing = isGHCi || inBracket\\n rdr_env1 | want_shadowing = shadowNames False rdr_env new_gres_env\\n | otherwise = rdr_env\\n\\n lcl_env3 = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_th_bndrs = extendNameEnvList th_bndrs\\n [ ( n, (TopLevel, th_lvl) )\\n | n <- new_names ] }) lcl_env2\\n\\n ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres\\n\\n ; let fix_env\' = foldl\' extend_fix_env fix_env new_gres\\n gbl_env\' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env\' }\\n\\n ; traceRn \\"extendGlobalRdrEnvRn 2\\" (pprGlobalRdrEnv True rdr_env2)\\n ; return (gbl_env\', lcl_env3) }\\n where\\n new_names = map greName new_gres\\n new_gres_env = mkGlobalRdrEnv new_gres\\n\\n -- If there is a fixity decl for the gre, add it to the fixity env\\n extend_fix_env fix_env gre\\n | Just (L _ fi) <- lookupMiniFixityEnv new_fixities name\\n = extendNameEnv fix_env name (FixItem occ fi)\\n | otherwise\\n = fix_env\\n where\\n name = greName gre\\n occ = greOccName gre\\n\\n add_gre :: GlobalRdrEnv -> GlobalRdrElt -> RnM GlobalRdrEnv\\n -- Extend the GlobalRdrEnv with a LocalDef GRE\\n -- If there is already a LocalDef GRE with the same OccName,\\n -- report an error and discard the new GRE\\n -- This establishes INVARIANT 1 of GlobalRdrEnvs\\n add_gre env gre\\n | not (null dups) -- Same OccName defined twice\\n = do { addDupDeclErr (gre :| dups); return env }\\n\\n | otherwise\\n = return (extendGlobalRdrEnv env gre)\\n where\\n -- See Note [Reporting duplicate local declarations]\\n dups = filter isBadDupGRE\\n $ lookupGRE env (LookupOccName (greOccName gre) (RelevantGREsFOS WantBoth))\\n isBadDupGRE old_gre = isLocalGRE old_gre && greClashesWith gre old_gre\\n\\n{- Note [Fail fast on duplicate definitions]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIf there are duplicate bindings for the same thing, we want to fail\\nfast. Having two bindings for the same thing can cause follow-on errors.\\nExample (test T9975a):\\n data Test = Test { x :: Int }\\n pattern Test wat = Test { x = wat }\\nThis defines \'Test\' twice. The second defn has no field-names; and then\\nwe get an error from Test { x=wat }, saying \\"Test has no field \'x\'\\".\\n\\nEasiest thing is to bale out fast on duplicate definitions, which\\nwe do via `checkNoErrs` on `extendGlobalRdrEnvRn`.\\n\\nNote [Reporting duplicate local declarations]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn general, a single module may not define the same OccName multiple times. This\\nis checked in extendGlobalRdrEnvRn: when adding a new locally-defined GRE to the\\nGlobalRdrEnv we report an error if there are already duplicates in the\\nenvironment. This establishes INVARIANT 1 (see comments on GlobalRdrEnv in\\nGHC.Types.Name.Reader), which says that for a given OccName, all the\\nGlobalRdrElts to which it maps must have distinct \'greName\'s.\\n\\nFor example, the following will be rejected:\\n\\n f x = x\\n g x = x\\n f x = x -- Duplicate!\\n\\nUsers are allowed to introduce new GREs with the same OccName as an imported GRE,\\nas disambiguation is possible through the module system, e.g.:\\n\\n module M where\\n import N (f)\\n f x = x\\n g x = M.f x + N.f x\\n\\nIf both GREs are local, the general rule is that two GREs clash if they have\\nthe same OccName, i.e. they share a textual name and live in the same namespace.\\nHowever, there are additional clashes due to record fields:\\n\\n - a new variable clashes with previously defined record fields\\n which define field selectors,\\n\\n - a new record field shadows:\\n\\n - previously defined variables, if it defines a field selector,\\n - previously defined record fields, unless it is a duplicate record field.\\n\\nThis logic is implemented in the function \'GHC.Types.Name.Reader.greClashesWith\'.\\n\\nSee also Note [Skipping ambiguity errors at use sites of local declarations] in\\nGHC.Rename.Utils.\\n-}\\n\\n\\n{- *********************************************************************\\n* *\\n getLocalDeclBindersd@ returns the names for an HsDecl\\n It\'s used for source code.\\n\\n *** See Note [The Naming story] in GHC.Hs.Decls ****\\n* *\\n********************************************************************* -}\\n\\ngetLocalNonValBinders :: MiniFixityEnv -> HsGroup GhcPs\\n -> RnM ((TcGblEnv, TcLclEnv), NameSet)\\n-- Get all the top-level binders bound the group *except*\\n-- for value bindings, which are treated separately\\n-- Specifically we return AvailInfo for\\n-- * type decls (incl constructors and record selectors)\\n-- * class decls (including class ops)\\n-- * associated types\\n-- * foreign imports\\n-- * value signatures (in hs-boot files only)\\n\\ngetLocalNonValBinders fixity_env\\n (HsGroup { hs_valds = binds,\\n hs_tyclds = tycl_decls,\\n hs_fords = foreign_decls })\\n = do { -- Process all type/class decls *except* family instances\\n ; let inst_decls = tycl_decls >>= group_instds\\n ; dup_fields_ok <- xopt_DuplicateRecordFields <$> getDynFlags\\n ; has_sel <- xopt_FieldSelectors <$> getDynFlags\\n ; tc_gres\\n <- concatMapM\\n (new_tc dup_fields_ok has_sel)\\n (tyClGroupTyClDecls tycl_decls)\\n ; traceRn \\"getLocalNonValBinders 1\\" (ppr tc_gres)\\n ; envs <- extendGlobalRdrEnvRn tc_gres fixity_env\\n ; restoreEnvs envs $ do {\\n -- Bring these things into scope first\\n -- See Note [Looking up family names in family instances]\\n\\n -- Process all family instances\\n -- to bring new data constructors into scope\\n ; nti_gress <- mapM (new_assoc dup_fields_ok has_sel) inst_decls\\n\\n -- Finish off with value binders:\\n -- foreign decls and pattern synonyms for an ordinary module\\n -- type sigs in case of a hs-boot file only\\n ; is_boot <- tcIsHsBootOrSig\\n ; let val_bndrs\\n | is_boot = case binds of\\n ValBinds _ val_binds ->\\n -- In a hs-boot file, the value binders come from the\\n -- *signatures*, and there should be no foreign binders\\n [ L (l2l decl_loc) (unLoc n)\\n | L decl_loc (TypeSig _ _ ns _) <- (val_sigs val_binds), n <- ns]\\n _ -> panic \\"Non-ValBinds in hs-boot group\\"\\n | otherwise = for_hs_bndrs\\n ; val_gres <- mapM new_simple val_bndrs\\n\\n ; let avails = concat nti_gress ++ val_gres\\n new_bndrs = gresToNameSet avails `unionNameSet`\\n gresToNameSet tc_gres\\n ; traceRn \\"getLocalNonValBinders 2\\" (ppr avails)\\n ; envs <- extendGlobalRdrEnvRn avails fixity_env\\n ; return (envs, new_bndrs) } }\\n where\\n for_hs_bndrs :: [LocatedN RdrName]\\n for_hs_bndrs = hsForeignDeclsBinders foreign_decls\\n\\n -- the SrcSpan attached to the input should be the span of the\\n -- declaration, not just the name\\n new_simple :: LocatedN RdrName -> RnM GlobalRdrElt\\n new_simple rdr_name = do { nm <- newTopSrcBinder rdr_name\\n ; return (mkLocalVanillaGRE NoParent nm) }\\n\\n new_tc :: DuplicateRecordFields -> FieldSelectors -> LTyClDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_tc dup_fields_ok has_sel tc_decl -- NOT for type/data instances\\n = do { let TyDeclBinders (main_bndr, tc_flav) at_bndrs sig_bndrs\\n (LConsWithFields cons_with_flds flds) = hsLTyClDeclBinders tc_decl\\n ; tycon_name <- newTopSrcBinder $ la2la main_bndr\\n ; at_names <- mapM (newTopSrcBinder . la2la . fst) at_bndrs\\n ; sig_names <- mapM (newTopSrcBinder . la2la) sig_bndrs\\n ; con_names_with_flds <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst con_names_with_flds) flds\\n ; mapM_ (add_dup_fld_errs flds\') con_names_with_flds\\n ; let tc_gre = mkLocalTyConGRE (fmap (const tycon_name) tc_flav) tycon_name\\n fld_env = mk_fld_env con_names_with_flds flds\'\\n at_gres = zipWith (\\\\ (_, at_flav) at_nm -> mkLocalTyConGRE (fmap (const tycon_name) at_flav) at_nm)\\n at_bndrs at_names\\n sig_gres = map (mkLocalVanillaGRE (ParentIs tycon_name)) sig_names\\n con_gres = map (mkLocalConLikeGRE (ParentIs tycon_name)) fld_env\\n fld_gres = mkLocalFieldGREs (ParentIs tycon_name) fld_env\\n sub_gres = at_gres ++ sig_gres ++ con_gres ++ fld_gres\\n ; traceRn \\"getLocalNonValBinders new_tc\\" $\\n vcat [ text \\"tycon:\\" <+> ppr tycon_name\\n , text \\"tc_gre:\\" <+> ppr tc_gre\\n , text \\"sub_gres:\\" <+> ppr sub_gres ]\\n ; return $ tc_gre : sub_gres }\\n\\n -- Calculate the record field information, which feeds into the GlobalRdrElts\\n -- for DataCons and their fields. It\'s convenient to do this here where\\n -- we are working with a single datatype definition.\\n --\\n -- The information we needed was all set up for us:\\n -- see Note [Collecting record fields in data declarations] in GHC.Hs.Utils.\\n mk_fld_env :: [(Name, Either VisArity [Located Int])] -> IntMap FieldLabel\\n -> [(ConLikeName, ConInfo)]\\n mk_fld_env names flds =\\n [ (DataConName con, ConInfo (ConIsData (map fst names)) fld_info)\\n | (con, con_fl_indxs) <- names\\n , let fld_info = case fmap (map ((flds IntMap.!) . unLoc)) con_fl_indxs of\\n Left 0 -> ConIsNullary\\n Left arity -> ConHasPositionalArgs arity\\n Right [] -> ConIsNullary\\n Right (fld:flds) -> ConHasRecordFields $ fld NE.:| flds ]\\n\\n new_assoc :: DuplicateRecordFields -> FieldSelectors -> LInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_assoc _ _ (L _ (TyFamInstD {})) = return []\\n -- type instances don\'t bind new names\\n\\n new_assoc dup_fields_ok has_sel (L _ (DataFamInstD _ d))\\n = new_di dup_fields_ok has_sel Nothing d\\n new_assoc dup_fields_ok has_sel\\n (L _ (ClsInstD _ (ClsInstDecl { cid_poly_ty = inst_ty\\n , cid_decls = decls })))\\n = do -- First, attempt to grab the name of the class from the instance.\\n -- This step could fail if the instance is not headed by a class,\\n -- such as in the following examples:\\n --\\n -- (1) The class is headed by a bang pattern, such as in\\n -- `instance !Show Int` (#3811c)\\n -- (2) The class is headed by a type variable, such as in\\n -- `instance c` (#16385)\\n --\\n -- If looking up the class name fails, then mb_cls_gre will\\n -- be Nothing.\\n mb_cls_gre <- runMaybeT $ do\\n -- See (1) above\\n L loc cls_rdr <- MaybeT $ pure $ getLHsInstDeclClass_maybe inst_ty\\n -- See (2) above\\n MaybeT $ setSrcSpan (locA loc) $ lookupGlobalOccRn_maybe SameNameSpace cls_rdr\\n -- Assuming the previous step succeeded, process any associated data\\n -- family instances. If the previous step failed, bail out.\\n case mb_cls_gre of\\n Nothing\\n -> pure []\\n Just cls_gre\\n -> let cls_nm = greName cls_gre\\n in concatMapM (new_di dup_fields_ok has_sel (Just cls_nm) . unLoc) (data_fam_insts decls)\\n\\n data_fam_insts decls = concatMap get decls\\n where\\n get (L l (InstD _ (DataFamInstD { dfid_inst = d}))) = [L l d]\\n get _ = []\\n\\n new_di :: DuplicateRecordFields -> FieldSelectors\\n -> Maybe Name -- class name\\n -> DataFamInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_di dup_fields_ok has_sel mb_cls dfid@(DataFamInstDecl { dfid_eqn = ti_decl })\\n = do { main_name <- unLoc <$> lookupFamInstName mb_cls (feqn_tycon ti_decl)\\n ; let LConsWithFields cons_with_flds flds = hsDataFamInstBinders dfid\\n ; sub_names <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst sub_names) flds\\n ; mapM_ (add_dup_fld_errs flds\') sub_names\\n ; let fld_env = mk_fld_env sub_names flds\'\\n con_gres = map (mkLocalConLikeGRE (ParentIs main_name)) fld_env\\n field_gres = mkLocalFieldGREs (ParentIs main_name) fld_env\\n -- NB: the data family name is not bound here,\\n -- so we don\'t return a GlobalRdrElt for it here!\\n ; return $ con_gres ++ field_gres }\\n\\n -- Add errors if a constructor has a duplicate record field.\\n add_dup_fld_errs :: IntMap FieldLabel\\n -> (Name, Either VisArity [Located Int])\\n -> IOEnv (Env TcGblEnv TcLclEnv) ()\\n add_dup_fld_errs all_flds (con, con_flds_or_arity)\\n | Right con_flds <- con_flds_or_arity\\n , let (_, dups) = removeDups (comparing unLoc) con_flds\\n = for_ dups $ \\\\ dup_flds ->\\n -- Report the error at the location of the second occurrence\\n -- of the duplicate field.\\n let loc =\\n case dup_flds of\\n _ :| ( L loc _ : _) -> loc\\n L loc _ :| _ -> loc\\n dup_rdrs = fmap (nameRdrName . flSelector . (all_flds IntMap.!) . unLoc) dup_flds\\n in addErrAt loc $ TcRnDuplicateFieldName (RecordFieldDecl con) dup_rdrs\\n | otherwise\\n = return ()\\n\\nnewRecordFieldLabel :: DuplicateRecordFields -> FieldSelectors -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel\\nnewRecordFieldLabel _ _ [] _ = error \\"newRecordFieldLabel: datatype has no constructors!\\"\\nnewRecordFieldLabel dup_fields_ok has_sel (dc:_) (L loc (FieldOcc _ (L _ fld)))\\n = do { selName <- newTopSrcBinder $ L (l2l loc) $ field\\n ; return $ FieldLabel { flHasDuplicateRecordFields = dup_fields_ok\\n , flHasFieldSelector = has_sel\\n , flSelector = selName } }\\n where\\n fld_occ = rdrNameOcc fld\\n dc_fs = occNameFS $ nameOccName dc\\n field\\n -- Use an Exact RdrName as-is, to preserve the bindings\\n -- of an already renamer-resolved field and its use\\n -- sites. This is needed to correctly support record\\n -- selectors in Template Haskell. See Note [Binders in\\n -- Template Haskell] in \\"GHC.ThToHs\\" and Note [Looking up\\n -- Exact RdrNames] in \\"GHC.Rename.Env\\".\\n | isExact fld\\n = assertPpr (fieldOcc_maybe fld_occ == Just dc_fs)\\n (vcat [ text \\"newRecordFieldLabel: incorrect namespace for exact Name\\" <+> quotes (ppr fld)\\n , text \\"expected namespace:\\" <+> pprNameSpace (fieldName dc_fs)\\n , text \\" actual namespace:\\" <+> pprNameSpace (occNameSpace fld_occ) ])\\n fld\\n\\n -- Field names produced by the parser are namespaced with VarName.\\n -- Here we namespace them according to the first constructor.\\n -- See Note [Record field namespacing] in GHC.Types.Name.Occurrence.\\n | otherwise\\n = mkRdrUnqual $ varToRecFieldOcc dc_fs fld_occ\\n\\n{-\\nNote [Looking up family names in family instances]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider\\n\\n module M where\\n type family T a :: *\\n type instance M.T Int = Bool\\n\\nWe might think that we can simply use \'lookupOccRn\' when processing the type\\ninstance to look up \'M.T\'. Alas, we can\'t! The type family declaration is in\\nthe *same* HsGroup as the type instance declaration. Hence, as we are\\ncurrently collecting the binders declared in that HsGroup, these binders will\\nnot have been added to the global environment yet.\\n\\nSolution is simple: process the type family declarations first, extend\\nthe environment, and then process the type instances.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Filtering imports}\\n* *\\n************************************************************************\\n\\n@filterImports@ takes the @ExportEnv@ telling what the imported module makes\\navailable, and filters it through the import spec (if any).\\n\\nNote [Dealing with imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nFor import M( ies ), we take each AvailInfo from the mi_exports of M, and make\\n\\n imp_occ_env :: OccEnv (NameEnv ImpOccItem)\\n\\nThis map contains one entry for each OccName that M exports, mapping each OccName\\nto the following information:\\n\\n 1. the GlobalRdrElt corresponding to the OccName,\\n 2. whether this GlobalRdrElt was the parent in the AvailInfo we found\\n the OccName in.\\n 3. the GlobalRdrElts that were bundled together in the AvailInfo we found\\n this OccName in (not including the parent),\\n\\nWe need (2) and (3) during the construction of the OccEnv because of associated\\ntypes and bundled pattern synonyms, respectively.\\n(3) is explained in Note [Importing PatternSynonyms].\\n\\nTo explain (2), consider for example:\\n\\n module M where\\n class C a where { data T a }\\n instance C Int where { data T Int = T1 | T2 }\\n instance C Bool where { data T Int = T3 }\\n\\nHere, M\'s exports avails are (recalling the AvailTC invariant from GHC.Types.Avail)\\n\\n C(C,T), T(T,T1,T2,T3)\\n\\nNotice that T appears *twice*, once as a child and once as a parent. From\\nthese two exports, respectively, during construction of the imp_occ_env, we begin\\nby associating the following two elements with the key T:\\n\\n T -> ImpOccItem { imp_item = gre1, imp_bundled = [C,T] , imp_is_parent = False }\\n T -> ImpOccItem { imp_item = gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nwhere `gre1`, `gre2` are two GlobalRdrElts with greName T.\\nWe combine these (in function \'combine\' in \'mkImportOccEnv\') by discarding the\\nnon-parent item, thusly:\\n\\n T -> IE_ITem { imp_item = gre1 `plusGRE` gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nNote the `plusGRE`: this ensures we don\'t drop parent information;\\nsee Note [Preserve parent information when combining import OccEnvs].\\n\\nSo the overall imp_occ_env is:\\n\\n C -> ImpOccItem { imp_item = C, imp_bundled = [T ], imp_is_parent = True }\\n T -> ImpOccItem { imp_item = T , imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n T1 -> ImpOccItem { imp_item = T1, imp_bundled = [T1,T2,T3], imp_is_parent = False }\\n -- similarly for T2, T3\\n\\nNote that the imp_occ_env will have entries for data constructors too,\\nalthough we never look up data constructors.\\n\\nNote [Importing PatternSynonyms]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nAs described in Note [Dealing with imports], associated types can lead to the\\nsame Name appearing twice, both as a child and once as a parent, when\\nconstructing the imp_occ_env. The same thing can happen with pattern synonyms\\nif they are exported bundled with a type.\\n\\nA simplified example, based on #11959:\\n\\n {-# LANGUAGE PatternSynonyms #-}\\n module M (T(P), pattern P) where -- Duplicate export warning, but allowed\\n data T = MkT\\n pattern P = MkT\\n\\nHere we have T(P) and P in export_avails, and respectively construct both\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n P -> ImpOccItem { imp_item = P, imp_bundled = [] , imp_is_parent = False }\\n\\nWe combine these by dropping the one with no siblings, leaving us with:\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n\\nThat is, we simply discard the non-bundled Avail.\\n\\nNote [Importing DuplicateRecordFields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn filterImports, another complicating factor is DuplicateRecordFields.\\nSuppose we have:\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (S(foo), T(foo)) where\\n data S = MkS { foo :: Int }\\n data T = MkT { foo :: Int }\\n\\n module N where\\n import M (foo) -- this is allowed (A)\\n import M (S(foo)) -- this is allowed (B)\\n\\nHere M exports \'foo\' at two different OccNames, with different namespaces for\\nthe two construtors MkS and MkT. Then, when we look up \'foo\' in lookup_names\\nfor case (A), we have a variable foo but must look in all the record field\\nnamespaces to find the two fields (and hence two different Avails).\\nWhereas in case (B) we reach the lookup_ie case for IEThingWith,\\nwhich looks up \'S\' and then finds the unique \'foo\' amongst its children.\\n\\nSee T16745 for a test of this.\\n\\nNote [Preserve parent information when combining import OccEnvs]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen discarding one ImpOccItem in favour of another, as described in\\nNote [Dealing with imports], we must make sure to combine the GREs so that\\nwe don\'t lose information.\\n\\nConsider for example #24084:\\n\\n module M1 where { class C a where { type T a } }\\n module M2 ( module M1 ) where { import M1 }\\n module M3 where { import M2 ( C, T ); instance C () where T () = () }\\n\\nWhen processing the import list of `M3`, we will have two `Avail`s attached\\nto `T`, namely `C(C, T)` and `T(T)`. We combine them in the `combine` function\\nof `mkImportOccEnv`; as described in Note [Dealing with imports] we discard\\n`C(C, T)` in favour of `T(T)`. However, in doing so, we **must not**\\ndiscard the information want that `C` is the parent of `T`. Indeed,\\nlosing track of this information can cause errors when importing,\\nas we could get an error of the form\\n\\n \\u2018T\\u2019 is not a (visible) associated type of class \\u2018C\\u2019\\n\\nThis explains why we use `plusGRE` when combining the two ImpOccItems, even\\nthough we are discarding one in favour of the other.\\n-}\\n\\n-- | All the \'GlobalRdrElt\'s associated with an \'AvailInfo\'.\\ngresFromAvail :: HasDebugCallStack\\n => HscEnv -> Maybe ImportSpec -> AvailInfo -> [GlobalRdrElt]\\ngresFromAvail hsc_env prov avail =\\n [ mk_gre nm info\\n | nm <- availNames avail\\n , let info = lookupGREInfo hsc_env nm ]\\n where\\n\\n mk_gre n info\\n = case prov of\\n -- Nothing => bound locally\\n -- Just is => imported from \'is\'\\n Nothing -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = True, gre_imp = emptyBag\\n , gre_info = info }\\n Just is -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = False, gre_imp = unitBag is\\n , gre_info = info }\\n\\n-- | All the \'GlobalRdrElt\'s associated with a collection of \'AvailInfo\'s.\\ngresFromAvails :: HscEnv -> Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]\\ngresFromAvails hsc_env prov = concatMap (gresFromAvail hsc_env prov)\\n\\nimportsFromIface :: HscEnv -> ModIface -> ImpDeclSpec -> Maybe NameSet -> GlobalRdrEnv\\nimportsFromIface hsc_env iface decl_spec hidden = mkGlobalRdrEnv $ case hidden of\\n Nothing -> all_gres\\n Just hidden_names -> filter (not . (`elemNameSet` hidden_names) . greName) all_gres\\n where\\n all_gres = gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\nrnNamespaceSpecifier :: NamespaceSpecifier GhcPs -> NamespaceSpecifier GhcRn\\nrnNamespaceSpecifier (NoNamespaceSpecifier _) = NoNamespaceSpecifier noExtField\\nrnNamespaceSpecifier (TypeNamespaceSpecifier x) = TypeNamespaceSpecifier x\\nrnNamespaceSpecifier (DataNamespaceSpecifier x) = DataNamespaceSpecifier x\\n\\nfilterImports\\n :: HasDebugCallStack\\n => HscEnv\\n -> ModIface\\n -> ImpDeclSpec\\n -- ^ Import spec\\n -> Maybe (ImportListInterpretation, [LIE GhcPs])\\n -- ^ Whether this is a \\"hiding\\" import list\\n -> RnM (Maybe (ImportListInterpretation, [LIE GhcRn]), -- Import spec w/ Names\\n ImpUserList, -- same, but designed for storage in interfaces\\n GlobalRdrEnv) -- Same again, but in GRE form\\nfilterImports hsc_env iface decl_spec Nothing\\n = return (Nothing, ImpUserAll, importsFromIface hsc_env iface decl_spec Nothing)\\nfilterImports hsc_env iface decl_spec (Just (want_hiding, import_items))\\n = do -- check for errors, convert RdrNames to Names\\n items1 <- mapM lookup_lie import_items\\n\\n let items2 :: [(LIE GhcRn, [GlobalRdrElt])]\\n items2 = concat items1\\n -- NB we may have duplicates, and several items\\n -- for the same parent; e.g N(x) and N(y)\\n\\n (gres, imp_user_list) = case want_hiding of\\n Exactly ->\\n let gres = concatMap (gresFromIE decl_spec) items2\\n gre_env = mkGlobalRdrEnv gres\\n implicit_parents = mkNameSet $ mapMaybe parentOfImplicitlyImportedGRE gres\\n in (gre_env, ImpUserExplicit (gresToAvailInfo $ globalRdrEnvElts $ gre_env) implicit_parents)\\n EverythingBut ->\\n let hidden_names = mkNameSet $ concatMap (map greName . snd) items2\\n in (importsFromIface hsc_env iface decl_spec (Just hidden_names), ImpUserEverythingBut hidden_names)\\n\\n return (Just (want_hiding, map fst items2), imp_user_list, gres)\\n where\\n import_mod = mi_module iface\\n all_avails = mi_exports iface\\n imp_occ_env = mkImportOccEnv hsc_env decl_spec all_avails\\n\\n -- Look up a parent (type constructor, class or data constructor)\\n -- in an import.\\n lookup_parent :: IE GhcPs -> RdrName -> IELookupM ImpOccItem\\n lookup_parent ie rdr =\\n assertPpr (not $ isVarNameSpace ns)\\n (vcat [ text \\"filterImports lookup_parent: unexpected variable\\"\\n , text \\"rdr:\\" <+> ppr rdr\\n , text \\"namespace:\\" <+> pprNameSpace ns ]) $\\n do { xs <- lookup_names ie rdr\\n ; case xs of\\n cax :| [] -> return cax\\n _ -> pprPanic \\"filter_imports lookup_parent ambiguous\\" $\\n vcat [ text \\"rdr:\\" <+> ppr rdr\\n , text \\"lookups:\\" <+> ppr (fmap imp_item xs) ] }\\n -- Looking up non-variables is always unambiguous,\\n -- as there can be at most one corresponding item\\n -- in the imp_occ_env.\\n -- See item (1) of Note [Exporting duplicate declarations]\\n -- in GHC.Tc.Gen.Export.\\n where\\n occ = rdrNameOcc rdr\\n ns = occNameSpace occ\\n\\n -- Look up a RdrName used in an import, returning multiple values if there\\n -- are several fields with the same name exposed by the module\\n lookup_names :: IE GhcPs -> RdrName -> IELookupM (NonEmpty ImpOccItem)\\n lookup_names ie rdr\\n | isQual rdr\\n = failLookupWith (QualImportError rdr)\\n | otherwise\\n = case lookups of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n item:items -> return $ item :| items\\n where\\n lookups = concatMap nonDetNameEnvElts\\n $ lookupImpOccEnv (RelevantGREsFOS WantNormal) imp_occ_env (rdrNameOcc rdr)\\n\\n lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, [GlobalRdrElt])]\\n lookup_lie (L loc ieRdr)\\n = setSrcSpanA loc $\\n do (stuff, warns) <- run_lookup ([],[]) (lookup_ie ieRdr)\\n mapM_ (addTcRnDiagnostic <=< warning_msg) warns\\n return [ (L loc ie, gres) | (ie,gres) <- stuff ]\\n where\\n\\n -- Warn when importing T(..) and no children are brought in scope\\n warning_msg (DodgyImport reason) =\\n pure (TcRnDodgyImports reason)\\n warning_msg MissingImportList =\\n pure (TcRnMissingImportList ieRdr)\\n warning_msg (BadImportW ie sub) = do\\n -- \'BadImportW\' is only constructed below in \'bad_import_w\', in\\n -- the \'EverythingBut\' case, so here we assume a \'hiding\' clause.\\n (reason :| _) <- badImportItemErr iface decl_spec ie sub all_avails\\n pure (TcRnDodgyImports (DodgyImportsHiding reason))\\n warning_msg (DeprecatedExport n w) =\\n pure $ TcRnPragmaWarning\\n PragmaWarningExport\\n { pwarn_occname = occName n\\n , pwarn_impmod = moduleName import_mod }\\n w\\n\\n run_lookup :: a -> IELookupM a -> TcRn a\\n run_lookup def m = case m of\\n Failed err -> do\\n msgs <- lookup_err_msgs err\\n forM_ msgs $ \\\\msg -> addErr (TcRnImportLookup msg)\\n return def\\n Succeeded a -> return a\\n\\n lookup_err_msgs err = case err of\\n BadImport ie sub -> badImportItemErr iface decl_spec ie sub all_avails\\n IllegalImport -> pure $ NE.singleton ImportLookupIllegal\\n QualImportError rdr -> pure $ NE.singleton (ImportLookupQualified rdr)\\n\\n -- For each import item, we convert its RdrNames to Names,\\n -- and at the same time compute all the GlobalRdrElt corresponding\\n -- to what is actually imported by this item.\\n -- Returns Nothing on error.\\n --\\n -- Returns a list because, with DuplicateRecordFields, a naked\\n -- import/export of a record field can correspond to multiple\\n -- different GlobalRdrElts. See Note [Importing DuplicateRecordFields].\\n lookup_ie :: IE GhcPs\\n -> IELookupM ([(IE GhcRn, [GlobalRdrElt])], [IELookupWarning])\\n lookup_ie ie = handle_bad_import $\\n case ie of\\n IEVar _ (L l n) _ -> do\\n -- See Note [Importing DuplicateRecordFields]\\n xs <- lookup_names ie (ieWrappedName n)\\n let gres = map imp_item $ NE.toList xs\\n export_depr_warns\\n | want_hiding == Exactly\\n = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ( [ (IEVar Nothing (L l (replaceWrappedName n name)) noDocstring, [gre])\\n | gre <- gres\\n , let name = greName gre ]\\n , export_depr_warns )\\n\\n IEThingAll x ns_spec (L l tc) _ -> do\\n ImpOccItem { imp_item = gre\\n , imp_bundled = bundled_gres\\n , imp_is_parent = is_par\\n }\\n <- lookup_parent ie $ ieWrappedName tc\\n let name = greName gre\\n\\n child_gres :: [GlobalRdrElt]\\n child_gres\\n | is_par = filterByNamespaceSpecifierGREs ns_spec bundled_gres\\n | otherwise = []\\n\\n imp_list_warn\\n\\n | null child_gres\\n -- e.g. f(..) or T(..) where T is a type synonym\\n = [DodgyImport (DodgyImportsEmptyParent ie ns_spec gre)]\\n\\n -- e.g. import M( T(..) )\\n | not (is_qual decl_spec)\\n = [MissingImportList]\\n\\n | otherwise\\n = []\\n\\n renamed_ie = IEThingAll (x { ieta_warning = Nothing })\\n (rnNamespaceSpecifier ns_spec)\\n (L l (replaceWrappedName tc name))\\n noDocstring\\n export_depr_warn\\n | want_hiding == Exactly\\n = maybeToList $ mk_depr_export_warning gre\\n -- We don\'t want to warn about the children as they\\n -- are not explicitly mentioned; the warning will\\n -- be emitted later on if they are used\\n | otherwise = []\\n\\n return ( [(renamed_ie, gre:child_gres)]\\n , imp_list_warn ++ export_depr_warn)\\n\\n\\n IEThingAbs _ (L l tc\') _\\n | want_hiding == EverythingBut -- hiding ( C )\\n -- Here the \'C\' can be a data constructor\\n -- *or* a type/class, or even both\\n -> let tc = ieWrappedName tc\'\\n tc_name = lookup_parent ie tc\\n dc_name = lookup_parent ie (setRdrNameSpace tc srcDataName)\\n in\\n case catIELookupM [ tc_name, dc_name ] of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n names -> return ( [mkIEThingAbs tc\' l (imp_item name) | name <- names], [])\\n | otherwise\\n -> do ImpOccItem { imp_item = gre } <- lookup_parent ie (ieWrappedName tc\')\\n return ( [mkIEThingAbs tc\' l gre]\\n , maybeToList $ mk_depr_export_warning gre)\\n\\n IEThingWith (deprecation, ann) ltc@(L l rdr_tc) wc rdr_ns _ -> do\\n ImpOccItem { imp_item = gre, imp_bundled = subnames }\\n <- lookup_parent (IEThingAbs Nothing ltc noDocstring) (ieWrappedName rdr_tc)\\n let name = greName gre\\n\\n -- Look up the children in the sub-names of the parent\\n -- See Note [Importing DuplicateRecordFields]\\n let (children_errs, childnames) = lookupChildren subnames rdr_ns\\n\\n bad_import_warns <-\\n if null children_errs then return [] else\\n let items = map lce_wrapped_name children_errs\\n ie = IEThingWith (deprecation, ann) ltc wc items noDocstring\\n -- We are trying to import T( a,b,c,d ), and failed\\n -- to find \'b\' and \'d\'. So we make up an import item\\n -- to report as failing, namely T( b, d ).\\n -- c.f. #15413\\n subordinate_err = mkSubordinateError gre children_errs\\n in bad_import_w ie subordinate_err\\n\\n let name\' = replaceWrappedName rdr_tc name\\n childnames\' = map (to_ie_post_rn . fmap greName) childnames\\n gres = gre : map unLoc childnames\\n export_depr_warns\\n | want_hiding == Exactly = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ([ (IEThingWith (Nothing, ann) (L l name\') wc childnames\' noDocstring\\n ,gres)]\\n , bad_import_warns ++ export_depr_warns)\\n\\n IEWholeNamespace x ns_spec -> do\\n let mod_name = moduleName import_mod\\n names = map greName gres\\n renamed_ie = IEWholeNamespace x { iewn_warning = Nothing\\n , iewn_names = names }\\n (rnNamespaceSpecifier ns_spec)\\n gres = filterByNamespaceSpecifierGREs ns_spec $\\n gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n dodgy_warn\\n | null gres = [DodgyImport (DodgyImportsWildcard mod_name ns_spec)]\\n | otherwise = []\\n return ([(renamed_ie, gres)],\\n dodgy_warn)\\n\\n _other -> failLookupWith IllegalImport\\n -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed...\\n -- all of those constitute errors.\\n\\n where\\n mkIEThingAbs tc l gre\\n = (IEThingAbs Nothing (L l (replaceWrappedName tc n)) noDocstring, [gre])\\n where n = greName gre\\n\\n -- N.B. imports never have docstrings\\n noDocstring = Nothing\\n\\n handle_bad_import m = catchIELookup m $ \\\\case\\n BadImport ie sub -> do\\n ws <- bad_import_w ie sub\\n return ([], ws)\\n err -> failLookupWith err\\n\\n bad_import_w :: IE GhcPs -> IsSubordinateError -> IELookupM [IELookupWarning]\\n bad_import_w ie sub\\n | want_hiding == EverythingBut = return [BadImportW ie sub]\\n | otherwise = failLookupWith (BadImport ie sub)\\n\\n mk_depr_export_warning gre\\n = DeprecatedExport name <$> mi_export_warn_fn iface name\\n where\\n name = greName gre\\n\\n-- | Assuming a subordinate item could not be found, do another lookup for a\\n-- more specific error message.\\nmkBadExportSubordinate :: [GlobalRdrElt] -> LIEWrappedName GhcPs -> BadExportSubordinate\\nmkBadExportSubordinate child_gres n =\\n case lookupChildren child_gres [n] of\\n (LookupChildNonType {lce_nontype_item = g} : _, _) -> BadExportSubordinateNonType g\\n (LookupChildNonData {lce_nondata_item = g} : _, _) -> BadExportSubordinateNonData g\\n _ -> BadExportSubordinateNotFound n\\n\\ntype IELookupM = MaybeErr IELookupError\\n\\ndata IELookupWarning\\n = BadImportW (IE GhcPs) IsSubordinateError\\n | MissingImportList\\n | DodgyImport DodgyImportsReason\\n | DeprecatedExport Name (WarningTxt GhcRn)\\n\\n-- | Is this import/export item a subordinate or not?\\ndata IsSubordinateError\\n = IsSubordinateError { subordinate_err_parent :: !GlobalRdrElt\\n , subordinate_err_unavailable :: [FastString]\\n , subordinate_err_nontype :: [GlobalRdrElt]\\n , subordinate_err_nondata :: [GlobalRdrElt] }\\n | IsNotSubordinate\\n\\nmkSubordinateError :: GlobalRdrElt -> [LookupChildError] -> IsSubordinateError\\nmkSubordinateError gre children_errs = foldr add init_acc children_errs\\n where\\n init_acc :: IsSubordinateError\\n init_acc = IsSubordinateError gre [] [] []\\n\\n add :: LookupChildError -> IsSubordinateError -> IsSubordinateError\\n add children_err sub@IsSubordinateError{} =\\n case children_err of\\n LookupChildNonType{lce_nontype_item = g} ->\\n sub { subordinate_err_nontype = g : subordinate_err_nontype sub }\\n LookupChildNonData{lce_nondata_item = g} ->\\n sub { subordinate_err_nondata = g : subordinate_err_nondata sub }\\n LookupChildNotFound (L _ wname) ->\\n let fs = (occNameFS . rdrNameOcc . ieWrappedName) wname\\n in sub { subordinate_err_unavailable = fs : subordinate_err_unavailable sub }\\n add _ IsNotSubordinate = panic \\"mkSubordinateError: IsNotSubordinate\\"\\n\\ndata IELookupError\\n = QualImportError RdrName\\n | BadImport (IE GhcPs) IsSubordinateError\\n | IllegalImport\\n\\nfailLookupWith :: IELookupError -> IELookupM a\\nfailLookupWith err = Failed err\\n\\ncatchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a\\ncatchIELookup m h = case m of\\n Succeeded r -> return r\\n Failed err -> h err\\n\\ncatIELookupM :: [IELookupM a] -> [a]\\ncatIELookupM ms = [ a | Succeeded a <- ms ]\\n\\n-- | Information associated to an \'AvailInfo\' used in constructing\\n-- an \'OccEnv\' corresponding to imports.\\n--\\n-- See Note [Dealing with imports].\\ndata ImpOccItem\\n = ImpOccItem\\n { imp_item :: GlobalRdrElt\\n -- ^ The import item\\n , imp_bundled :: [GlobalRdrElt]\\n -- ^ Items bundled in the Avail this import item came from,\\n -- not including the import item itself if it is a parent.\\n , imp_is_parent :: Bool\\n -- ^ Is the import item a parent? See Note [Dealing with imports].\\n }\\n\\ninstance Outputable ImpOccItem where\\n ppr (ImpOccItem { imp_item = item, imp_bundled = bundled, imp_is_parent = is_par })\\n = braces $ hsep\\n [ text \\"ImpOccItem\\"\\n , if is_par then text \\"[is_par]\\" else empty\\n , ppr (greName item) <+> ppr (greParent item)\\n , braces $ text \\"bundled:\\" <+> ppr (map greName bundled) ]\\n\\n-- | Make an \'OccEnv\' of all the imports.\\n--\\n-- Complicated by the fact that associated data types and pattern synonyms\\n-- can appear twice. See Note [Dealing with imports].\\nmkImportOccEnv :: HscEnv -> ImpDeclSpec -> [IfaceExport] -> OccEnv (NameEnv ImpOccItem)\\nmkImportOccEnv hsc_env decl_spec all_avails =\\n mkOccEnv_C (plusNameEnv_C combine)\\n [ (occ, mkNameEnv [(nm, item)])\\n | avail <- all_avails\\n , let gres = gresFromAvail hsc_env (Just hiding_spec) avail\\n , gre <- gres\\n , let nm = greName gre\\n occ = greOccName gre\\n (is_parent, bundled) = case avail of\\n AvailTC c _\\n | c == nm -- (Recall the AvailTC invariant from GHC.Types.AvailInfo)\\n -> ( True, drop 1 gres ) -- \\"drop 1\\": don\'t include the parent itself.\\n | otherwise\\n -> ( False, gres )\\n _ -> ( False, [] )\\n item = ImpOccItem\\n { imp_item = gre\\n , imp_bundled = bundled\\n , imp_is_parent = is_parent }\\n ]\\n where\\n\\n hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\n -- See Note [Dealing with imports]\\n -- \'combine\' may be called for associated data types which appear\\n -- twice in the all_avails. In the example, we have two Avails for T,\\n -- namely T(T,T1,T2,T3) and C(C,T), and we combine them by dropping the\\n -- latter, in which T is not the parent.\\n combine :: ImpOccItem -> ImpOccItem -> ImpOccItem\\n combine item1@(ImpOccItem { imp_item = gre1, imp_is_parent = is_parent1 })\\n item2@(ImpOccItem { imp_item = gre2, imp_is_parent = is_parent2 })\\n | is_parent1 || is_parent2\\n , not (isRecFldGRE gre1 || isRecFldGRE gre2) -- NB: does not force GREInfo.\\n , let name1 = greName gre1\\n name2 = greName gre2\\n gre = gre1 `plusGRE` gre2\\n -- See Note [Preserve parent information when combining import OccEnvs]\\n = assertPpr (name1 == name2)\\n (ppr name1 <+> ppr name2) $\\n if is_parent1\\n then item1 { imp_item = gre }\\n else item2 { imp_item = gre }\\n -- Discard C(C,T) in favour of T(T, T1, T2, T3).\\n\\n -- \'combine\' may also be called for pattern synonyms which appear both\\n -- unassociated and associated (see Note [Importing PatternSynonyms]).\\n combine item1@(ImpOccItem { imp_item = c1, imp_bundled = kids1 })\\n item2@(ImpOccItem { imp_item = c2, imp_bundled = kids2 })\\n = assertPpr (greName c1 == greName c2\\n && (not (null kids1 && null kids2)))\\n (ppr c1 <+> ppr c2 <+> ppr kids1 <+> ppr kids2) $\\n if null kids1\\n then item2\\n else item1\\n -- Discard standalone pattern P in favour of T(P).\\n\\n-- | Essentially like @lookupGRE env (LookupOccName occ which_gres)@,\\n-- but working with \'ImpOccItem\'s instead of \'GlobalRdrElt\'s.\\nlookupImpOccEnv :: WhichGREs GREInfo\\n -> OccEnv (NameEnv ImpOccItem) -> OccName -> [NameEnv ImpOccItem]\\nlookupImpOccEnv which_gres env occ =\\n mapMaybe relevant_items $ lookupOccEnv_AllNameSpaces env occ\\n where\\n is_relevant :: ImpOccItem -> Bool\\n is_relevant (ImpOccItem { imp_item = gre }) =\\n greIsRelevant which_gres (occNameSpace occ) gre\\n relevant_items :: NameEnv ImpOccItem -> Maybe (NameEnv ImpOccItem)\\n relevant_items nms\\n | let nms\' = filterNameEnv is_relevant nms\\n = if isEmptyNameEnv nms\'\\n then Nothing\\n else Just nms\'\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{Import/Export Utils}\\n* *\\n************************************************************************\\n-}\\n\\n-- | Given an import\\\\/export spec, appropriately set the @gre_imp@ field\\n-- for the \'GlobalRdrElt\'s.\\ngresFromIE :: ImpDeclSpec -> (LIE GhcRn, [GlobalRdrElt]) -> [GlobalRdrElt]\\ngresFromIE decl_spec (L loc ie, gres)\\n = map set_gre_imp gres\\n where\\n is_explicit = case ie of\\n IEThingAll _ _ name _ -> \\\\n -> n == lieWrappedName name\\n IEWholeNamespace _ _ -> \\\\_ -> False\\n _ -> \\\\_ -> True\\n prov_fn name\\n = ImpSpec { is_decl = decl_spec, is_item = item_spec }\\n where\\n item_spec = ImpSome { is_explicit = is_explicit name\\n , is_iloc = locA loc }\\n set_gre_imp gre@( GRE { gre_name = nm } )\\n = gre { gre_imp = unitBag $ prov_fn nm }\\n\\nparentOfImplicitlyImportedGRE :: Outputable info => GlobalRdrEltX info -> Maybe Name\\nparentOfImplicitlyImportedGRE gre =\\n if any (explicit_import . is_item) $ gre_imp gre\\n then Nothing\\n else greParent_maybe gre\\n where\\n explicit_import :: ImpItemSpec -> Bool\\n explicit_import (ImpAll {}) =\\n pprPanic \\"parentOfImplicitlyImportedGRE: ImpAll\\" (ppr gre)\\n explicit_import (ImpSome { is_explicit }) = is_explicit\\n\\n{- Note [Children for duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider the module\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (F(foo, MkFInt, MkFBool)) where\\n data family F a\\n data instance F Int = MkFInt { foo :: Int }\\n data instance F Bool = MkFBool { foo :: Bool }\\n\\nThe `foo` in the export list refers to *both* selectors! For this\\nreason, lookupChildren builds an environment that maps the FastString\\nto a list of items, rather than a single item.\\n-}\\n\\nmkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]\\nmkChildEnv gres = foldr add emptyNameEnv gres\\n where\\n add gre env = case greParent gre of\\n ParentIs p -> extendNameEnv_Acc (:) Utils.singleton env p gre\\n NoParent -> env\\n\\nfindChildren :: NameEnv [a] -> Name -> [a]\\nfindChildren env n = lookupNameEnv env n `orElse` []\\n\\ndata LookupChildError\\n = LookupChildNotFound { lce_wrapped_name :: !(LIEWrappedName GhcPs) }\\n | LookupChildNonType { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nontype_item :: !GlobalRdrElt }\\n | LookupChildNonData { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nondata_item :: !GlobalRdrElt }\\n\\nlookupChildren :: [GlobalRdrElt]\\n -> [LIEWrappedName GhcPs]\\n -> ( [LookupChildError] -- The ones for which the lookup failed\\n , [LocatedA GlobalRdrElt] )\\n-- (lookupChildren all_kids rdr_items) maps each rdr_item to its\\n-- corresponding Name in all_kids, if the former exists\\n-- The matching is done by FastString, not OccName, so that\\n-- Cls( meth, AssocTy )\\n-- will correctly find AssocTy among the all_kids of Cls, even though\\n-- the RdrName for AssocTy may have a (bogus) DataName namespace\\n-- (Really the rdr_items should be FastStrings in the first place.)\\nlookupChildren all_kids rdr_items = (fails, successes)\\n where\\n mb_xs = map do_one rdr_items\\n fails = [ err | Failed err <- mb_xs ]\\n successes = [ ok | Succeeded oks <- mb_xs, ok <- NE.toList oks ]\\n\\n do_one :: LIEWrappedName GhcPs -> MaybeErr LookupChildError (NonEmpty (LocatedA GlobalRdrElt))\\n do_one item@(L l r) =\\n case r of\\n IEName{}\\n -- IEName (unadorned name) places no restriction on the namespace of\\n -- the imported entity, so we look in both `val_gres` and `typ_gres`.\\n -- In case of conflict (punning), the value namespace takes priority.\\n -- See Note [Prioritise the value namespace in subordinate import lists]\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEType{}\\n -- IEType (\'type\' namespace specifier) restricts the lookup to the\\n -- type namespace, i.e. to `typ_gres`. In case of failure, we check\\n -- `val_gres` to produce a more helpful error message.\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- val_gres -> Failed $ LookupChildNonType item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEData{}\\n -- IEData (\'data\' namespace specifier) restricts the lookup to the\\n -- data namespace, i.e. to `val_gres`. In case of failure, we check\\n -- `typ_gres` to produce a more helpful error message.\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- typ_gres -> Failed $ LookupChildNonData item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEPattern{} -> panic \\"lookupChildren: IEPattern\\" -- Never happens (invalid syntax)\\n IEDefault{} -> panic \\"lookupChildren: IEDefault\\" -- Never happens (invalid syntax)\\n where\\n fs = (occNameFS . rdrNameOcc . ieWrappedName) r\\n gres = fromMaybe [] (lookupFsEnv kid_env fs)\\n (val_gres, typ_gres) = partition (isValNameSpace . greNameSpace) gres\\n\\n -- See Note [Children for duplicate record fields]\\n kid_env :: FastStringEnv [GlobalRdrElt]\\n kid_env = extendFsEnvList_C (++) emptyFsEnv\\n [(occNameFS (occName x), [x]) | x <- all_kids]\\n\\n\\n{- Note [Prioritise the value namespace in subordinate import lists]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider this program that defines a class that has both an associated type\\nnamed (#) and a method named (#)\\n\\n module M_assoc where\\n class C a b where\\n type a # b\\n (#) :: a -> b -> ()\\n module N_assoc where\\n import M_assoc( C((#)) )\\n\\nIn the import declaration, when we see the unadorned name (#) in the subordinate\\nimport list of C, which children should we bring into scope? Our options are:\\n\\n a) only the method (#)\\n b) only the associated type (#)\\n c) both the method and the associated type\\n\\nTo follow the precedent established by top-level items, we go with option (a).\\nIndeed, consider a slightly different program\\n\\n module M_top where\\n type family a # b\\n a # b = ()\\n module N_top where\\n import M_top( (#) )\\n\\nHere the import brings only the function (#) into scope, and one has to say\\n`type (#)` to get the type family.\\n-}\\n\\n-------------------------------\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused names}\\n* *\\n*********************************************************\\n-}\\n\\nreportUnusedNames :: TcGblEnv -> HscSource -> RnM ()\\nreportUnusedNames gbl_env hsc_src\\n = do { keep <- readTcRef (tcg_keep gbl_env)\\n ; traceRn \\"RUN\\" (ppr (tcg_dus gbl_env))\\n ; warnUnusedImportDecls gbl_env hsc_src\\n ; warnUnusedTopBinds $ unused_locals keep\\n ; warnMissingSignatures gbl_env\\n ; warnMissingKindSignatures gbl_env }\\n where\\n used_names :: NameSet -> NameSet\\n used_names keep = findUses (tcg_dus gbl_env) emptyNameSet `unionNameSet` keep\\n -- NB: currently, if f x = g, we only treat \'g\' as used if \'f\' is used\\n -- Hence findUses\\n\\n -- Collect the defined names from the in-scope environment\\n defined_names :: [GlobalRdrElt]\\n defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)\\n\\n kids_env = mkChildEnv defined_names\\n -- This is done in mkExports too; duplicated work\\n\\n gre_is_used :: NameSet -> GlobalRdrElt -> Bool\\n gre_is_used used_names gre0\\n = name `elemNameSet` used_names\\n || any (\\\\ gre -> greName gre `elemNameSet` used_names) (findChildren kids_env name)\\n -- A use of C implies a use of T,\\n -- if C was brought into scope by T(..) or T(C)\\n where\\n name = greName gre0\\n\\n -- Filter out the ones that are\\n -- (a) defined in this module, and\\n -- (b) not defined by a \'deriving\' clause\\n -- The latter have an Internal Name, so we can filter them out easily\\n unused_locals :: NameSet -> [GlobalRdrElt]\\n unused_locals keep =\\n let -- Note that defined_and_used, defined_but_not_used\\n -- are both [GRE]; that\'s why we need defined_and_used\\n -- rather than just used_names\\n _defined_and_used, defined_but_not_used :: [GlobalRdrElt]\\n (_defined_and_used, defined_but_not_used)\\n = partition (gre_is_used (used_names keep)) defined_names\\n\\n in filter is_unused_local defined_but_not_used\\n is_unused_local :: GlobalRdrElt -> Bool\\n is_unused_local gre = isLocalGRE gre\\n && isExternalName (greName gre)\\n\\n{- *********************************************************************\\n* *\\n Missing signatures\\n* *\\n********************************************************************* -}\\n\\n{-\\nNote [Missing signatures]\\n~~~~~~~~~~~~~~~~~~~~~~~~~\\nThere are four warning flags in play:\\n\\n * -Wmissing-exported-signatures\\n Warn about any exported top-level function/value without a type signature.\\n Does not include pattern synonyms.\\n\\n * -Wmissing-signatures\\n Warn about any top-level function/value without a type signature. Does not\\n include pattern synonyms. Takes priority over -Wmissing-exported-signatures.\\n\\n * -Wmissing-exported-pattern-synonym-signatures\\n Warn about any exported pattern synonym without a type signature.\\n\\n * -Wmissing-pattern-synonym-signatures\\n Warn about any pattern synonym without a type signature. Takes priority over\\n -Wmissing-exported-pattern-synonym-signatures.\\n\\n-}\\n\\n-- | Warn the user about top level binders that lack type signatures.\\n-- Called /after/ type inference, so that we can report the\\n-- inferred type of the function\\nwarnMissingSignatures :: TcGblEnv -> RnM ()\\nwarnMissingSignatures gbl_env\\n = do { let exports = availsToNameSet (tcg_exports gbl_env)\\n sig_ns = tcg_sigs gbl_env\\n -- We use sig_ns to exclude top-level bindings that are generated by GHC\\n binds = collectHsBindsBinders CollNoDictBinders $ tcg_binds gbl_env\\n pat_syns = tcg_patsyns gbl_env\\n\\n not_ghc_generated :: Name -> Bool\\n not_ghc_generated name = name `elemNameSet` sig_ns\\n\\n add_binding_warn :: Id -> RnM ()\\n add_binding_warn id =\\n when (not_ghc_generated name) $\\n do { env <- liftZonkM $ tcInitTidyEnv -- Why not use emptyTidyEnv?\\n ; let ty = tidyOpenType env (idType id)\\n missing = MissingTopLevelBindingSig name ty\\n diag = TcRnMissingSignature missing exported\\n ; addDiagnosticAt (getSrcSpan name) diag }\\n where\\n name = idName id\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n add_patsyn_warn :: PatSyn -> RnM ()\\n add_patsyn_warn ps =\\n when (not_ghc_generated name) $\\n addDiagnosticAt (getSrcSpan name)\\n (TcRnMissingSignature missing exported)\\n where\\n name = patSynName ps\\n missing = MissingPatSynSig ps\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n -- Warn about missing signatures\\n -- Do this only when we have a type to offer\\n -- See Note [Missing signatures]\\n ; mapM_ add_binding_warn binds\\n ; mapM_ add_patsyn_warn pat_syns\\n }\\n\\n-- | Warn the user about tycons that lack kind signatures.\\n-- Called /after/ type (and kind) inference, so that we can report the\\n-- inferred kinds.\\nwarnMissingKindSignatures :: TcGblEnv -> RnM ()\\nwarnMissingKindSignatures gbl_env\\n = do { cusks_enabled <- xoptM LangExt.CUSKs\\n ; mapM_ (add_ty_warn cusks_enabled) tcs\\n }\\n where\\n tcs = tcg_tcs gbl_env\\n ksig_ns = tcg_ksigs gbl_env\\n exports = availsToNameSet (tcg_exports gbl_env)\\n\\n has_kind_signature :: Name -> Bool\\n has_kind_signature name = name `elemNameSet` ksig_ns\\n\\n add_ty_warn :: Bool -> TyCon -> RnM ()\\n add_ty_warn cusks_enabled tyCon =\\n when (has_kind_signature name) $\\n addDiagnosticAt (getSrcSpan name) diag\\n where\\n name = tyConName tyCon\\n diag = TcRnMissingSignature missing exported\\n missing = MissingTyConKindSig tyCon cusks_enabled\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused imports}\\n* *\\n*********************************************************\\n\\nThis code finds which import declarations are unused. The\\nspecification and implementation notes are here:\\n https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/unused-imports\\n\\nSee also Note [Choosing the best import declaration] in GHC.Types.Name.Reader\\n-}\\n\\ntype ImportDeclUsage\\n = ( LImportDecl GhcRn -- The import declaration\\n , [GlobalRdrElt] -- What *is* used (normalised)\\n , [Name] -- What is imported but *not* used\\n , [NamespaceSpecifier GhcRn] ) -- Unused wildcards\\n\\nwarnUnusedImportDecls :: TcGblEnv -> HscSource -> RnM ()\\nwarnUnusedImportDecls gbl_env hsc_src\\n = do { uses <- readMutVar (tcg_used_gres gbl_env)\\n ; let imports = tcg_rn_imports gbl_env\\n rdr_env = tcg_rdr_env gbl_env\\n\\n -- We should only warn for unnecessary *user* imports, but deciding\\n -- minimal imports should take generated imports into account\\n ; let usageUserImports = findImportUsage (excludeGenerated imports) uses\\n usageAllImports = findImportUsage imports uses\\n\\n ; traceRn \\"warnUnusedImportDecls\\" $\\n (vcat [ text \\"Uses:\\" <+> ppr uses\\n , text \\"Usage all user imports: \\" <+> ppr usageUserImports\\n , text \\"Usage all imports: \\" <+> ppr usageAllImports])\\n\\n ; mapM_ (warnUnusedImport rdr_env) usageUserImports\\n\\n ; whenGOptM Opt_D_dump_minimal_imports $\\n printMinimalImports hsc_src usageAllImports }\\n\\n-- | Exclude generated imports\\nexcludeGenerated :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\nexcludeGenerated = filterOut (isGeneratedImport . ideclOrigin . ideclExt . unLoc)\\n\\nfindImportUsage :: [LImportDecl GhcRn]\\n -> [GlobalRdrElt]\\n -> [ImportDeclUsage]\\n\\nfindImportUsage imports used_gres\\n = map unused_decl imports\\n where\\n import_usage :: ImportMap\\n import_usage = mkImportMap used_gres\\n\\n unused_decl :: LImportDecl GhcRn -> ImportDeclUsage\\n unused_decl decl@(L _ (ImportDecl { ideclImportList = imps }))\\n = -- pprTrace \\"unused_decl\\" (vcat [ ppr decl\\n -- , text \\"used\\" <+> ppr used_gres\\n -- , text \\"unused\\" <+> ppr unused_names ]) $\\n (decl, used_gres, unused_names, unused_wcs)\\n where\\n used_gres = lookupImportMap decl import_usage\\n\\n used_gre_env = mkGlobalRdrEnv used_gres\\n used_parents = mkNameSet (mapMaybe greParent_maybe used_gres)\\n\\n (unused_names, unused_wcs) -- Not trivial; see eg #7454\\n = case imps of\\n Just (Exactly, imp_ies) ->\\n let unused = foldr (add_unused . unLoc) emptyUnusedNames imp_ies\\n nms = nameSetElemsStable (collectUnusedNames unused)\\n wcs = collectUnusedWildcards unused\\n in (nms, wcs)\\n _other -> ([], []) -- No explicit import list => no unused-name list\\n\\n add_unused :: IE GhcRn -> UnusedNames -> UnusedNames\\n add_unused (IEVar _ n _) acc = add_unused_name (lieWrappedName n) True acc\\n add_unused (IEThingAbs _ n _) acc = add_unused_name (lieWrappedName n) False acc\\n add_unused (IEThingAll _ _ n _) acc = add_unused_all (lieWrappedName n) acc\\n add_unused (IEThingWith _ p wc ns _) acc = add_wc_all (add_unused_with pn xs acc)\\n where pn = lieWrappedName p\\n xs = map lieWrappedName ns\\n add_wc_all = case wc of\\n NoIEWildcard -> id\\n IEWildcard _ -> add_unused_all pn\\n add_unused (IEWholeNamespace x ns_spec) acc = add_unused_wildcard ns_spec (iewn_names x) acc\\n add_unused _ acc = acc\\n\\n add_unused_name :: Name -> Bool -> UnusedNames -> UnusedNames\\n add_unused_name n is_ie_var acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | is_ie_var\\n , isFieldName n\\n -- See Note [Reporting unused imported duplicate record fields]\\n = let\\n fs = getOccFS n\\n (flds, flds_used) = lookupFsEnv acc_fs fs `orElse` (emptyNameSet, Any False)\\n acc_fs\' = extendFsEnv acc_fs fs (extendNameSet flds n, Any used S.<> flds_used)\\n in UnusedNames acc_ns acc_wcs acc_fs\'\\n\\n | used\\n = acc\\n\\n | otherwise\\n = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n where\\n used = isJust $ lookupGRE_Name used_gre_env n\\n\\n add_unused_all :: Name -> UnusedNames -> UnusedNames\\n add_unused_all n acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | Just {} <- lookupGRE_Name used_gre_env n = acc\\n | n `elemNameSet` used_parents = acc\\n | otherwise = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n\\n add_unused_with :: Name -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_with p ns acc\\n | all (`elemNameSet` acc1_ns) ns = add_unused_name p False acc1\\n | otherwise = acc1\\n where\\n acc1@(UnusedNames acc1_ns _ _) = foldr (\\\\n acc\' -> add_unused_name n False acc\') acc ns\\n -- If you use \'signum\' from Num, then the user may well have\\n -- imported Num(signum). We don\'t want to complain that\\n -- Num is not itself mentioned. Hence the two cases in add_unused_with.\\n\\n add_unused_wildcard :: NamespaceSpecifier GhcRn -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_wildcard ns_spec names acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | any_used = acc\\n | otherwise = UnusedNames acc_ns (ns_spec : acc_wcs) acc_fs\\n where\\n -- A wildcard `type ..` or `data ..` is used if at least one of\\n -- the names it expands to is used\\n any_used = any (isJust . lookupGRE_Name used_gre_env) names\\n\\n\\n-- | An accumulator for unused names in an import list.\\n--\\n-- See Note [Reporting unused imported duplicate record fields].\\ndata UnusedNames =\\n UnusedNames\\n { unused_names :: NameSet\\n -- ^ Unused \'Name\'s in an import list, not including record fields\\n -- that are plain \'IEVar\' imports (tracked by \'rec_fld_uses\')\\n -- or wildcard imports (tracked by \'unused_wildcards\').\\n , unused_wildcards :: [NamespaceSpecifier GhcRn]\\n -- ^ Unused wildcards @type ..@ or @data ..@ in an import list.\\n , rec_fld_uses :: FastStringEnv (NameSet, Any)\\n -- ^ Record fields imported without a parent (i.e. an \'IEVar\' import).\\n --\\n -- The \'Any\' value records whether any of the record fields\\n -- sharing the same underlying \'FastString\' have been used.\\n }\\n\\nemptyUnusedNames :: UnusedNames\\nemptyUnusedNames = UnusedNames emptyNameSet [] emptyFsEnv\\n\\ninstance Outputable UnusedNames where\\n ppr (UnusedNames nms wcs flds) =\\n text \\"UnusedNames\\" <+>\\n braces (ppr nms <+> ppr wcs <+> ppr (fmap (second getAny) flds))\\n\\n-- | Collect all unused names from a \'UnusedNames\' value.\\ncollectUnusedNames :: UnusedNames -> NameSet\\ncollectUnusedNames (UnusedNames { unused_names = nms, rec_fld_uses = flds })\\n = nms S.<> unused_flds\\n where\\n unused_flds = nonDetFoldFsEnv collect_unused emptyNameSet flds\\n collect_unused :: (NameSet, Any) -> NameSet -> NameSet\\n collect_unused (nms, Any at_least_one_name_is_used) acc\\n | at_least_one_name_is_used = acc\\n | otherwise = unionNameSet nms acc\\n\\ncollectUnusedWildcards :: UnusedNames -> [NamespaceSpecifier GhcRn]\\ncollectUnusedWildcards = unused_wildcards\\n\\n{- Note [Reporting unused imported duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have (#24035):\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M1 (R1(..), R2(..)) where\\n data R1 = MkR1 { fld :: Int }\\n data R2 = MkR2 { fld :: Int }\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M2 where\\n import M1 (R1(MkR1), R2, fld)\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nIn the import of \'M1\' in \'M2\', the \'fld\' import resolves to two separate GREs,\\nnamely R1(fld) and R2(fld). From the perspective of the renamer, and in particular\\nthe \'findImportUsage\' function, it\'s as if the user had imported the two names\\nseparately (even though no source syntax allows that).\\n\\nThis means that we need to be careful when reporting unused imports: the R2(fld)\\nimport is indeed unused, but because R1(fld) is used, we should not report\\nfld as unused altogether.\\n\\nTo achieve this, we keep track of record field imports without a parent (i.e.\\nusing the IEVar constructor) separately from other import items, using the\\nUnusedNames datatype.\\nOnce we have accumulated usages, we emit warnings for unused record fields\\nwithout parents one whole group (of record fields sharing the same textual name)\\nat a time, and only if *all* of the record fields in the group are unused;\\nsee \'collectUnusedNames\'.\\n\\nNote that this only applies to record fields imported without a parent. If we\\nhad:\\n\\n import M1 (R1(MkR1, fld), R2(fld))\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nthen of course we should report the second \'fld\' as unused.\\n-}\\n\\n\\n{- Note [The ImportMap]\\n~~~~~~~~~~~~~~~~~~~~~~~\\nThe ImportMap is a short-lived intermediate data structure records, for\\neach import declaration, what stuff brought into scope by that\\ndeclaration is actually used in the module.\\n\\nThe [GlobalRdrElt] are the things imported from that decl.\\n-}\\n\\ndata ImportMap = ImportMap\\n { im_imports :: Map RealSrcSpan [GlobalRdrElt]\\n -- ^ See [The ImportMap]\\n -- If loc :-> gres, then\\n -- \'loc\' = the end loc of the bestImport of each GRE in \'gres\'\\n , im_generatedImports :: Map ModuleName [GlobalRdrElt]\\n }\\n\\nmkImportMap :: [GlobalRdrElt] -> ImportMap\\n-- For each of a list of used GREs, find all the import decls that brought\\n-- it into scope; choose one of them (bestImport), and record\\n-- the RdrName in that import decl\'s entry in the ImportMap\\nmkImportMap = foldr insertImportMap $ ImportMap Map.empty Map.empty\\n\\ninsertImportMap :: GlobalRdrElt -> ImportMap -> ImportMap\\ninsertImportMap gre@(GRE { gre_imp = imp_specs }) importMap\\n | RealSrcSpan importSpan _ <- is_dloc best_imp_spec =\\n importMap{im_imports = insertElem importSpan gre $ im_imports importMap}\\n | GeneratedSrcSpan{} <- is_dloc best_imp_spec =\\n importMap{im_generatedImports = insertElem (moduleName $ is_mod best_imp_spec) gre $ im_generatedImports importMap}\\n | otherwise = importMap\\n where\\n best_imp_spec =\\n case bagToList imp_specs of\\n [] -> pprPanic \\"mkImportMap: GRE with no ImportSpecs\\" (ppr gre)\\n is:iss -> is_decl $ bestImport (is NE.:| iss)\\n\\n -- https://github.com/haskell/containers/issues/784\\n insertElem :: Ord k => k -> v -> Map k [v] -> Map k [v]\\n insertElem k v = flip Map.alter k $ \\\\case\\n Just vs -> Just (v : vs)\\n Nothing -> Just [v]\\n\\nlookupImportMap :: LImportDecl GhcRn -> ImportMap -> [GlobalRdrElt]\\nlookupImportMap (L srcSpan ImportDecl{ideclName = L _ modName}) importMap =\\n fromMaybe [] $\\n -- should match logic in insertImportMap\\n case locA srcSpan of\\n RealSrcSpan realSrcSpan _ -> realSrcSpan `Map.lookup` im_imports importMap\\n GeneratedSrcSpan{} -> modName `Map.lookup` im_generatedImports importMap\\n _ -> Nothing\\n\\nlieNames :: LIE (GhcPass p) -> [Located (IdP (GhcPass p))]\\nlieNames = _\\n\\nwarnUnusedImport :: GlobalRdrEnv -> ImportDeclUsage -> RnM ()\\nwarnUnusedImport rdr_env (L loc decl, used, unused, unused_wcs)\\n\\n -- Do not warn for \'import M()\'\\n -- See (UI1) in Note [Unused imports]\\n | Just (Exactly, _) <- ideclImportList decl\\n , null unused && null unused_wcs\\n = return ()\\n\\n -- Note [Do not warn about Prelude hiding]\\n | Just (EverythingBut, hides) <- ideclImportList decl\\n , not (null hides)\\n , pRELUDE_NAME == unLoc (ideclName decl)\\n = return ()\\n\\n -- Do not warn about import X as Rebindable\\n -- See (UI2) in Note [Unused imports]\\n | Just (L _ mod) <- ideclAs decl\\n , mod == rEBINDABLE_MOD_NAME\\n = return ()\\n\\n -- Nothing used; drop entire declaration\\n | null used\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl UnusedImportNone)\\n\\n -- Everything imported is used; nop\\n | null unused && null unused_wcs\\n = return ()\\n\\n -- Some imports are unused: make the `SrcSpan` cover only the unused\\n -- items instead of the whole import statement\\n | Just (_, imports) <- ideclImportList decl\\n , let unused_locs = [ locA loc | L loc ie <- imports\\n , name <- ieNames ie\\n , name `elem` unused ]\\n , loc1 : locs <- unused_locs\\n , let span = foldr1 combineSrcSpans ( loc1 NE.:| locs )\\n = addDiagnosticAt span (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n -- Some imports are unused\\n | otherwise\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n where\\n -- In warning message, pretty-print identifiers unqualified unconditionally\\n -- to improve the consistent for ambiguous/unambiguous identifiers.\\n -- See #14881.\\n possible_field n =\\n case lookupGRE_Name rdr_env n of\\n Just (GRE { gre_par = par, gre_info = IAmRecField info }) ->\\n let fld_occ :: OccName\\n fld_occ = nameOccName $ flSelector $ recFieldLabel info\\n in UnusedImportNameRecField par fld_occ\\n _ -> UnusedImportNameRegular n\\n\\n -- Print unused names in a deterministic (lexicographic) order\\n sort_unused :: [UnusedImportName]\\n sort_unused =\\n [ UnusedImportWildcard wc | wc <- unused_wcs ] ++\\n [ possible_field nm | nm <- sortBy (comparing nameOccName) unused ]\\n\\ngetMinimalImports :: [ImportDeclUsage] -> RnM [LImportDecl GhcRn]\\ngetMinimalImports ie_decls\\n = do { rdr_env <- getGlobalRdrEnv\\n ; fmap combine $ mapM (mk_minimal rdr_env) ie_decls }\\n where\\n mk_minimal rdr_env (L l decl, used_gres, unused, unused_wcs)\\n | null unused && null unused_wcs\\n , Just (Exactly, _) <- ideclImportList decl\\n = return (L l decl)\\n | otherwise\\n = do { let ImportDecl { ideclName = L _ mod_name\\n , ideclSource = is_boot\\n , ideclPkgQual = pkg_qual\\n , ideclExt = XImportDeclPass { ideclOrigin = origin } } = decl\\n ; iface <- loadSrcInterface doc (importDeclLookupScope origin)\\n mod_name is_boot pkg_qual\\n ; let used_avails = gresToAvailInfo used_gres\\n ; lies <- map (L l) <$> concatMapM (to_ie rdr_env iface) used_avails\\n ; return (L l (decl { ideclImportList = Just (Exactly, lies) })) }\\n where\\n doc = text \\"Compute minimal imports for\\" <+> ppr decl\\n\\n to_ie :: GlobalRdrEnv -> ModIface -> AvailInfo -> RnM [IE GhcRn]\\n -- The main trick here is that if we\'re importing all the constructors\\n -- we want to say \\"T(..)\\", but if we\'re importing only a subset we want\\n -- to say \\"T(A,B,C)\\". So we have to find out what the module exports.\\n to_ie rdr_env _ (Avail c) -- Note [Overloaded field import]\\n = do { let\\n gre = expectJust $ lookupGRE_Name rdr_env c\\n ; return $ [IEVar Nothing (to_ie_post_rn $ noLocA $ greName gre) Nothing] }\\n to_ie _ _ avail@(AvailTC n [_]) -- Exporting the main decl and nothing else\\n | availExportsDecl avail\\n = return [IEThingAbs Nothing (to_ie_post_rn $ noLocA n) Nothing]\\n to_ie rdr_env iface (AvailTC n cs) =\\n case [ xs | avail@(AvailTC x xs) <- mi_exports iface\\n , x == n\\n , availExportsDecl avail -- Note [Partial export]\\n ] of\\n [xs]\\n | all_used xs\\n -> return [IEThingAll (IEThingAllExt Nothing noAnn noAnn noAnn)\\n (NoNamespaceSpecifier noExtField)\\n (to_ie_post_rn $ noLocA n)\\n Nothing]\\n | otherwise\\n -> do { let ns_gres = map (expectJust . lookupGRE_Name rdr_env) cs\\n ns = map greName ns_gres\\n ; return [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n -- Note [Overloaded field import]\\n _other\\n -> do { let infos = map (expectJust . lookupGRE_Name rdr_env) cs\\n (ns_gres,fs_gres) = classifyGREs infos\\n ns = map greName (ns_gres ++ fs_gres)\\n fs = map fieldGREInfo fs_gres\\n ; return $\\n if all_non_overloaded fs\\n then map (\\\\nm -> IEVar Nothing (to_ie_post_rn_var $ noLocA nm) Nothing) ns\\n else [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n where\\n\\n all_used avail_cs = all (`elem` cs) avail_cs\\n\\n all_non_overloaded = all (not . flIsOverloaded . recFieldLabel)\\n\\n combine :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\n combine = map merge . NE.groupAllWith getKey\\n\\n getKey :: LImportDecl GhcRn -> (Bool, Maybe ModuleName, ModuleName)\\n getKey decl =\\n ( isImportDeclQualified . ideclQualified $ idecl -- is this qualified? (important that this be first)\\n , unLoc <$> ideclAs idecl -- what is the qualifier (inside Maybe monad)\\n , unLoc . ideclName $ idecl -- Module Name\\n )\\n where\\n idecl :: ImportDecl GhcRn\\n idecl = unLoc decl\\n\\n merge :: NonEmpty (LImportDecl GhcRn) -> LImportDecl GhcRn\\n merge decls@((L l decl) :| _) = L l (decl { ideclImportList = Just (Exactly, lies) })\\n where lies = concatMap snd $ mapMaybe (ideclImportList . unLoc) $ NE.toList decls\\n\\nclassifyGREs :: [GlobalRdrElt] -> ([GlobalRdrElt], [FieldGlobalRdrElt])\\nclassifyGREs = partition (not . isRecFldGRE)\\n\\nprintMinimalImports :: HscSource -> [ImportDeclUsage] -> RnM ()\\n-- See Note [Printing minimal imports]\\nprintMinimalImports hsc_src imports_w_usage\\n = do { imports\' <- excludeGenerated <$> getMinimalImports imports_w_usage\\n ; this_mod <- getModule\\n ; dflags <- getDynFlags\\n ; liftIO $ withFile (mkFilename dflags this_mod) WriteMode $ \\\\h ->\\n printForUser dflags h neverQualify AllTheWay (vcat (map ppr imports\'))\\n -- The neverQualify is important. We are printing Names\\n -- but they are in the context of an \'import\' decl, and\\n -- we never qualify things inside there\\n -- E.g. import Blag( f, b )\\n -- not import Blag( Blag.f, Blag.g )!\\n }\\n where\\n mkFilename dflags this_mod\\n | Just d <- dumpDir dflags = d basefn\\n | otherwise = basefn\\n where\\n suffix = case hsc_src of\\n HsBootFile -> \\".imports-boot\\"\\n HsSrcFile -> \\".imports\\"\\n HsigFile -> \\".imports\\"\\n basefn = moduleNameString (moduleName this_mod) ++ suffix\\n\\n\\nto_ie_post_rn_var :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn_var (L l n)\\n | isDataOcc $ occName n = L l (IEPattern noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n\\n\\nto_ie_post_rn :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn (L l n)\\n | isTcOcc occ && isSymOcc occ = L l (IEType noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n where occ = occName n\\n\\n{- Note [Do not warn about Prelude hiding]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWe do not warn about\\n import Prelude hiding( x, y )\\nbecause even if nothing else from Prelude is used, it may be essential to hide\\nx,y to avoid name-shadowing warnings. Example (#9061)\\n import Prelude hiding( log )\\n f x = log where log = ()\\n\\nNote [Unused imports]\\n~~~~~~~~~~~~~~~~~~~~~\\nIn `warnUnusedImport`, if we see an import with an explicit list imports, thus\\n import M( a, b )\\nand neither `a` nor `b` is used, we report the entire import decl as unused. We\\ncheck this by looking at the names that it brings into scope scope; if there are\\nno ununused names, don\'t report.\\n\\n(UI1) We don\'t want to complain about `import M()`, because that is often used to bring\\n M\'s /instances/ into scope. That is neatly dealt with by the \\"no unused\\n names\\" (nor unused wildcard imports) criterion.\\n\\n(UI2) We don\'t report a decl as unused if it has an `as Rebindable` qualifier.\\n See (KN1) in Note [Overview of known entities] in GHC.Builtin\\n\\n\\nNote [Printing minimal imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nTo print the minimal imports we walk over all import decls (both user-supplied\\nand generated), trim their import lists, then filter out generated decls.\\n\\nNB that\\n\\n * We do *not* change the \'qualified\' or \'as\' parts!\\n\\n * We do not discard a decl altogether; we might need instances\\n from it. Instead we just trim to an empty import list\\n\\nNote [Partial export]\\n~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have\\n\\n module A( op ) where\\n class C a where\\n op :: a -> a\\n\\n module B where\\n import A\\n f = ..op...\\n\\nThen the minimal import for module B is\\n import A( op )\\nnot\\n import A( C( op ) )\\nwhich we would usually generate if C was exported from B. Hence\\nthe availExportsDecl test when deciding what to generate.\\n\\n\\nNote [Overloaded field import]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nOn the other hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n data T = MkT { foo :: Int }\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( T(foo) )\\nbecause when DuplicateRecordFields is enabled, field selectors are\\nnot in scope without their enclosing datatype.\\n\\nOn the third hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n pattern MkT { foo } = Just foo\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( foo )\\nbecause foo doesn\'t have a parent. This might actually be ambiguous if A\\nexports another field called foo, but there is no good answer to return and this\\nis a very obscure corner, so it seems to be the best we can do. See\\nDRFPatSynExport for a test of this.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Errors}\\n* *\\n************************************************************************\\n-}\\n\\nbadImportItemErr\\n :: ModIface -> ImpDeclSpec -> IE GhcPs\\n -> IsSubordinateError\\n -> [AvailInfo]\\n -> TcRn (NonEmpty ImportLookupReason)\\nbadImportItemErr iface decl_spec ie sub avails = do\\n exts <- importLookupExtensions\\n let import_lookup_bad :: BadImportKind -> ImportLookupReason\\n import_lookup_bad k = ImportLookupBad k iface decl_spec ie exts\\n dflags <- getDynFlags\\n hsc_env <- getTopEnv\\n let rdr_env = mkGlobalRdrEnv\\n $ gresFromAvails hsc_env (Just imp_spec) all_avails\\n pure $ fmap import_lookup_bad (importErrorKind dflags rdr_env)\\n where\\n importErrorKind :: DynFlags -> GlobalRdrEnv -> NonEmpty BadImportKind\\n importErrorKind dflags rdr_env\\n | any checkIfTyCon avails = case sub of\\n IsNotSubordinate -> NE.singleton BadImportAvailTyCon\\n IsSubordinateError { subordinate_err_parent = gre\\n , subordinate_err_unavailable = unavailable\\n , subordinate_err_nontype = nontype\\n , subordinate_err_nondata = nondata }\\n -> NE.fromList $ catMaybes $\\n [ fmap (BadImportNotExportedSubordinates gre) (NE.nonEmpty unavailable)\\n , fmap (BadImportNonTypeSubordinates gre) (NE.nonEmpty nontype)\\n , fmap (BadImportNonDataSubordinates gre) (NE.nonEmpty nondata) ]\\n | any checkIfVarName avails = NE.singleton BadImportAvailVar\\n | Just con <- find checkIfDataCon avails = NE.singleton (BadImportAvailDataCon (availOccName con))\\n | otherwise = NE.singleton (BadImportNotExported suggs)\\n where\\n suggs = similar_suggs ++ fieldSelectorSuggestions rdr_env rdr\\n what_look = case sub of\\n IsNotSubordinate -> WL_TyCon_or_TermVar\\n IsSubordinateError { subordinate_err_parent = gre } ->\\n case greInfo gre of\\n IAmTyCon ClassFlavour\\n -> WL_TyCon_or_TermVar\\n _ -> WL_Term\\n similar_names =\\n similarNameSuggestions (Unbound.LF what_look WL_Global)\\n dflags rdr_env emptyLocalRdrEnv rdr\\n similar_suggs =\\n case NE.nonEmpty $ mapMaybe imported_item $ similar_names of\\n Just similar -> [ SuggestSimilarNames rdr similar ]\\n Nothing -> [ ]\\n\\n -- Only keep imported items, and set the \\"HowInScope\\" to\\n -- \\"Nothing\\" to avoid printing \\"imported from...\\" in the suggestion\\n -- error message.\\n imported_item (SimilarRdrName rdr_name gre (Just (ImportedBy {})))\\n = Just (SimilarRdrName rdr_name gre Nothing)\\n imported_item _ = Nothing\\n\\n checkIfDataCon = checkIfAvailMatches isDataConName\\n checkIfTyCon = checkIfAvailMatches isTyConName\\n checkIfVarName =\\n \\\\case\\n AvailTC{} -> False\\n Avail n -> importedFS == occNameFS (occName n)\\n && (isVarOcc <||> isFieldOcc) (occName n)\\n checkIfAvailMatches namePred =\\n \\\\case\\n AvailTC _ ns ->\\n case find (\\\\n -> importedFS == occNameFS (occName n)) ns of\\n Just n -> namePred n\\n Nothing -> False\\n Avail{} -> False\\n availOccName = occName . availName\\n rdr = ieName ie\\n importedFS = occNameFS $ rdrNameOcc rdr\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n all_avails = mi_exports iface\\n\\nimportLookupExtensions :: TcRn ImportLookupExtensions\\nimportLookupExtensions = do\\n ile_pattern_synonyms <- xoptM LangExt.PatternSynonyms\\n ile_explicit_namespaces <- xoptM LangExt.ExplicitNamespaces\\n return ImportLookupExtensions{ile_pattern_synonyms, ile_explicit_namespaces}\\n\\naddDupDeclErr :: NonEmpty GlobalRdrElt -> TcRn ()\\naddDupDeclErr gres@(gre :| _)\\n -- Report the error at the later location\\n = addErrAt (getSrcSpan (NE.last sorted_names)) $ (TcRnDuplicateDecls (greOccName gre) sorted_names)\\n where\\n sorted_names =\\n NE.sortBy (SrcLoc.leftmost_smallest `on` nameSrcSpan)\\n (fmap greName gres)\\n\\n-- This data decl will parse OK\\n-- data T = a Int\\n-- treating \\"a\\" as the constructor.\\n-- It is really hard to make the parser spot this malformation.\\n-- So the renamer has to check that the constructor is legal\\n--\\n-- We can get an operator as the constructor, even in the prefix form:\\n-- data T = :% Int Int\\n-- from interface files, which always print in prefix form\\n--\\n-- We also allow type constructor names, which are defined by \\"type data\\"\\n-- declarations. See Note [Type data declarations] in GHC.Rename.Module.\\n\\ncheckConName :: RdrName -> TcRn ()\\ncheckConName name\\n = checkErr (isRdrDataCon name || isRdrTc name) (TcRnIllegalDataCon name)\\n", "filetypes": ["haskell"]}}}' 2026-10-16 14:46:50,909 - DEBUG - POST b'http://127.0.0.1:37093/receive_messages' {'content-type': 'application/json', 'x-ycm-hmac': b'Rga7Yd4l4fgfufwYw+0sxzurvznImlBO0MPmgAlS4EY='} b'{"filepath": "/home/enrico/ghc/compiler/GHC/Rename/Names.hs", "line_num": 1, "column_num": 1, "working_dir": "/home/enrico/ghc", "file_data": {"/home/enrico/ghc/compiler/GHC/Rename/Names.hs": {"contents": "{-\\n(c) The GRASP/AQUA Project, Glasgow University, 1992-1998\\n\\nExtracting imported and top-level names in scope\\n-}\\n\\n{-# LANGUAGE NondecreasingIndentation #-}\\n{-# LANGUAGE TypeFamilies #-}\\n\\nmodule GHC.Rename.Names (\\n rnImports, getLocalNonValBinders, newRecordFieldLabel,\\n importsFromIface,\\n ImportUserSpec(..),\\n extendGlobalRdrEnvRn,\\n gresFromAvails,\\n calculateAvails,\\n reportUnusedNames,\\n checkConName,\\n mkChildEnv,\\n findChildren,\\n mkBadExportSubordinate,\\n findImportUsage,\\n getMinimalImports,\\n printMinimalImports,\\n renamePkgQual, renameRawPkgQual,\\n classifyGREs,\\n ImportDeclUsage,\\n rnNamespaceSpecifier\\n ) where\\n\\nimport GHC.Prelude hiding ( head, init, last, tail )\\n\\nimport GHC.Driver.Env\\nimport GHC.Driver.Session\\nimport GHC.Driver.Ppr\\n\\nimport GHC.Rename.Env\\nimport GHC.Rename.Fixity\\nimport GHC.Rename.Utils ( warnUnusedTopBinds )\\nimport GHC.Rename.Unbound\\nimport qualified GHC.Rename.Unbound as Unbound\\n\\nimport GHC.Tc.Errors.Types\\nimport GHC.Tc.Utils.Env\\nimport GHC.Tc.Utils.Monad\\nimport GHC.Tc.Types.LclEnv\\nimport GHC.Tc.Zonk.TcType ( tcInitTidyEnv )\\n\\nimport GHC.Hs\\nimport GHC.Iface.Load ( loadSrcInterface, loadSrcInterface_maybe )\\nimport GHC.Iface.Errors.Types\\n ( IfaceMessage(..), MissingInterfaceError, InterfaceLookingFor(..)\\n , LoadEssentialsReason(..) )\\nimport GHC.Iface.Syntax ( fromIfaceWarnings )\\nimport GHC.Builtin.Modules( pRELUDE_NAME, rEBINDABLE_MOD_NAME )\\nimport GHC.Parser.PostProcess ( setRdrNameSpace )\\nimport GHC.Core.TyCo.Tidy\\nimport GHC.Core.PatSyn\\nimport GHC.Core.TyCon ( TyCon, tyConName )\\nimport qualified GHC.LanguageExtensions as LangExt\\n\\nimport GHC.Utils.Outputable as Outputable\\nimport GHC.Utils.Misc as Utils\\nimport GHC.Utils.Panic\\n\\nimport GHC.Types.Fixity.Env\\nimport GHC.Types.SafeHaskell\\nimport GHC.Types.Name\\nimport GHC.Types.Name.Env\\nimport GHC.Types.Name.Set\\nimport GHC.Types.Name.Reader\\nimport GHC.Types.Avail\\nimport GHC.Types.FieldLabel\\nimport GHC.Types.Hint\\nimport GHC.Types.SourceFile\\nimport GHC.Types.SrcLoc as SrcLoc\\nimport GHC.Types.Basic (TyConFlavour (..), convImportLevel, VisArity)\\nimport GHC.Types.UnresolvedImport\\nimport GHC.Types.Id\\nimport GHC.Types.PkgQual\\nimport GHC.Types.GREInfo (ConInfo(..), ConFieldInfo (..), ConLikeInfo (ConIsData))\\n\\nimport GHC.Unit\\nimport GHC.Unit.Module.Warnings\\nimport GHC.Unit.Module.ModIface\\nimport GHC.Unit.Module.Imported\\nimport GHC.Unit.Module.Deps\\nimport GHC.Unit.Env\\n\\nimport GHC.Data.Bag\\nimport GHC.Data.FastString\\nimport GHC.Data.FastString.Env\\nimport GHC.Data.Maybe\\nimport GHC.Data.List.SetOps ( removeDups )\\n\\nimport Control.Arrow ( second )\\nimport Control.Monad\\nimport Data.Foldable ( for_ )\\nimport Data.IntMap ( IntMap )\\nimport qualified Data.IntMap as IntMap\\nimport Data.Map ( Map )\\nimport qualified Data.Map as Map\\nimport Data.Ord ( comparing )\\nimport Data.Semigroup ( Any(..) )\\nimport qualified Data.Semigroup as S\\nimport Data.List ( partition, find, sortBy )\\nimport Data.List.NonEmpty (NonEmpty(..))\\nimport qualified Data.List.NonEmpty as NE\\nimport Data.Function ( on )\\nimport qualified Data.Set as S\\nimport System.FilePath (())\\nimport System.IO\\n\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{rnImports}\\n* *\\n************************************************************************\\n\\nNote [Tracking Trust Transitively]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen we import a package as well as checking that the direct imports are safe\\naccording to the rules outlined in the Note [Safe Haskell Trust Check] in GHC.Driver.Main\\nwe must also check that these rules hold transitively for all dependent modules\\nand packages. Doing this without caching any trust information would be very\\nslow as we would need to touch all packages and interface files a module depends\\non. To avoid this we make use of the property that if a modules Safe Haskell\\nmode changes, this triggers a recompilation from that module in the dependency\\ngraph. So we can just worry mostly about direct imports.\\n\\nThere is one trust property that can change for a package though without\\nrecompilation being triggered: package trust. So we must check that all\\npackages a module transitively depends on to be trusted are still trusted when\\nwe are compiling this module (as due to recompilation avoidance some modules\\nbelow may not be considered trusted any more without recompilation being\\ntriggered).\\n\\nWe handle this by augmenting the existing transitive list of packages a module M\\ndepends on with a bool for each package that says if it must be trusted when the\\nmodule M is being checked for trust. This list of trust required packages for a\\nsingle import is gathered in the rnImportDecl function and stored in an\\nImportAvails data structure. The union of these trust required packages for all\\nimports is done by the rnImports function using the combine function which calls\\nthe plusImportAvails function that is a union operation for the ImportAvails\\ntype. This gives us in an ImportAvails structure all packages required to be\\ntrusted for the module we are currently compiling. Checking that these packages\\nare still trusted (and that direct imports are trusted) is done in\\nGHC.Driver.Main.checkSafeImports.\\n\\nSee the note below, [Trust Own Package] for a corner case in this method and\\nhow its handled.\\n\\n\\nNote [Trust Own Package]\\n~~~~~~~~~~~~~~~~~~~~~~~~\\nThere is a corner case of package trust checking that the usual transitive check\\ndoesn\'t cover. (For how the usual check operates see the Note [Tracking Trust\\nTransitively] below). The case is when you import a -XSafe module M and M\\nimports a -XTrustworthy module N. If N resides in a different package than M,\\nthen the usual check works as M will record a package dependency on N\'s package\\nand mark it as required to be trusted. If N resides in the same package as M\\nthough, then importing M should require its own package be trusted due to N\\n(since M is -XSafe so doesn\'t create this requirement by itself). The usual\\ncheck fails as a module doesn\'t record a package dependency of its own package.\\nSo instead we now have a bool field in a modules interface file that simply\\nstates if the module requires its own package to be trusted. This field avoids\\nus having to load all interface files that the module depends on to see if one\\nis trustworthy.\\n\\n\\nNote [Trust Transitive Property]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSo there is an interesting design question in regards to transitive trust\\nchecking. Say I have a module B compiled with -XSafe. B is dependent on a bunch\\nof modules and packages, some packages it requires to be trusted as its using\\n-XTrustworthy modules from them. Now if I have a module A that doesn\'t use safe\\nhaskell at all and simply imports B, should A inherit all the trust\\nrequirements from B? Should A now also require that a package p is trusted since\\nB required it?\\n\\nWe currently say no but saying yes also makes sense. The difference is, if a\\nmodule M that doesn\'t use Safe Haskell imports a module N that does, should all\\nthe trusted package requirements be dropped since M didn\'t declare that it cares\\nabout Safe Haskell (so -XSafe is more strongly associated with the module doing\\nthe importing) or should it be done still since the author of the module N that\\nuses Safe Haskell said they cared (so -XSafe is more strongly associated with\\nthe module that was compiled that used it).\\n\\nGoing with yes is a simpler semantics we think and harder for the user to stuff\\nup but it does mean that Safe Haskell will affect users who don\'t care about\\nSafe Haskell as they might grab a package from Cabal which uses safe haskell (say\\nnetwork) and that packages imports -XTrustworthy modules from another package\\n(say bytestring), so requires that package is trusted. The user may now get\\ncompilation errors in code that doesn\'t do anything with Safe Haskell simply\\nbecause they are using the network package. They will have to call \'ghc-pkg\\ntrust network\' to get everything working. Due to this invasive nature of going\\nwith yes we have gone with no for now.\\n-}\\n\\n-- | Process Import Decls. See \'rnImportDecl\' for a description of what\\n-- the return types represent.\\n-- Note: Do the non SOURCE ones first, so that we get a helpful warning\\n-- for SOURCE ones that are unnecessary\\nrnImports :: [(LImportDecl GhcPs, SDoc)]\\n -> RnM ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\nrnImports imports = do\\n tcg_env <- getGblEnv\\n -- NB: want an identity module here, because it\'s OK for a signature\\n -- module to import from its implementor\\n let this_mod = tcg_mod tcg_env\\n let (source, ordinary) = partition (is_source_import . fst) imports\\n is_source_import (d::LImportDecl GhcPs) = ideclSource (unLoc d) == IsBoot\\n stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary\\n stuff2 <- mapAndReportM (rnImportDecl this_mod) source\\n -- Safe Haskell: See Note [Tracking Trust Transitively]\\n let (decls, imp_user_spec, rdr_env, imp_avails) = combine (stuff1 ++ stuff2)\\n -- Update imp_boot_mods if imp_direct_mods mentions any of them\\n let merged_import_avail = clobberSourceImports imp_avails\\n return (decls, imp_user_spec, rdr_env, merged_import_avail)\\n\\n where\\n clobberSourceImports imp_avails =\\n imp_avails { imp_boot_mods = imp_boot_mods\' }\\n where\\n imp_boot_mods\' = mergeInstalledModuleEnv combJ id (const emptyInstalledModuleEnv)\\n (imp_boot_mods imp_avails)\\n (imp_direct_dep_mods imp_avails)\\n\\n combJ (GWIB _ IsBoot) (_, x) = Just x\\n combJ r _ = Just r\\n -- See Note [Combining ImportAvails]\\n combine :: [(LImportDecl GhcRn, ImportUserSpec, GlobalRdrEnv, ImportAvails)]\\n -> ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\n combine ss =\\n let (decls, imp_user_spec, rdr_env, imp_avails, finsts) = foldr\\n plus\\n ([], [], emptyGlobalRdrEnv, emptyImportAvails, emptyModuleSet)\\n ss\\n in (decls, imp_user_spec, rdr_env, imp_avails { imp_finsts = moduleSetElts finsts })\\n\\n plus (decl, us, gbl_env1, imp_avails1)\\n (decls, uss, gbl_env2, imp_avails2, finsts_set)\\n = ( decl:decls,\\n us:uss,\\n gbl_env1 `plusGlobalRdrEnv` gbl_env2,\\n imp_avails1\' `plusImportAvails` imp_avails2,\\n extendModuleSetList finsts_set new_finsts )\\n where\\n imp_avails1\' = imp_avails1 { imp_finsts = [] }\\n new_finsts = imp_finsts imp_avails1\\n\\n{-\\nNote [Combining ImportAvails]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nimp_finsts in ImportAvails is a list of family instance modules\\ntransitively depended on by an import. imp_finsts for a currently\\ncompiled module is a union of all the imp_finsts of imports.\\nComputing the union of two lists of size N is O(N^2) and if we\\ndo it to M imports we end up with O(M*N^2). That can get very\\nexpensive for bigger module hierarchies.\\n\\nUnion can be optimized to O(N log N) if we use a Set.\\nimp_finsts is converted back and forth between dep_finsts, so\\nchanging a type of imp_finsts means either paying for the conversions\\nor changing the type of dep_finsts as well.\\n\\nI\'ve measured that the conversions would cost 20% of allocations on my\\ntest case, so that can be ruled out.\\n\\nChanging the type of dep_finsts forces checkFamInsts to\\nget the module lists in non-deterministic order. If we wanted to restore\\nthe deterministic order, we\'d have to sort there, which is an additional\\ncost. As far as I can tell, using a non-deterministic order is fine there,\\nbut that\'s a brittle nonlocal property which I\'d like to avoid.\\n\\nAdditionally, dep_finsts is read from an interface file, so its \\"natural\\"\\ntype is a list. Which makes it a natural type for imp_finsts.\\n\\nSince rnImports.combine is really the only place that would benefit from\\nit being a Set, it makes sense to optimize the hot loop in rnImports.combine\\nwithout changing the representation.\\n\\nSo here\'s what we do: instead of naively merging ImportAvails with\\nplusImportAvails in a loop, we make plusImportAvails merge empty imp_finsts\\nand compute the union on the side using Sets. When we\'re done, we can\\nconvert it back to a list. One nice side effect of this approach is that\\nif there\'s a lot of overlap in the imp_finsts of imports, the\\nSet doesn\'t really need to grow and we don\'t need to allocate.\\n\\nRunning generateModules from #14693 with DEPTH=16, WIDTH=30 finishes in\\n23s before, and 11s after.\\n-}\\n\\n-- | Given a located import declaration @decl@ from @this_mod@,\\n-- calculate the following pieces of information:\\n--\\n-- 1. An updated \'LImportDecl\', where all unresolved \'RdrName\' in\\n-- the entity lists have been resolved into \'Name\'s,\\n--\\n-- 2. A \'GlobalRdrEnv\' representing the new identifiers that were\\n-- brought into scope (taking into account module qualification\\n-- and hiding),\\n--\\n-- 3. \'ImportAvails\' summarizing the identifiers that were imported\\n-- by this declaration, and\\n--\\n-- 4. A boolean \'AnyHpcUsage\' which is true if the imported module\\n-- used HPC.\\nrnImportDecl :: Module -> (LImportDecl GhcPs, SDoc)\\n -> RnM (LImportDecl GhcRn, ImportUserSpec , GlobalRdrEnv, ImportAvails)\\nrnImportDecl this_mod\\n (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name\\n , ideclPkgQual = raw_pkg_qual\\n , ideclSource = want_boot\\n , ideclSafe = mod_safe\\n , ideclLevelSpec = import_level\\n , ideclQualified = qual_style\\n , ideclExt = XImportDeclPass { ideclOrigin = origin }\\n , ideclAs = as_mod, ideclImportList = imp_details }), import_reason)\\n = setSrcSpanA loc $ do\\n\\n case raw_pkg_qual of\\n NoRawPkgQual -> pure ()\\n RawPkgQual {} -> do\\n pkg_imports <- xoptM LangExt.PackageImports\\n when (not pkg_imports) $ addErr TcRnPackageImportsDisabled\\n\\n let qual_only = isImportDeclQualified qual_style\\n generated = isGeneratedImport origin\\n\\n lookup_scope = importDeclLookupScope origin\\n\\n -- If there\'s an error in loadInterface, (e.g. interface\\n -- file not found) we get lots of spurious errors from \'filterImports\'\\n let imp_mod_name = unLoc loc_imp_mod_name\\n doc = ppr imp_mod_name <+> import_reason\\n\\n hsc_env <- getTopEnv\\n unit_env <- hsc_unit_env <$> getTopEnv\\n let pkg_qual = renameRawPkgQual unit_env imp_mod_name raw_pkg_qual\\n\\n -- Check for self-import, which confuses the typechecker (#9032)\\n -- ghc --make rejects self-import cycles already, but batch-mode may not\\n -- at least not until GHC.IfaceToCore.tcHiBootIface, which is too late to avoid\\n -- typechecker crashes. (Indirect self imports are not caught until\\n -- GHC.IfaceToCore, see #10337 tracking how to make this error better.)\\n --\\n -- Originally, we also allowed \'import {-# SOURCE #-} M\', but this\\n -- caused bug #10182: in one-shot mode, we should never load an hs-boot\\n -- file for the module we are compiling into the EPS. In principle,\\n -- it should be possible to support this mode of use, but we would have to\\n -- extend Provenance to support a local definition in a qualified location.\\n -- For now, we don\'t support it, but see #10336\\n when (imp_mod_name == moduleName this_mod &&\\n (case pkg_qual of -- If we have import \\"\\" M, then we should\\n -- check that \\"\\" is \\"this\\" (which is magic)\\n -- or the name of this_mod\'s package. Yurgh!\\n -- c.f. GHC.findModule, and #9997\\n NoPkgQual -> True\\n ThisPkg uid -> uid == homeUnitId_ (hsc_dflags hsc_env)\\n OtherPkg _ -> False))\\n (addErr (TcRnSelfImport imp_mod_name))\\n\\n -- Check for a missing import list (Opt_WarnMissingImportList also\\n -- checks for T(..) items but that is done in checkDodgyImport below)\\n case imp_details of\\n Just (Exactly, _) -> return () -- Explicit import list\\n _ | generated -> return () -- Do not bleat for generated imports\\n | qual_only -> return ()\\n | otherwise -> addDiagnostic (TcRnNoExplicitImportList imp_mod_name)\\n\\n\\n mb_iface <- loadSrcInterface_maybe doc lookup_scope imp_mod_name want_boot pkg_qual\\n iface <- case mb_iface of\\n Succeeded iface -> return iface\\n Failed err -> failWithTc $\\n importDeclLoadFailure origin imp_mod_name want_boot err\\n\\n -- Compiler sanity check: if the import didn\'t say\\n -- {-# SOURCE #-} we should not get a hi-boot file\\n warnPprTrace ((want_boot == NotBoot) && (mi_boot iface == IsBoot)) \\"rnImportDecl\\" (ppr imp_mod_name) $ do\\n\\n -- Issue a user warning for a redundant {- SOURCE -} import\\n -- NB that we arrange to read all the ordinary imports before\\n -- any of the {- SOURCE -} imports.\\n --\\n -- in --make and GHCi, the compilation manager checks for this,\\n -- and indeed we shouldn\'t do it here because the existence of\\n -- the non-boot module depends on the compilation order, which\\n -- is not deterministic. The hs-boot test can show this up.\\n dflags <- getDynFlags\\n warnIf ((want_boot == IsBoot) && (mi_boot iface == NotBoot) && isOneShot (ghcMode dflags))\\n (TcRnRedundantSourceImport imp_mod_name)\\n when (mod_safe && not (safeImportsOn dflags)) $\\n addErr (TcRnSafeImportsDisabled imp_mod_name)\\n\\n let imp_mod = mi_module iface\\n qual_mod_name = fmap unLoc as_mod `orElse` imp_mod_name\\n imp_spec = ImpDeclSpec { is_mod = imp_mod, is_qual = qual_only,\\n is_dloc = locA loc, is_as = qual_mod_name,\\n is_pkg_qual = pkg_qual, is_isboot = want_boot,\\n is_level = convImportLevel import_level }\\n\\n let filter_imports = do\\n -- filter the imports according to the import declaration\\n (new_imp_details, imp_user_list, gbl_env)\\n <- filterImports hsc_env iface imp_spec imp_details\\n -- for certain error messages, we\\u2019d like to know what could be\\n -- imported here, if everything were imported\\n potential_gres <- (\\\\(_,_,x) -> x) <$> filterImports hsc_env iface imp_spec Nothing\\n return (new_imp_details, imp_user_list, gbl_env, potential_gres)\\n\\n (new_imp_details, imp_user_list, gbl_env, potential_gres) <-\\n case origin of\\n ImplicitEssentialsImport ->\\n -- The implicit GHC.Essentials import does not bring anything into scope.\\n -- See Note [Finding GHC.Essentials] in GHC.Builtin.\\n return (Nothing, ImpUserDependOnly, emptyGlobalRdrEnv, emptyGlobalRdrEnv)\\n UserWrittenImport -> filter_imports\\n ImplicitPreludeImport -> filter_imports\\n PluginImport -> filter_imports\\n\\n let is_hiding | Just (EverythingBut,_) <- imp_details = True\\n | otherwise = False\\n\\n -- should the import be safe?\\n mod_safe\' = mod_safe\\n || (not generated && safeDirectImpsReq dflags)\\n || (generated && safeImplicitImpsReq dflags)\\n\\n hsc_env <- getTopEnv\\n let home_unit = hsc_home_unit hsc_env\\n other_home_units = hsc_all_home_unit_ids hsc_env\\n\\n imported_by\\n | isDependOnlyImport imp_user_list\\n = ImportedBySystem\\n | otherwise\\n = ImportedByUser $ ImportedModsVal\\n { imv_name = is_as imp_spec\\n , imv_span = locA loc\\n , imv_is_safe = mod_safe\'\\n , imv_is_hiding = is_hiding\\n , imv_all_exports = potential_gres\\n , imv_qualified = qual_only\\n , imv_is_level = convImportLevel import_level\\n }\\n imports = calculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by\\n\\n -- Complain if we import a deprecated module\\n case fromIfaceWarnings (mi_warns iface) of\\n WarnAll txt -> addDiagnostic (TcRnDeprecatedModule imp_mod_name txt)\\n _ -> return ()\\n\\n let new_imp_decl = ImportDecl\\n { ideclExt = ideclExt decl\\n , ideclName = ideclName decl\\n , ideclPkgQual = pkg_qual\\n , ideclSource = ideclSource decl\\n , ideclSafe = mod_safe\'\\n , ideclQualified = ideclQualified decl\\n , ideclAs = ideclAs decl\\n , ideclImportList = new_imp_details\\n , ideclLevelSpec = ideclLevelSpec decl\\n }\\n\\n return (L loc new_imp_decl, ImpUserSpec imp_spec imp_user_list, gbl_env, imports)\\n\\n-- | The error message to emit when we failed to load an interface.\\nimportDeclLoadFailure :: ImportDeclOrigin -> ModuleName -> IsBootInterface\\n -> MissingInterfaceError -> TcRnMessage\\nimportDeclLoadFailure ImplicitEssentialsImport _ _ err\\n = TcRnInterfaceError $ CantFindEssentials err LookingForEssentialsModule\\nimportDeclLoadFailure _ mod_name want_boot err\\n = TcRnInterfaceError $ Can\'tFindInterface err $ LookingForModule mod_name want_boot\\n\\n-- | Rename raw package imports\\nrenameRawPkgQual :: UnitEnv -> ModuleName -> RawPkgQual -> PkgQual\\nrenameRawPkgQual unit_env mn = \\\\case\\n NoRawPkgQual -> NoPkgQual\\n RawPkgQual _ fs -> renamePkgQual unit_env mn $ Just fs\\n\\n-- | Rename raw package imports\\nrenamePkgQual :: UnitEnv -> ModuleName -> Maybe FastString -> PkgQual\\nrenamePkgQual unit_env mn mb_pkg = case mb_pkg of\\n Nothing -> NoPkgQual\\n Just pkg_fs\\n | Just uid <- homeUnitId <$> ue_homeUnit unit_env\\n , pkg_fs == fsLit \\"this\\"\\n -> ThisPkg uid\\n\\n | Just (uid, _) <- find (fromMaybe False . fmap (== pkg_fs) . snd) home_names\\n -> ThisPkg uid\\n\\n | Just uid <- resolvePackageImport unit_state mn (PackageName pkg_fs)\\n -> OtherPkg uid\\n\\n | otherwise\\n -> OtherPkg (UnitId pkg_fs)\\n -- not really correct as pkg_fs is unlikely to be a valid unit-id but\\n -- we will report the failure later...\\n where\\n home_names =\\n [ (uid, mkFastString <$> thisPackageName (homeUnitEnv_dflags (ue_findHomeUnitEnv uid unit_env)))\\n | uid <- S.toList hpt_deps\\n ]\\n\\n unit_state = ue_homeUnitState unit_env\\n\\n hpt_deps :: S.Set UnitId\\n hpt_deps = homeUnitDepends unit_state\\n\\n\\n-- | Calculate the \'ImportAvails\' induced by an import of a particular\\n-- interface, but without \'imp_mods\'.\\ncalculateAvails :: HomeUnit\\n -> S.Set UnitId\\n -> ModIface\\n -> IsSafeImport\\n -> IsBootInterface\\n -> ImportedBy\\n -> ImportAvails\\ncalculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by =\\n let imp_mod = mi_module iface\\n imp_sem_mod= mi_semantic_module iface\\n orph_iface = mi_orphan iface\\n has_finsts = mi_finsts iface\\n deps = mi_deps iface\\n trust = getSafeMode $ mi_trust iface\\n trust_pkg = mi_trust_pkg iface\\n is_sig = mi_hsc_src iface == HsigFile\\n\\n -- If the module exports anything defined in this module, just\\n -- ignore it. Reason: otherwise it looks as if there are two\\n -- local definition sites for the thing, and an error gets\\n -- reported. Easiest thing is just to filter them out up\\n -- front. This situation only arises if a module imports\\n -- itself, or another module that imported it. (Necessarily,\\n -- this involves a loop.)\\n --\\n -- We do this *after* filterImports, so that if you say\\n -- module A where\\n -- import B( AType )\\n -- type AType = ...\\n --\\n -- module B( AType ) where\\n -- import {-# SOURCE #-} A( AType )\\n --\\n -- then you won\'t get a \'B does not export AType\' message.\\n\\n\\n -- Compute new transitive dependencies\\n --\\n -- \'dep_orphs\' and \'dep_finsts\' do NOT include the imported module\\n -- itself, but we DO need to include this module in \'imp_orphs\' and\\n -- \'imp_finsts\' if it defines an orphan or instance family; thus the\\n -- orph_iface/has_iface tests.\\n\\n deporphs = dep_orphs deps\\n depfinsts = dep_finsts deps\\n\\n orphans | orph_iface = assertPpr (not (imp_sem_mod `elem` deporphs)) (ppr imp_sem_mod <+> ppr deporphs) $\\n imp_sem_mod : deporphs\\n | otherwise = deporphs\\n\\n finsts | has_finsts = assertPpr (not (imp_sem_mod `elem` depfinsts)) (ppr imp_sem_mod <+> ppr depfinsts) $\\n imp_sem_mod : depfinsts\\n | otherwise = depfinsts\\n\\n -- Trusted packages are a lot like orphans.\\n trusted_pkgs | mod_safe\' = dep_trusted_pkgs deps\\n | otherwise = S.empty\\n\\n\\n pkg = moduleUnit (mi_module iface)\\n ipkg = toUnitId pkg\\n\\n -- Does this import mean we now require our own pkg\\n -- to be trusted? See Note [Trust Own Package]\\n ptrust = trust == Sf_Trustworthy || trust_pkg\\n pkg_trust_req\\n | isHomeUnit home_unit pkg = ptrust\\n | otherwise = False\\n\\n dependent_pkgs = if toUnitId pkg `S.member` other_home_units\\n then S.empty\\n else S.singleton (lvl, ipkg)\\n\\n lvl = case imported_by of\\n ImportedByUser imv -> imv_is_level imv\\n ImportedBySystem -> NormalLevel\\n\\n\\n direct_mods = if toUnitId pkg `S.member` other_home_units\\n then mkPlusModDeps (moduleUnitId imp_mod) lvl (GWIB (moduleName imp_mod) want_boot)\\n else emptyInstalledModuleEnv\\n\\n dep_boot_mods_map = mkModDeps (dep_boot_mods deps)\\n\\n\\n boot_mods\\n -- If we are looking for a boot module, it must be HPT\\n | IsBoot <- want_boot = extendInstalledModuleEnv dep_boot_mods_map (toUnitId <$> imp_mod) (GWIB (moduleName imp_mod) IsBoot)\\n -- Now we are importing A properly, so don\'t go looking for\\n -- A.hs-boot\\n | isHomeUnit home_unit pkg = dep_boot_mods_map\\n -- There\'s no boot files to find in external imports\\n | otherwise = emptyInstalledModuleEnv\\n\\n sig_mods =\\n if is_sig\\n then moduleName imp_mod : dep_sig_mods deps\\n else dep_sig_mods deps\\n\\n\\n in ImportAvails {\\n imp_mods = Map.singleton (mi_module iface) [imported_by],\\n imp_orphs = orphans,\\n imp_finsts = finsts,\\n imp_sig_mods = sig_mods,\\n imp_direct_dep_mods = direct_mods,\\n imp_dep_direct_pkgs = dependent_pkgs,\\n imp_boot_mods = boot_mods,\\n\\n -- Add in the imported modules trusted package\\n -- requirements. ONLY do this though if we import the\\n -- module as a safe import.\\n -- See Note [Tracking Trust Transitively]\\n -- and Note [Trust Transitive Property]\\n imp_trust_pkgs = trusted_pkgs,\\n -- Do we require our own pkg to be trusted?\\n -- See Note [Trust Own Package]\\n imp_trust_own_pkg = pkg_trust_req\\n }\\n\\nmkPlusModDeps :: UnitId -> ImportLevel -> ModuleNameWithIsBoot\\n -> InstalledModuleEnv (S.Set ImportLevel, ModuleNameWithIsBoot)\\nmkPlusModDeps uid st elt = extendInstalledModuleEnv emptyInstalledModuleEnv (mkModule uid (gwib_mod elt)) (S.singleton st, elt)\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{importsFromLocalDecls}\\n* *\\n************************************************************************\\n\\nFrom the top-level declarations of this module produce\\n * the lexical environment\\n * the ImportAvails\\ncreated by its bindings.\\n\\nNote [Top-level Names in Template Haskell decl quotes]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSee also: Note [Interactively-bound Ids in GHCi] in GHC.Driver.Env\\n Note [Looking up Exact RdrNames] in GHC.Rename.Env\\n\\nConsider a Template Haskell declaration quotation like this:\\n module M where\\n f x = h [d| f = 3 |]\\nWhen renaming the declarations inside [d| ...|], we treat the\\ntop level binders specially in two ways\\n\\n1. We give them an Internal Name, not (as usual) an External one.\\n This is done by GHC.Rename.Env.newTopSrcBinder.\\n\\n2. We make them *shadow* the outer bindings.\\n See Note [GlobalRdrEnv shadowing]\\n\\n3. We find out whether we are inside a [d| ... |] by testing the TH\\n level. This is a slight hack, because the level field was really\\n meant for the type checker, and here we are not interested in the\\n fields of Brack, hence the error thunks in thRnBrack.\\n-}\\n\\nextendGlobalRdrEnvRn :: [GlobalRdrElt]\\n -> MiniFixityEnv\\n -> RnM (TcGblEnv, TcLclEnv)\\n-- Updates both the GlobalRdrEnv and the FixityEnv\\n-- We return a new TcLclEnv only because we might have to\\n-- delete some bindings from it;\\n-- see Note [Top-level Names in Template Haskell decl quotes]\\n\\nextendGlobalRdrEnvRn new_gres new_fixities\\n = checkNoErrs $ -- See Note [Fail fast on duplicate definitions]\\n do { (gbl_env, lcl_env) <- getEnvs\\n ; level <- getThLevel\\n ; isGHCi <- getIsGHCi\\n ; let rdr_env = tcg_rdr_env gbl_env\\n fix_env = tcg_fix_env gbl_env\\n th_bndrs = getLclEnvThBndrs lcl_env\\n th_lvl = thLevelIndex level\\n\\n -- Delete new_occs from global and local envs\\n -- If we are in a TemplateHaskell decl bracket,\\n -- we are going to shadow them\\n -- See Note [GlobalRdrEnv shadowing]\\n inBracket = isBrackLevel level\\n\\n lcl_env_TH = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_rdr = minusLocalRdrEnv (tcl_rdr lcl_env) new_gres_env }) lcl_env\\n -- See Note [GlobalRdrEnv shadowing]\\n\\n lcl_env2 | inBracket = lcl_env_TH\\n | otherwise = lcl_env\\n\\n -- Deal with shadowing: see Note [GlobalRdrEnv shadowing]\\n want_shadowing = isGHCi || inBracket\\n rdr_env1 | want_shadowing = shadowNames False rdr_env new_gres_env\\n | otherwise = rdr_env\\n\\n lcl_env3 = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_th_bndrs = extendNameEnvList th_bndrs\\n [ ( n, (TopLevel, th_lvl) )\\n | n <- new_names ] }) lcl_env2\\n\\n ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres\\n\\n ; let fix_env\' = foldl\' extend_fix_env fix_env new_gres\\n gbl_env\' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env\' }\\n\\n ; traceRn \\"extendGlobalRdrEnvRn 2\\" (pprGlobalRdrEnv True rdr_env2)\\n ; return (gbl_env\', lcl_env3) }\\n where\\n new_names = map greName new_gres\\n new_gres_env = mkGlobalRdrEnv new_gres\\n\\n -- If there is a fixity decl for the gre, add it to the fixity env\\n extend_fix_env fix_env gre\\n | Just (L _ fi) <- lookupMiniFixityEnv new_fixities name\\n = extendNameEnv fix_env name (FixItem occ fi)\\n | otherwise\\n = fix_env\\n where\\n name = greName gre\\n occ = greOccName gre\\n\\n add_gre :: GlobalRdrEnv -> GlobalRdrElt -> RnM GlobalRdrEnv\\n -- Extend the GlobalRdrEnv with a LocalDef GRE\\n -- If there is already a LocalDef GRE with the same OccName,\\n -- report an error and discard the new GRE\\n -- This establishes INVARIANT 1 of GlobalRdrEnvs\\n add_gre env gre\\n | not (null dups) -- Same OccName defined twice\\n = do { addDupDeclErr (gre :| dups); return env }\\n\\n | otherwise\\n = return (extendGlobalRdrEnv env gre)\\n where\\n -- See Note [Reporting duplicate local declarations]\\n dups = filter isBadDupGRE\\n $ lookupGRE env (LookupOccName (greOccName gre) (RelevantGREsFOS WantBoth))\\n isBadDupGRE old_gre = isLocalGRE old_gre && greClashesWith gre old_gre\\n\\n{- Note [Fail fast on duplicate definitions]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIf there are duplicate bindings for the same thing, we want to fail\\nfast. Having two bindings for the same thing can cause follow-on errors.\\nExample (test T9975a):\\n data Test = Test { x :: Int }\\n pattern Test wat = Test { x = wat }\\nThis defines \'Test\' twice. The second defn has no field-names; and then\\nwe get an error from Test { x=wat }, saying \\"Test has no field \'x\'\\".\\n\\nEasiest thing is to bale out fast on duplicate definitions, which\\nwe do via `checkNoErrs` on `extendGlobalRdrEnvRn`.\\n\\nNote [Reporting duplicate local declarations]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn general, a single module may not define the same OccName multiple times. This\\nis checked in extendGlobalRdrEnvRn: when adding a new locally-defined GRE to the\\nGlobalRdrEnv we report an error if there are already duplicates in the\\nenvironment. This establishes INVARIANT 1 (see comments on GlobalRdrEnv in\\nGHC.Types.Name.Reader), which says that for a given OccName, all the\\nGlobalRdrElts to which it maps must have distinct \'greName\'s.\\n\\nFor example, the following will be rejected:\\n\\n f x = x\\n g x = x\\n f x = x -- Duplicate!\\n\\nUsers are allowed to introduce new GREs with the same OccName as an imported GRE,\\nas disambiguation is possible through the module system, e.g.:\\n\\n module M where\\n import N (f)\\n f x = x\\n g x = M.f x + N.f x\\n\\nIf both GREs are local, the general rule is that two GREs clash if they have\\nthe same OccName, i.e. they share a textual name and live in the same namespace.\\nHowever, there are additional clashes due to record fields:\\n\\n - a new variable clashes with previously defined record fields\\n which define field selectors,\\n\\n - a new record field shadows:\\n\\n - previously defined variables, if it defines a field selector,\\n - previously defined record fields, unless it is a duplicate record field.\\n\\nThis logic is implemented in the function \'GHC.Types.Name.Reader.greClashesWith\'.\\n\\nSee also Note [Skipping ambiguity errors at use sites of local declarations] in\\nGHC.Rename.Utils.\\n-}\\n\\n\\n{- *********************************************************************\\n* *\\n getLocalDeclBindersd@ returns the names for an HsDecl\\n It\'s used for source code.\\n\\n *** See Note [The Naming story] in GHC.Hs.Decls ****\\n* *\\n********************************************************************* -}\\n\\ngetLocalNonValBinders :: MiniFixityEnv -> HsGroup GhcPs\\n -> RnM ((TcGblEnv, TcLclEnv), NameSet)\\n-- Get all the top-level binders bound the group *except*\\n-- for value bindings, which are treated separately\\n-- Specifically we return AvailInfo for\\n-- * type decls (incl constructors and record selectors)\\n-- * class decls (including class ops)\\n-- * associated types\\n-- * foreign imports\\n-- * value signatures (in hs-boot files only)\\n\\ngetLocalNonValBinders fixity_env\\n (HsGroup { hs_valds = binds,\\n hs_tyclds = tycl_decls,\\n hs_fords = foreign_decls })\\n = do { -- Process all type/class decls *except* family instances\\n ; let inst_decls = tycl_decls >>= group_instds\\n ; dup_fields_ok <- xopt_DuplicateRecordFields <$> getDynFlags\\n ; has_sel <- xopt_FieldSelectors <$> getDynFlags\\n ; tc_gres\\n <- concatMapM\\n (new_tc dup_fields_ok has_sel)\\n (tyClGroupTyClDecls tycl_decls)\\n ; traceRn \\"getLocalNonValBinders 1\\" (ppr tc_gres)\\n ; envs <- extendGlobalRdrEnvRn tc_gres fixity_env\\n ; restoreEnvs envs $ do {\\n -- Bring these things into scope first\\n -- See Note [Looking up family names in family instances]\\n\\n -- Process all family instances\\n -- to bring new data constructors into scope\\n ; nti_gress <- mapM (new_assoc dup_fields_ok has_sel) inst_decls\\n\\n -- Finish off with value binders:\\n -- foreign decls and pattern synonyms for an ordinary module\\n -- type sigs in case of a hs-boot file only\\n ; is_boot <- tcIsHsBootOrSig\\n ; let val_bndrs\\n | is_boot = case binds of\\n ValBinds _ val_binds ->\\n -- In a hs-boot file, the value binders come from the\\n -- *signatures*, and there should be no foreign binders\\n [ L (l2l decl_loc) (unLoc n)\\n | L decl_loc (TypeSig _ _ ns _) <- (val_sigs val_binds), n <- ns]\\n _ -> panic \\"Non-ValBinds in hs-boot group\\"\\n | otherwise = for_hs_bndrs\\n ; val_gres <- mapM new_simple val_bndrs\\n\\n ; let avails = concat nti_gress ++ val_gres\\n new_bndrs = gresToNameSet avails `unionNameSet`\\n gresToNameSet tc_gres\\n ; traceRn \\"getLocalNonValBinders 2\\" (ppr avails)\\n ; envs <- extendGlobalRdrEnvRn avails fixity_env\\n ; return (envs, new_bndrs) } }\\n where\\n for_hs_bndrs :: [LocatedN RdrName]\\n for_hs_bndrs = hsForeignDeclsBinders foreign_decls\\n\\n -- the SrcSpan attached to the input should be the span of the\\n -- declaration, not just the name\\n new_simple :: LocatedN RdrName -> RnM GlobalRdrElt\\n new_simple rdr_name = do { nm <- newTopSrcBinder rdr_name\\n ; return (mkLocalVanillaGRE NoParent nm) }\\n\\n new_tc :: DuplicateRecordFields -> FieldSelectors -> LTyClDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_tc dup_fields_ok has_sel tc_decl -- NOT for type/data instances\\n = do { let TyDeclBinders (main_bndr, tc_flav) at_bndrs sig_bndrs\\n (LConsWithFields cons_with_flds flds) = hsLTyClDeclBinders tc_decl\\n ; tycon_name <- newTopSrcBinder $ la2la main_bndr\\n ; at_names <- mapM (newTopSrcBinder . la2la . fst) at_bndrs\\n ; sig_names <- mapM (newTopSrcBinder . la2la) sig_bndrs\\n ; con_names_with_flds <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst con_names_with_flds) flds\\n ; mapM_ (add_dup_fld_errs flds\') con_names_with_flds\\n ; let tc_gre = mkLocalTyConGRE (fmap (const tycon_name) tc_flav) tycon_name\\n fld_env = mk_fld_env con_names_with_flds flds\'\\n at_gres = zipWith (\\\\ (_, at_flav) at_nm -> mkLocalTyConGRE (fmap (const tycon_name) at_flav) at_nm)\\n at_bndrs at_names\\n sig_gres = map (mkLocalVanillaGRE (ParentIs tycon_name)) sig_names\\n con_gres = map (mkLocalConLikeGRE (ParentIs tycon_name)) fld_env\\n fld_gres = mkLocalFieldGREs (ParentIs tycon_name) fld_env\\n sub_gres = at_gres ++ sig_gres ++ con_gres ++ fld_gres\\n ; traceRn \\"getLocalNonValBinders new_tc\\" $\\n vcat [ text \\"tycon:\\" <+> ppr tycon_name\\n , text \\"tc_gre:\\" <+> ppr tc_gre\\n , text \\"sub_gres:\\" <+> ppr sub_gres ]\\n ; return $ tc_gre : sub_gres }\\n\\n -- Calculate the record field information, which feeds into the GlobalRdrElts\\n -- for DataCons and their fields. It\'s convenient to do this here where\\n -- we are working with a single datatype definition.\\n --\\n -- The information we needed was all set up for us:\\n -- see Note [Collecting record fields in data declarations] in GHC.Hs.Utils.\\n mk_fld_env :: [(Name, Either VisArity [Located Int])] -> IntMap FieldLabel\\n -> [(ConLikeName, ConInfo)]\\n mk_fld_env names flds =\\n [ (DataConName con, ConInfo (ConIsData (map fst names)) fld_info)\\n | (con, con_fl_indxs) <- names\\n , let fld_info = case fmap (map ((flds IntMap.!) . unLoc)) con_fl_indxs of\\n Left 0 -> ConIsNullary\\n Left arity -> ConHasPositionalArgs arity\\n Right [] -> ConIsNullary\\n Right (fld:flds) -> ConHasRecordFields $ fld NE.:| flds ]\\n\\n new_assoc :: DuplicateRecordFields -> FieldSelectors -> LInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_assoc _ _ (L _ (TyFamInstD {})) = return []\\n -- type instances don\'t bind new names\\n\\n new_assoc dup_fields_ok has_sel (L _ (DataFamInstD _ d))\\n = new_di dup_fields_ok has_sel Nothing d\\n new_assoc dup_fields_ok has_sel\\n (L _ (ClsInstD _ (ClsInstDecl { cid_poly_ty = inst_ty\\n , cid_decls = decls })))\\n = do -- First, attempt to grab the name of the class from the instance.\\n -- This step could fail if the instance is not headed by a class,\\n -- such as in the following examples:\\n --\\n -- (1) The class is headed by a bang pattern, such as in\\n -- `instance !Show Int` (#3811c)\\n -- (2) The class is headed by a type variable, such as in\\n -- `instance c` (#16385)\\n --\\n -- If looking up the class name fails, then mb_cls_gre will\\n -- be Nothing.\\n mb_cls_gre <- runMaybeT $ do\\n -- See (1) above\\n L loc cls_rdr <- MaybeT $ pure $ getLHsInstDeclClass_maybe inst_ty\\n -- See (2) above\\n MaybeT $ setSrcSpan (locA loc) $ lookupGlobalOccRn_maybe SameNameSpace cls_rdr\\n -- Assuming the previous step succeeded, process any associated data\\n -- family instances. If the previous step failed, bail out.\\n case mb_cls_gre of\\n Nothing\\n -> pure []\\n Just cls_gre\\n -> let cls_nm = greName cls_gre\\n in concatMapM (new_di dup_fields_ok has_sel (Just cls_nm) . unLoc) (data_fam_insts decls)\\n\\n data_fam_insts decls = concatMap get decls\\n where\\n get (L l (InstD _ (DataFamInstD { dfid_inst = d}))) = [L l d]\\n get _ = []\\n\\n new_di :: DuplicateRecordFields -> FieldSelectors\\n -> Maybe Name -- class name\\n -> DataFamInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_di dup_fields_ok has_sel mb_cls dfid@(DataFamInstDecl { dfid_eqn = ti_decl })\\n = do { main_name <- unLoc <$> lookupFamInstName mb_cls (feqn_tycon ti_decl)\\n ; let LConsWithFields cons_with_flds flds = hsDataFamInstBinders dfid\\n ; sub_names <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst sub_names) flds\\n ; mapM_ (add_dup_fld_errs flds\') sub_names\\n ; let fld_env = mk_fld_env sub_names flds\'\\n con_gres = map (mkLocalConLikeGRE (ParentIs main_name)) fld_env\\n field_gres = mkLocalFieldGREs (ParentIs main_name) fld_env\\n -- NB: the data family name is not bound here,\\n -- so we don\'t return a GlobalRdrElt for it here!\\n ; return $ con_gres ++ field_gres }\\n\\n -- Add errors if a constructor has a duplicate record field.\\n add_dup_fld_errs :: IntMap FieldLabel\\n -> (Name, Either VisArity [Located Int])\\n -> IOEnv (Env TcGblEnv TcLclEnv) ()\\n add_dup_fld_errs all_flds (con, con_flds_or_arity)\\n | Right con_flds <- con_flds_or_arity\\n , let (_, dups) = removeDups (comparing unLoc) con_flds\\n = for_ dups $ \\\\ dup_flds ->\\n -- Report the error at the location of the second occurrence\\n -- of the duplicate field.\\n let loc =\\n case dup_flds of\\n _ :| ( L loc _ : _) -> loc\\n L loc _ :| _ -> loc\\n dup_rdrs = fmap (nameRdrName . flSelector . (all_flds IntMap.!) . unLoc) dup_flds\\n in addErrAt loc $ TcRnDuplicateFieldName (RecordFieldDecl con) dup_rdrs\\n | otherwise\\n = return ()\\n\\nnewRecordFieldLabel :: DuplicateRecordFields -> FieldSelectors -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel\\nnewRecordFieldLabel _ _ [] _ = error \\"newRecordFieldLabel: datatype has no constructors!\\"\\nnewRecordFieldLabel dup_fields_ok has_sel (dc:_) (L loc (FieldOcc _ (L _ fld)))\\n = do { selName <- newTopSrcBinder $ L (l2l loc) $ field\\n ; return $ FieldLabel { flHasDuplicateRecordFields = dup_fields_ok\\n , flHasFieldSelector = has_sel\\n , flSelector = selName } }\\n where\\n fld_occ = rdrNameOcc fld\\n dc_fs = occNameFS $ nameOccName dc\\n field\\n -- Use an Exact RdrName as-is, to preserve the bindings\\n -- of an already renamer-resolved field and its use\\n -- sites. This is needed to correctly support record\\n -- selectors in Template Haskell. See Note [Binders in\\n -- Template Haskell] in \\"GHC.ThToHs\\" and Note [Looking up\\n -- Exact RdrNames] in \\"GHC.Rename.Env\\".\\n | isExact fld\\n = assertPpr (fieldOcc_maybe fld_occ == Just dc_fs)\\n (vcat [ text \\"newRecordFieldLabel: incorrect namespace for exact Name\\" <+> quotes (ppr fld)\\n , text \\"expected namespace:\\" <+> pprNameSpace (fieldName dc_fs)\\n , text \\" actual namespace:\\" <+> pprNameSpace (occNameSpace fld_occ) ])\\n fld\\n\\n -- Field names produced by the parser are namespaced with VarName.\\n -- Here we namespace them according to the first constructor.\\n -- See Note [Record field namespacing] in GHC.Types.Name.Occurrence.\\n | otherwise\\n = mkRdrUnqual $ varToRecFieldOcc dc_fs fld_occ\\n\\n{-\\nNote [Looking up family names in family instances]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider\\n\\n module M where\\n type family T a :: *\\n type instance M.T Int = Bool\\n\\nWe might think that we can simply use \'lookupOccRn\' when processing the type\\ninstance to look up \'M.T\'. Alas, we can\'t! The type family declaration is in\\nthe *same* HsGroup as the type instance declaration. Hence, as we are\\ncurrently collecting the binders declared in that HsGroup, these binders will\\nnot have been added to the global environment yet.\\n\\nSolution is simple: process the type family declarations first, extend\\nthe environment, and then process the type instances.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Filtering imports}\\n* *\\n************************************************************************\\n\\n@filterImports@ takes the @ExportEnv@ telling what the imported module makes\\navailable, and filters it through the import spec (if any).\\n\\nNote [Dealing with imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nFor import M( ies ), we take each AvailInfo from the mi_exports of M, and make\\n\\n imp_occ_env :: OccEnv (NameEnv ImpOccItem)\\n\\nThis map contains one entry for each OccName that M exports, mapping each OccName\\nto the following information:\\n\\n 1. the GlobalRdrElt corresponding to the OccName,\\n 2. whether this GlobalRdrElt was the parent in the AvailInfo we found\\n the OccName in.\\n 3. the GlobalRdrElts that were bundled together in the AvailInfo we found\\n this OccName in (not including the parent),\\n\\nWe need (2) and (3) during the construction of the OccEnv because of associated\\ntypes and bundled pattern synonyms, respectively.\\n(3) is explained in Note [Importing PatternSynonyms].\\n\\nTo explain (2), consider for example:\\n\\n module M where\\n class C a where { data T a }\\n instance C Int where { data T Int = T1 | T2 }\\n instance C Bool where { data T Int = T3 }\\n\\nHere, M\'s exports avails are (recalling the AvailTC invariant from GHC.Types.Avail)\\n\\n C(C,T), T(T,T1,T2,T3)\\n\\nNotice that T appears *twice*, once as a child and once as a parent. From\\nthese two exports, respectively, during construction of the imp_occ_env, we begin\\nby associating the following two elements with the key T:\\n\\n T -> ImpOccItem { imp_item = gre1, imp_bundled = [C,T] , imp_is_parent = False }\\n T -> ImpOccItem { imp_item = gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nwhere `gre1`, `gre2` are two GlobalRdrElts with greName T.\\nWe combine these (in function \'combine\' in \'mkImportOccEnv\') by discarding the\\nnon-parent item, thusly:\\n\\n T -> IE_ITem { imp_item = gre1 `plusGRE` gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nNote the `plusGRE`: this ensures we don\'t drop parent information;\\nsee Note [Preserve parent information when combining import OccEnvs].\\n\\nSo the overall imp_occ_env is:\\n\\n C -> ImpOccItem { imp_item = C, imp_bundled = [T ], imp_is_parent = True }\\n T -> ImpOccItem { imp_item = T , imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n T1 -> ImpOccItem { imp_item = T1, imp_bundled = [T1,T2,T3], imp_is_parent = False }\\n -- similarly for T2, T3\\n\\nNote that the imp_occ_env will have entries for data constructors too,\\nalthough we never look up data constructors.\\n\\nNote [Importing PatternSynonyms]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nAs described in Note [Dealing with imports], associated types can lead to the\\nsame Name appearing twice, both as a child and once as a parent, when\\nconstructing the imp_occ_env. The same thing can happen with pattern synonyms\\nif they are exported bundled with a type.\\n\\nA simplified example, based on #11959:\\n\\n {-# LANGUAGE PatternSynonyms #-}\\n module M (T(P), pattern P) where -- Duplicate export warning, but allowed\\n data T = MkT\\n pattern P = MkT\\n\\nHere we have T(P) and P in export_avails, and respectively construct both\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n P -> ImpOccItem { imp_item = P, imp_bundled = [] , imp_is_parent = False }\\n\\nWe combine these by dropping the one with no siblings, leaving us with:\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n\\nThat is, we simply discard the non-bundled Avail.\\n\\nNote [Importing DuplicateRecordFields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn filterImports, another complicating factor is DuplicateRecordFields.\\nSuppose we have:\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (S(foo), T(foo)) where\\n data S = MkS { foo :: Int }\\n data T = MkT { foo :: Int }\\n\\n module N where\\n import M (foo) -- this is allowed (A)\\n import M (S(foo)) -- this is allowed (B)\\n\\nHere M exports \'foo\' at two different OccNames, with different namespaces for\\nthe two construtors MkS and MkT. Then, when we look up \'foo\' in lookup_names\\nfor case (A), we have a variable foo but must look in all the record field\\nnamespaces to find the two fields (and hence two different Avails).\\nWhereas in case (B) we reach the lookup_ie case for IEThingWith,\\nwhich looks up \'S\' and then finds the unique \'foo\' amongst its children.\\n\\nSee T16745 for a test of this.\\n\\nNote [Preserve parent information when combining import OccEnvs]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen discarding one ImpOccItem in favour of another, as described in\\nNote [Dealing with imports], we must make sure to combine the GREs so that\\nwe don\'t lose information.\\n\\nConsider for example #24084:\\n\\n module M1 where { class C a where { type T a } }\\n module M2 ( module M1 ) where { import M1 }\\n module M3 where { import M2 ( C, T ); instance C () where T () = () }\\n\\nWhen processing the import list of `M3`, we will have two `Avail`s attached\\nto `T`, namely `C(C, T)` and `T(T)`. We combine them in the `combine` function\\nof `mkImportOccEnv`; as described in Note [Dealing with imports] we discard\\n`C(C, T)` in favour of `T(T)`. However, in doing so, we **must not**\\ndiscard the information want that `C` is the parent of `T`. Indeed,\\nlosing track of this information can cause errors when importing,\\nas we could get an error of the form\\n\\n \\u2018T\\u2019 is not a (visible) associated type of class \\u2018C\\u2019\\n\\nThis explains why we use `plusGRE` when combining the two ImpOccItems, even\\nthough we are discarding one in favour of the other.\\n-}\\n\\n-- | All the \'GlobalRdrElt\'s associated with an \'AvailInfo\'.\\ngresFromAvail :: HasDebugCallStack\\n => HscEnv -> Maybe ImportSpec -> AvailInfo -> [GlobalRdrElt]\\ngresFromAvail hsc_env prov avail =\\n [ mk_gre nm info\\n | nm <- availNames avail\\n , let info = lookupGREInfo hsc_env nm ]\\n where\\n\\n mk_gre n info\\n = case prov of\\n -- Nothing => bound locally\\n -- Just is => imported from \'is\'\\n Nothing -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = True, gre_imp = emptyBag\\n , gre_info = info }\\n Just is -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = False, gre_imp = unitBag is\\n , gre_info = info }\\n\\n-- | All the \'GlobalRdrElt\'s associated with a collection of \'AvailInfo\'s.\\ngresFromAvails :: HscEnv -> Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]\\ngresFromAvails hsc_env prov = concatMap (gresFromAvail hsc_env prov)\\n\\nimportsFromIface :: HscEnv -> ModIface -> ImpDeclSpec -> Maybe NameSet -> GlobalRdrEnv\\nimportsFromIface hsc_env iface decl_spec hidden = mkGlobalRdrEnv $ case hidden of\\n Nothing -> all_gres\\n Just hidden_names -> filter (not . (`elemNameSet` hidden_names) . greName) all_gres\\n where\\n all_gres = gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\nrnNamespaceSpecifier :: NamespaceSpecifier GhcPs -> NamespaceSpecifier GhcRn\\nrnNamespaceSpecifier (NoNamespaceSpecifier _) = NoNamespaceSpecifier noExtField\\nrnNamespaceSpecifier (TypeNamespaceSpecifier x) = TypeNamespaceSpecifier x\\nrnNamespaceSpecifier (DataNamespaceSpecifier x) = DataNamespaceSpecifier x\\n\\nfilterImports\\n :: HasDebugCallStack\\n => HscEnv\\n -> ModIface\\n -> ImpDeclSpec\\n -- ^ Import spec\\n -> Maybe (ImportListInterpretation, [LIE GhcPs])\\n -- ^ Whether this is a \\"hiding\\" import list\\n -> RnM (Maybe (ImportListInterpretation, [LIE GhcRn]), -- Import spec w/ Names\\n ImpUserList, -- same, but designed for storage in interfaces\\n GlobalRdrEnv) -- Same again, but in GRE form\\nfilterImports hsc_env iface decl_spec Nothing\\n = return (Nothing, ImpUserAll, importsFromIface hsc_env iface decl_spec Nothing)\\nfilterImports hsc_env iface decl_spec (Just (want_hiding, import_items))\\n = do -- check for errors, convert RdrNames to Names\\n items1 <- mapM lookup_lie import_items\\n\\n let items2 :: [(LIE GhcRn, [GlobalRdrElt])]\\n items2 = concat items1\\n -- NB we may have duplicates, and several items\\n -- for the same parent; e.g N(x) and N(y)\\n\\n (gres, imp_user_list) = case want_hiding of\\n Exactly ->\\n let gres = concatMap (gresFromIE decl_spec) items2\\n gre_env = mkGlobalRdrEnv gres\\n implicit_parents = mkNameSet $ mapMaybe parentOfImplicitlyImportedGRE gres\\n in (gre_env, ImpUserExplicit (gresToAvailInfo $ globalRdrEnvElts $ gre_env) implicit_parents)\\n EverythingBut ->\\n let hidden_names = mkNameSet $ concatMap (map greName . snd) items2\\n in (importsFromIface hsc_env iface decl_spec (Just hidden_names), ImpUserEverythingBut hidden_names)\\n\\n return (Just (want_hiding, map fst items2), imp_user_list, gres)\\n where\\n import_mod = mi_module iface\\n all_avails = mi_exports iface\\n imp_occ_env = mkImportOccEnv hsc_env decl_spec all_avails\\n\\n -- Look up a parent (type constructor, class or data constructor)\\n -- in an import.\\n lookup_parent :: IE GhcPs -> RdrName -> IELookupM ImpOccItem\\n lookup_parent ie rdr =\\n assertPpr (not $ isVarNameSpace ns)\\n (vcat [ text \\"filterImports lookup_parent: unexpected variable\\"\\n , text \\"rdr:\\" <+> ppr rdr\\n , text \\"namespace:\\" <+> pprNameSpace ns ]) $\\n do { xs <- lookup_names ie rdr\\n ; case xs of\\n cax :| [] -> return cax\\n _ -> pprPanic \\"filter_imports lookup_parent ambiguous\\" $\\n vcat [ text \\"rdr:\\" <+> ppr rdr\\n , text \\"lookups:\\" <+> ppr (fmap imp_item xs) ] }\\n -- Looking up non-variables is always unambiguous,\\n -- as there can be at most one corresponding item\\n -- in the imp_occ_env.\\n -- See item (1) of Note [Exporting duplicate declarations]\\n -- in GHC.Tc.Gen.Export.\\n where\\n occ = rdrNameOcc rdr\\n ns = occNameSpace occ\\n\\n -- Look up a RdrName used in an import, returning multiple values if there\\n -- are several fields with the same name exposed by the module\\n lookup_names :: IE GhcPs -> RdrName -> IELookupM (NonEmpty ImpOccItem)\\n lookup_names ie rdr\\n | isQual rdr\\n = failLookupWith (QualImportError rdr)\\n | otherwise\\n = case lookups of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n item:items -> return $ item :| items\\n where\\n lookups = concatMap nonDetNameEnvElts\\n $ lookupImpOccEnv (RelevantGREsFOS WantNormal) imp_occ_env (rdrNameOcc rdr)\\n\\n lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, [GlobalRdrElt])]\\n lookup_lie (L loc ieRdr)\\n = setSrcSpanA loc $\\n do (stuff, warns) <- run_lookup ([],[]) (lookup_ie ieRdr)\\n mapM_ (addTcRnDiagnostic <=< warning_msg) warns\\n return [ (L loc ie, gres) | (ie,gres) <- stuff ]\\n where\\n\\n -- Warn when importing T(..) and no children are brought in scope\\n warning_msg (DodgyImport reason) =\\n pure (TcRnDodgyImports reason)\\n warning_msg MissingImportList =\\n pure (TcRnMissingImportList ieRdr)\\n warning_msg (BadImportW ie sub) = do\\n -- \'BadImportW\' is only constructed below in \'bad_import_w\', in\\n -- the \'EverythingBut\' case, so here we assume a \'hiding\' clause.\\n (reason :| _) <- badImportItemErr iface decl_spec ie sub all_avails\\n pure (TcRnDodgyImports (DodgyImportsHiding reason))\\n warning_msg (DeprecatedExport n w) =\\n pure $ TcRnPragmaWarning\\n PragmaWarningExport\\n { pwarn_occname = occName n\\n , pwarn_impmod = moduleName import_mod }\\n w\\n\\n run_lookup :: a -> IELookupM a -> TcRn a\\n run_lookup def m = case m of\\n Failed err -> do\\n msgs <- lookup_err_msgs err\\n forM_ msgs $ \\\\msg -> addErr (TcRnImportLookup msg)\\n return def\\n Succeeded a -> return a\\n\\n lookup_err_msgs err = case err of\\n BadImport ie sub -> badImportItemErr iface decl_spec ie sub all_avails\\n IllegalImport -> pure $ NE.singleton ImportLookupIllegal\\n QualImportError rdr -> pure $ NE.singleton (ImportLookupQualified rdr)\\n\\n -- For each import item, we convert its RdrNames to Names,\\n -- and at the same time compute all the GlobalRdrElt corresponding\\n -- to what is actually imported by this item.\\n -- Returns Nothing on error.\\n --\\n -- Returns a list because, with DuplicateRecordFields, a naked\\n -- import/export of a record field can correspond to multiple\\n -- different GlobalRdrElts. See Note [Importing DuplicateRecordFields].\\n lookup_ie :: IE GhcPs\\n -> IELookupM ([(IE GhcRn, [GlobalRdrElt])], [IELookupWarning])\\n lookup_ie ie = handle_bad_import $\\n case ie of\\n IEVar _ (L l n) _ -> do\\n -- See Note [Importing DuplicateRecordFields]\\n xs <- lookup_names ie (ieWrappedName n)\\n let gres = map imp_item $ NE.toList xs\\n export_depr_warns\\n | want_hiding == Exactly\\n = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ( [ (IEVar Nothing (L l (replaceWrappedName n name)) noDocstring, [gre])\\n | gre <- gres\\n , let name = greName gre ]\\n , export_depr_warns )\\n\\n IEThingAll x ns_spec (L l tc) _ -> do\\n ImpOccItem { imp_item = gre\\n , imp_bundled = bundled_gres\\n , imp_is_parent = is_par\\n }\\n <- lookup_parent ie $ ieWrappedName tc\\n let name = greName gre\\n\\n child_gres :: [GlobalRdrElt]\\n child_gres\\n | is_par = filterByNamespaceSpecifierGREs ns_spec bundled_gres\\n | otherwise = []\\n\\n imp_list_warn\\n\\n | null child_gres\\n -- e.g. f(..) or T(..) where T is a type synonym\\n = [DodgyImport (DodgyImportsEmptyParent ie ns_spec gre)]\\n\\n -- e.g. import M( T(..) )\\n | not (is_qual decl_spec)\\n = [MissingImportList]\\n\\n | otherwise\\n = []\\n\\n renamed_ie = IEThingAll (x { ieta_warning = Nothing })\\n (rnNamespaceSpecifier ns_spec)\\n (L l (replaceWrappedName tc name))\\n noDocstring\\n export_depr_warn\\n | want_hiding == Exactly\\n = maybeToList $ mk_depr_export_warning gre\\n -- We don\'t want to warn about the children as they\\n -- are not explicitly mentioned; the warning will\\n -- be emitted later on if they are used\\n | otherwise = []\\n\\n return ( [(renamed_ie, gre:child_gres)]\\n , imp_list_warn ++ export_depr_warn)\\n\\n\\n IEThingAbs _ (L l tc\') _\\n | want_hiding == EverythingBut -- hiding ( C )\\n -- Here the \'C\' can be a data constructor\\n -- *or* a type/class, or even both\\n -> let tc = ieWrappedName tc\'\\n tc_name = lookup_parent ie tc\\n dc_name = lookup_parent ie (setRdrNameSpace tc srcDataName)\\n in\\n case catIELookupM [ tc_name, dc_name ] of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n names -> return ( [mkIEThingAbs tc\' l (imp_item name) | name <- names], [])\\n | otherwise\\n -> do ImpOccItem { imp_item = gre } <- lookup_parent ie (ieWrappedName tc\')\\n return ( [mkIEThingAbs tc\' l gre]\\n , maybeToList $ mk_depr_export_warning gre)\\n\\n IEThingWith (deprecation, ann) ltc@(L l rdr_tc) wc rdr_ns _ -> do\\n ImpOccItem { imp_item = gre, imp_bundled = subnames }\\n <- lookup_parent (IEThingAbs Nothing ltc noDocstring) (ieWrappedName rdr_tc)\\n let name = greName gre\\n\\n -- Look up the children in the sub-names of the parent\\n -- See Note [Importing DuplicateRecordFields]\\n let (children_errs, childnames) = lookupChildren subnames rdr_ns\\n\\n bad_import_warns <-\\n if null children_errs then return [] else\\n let items = map lce_wrapped_name children_errs\\n ie = IEThingWith (deprecation, ann) ltc wc items noDocstring\\n -- We are trying to import T( a,b,c,d ), and failed\\n -- to find \'b\' and \'d\'. So we make up an import item\\n -- to report as failing, namely T( b, d ).\\n -- c.f. #15413\\n subordinate_err = mkSubordinateError gre children_errs\\n in bad_import_w ie subordinate_err\\n\\n let name\' = replaceWrappedName rdr_tc name\\n childnames\' = map (to_ie_post_rn . fmap greName) childnames\\n gres = gre : map unLoc childnames\\n export_depr_warns\\n | want_hiding == Exactly = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ([ (IEThingWith (Nothing, ann) (L l name\') wc childnames\' noDocstring\\n ,gres)]\\n , bad_import_warns ++ export_depr_warns)\\n\\n IEWholeNamespace x ns_spec -> do\\n let mod_name = moduleName import_mod\\n names = map greName gres\\n renamed_ie = IEWholeNamespace x { iewn_warning = Nothing\\n , iewn_names = names }\\n (rnNamespaceSpecifier ns_spec)\\n gres = filterByNamespaceSpecifierGREs ns_spec $\\n gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n dodgy_warn\\n | null gres = [DodgyImport (DodgyImportsWildcard mod_name ns_spec)]\\n | otherwise = []\\n return ([(renamed_ie, gres)],\\n dodgy_warn)\\n\\n _other -> failLookupWith IllegalImport\\n -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed...\\n -- all of those constitute errors.\\n\\n where\\n mkIEThingAbs tc l gre\\n = (IEThingAbs Nothing (L l (replaceWrappedName tc n)) noDocstring, [gre])\\n where n = greName gre\\n\\n -- N.B. imports never have docstrings\\n noDocstring = Nothing\\n\\n handle_bad_import m = catchIELookup m $ \\\\case\\n BadImport ie sub -> do\\n ws <- bad_import_w ie sub\\n return ([], ws)\\n err -> failLookupWith err\\n\\n bad_import_w :: IE GhcPs -> IsSubordinateError -> IELookupM [IELookupWarning]\\n bad_import_w ie sub\\n | want_hiding == EverythingBut = return [BadImportW ie sub]\\n | otherwise = failLookupWith (BadImport ie sub)\\n\\n mk_depr_export_warning gre\\n = DeprecatedExport name <$> mi_export_warn_fn iface name\\n where\\n name = greName gre\\n\\n-- | Assuming a subordinate item could not be found, do another lookup for a\\n-- more specific error message.\\nmkBadExportSubordinate :: [GlobalRdrElt] -> LIEWrappedName GhcPs -> BadExportSubordinate\\nmkBadExportSubordinate child_gres n =\\n case lookupChildren child_gres [n] of\\n (LookupChildNonType {lce_nontype_item = g} : _, _) -> BadExportSubordinateNonType g\\n (LookupChildNonData {lce_nondata_item = g} : _, _) -> BadExportSubordinateNonData g\\n _ -> BadExportSubordinateNotFound n\\n\\ntype IELookupM = MaybeErr IELookupError\\n\\ndata IELookupWarning\\n = BadImportW (IE GhcPs) IsSubordinateError\\n | MissingImportList\\n | DodgyImport DodgyImportsReason\\n | DeprecatedExport Name (WarningTxt GhcRn)\\n\\n-- | Is this import/export item a subordinate or not?\\ndata IsSubordinateError\\n = IsSubordinateError { subordinate_err_parent :: !GlobalRdrElt\\n , subordinate_err_unavailable :: [FastString]\\n , subordinate_err_nontype :: [GlobalRdrElt]\\n , subordinate_err_nondata :: [GlobalRdrElt] }\\n | IsNotSubordinate\\n\\nmkSubordinateError :: GlobalRdrElt -> [LookupChildError] -> IsSubordinateError\\nmkSubordinateError gre children_errs = foldr add init_acc children_errs\\n where\\n init_acc :: IsSubordinateError\\n init_acc = IsSubordinateError gre [] [] []\\n\\n add :: LookupChildError -> IsSubordinateError -> IsSubordinateError\\n add children_err sub@IsSubordinateError{} =\\n case children_err of\\n LookupChildNonType{lce_nontype_item = g} ->\\n sub { subordinate_err_nontype = g : subordinate_err_nontype sub }\\n LookupChildNonData{lce_nondata_item = g} ->\\n sub { subordinate_err_nondata = g : subordinate_err_nondata sub }\\n LookupChildNotFound (L _ wname) ->\\n let fs = (occNameFS . rdrNameOcc . ieWrappedName) wname\\n in sub { subordinate_err_unavailable = fs : subordinate_err_unavailable sub }\\n add _ IsNotSubordinate = panic \\"mkSubordinateError: IsNotSubordinate\\"\\n\\ndata IELookupError\\n = QualImportError RdrName\\n | BadImport (IE GhcPs) IsSubordinateError\\n | IllegalImport\\n\\nfailLookupWith :: IELookupError -> IELookupM a\\nfailLookupWith err = Failed err\\n\\ncatchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a\\ncatchIELookup m h = case m of\\n Succeeded r -> return r\\n Failed err -> h err\\n\\ncatIELookupM :: [IELookupM a] -> [a]\\ncatIELookupM ms = [ a | Succeeded a <- ms ]\\n\\n-- | Information associated to an \'AvailInfo\' used in constructing\\n-- an \'OccEnv\' corresponding to imports.\\n--\\n-- See Note [Dealing with imports].\\ndata ImpOccItem\\n = ImpOccItem\\n { imp_item :: GlobalRdrElt\\n -- ^ The import item\\n , imp_bundled :: [GlobalRdrElt]\\n -- ^ Items bundled in the Avail this import item came from,\\n -- not including the import item itself if it is a parent.\\n , imp_is_parent :: Bool\\n -- ^ Is the import item a parent? See Note [Dealing with imports].\\n }\\n\\ninstance Outputable ImpOccItem where\\n ppr (ImpOccItem { imp_item = item, imp_bundled = bundled, imp_is_parent = is_par })\\n = braces $ hsep\\n [ text \\"ImpOccItem\\"\\n , if is_par then text \\"[is_par]\\" else empty\\n , ppr (greName item) <+> ppr (greParent item)\\n , braces $ text \\"bundled:\\" <+> ppr (map greName bundled) ]\\n\\n-- | Make an \'OccEnv\' of all the imports.\\n--\\n-- Complicated by the fact that associated data types and pattern synonyms\\n-- can appear twice. See Note [Dealing with imports].\\nmkImportOccEnv :: HscEnv -> ImpDeclSpec -> [IfaceExport] -> OccEnv (NameEnv ImpOccItem)\\nmkImportOccEnv hsc_env decl_spec all_avails =\\n mkOccEnv_C (plusNameEnv_C combine)\\n [ (occ, mkNameEnv [(nm, item)])\\n | avail <- all_avails\\n , let gres = gresFromAvail hsc_env (Just hiding_spec) avail\\n , gre <- gres\\n , let nm = greName gre\\n occ = greOccName gre\\n (is_parent, bundled) = case avail of\\n AvailTC c _\\n | c == nm -- (Recall the AvailTC invariant from GHC.Types.AvailInfo)\\n -> ( True, drop 1 gres ) -- \\"drop 1\\": don\'t include the parent itself.\\n | otherwise\\n -> ( False, gres )\\n _ -> ( False, [] )\\n item = ImpOccItem\\n { imp_item = gre\\n , imp_bundled = bundled\\n , imp_is_parent = is_parent }\\n ]\\n where\\n\\n hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\n -- See Note [Dealing with imports]\\n -- \'combine\' may be called for associated data types which appear\\n -- twice in the all_avails. In the example, we have two Avails for T,\\n -- namely T(T,T1,T2,T3) and C(C,T), and we combine them by dropping the\\n -- latter, in which T is not the parent.\\n combine :: ImpOccItem -> ImpOccItem -> ImpOccItem\\n combine item1@(ImpOccItem { imp_item = gre1, imp_is_parent = is_parent1 })\\n item2@(ImpOccItem { imp_item = gre2, imp_is_parent = is_parent2 })\\n | is_parent1 || is_parent2\\n , not (isRecFldGRE gre1 || isRecFldGRE gre2) -- NB: does not force GREInfo.\\n , let name1 = greName gre1\\n name2 = greName gre2\\n gre = gre1 `plusGRE` gre2\\n -- See Note [Preserve parent information when combining import OccEnvs]\\n = assertPpr (name1 == name2)\\n (ppr name1 <+> ppr name2) $\\n if is_parent1\\n then item1 { imp_item = gre }\\n else item2 { imp_item = gre }\\n -- Discard C(C,T) in favour of T(T, T1, T2, T3).\\n\\n -- \'combine\' may also be called for pattern synonyms which appear both\\n -- unassociated and associated (see Note [Importing PatternSynonyms]).\\n combine item1@(ImpOccItem { imp_item = c1, imp_bundled = kids1 })\\n item2@(ImpOccItem { imp_item = c2, imp_bundled = kids2 })\\n = assertPpr (greName c1 == greName c2\\n && (not (null kids1 && null kids2)))\\n (ppr c1 <+> ppr c2 <+> ppr kids1 <+> ppr kids2) $\\n if null kids1\\n then item2\\n else item1\\n -- Discard standalone pattern P in favour of T(P).\\n\\n-- | Essentially like @lookupGRE env (LookupOccName occ which_gres)@,\\n-- but working with \'ImpOccItem\'s instead of \'GlobalRdrElt\'s.\\nlookupImpOccEnv :: WhichGREs GREInfo\\n -> OccEnv (NameEnv ImpOccItem) -> OccName -> [NameEnv ImpOccItem]\\nlookupImpOccEnv which_gres env occ =\\n mapMaybe relevant_items $ lookupOccEnv_AllNameSpaces env occ\\n where\\n is_relevant :: ImpOccItem -> Bool\\n is_relevant (ImpOccItem { imp_item = gre }) =\\n greIsRelevant which_gres (occNameSpace occ) gre\\n relevant_items :: NameEnv ImpOccItem -> Maybe (NameEnv ImpOccItem)\\n relevant_items nms\\n | let nms\' = filterNameEnv is_relevant nms\\n = if isEmptyNameEnv nms\'\\n then Nothing\\n else Just nms\'\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{Import/Export Utils}\\n* *\\n************************************************************************\\n-}\\n\\n-- | Given an import\\\\/export spec, appropriately set the @gre_imp@ field\\n-- for the \'GlobalRdrElt\'s.\\ngresFromIE :: ImpDeclSpec -> (LIE GhcRn, [GlobalRdrElt]) -> [GlobalRdrElt]\\ngresFromIE decl_spec (L loc ie, gres)\\n = map set_gre_imp gres\\n where\\n is_explicit = case ie of\\n IEThingAll _ _ name _ -> \\\\n -> n == lieWrappedName name\\n IEWholeNamespace _ _ -> \\\\_ -> False\\n _ -> \\\\_ -> True\\n prov_fn name\\n = ImpSpec { is_decl = decl_spec, is_item = item_spec }\\n where\\n item_spec = ImpSome { is_explicit = is_explicit name\\n , is_iloc = locA loc }\\n set_gre_imp gre@( GRE { gre_name = nm } )\\n = gre { gre_imp = unitBag $ prov_fn nm }\\n\\nparentOfImplicitlyImportedGRE :: Outputable info => GlobalRdrEltX info -> Maybe Name\\nparentOfImplicitlyImportedGRE gre =\\n if any (explicit_import . is_item) $ gre_imp gre\\n then Nothing\\n else greParent_maybe gre\\n where\\n explicit_import :: ImpItemSpec -> Bool\\n explicit_import (ImpAll {}) =\\n pprPanic \\"parentOfImplicitlyImportedGRE: ImpAll\\" (ppr gre)\\n explicit_import (ImpSome { is_explicit }) = is_explicit\\n\\n{- Note [Children for duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider the module\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (F(foo, MkFInt, MkFBool)) where\\n data family F a\\n data instance F Int = MkFInt { foo :: Int }\\n data instance F Bool = MkFBool { foo :: Bool }\\n\\nThe `foo` in the export list refers to *both* selectors! For this\\nreason, lookupChildren builds an environment that maps the FastString\\nto a list of items, rather than a single item.\\n-}\\n\\nmkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]\\nmkChildEnv gres = foldr add emptyNameEnv gres\\n where\\n add gre env = case greParent gre of\\n ParentIs p -> extendNameEnv_Acc (:) Utils.singleton env p gre\\n NoParent -> env\\n\\nfindChildren :: NameEnv [a] -> Name -> [a]\\nfindChildren env n = lookupNameEnv env n `orElse` []\\n\\ndata LookupChildError\\n = LookupChildNotFound { lce_wrapped_name :: !(LIEWrappedName GhcPs) }\\n | LookupChildNonType { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nontype_item :: !GlobalRdrElt }\\n | LookupChildNonData { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nondata_item :: !GlobalRdrElt }\\n\\nlookupChildren :: [GlobalRdrElt]\\n -> [LIEWrappedName GhcPs]\\n -> ( [LookupChildError] -- The ones for which the lookup failed\\n , [LocatedA GlobalRdrElt] )\\n-- (lookupChildren all_kids rdr_items) maps each rdr_item to its\\n-- corresponding Name in all_kids, if the former exists\\n-- The matching is done by FastString, not OccName, so that\\n-- Cls( meth, AssocTy )\\n-- will correctly find AssocTy among the all_kids of Cls, even though\\n-- the RdrName for AssocTy may have a (bogus) DataName namespace\\n-- (Really the rdr_items should be FastStrings in the first place.)\\nlookupChildren all_kids rdr_items = (fails, successes)\\n where\\n mb_xs = map do_one rdr_items\\n fails = [ err | Failed err <- mb_xs ]\\n successes = [ ok | Succeeded oks <- mb_xs, ok <- NE.toList oks ]\\n\\n do_one :: LIEWrappedName GhcPs -> MaybeErr LookupChildError (NonEmpty (LocatedA GlobalRdrElt))\\n do_one item@(L l r) =\\n case r of\\n IEName{}\\n -- IEName (unadorned name) places no restriction on the namespace of\\n -- the imported entity, so we look in both `val_gres` and `typ_gres`.\\n -- In case of conflict (punning), the value namespace takes priority.\\n -- See Note [Prioritise the value namespace in subordinate import lists]\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEType{}\\n -- IEType (\'type\' namespace specifier) restricts the lookup to the\\n -- type namespace, i.e. to `typ_gres`. In case of failure, we check\\n -- `val_gres` to produce a more helpful error message.\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- val_gres -> Failed $ LookupChildNonType item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEData{}\\n -- IEData (\'data\' namespace specifier) restricts the lookup to the\\n -- data namespace, i.e. to `val_gres`. In case of failure, we check\\n -- `typ_gres` to produce a more helpful error message.\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- typ_gres -> Failed $ LookupChildNonData item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEPattern{} -> panic \\"lookupChildren: IEPattern\\" -- Never happens (invalid syntax)\\n IEDefault{} -> panic \\"lookupChildren: IEDefault\\" -- Never happens (invalid syntax)\\n where\\n fs = (occNameFS . rdrNameOcc . ieWrappedName) r\\n gres = fromMaybe [] (lookupFsEnv kid_env fs)\\n (val_gres, typ_gres) = partition (isValNameSpace . greNameSpace) gres\\n\\n -- See Note [Children for duplicate record fields]\\n kid_env :: FastStringEnv [GlobalRdrElt]\\n kid_env = extendFsEnvList_C (++) emptyFsEnv\\n [(occNameFS (occName x), [x]) | x <- all_kids]\\n\\n\\n{- Note [Prioritise the value namespace in subordinate import lists]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider this program that defines a class that has both an associated type\\nnamed (#) and a method named (#)\\n\\n module M_assoc where\\n class C a b where\\n type a # b\\n (#) :: a -> b -> ()\\n module N_assoc where\\n import M_assoc( C((#)) )\\n\\nIn the import declaration, when we see the unadorned name (#) in the subordinate\\nimport list of C, which children should we bring into scope? Our options are:\\n\\n a) only the method (#)\\n b) only the associated type (#)\\n c) both the method and the associated type\\n\\nTo follow the precedent established by top-level items, we go with option (a).\\nIndeed, consider a slightly different program\\n\\n module M_top where\\n type family a # b\\n a # b = ()\\n module N_top where\\n import M_top( (#) )\\n\\nHere the import brings only the function (#) into scope, and one has to say\\n`type (#)` to get the type family.\\n-}\\n\\n-------------------------------\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused names}\\n* *\\n*********************************************************\\n-}\\n\\nreportUnusedNames :: TcGblEnv -> HscSource -> RnM ()\\nreportUnusedNames gbl_env hsc_src\\n = do { keep <- readTcRef (tcg_keep gbl_env)\\n ; traceRn \\"RUN\\" (ppr (tcg_dus gbl_env))\\n ; warnUnusedImportDecls gbl_env hsc_src\\n ; warnUnusedTopBinds $ unused_locals keep\\n ; warnMissingSignatures gbl_env\\n ; warnMissingKindSignatures gbl_env }\\n where\\n used_names :: NameSet -> NameSet\\n used_names keep = findUses (tcg_dus gbl_env) emptyNameSet `unionNameSet` keep\\n -- NB: currently, if f x = g, we only treat \'g\' as used if \'f\' is used\\n -- Hence findUses\\n\\n -- Collect the defined names from the in-scope environment\\n defined_names :: [GlobalRdrElt]\\n defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)\\n\\n kids_env = mkChildEnv defined_names\\n -- This is done in mkExports too; duplicated work\\n\\n gre_is_used :: NameSet -> GlobalRdrElt -> Bool\\n gre_is_used used_names gre0\\n = name `elemNameSet` used_names\\n || any (\\\\ gre -> greName gre `elemNameSet` used_names) (findChildren kids_env name)\\n -- A use of C implies a use of T,\\n -- if C was brought into scope by T(..) or T(C)\\n where\\n name = greName gre0\\n\\n -- Filter out the ones that are\\n -- (a) defined in this module, and\\n -- (b) not defined by a \'deriving\' clause\\n -- The latter have an Internal Name, so we can filter them out easily\\n unused_locals :: NameSet -> [GlobalRdrElt]\\n unused_locals keep =\\n let -- Note that defined_and_used, defined_but_not_used\\n -- are both [GRE]; that\'s why we need defined_and_used\\n -- rather than just used_names\\n _defined_and_used, defined_but_not_used :: [GlobalRdrElt]\\n (_defined_and_used, defined_but_not_used)\\n = partition (gre_is_used (used_names keep)) defined_names\\n\\n in filter is_unused_local defined_but_not_used\\n is_unused_local :: GlobalRdrElt -> Bool\\n is_unused_local gre = isLocalGRE gre\\n && isExternalName (greName gre)\\n\\n{- *********************************************************************\\n* *\\n Missing signatures\\n* *\\n********************************************************************* -}\\n\\n{-\\nNote [Missing signatures]\\n~~~~~~~~~~~~~~~~~~~~~~~~~\\nThere are four warning flags in play:\\n\\n * -Wmissing-exported-signatures\\n Warn about any exported top-level function/value without a type signature.\\n Does not include pattern synonyms.\\n\\n * -Wmissing-signatures\\n Warn about any top-level function/value without a type signature. Does not\\n include pattern synonyms. Takes priority over -Wmissing-exported-signatures.\\n\\n * -Wmissing-exported-pattern-synonym-signatures\\n Warn about any exported pattern synonym without a type signature.\\n\\n * -Wmissing-pattern-synonym-signatures\\n Warn about any pattern synonym without a type signature. Takes priority over\\n -Wmissing-exported-pattern-synonym-signatures.\\n\\n-}\\n\\n-- | Warn the user about top level binders that lack type signatures.\\n-- Called /after/ type inference, so that we can report the\\n-- inferred type of the function\\nwarnMissingSignatures :: TcGblEnv -> RnM ()\\nwarnMissingSignatures gbl_env\\n = do { let exports = availsToNameSet (tcg_exports gbl_env)\\n sig_ns = tcg_sigs gbl_env\\n -- We use sig_ns to exclude top-level bindings that are generated by GHC\\n binds = collectHsBindsBinders CollNoDictBinders $ tcg_binds gbl_env\\n pat_syns = tcg_patsyns gbl_env\\n\\n not_ghc_generated :: Name -> Bool\\n not_ghc_generated name = name `elemNameSet` sig_ns\\n\\n add_binding_warn :: Id -> RnM ()\\n add_binding_warn id =\\n when (not_ghc_generated name) $\\n do { env <- liftZonkM $ tcInitTidyEnv -- Why not use emptyTidyEnv?\\n ; let ty = tidyOpenType env (idType id)\\n missing = MissingTopLevelBindingSig name ty\\n diag = TcRnMissingSignature missing exported\\n ; addDiagnosticAt (getSrcSpan name) diag }\\n where\\n name = idName id\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n add_patsyn_warn :: PatSyn -> RnM ()\\n add_patsyn_warn ps =\\n when (not_ghc_generated name) $\\n addDiagnosticAt (getSrcSpan name)\\n (TcRnMissingSignature missing exported)\\n where\\n name = patSynName ps\\n missing = MissingPatSynSig ps\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n -- Warn about missing signatures\\n -- Do this only when we have a type to offer\\n -- See Note [Missing signatures]\\n ; mapM_ add_binding_warn binds\\n ; mapM_ add_patsyn_warn pat_syns\\n }\\n\\n-- | Warn the user about tycons that lack kind signatures.\\n-- Called /after/ type (and kind) inference, so that we can report the\\n-- inferred kinds.\\nwarnMissingKindSignatures :: TcGblEnv -> RnM ()\\nwarnMissingKindSignatures gbl_env\\n = do { cusks_enabled <- xoptM LangExt.CUSKs\\n ; mapM_ (add_ty_warn cusks_enabled) tcs\\n }\\n where\\n tcs = tcg_tcs gbl_env\\n ksig_ns = tcg_ksigs gbl_env\\n exports = availsToNameSet (tcg_exports gbl_env)\\n\\n has_kind_signature :: Name -> Bool\\n has_kind_signature name = name `elemNameSet` ksig_ns\\n\\n add_ty_warn :: Bool -> TyCon -> RnM ()\\n add_ty_warn cusks_enabled tyCon =\\n when (has_kind_signature name) $\\n addDiagnosticAt (getSrcSpan name) diag\\n where\\n name = tyConName tyCon\\n diag = TcRnMissingSignature missing exported\\n missing = MissingTyConKindSig tyCon cusks_enabled\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused imports}\\n* *\\n*********************************************************\\n\\nThis code finds which import declarations are unused. The\\nspecification and implementation notes are here:\\n https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/unused-imports\\n\\nSee also Note [Choosing the best import declaration] in GHC.Types.Name.Reader\\n-}\\n\\ntype ImportDeclUsage\\n = ( LImportDecl GhcRn -- The import declaration\\n , [GlobalRdrElt] -- What *is* used (normalised)\\n , [Name] -- What is imported but *not* used\\n , [NamespaceSpecifier GhcRn] ) -- Unused wildcards\\n\\nwarnUnusedImportDecls :: TcGblEnv -> HscSource -> RnM ()\\nwarnUnusedImportDecls gbl_env hsc_src\\n = do { uses <- readMutVar (tcg_used_gres gbl_env)\\n ; let imports = tcg_rn_imports gbl_env\\n rdr_env = tcg_rdr_env gbl_env\\n\\n -- We should only warn for unnecessary *user* imports, but deciding\\n -- minimal imports should take generated imports into account\\n ; let usageUserImports = findImportUsage (excludeGenerated imports) uses\\n usageAllImports = findImportUsage imports uses\\n\\n ; traceRn \\"warnUnusedImportDecls\\" $\\n (vcat [ text \\"Uses:\\" <+> ppr uses\\n , text \\"Usage all user imports: \\" <+> ppr usageUserImports\\n , text \\"Usage all imports: \\" <+> ppr usageAllImports])\\n\\n ; mapM_ (warnUnusedImport rdr_env) usageUserImports\\n\\n ; whenGOptM Opt_D_dump_minimal_imports $\\n printMinimalImports hsc_src usageAllImports }\\n\\n-- | Exclude generated imports\\nexcludeGenerated :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\nexcludeGenerated = filterOut (isGeneratedImport . ideclOrigin . ideclExt . unLoc)\\n\\nfindImportUsage :: [LImportDecl GhcRn]\\n -> [GlobalRdrElt]\\n -> [ImportDeclUsage]\\n\\nfindImportUsage imports used_gres\\n = map unused_decl imports\\n where\\n import_usage :: ImportMap\\n import_usage = mkImportMap used_gres\\n\\n unused_decl :: LImportDecl GhcRn -> ImportDeclUsage\\n unused_decl decl@(L _ (ImportDecl { ideclImportList = imps }))\\n = -- pprTrace \\"unused_decl\\" (vcat [ ppr decl\\n -- , text \\"used\\" <+> ppr used_gres\\n -- , text \\"unused\\" <+> ppr unused_names ]) $\\n (decl, used_gres, unused_names, unused_wcs)\\n where\\n used_gres = lookupImportMap decl import_usage\\n\\n used_gre_env = mkGlobalRdrEnv used_gres\\n used_parents = mkNameSet (mapMaybe greParent_maybe used_gres)\\n\\n (unused_names, unused_wcs) -- Not trivial; see eg #7454\\n = case imps of\\n Just (Exactly, imp_ies) ->\\n let unused = foldr (add_unused . unLoc) emptyUnusedNames imp_ies\\n nms = nameSetElemsStable (collectUnusedNames unused)\\n wcs = collectUnusedWildcards unused\\n in (nms, wcs)\\n _other -> ([], []) -- No explicit import list => no unused-name list\\n\\n add_unused :: IE GhcRn -> UnusedNames -> UnusedNames\\n add_unused (IEVar _ n _) acc = add_unused_name (lieWrappedName n) True acc\\n add_unused (IEThingAbs _ n _) acc = add_unused_name (lieWrappedName n) False acc\\n add_unused (IEThingAll _ _ n _) acc = add_unused_all (lieWrappedName n) acc\\n add_unused (IEThingWith _ p wc ns _) acc = add_wc_all (add_unused_with pn xs acc)\\n where pn = lieWrappedName p\\n xs = map lieWrappedName ns\\n add_wc_all = case wc of\\n NoIEWildcard -> id\\n IEWildcard _ -> add_unused_all pn\\n add_unused (IEWholeNamespace x ns_spec) acc = add_unused_wildcard ns_spec (iewn_names x) acc\\n add_unused _ acc = acc\\n\\n add_unused_name :: Name -> Bool -> UnusedNames -> UnusedNames\\n add_unused_name n is_ie_var acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | is_ie_var\\n , isFieldName n\\n -- See Note [Reporting unused imported duplicate record fields]\\n = let\\n fs = getOccFS n\\n (flds, flds_used) = lookupFsEnv acc_fs fs `orElse` (emptyNameSet, Any False)\\n acc_fs\' = extendFsEnv acc_fs fs (extendNameSet flds n, Any used S.<> flds_used)\\n in UnusedNames acc_ns acc_wcs acc_fs\'\\n\\n | used\\n = acc\\n\\n | otherwise\\n = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n where\\n used = isJust $ lookupGRE_Name used_gre_env n\\n\\n add_unused_all :: Name -> UnusedNames -> UnusedNames\\n add_unused_all n acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | Just {} <- lookupGRE_Name used_gre_env n = acc\\n | n `elemNameSet` used_parents = acc\\n | otherwise = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n\\n add_unused_with :: Name -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_with p ns acc\\n | all (`elemNameSet` acc1_ns) ns = add_unused_name p False acc1\\n | otherwise = acc1\\n where\\n acc1@(UnusedNames acc1_ns _ _) = foldr (\\\\n acc\' -> add_unused_name n False acc\') acc ns\\n -- If you use \'signum\' from Num, then the user may well have\\n -- imported Num(signum). We don\'t want to complain that\\n -- Num is not itself mentioned. Hence the two cases in add_unused_with.\\n\\n add_unused_wildcard :: NamespaceSpecifier GhcRn -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_wildcard ns_spec names acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | any_used = acc\\n | otherwise = UnusedNames acc_ns (ns_spec : acc_wcs) acc_fs\\n where\\n -- A wildcard `type ..` or `data ..` is used if at least one of\\n -- the names it expands to is used\\n any_used = any (isJust . lookupGRE_Name used_gre_env) names\\n\\n\\n-- | An accumulator for unused names in an import list.\\n--\\n-- See Note [Reporting unused imported duplicate record fields].\\ndata UnusedNames =\\n UnusedNames\\n { unused_names :: NameSet\\n -- ^ Unused \'Name\'s in an import list, not including record fields\\n -- that are plain \'IEVar\' imports (tracked by \'rec_fld_uses\')\\n -- or wildcard imports (tracked by \'unused_wildcards\').\\n , unused_wildcards :: [NamespaceSpecifier GhcRn]\\n -- ^ Unused wildcards @type ..@ or @data ..@ in an import list.\\n , rec_fld_uses :: FastStringEnv (NameSet, Any)\\n -- ^ Record fields imported without a parent (i.e. an \'IEVar\' import).\\n --\\n -- The \'Any\' value records whether any of the record fields\\n -- sharing the same underlying \'FastString\' have been used.\\n }\\n\\nemptyUnusedNames :: UnusedNames\\nemptyUnusedNames = UnusedNames emptyNameSet [] emptyFsEnv\\n\\ninstance Outputable UnusedNames where\\n ppr (UnusedNames nms wcs flds) =\\n text \\"UnusedNames\\" <+>\\n braces (ppr nms <+> ppr wcs <+> ppr (fmap (second getAny) flds))\\n\\n-- | Collect all unused names from a \'UnusedNames\' value.\\ncollectUnusedNames :: UnusedNames -> NameSet\\ncollectUnusedNames (UnusedNames { unused_names = nms, rec_fld_uses = flds })\\n = nms S.<> unused_flds\\n where\\n unused_flds = nonDetFoldFsEnv collect_unused emptyNameSet flds\\n collect_unused :: (NameSet, Any) -> NameSet -> NameSet\\n collect_unused (nms, Any at_least_one_name_is_used) acc\\n | at_least_one_name_is_used = acc\\n | otherwise = unionNameSet nms acc\\n\\ncollectUnusedWildcards :: UnusedNames -> [NamespaceSpecifier GhcRn]\\ncollectUnusedWildcards = unused_wildcards\\n\\n{- Note [Reporting unused imported duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have (#24035):\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M1 (R1(..), R2(..)) where\\n data R1 = MkR1 { fld :: Int }\\n data R2 = MkR2 { fld :: Int }\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M2 where\\n import M1 (R1(MkR1), R2, fld)\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nIn the import of \'M1\' in \'M2\', the \'fld\' import resolves to two separate GREs,\\nnamely R1(fld) and R2(fld). From the perspective of the renamer, and in particular\\nthe \'findImportUsage\' function, it\'s as if the user had imported the two names\\nseparately (even though no source syntax allows that).\\n\\nThis means that we need to be careful when reporting unused imports: the R2(fld)\\nimport is indeed unused, but because R1(fld) is used, we should not report\\nfld as unused altogether.\\n\\nTo achieve this, we keep track of record field imports without a parent (i.e.\\nusing the IEVar constructor) separately from other import items, using the\\nUnusedNames datatype.\\nOnce we have accumulated usages, we emit warnings for unused record fields\\nwithout parents one whole group (of record fields sharing the same textual name)\\nat a time, and only if *all* of the record fields in the group are unused;\\nsee \'collectUnusedNames\'.\\n\\nNote that this only applies to record fields imported without a parent. If we\\nhad:\\n\\n import M1 (R1(MkR1, fld), R2(fld))\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nthen of course we should report the second \'fld\' as unused.\\n-}\\n\\n\\n{- Note [The ImportMap]\\n~~~~~~~~~~~~~~~~~~~~~~~\\nThe ImportMap is a short-lived intermediate data structure records, for\\neach import declaration, what stuff brought into scope by that\\ndeclaration is actually used in the module.\\n\\nThe [GlobalRdrElt] are the things imported from that decl.\\n-}\\n\\ndata ImportMap = ImportMap\\n { im_imports :: Map RealSrcSpan [GlobalRdrElt]\\n -- ^ See [The ImportMap]\\n -- If loc :-> gres, then\\n -- \'loc\' = the end loc of the bestImport of each GRE in \'gres\'\\n , im_generatedImports :: Map ModuleName [GlobalRdrElt]\\n }\\n\\nmkImportMap :: [GlobalRdrElt] -> ImportMap\\n-- For each of a list of used GREs, find all the import decls that brought\\n-- it into scope; choose one of them (bestImport), and record\\n-- the RdrName in that import decl\'s entry in the ImportMap\\nmkImportMap = foldr insertImportMap $ ImportMap Map.empty Map.empty\\n\\ninsertImportMap :: GlobalRdrElt -> ImportMap -> ImportMap\\ninsertImportMap gre@(GRE { gre_imp = imp_specs }) importMap\\n | RealSrcSpan importSpan _ <- is_dloc best_imp_spec =\\n importMap{im_imports = insertElem importSpan gre $ im_imports importMap}\\n | GeneratedSrcSpan{} <- is_dloc best_imp_spec =\\n importMap{im_generatedImports = insertElem (moduleName $ is_mod best_imp_spec) gre $ im_generatedImports importMap}\\n | otherwise = importMap\\n where\\n best_imp_spec =\\n case bagToList imp_specs of\\n [] -> pprPanic \\"mkImportMap: GRE with no ImportSpecs\\" (ppr gre)\\n is:iss -> is_decl $ bestImport (is NE.:| iss)\\n\\n -- https://github.com/haskell/containers/issues/784\\n insertElem :: Ord k => k -> v -> Map k [v] -> Map k [v]\\n insertElem k v = flip Map.alter k $ \\\\case\\n Just vs -> Just (v : vs)\\n Nothing -> Just [v]\\n\\nlookupImportMap :: LImportDecl GhcRn -> ImportMap -> [GlobalRdrElt]\\nlookupImportMap (L srcSpan ImportDecl{ideclName = L _ modName}) importMap =\\n fromMaybe [] $\\n -- should match logic in insertImportMap\\n case locA srcSpan of\\n RealSrcSpan realSrcSpan _ -> realSrcSpan `Map.lookup` im_imports importMap\\n GeneratedSrcSpan{} -> modName `Map.lookup` im_generatedImports importMap\\n _ -> Nothing\\n\\nlieNames :: LIE (GhcPass p) -> [Located (IdP (GhcPass p))]\\nlieNames = _\\n\\nwarnUnusedImport :: GlobalRdrEnv -> ImportDeclUsage -> RnM ()\\nwarnUnusedImport rdr_env (L loc decl, used, unused, unused_wcs)\\n\\n -- Do not warn for \'import M()\'\\n -- See (UI1) in Note [Unused imports]\\n | Just (Exactly, _) <- ideclImportList decl\\n , null unused && null unused_wcs\\n = return ()\\n\\n -- Note [Do not warn about Prelude hiding]\\n | Just (EverythingBut, hides) <- ideclImportList decl\\n , not (null hides)\\n , pRELUDE_NAME == unLoc (ideclName decl)\\n = return ()\\n\\n -- Do not warn about import X as Rebindable\\n -- See (UI2) in Note [Unused imports]\\n | Just (L _ mod) <- ideclAs decl\\n , mod == rEBINDABLE_MOD_NAME\\n = return ()\\n\\n -- Nothing used; drop entire declaration\\n | null used\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl UnusedImportNone)\\n\\n -- Everything imported is used; nop\\n | null unused && null unused_wcs\\n = return ()\\n\\n -- Some imports are unused: make the `SrcSpan` cover only the unused\\n -- items instead of the whole import statement\\n | Just (_, imports) <- ideclImportList decl\\n , let unused_locs = [ locA loc | L loc ie <- imports\\n , name <- ieNames ie\\n , name `elem` unused ]\\n , loc1 : locs <- unused_locs\\n , let span = foldr1 combineSrcSpans ( loc1 NE.:| locs )\\n = addDiagnosticAt span (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n -- Some imports are unused\\n | otherwise\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n where\\n -- In warning message, pretty-print identifiers unqualified unconditionally\\n -- to improve the consistent for ambiguous/unambiguous identifiers.\\n -- See #14881.\\n possible_field n =\\n case lookupGRE_Name rdr_env n of\\n Just (GRE { gre_par = par, gre_info = IAmRecField info }) ->\\n let fld_occ :: OccName\\n fld_occ = nameOccName $ flSelector $ recFieldLabel info\\n in UnusedImportNameRecField par fld_occ\\n _ -> UnusedImportNameRegular n\\n\\n -- Print unused names in a deterministic (lexicographic) order\\n sort_unused :: [UnusedImportName]\\n sort_unused =\\n [ UnusedImportWildcard wc | wc <- unused_wcs ] ++\\n [ possible_field nm | nm <- sortBy (comparing nameOccName) unused ]\\n\\ngetMinimalImports :: [ImportDeclUsage] -> RnM [LImportDecl GhcRn]\\ngetMinimalImports ie_decls\\n = do { rdr_env <- getGlobalRdrEnv\\n ; fmap combine $ mapM (mk_minimal rdr_env) ie_decls }\\n where\\n mk_minimal rdr_env (L l decl, used_gres, unused, unused_wcs)\\n | null unused && null unused_wcs\\n , Just (Exactly, _) <- ideclImportList decl\\n = return (L l decl)\\n | otherwise\\n = do { let ImportDecl { ideclName = L _ mod_name\\n , ideclSource = is_boot\\n , ideclPkgQual = pkg_qual\\n , ideclExt = XImportDeclPass { ideclOrigin = origin } } = decl\\n ; iface <- loadSrcInterface doc (importDeclLookupScope origin)\\n mod_name is_boot pkg_qual\\n ; let used_avails = gresToAvailInfo used_gres\\n ; lies <- map (L l) <$> concatMapM (to_ie rdr_env iface) used_avails\\n ; return (L l (decl { ideclImportList = Just (Exactly, lies) })) }\\n where\\n doc = text \\"Compute minimal imports for\\" <+> ppr decl\\n\\n to_ie :: GlobalRdrEnv -> ModIface -> AvailInfo -> RnM [IE GhcRn]\\n -- The main trick here is that if we\'re importing all the constructors\\n -- we want to say \\"T(..)\\", but if we\'re importing only a subset we want\\n -- to say \\"T(A,B,C)\\". So we have to find out what the module exports.\\n to_ie rdr_env _ (Avail c) -- Note [Overloaded field import]\\n = do { let\\n gre = expectJust $ lookupGRE_Name rdr_env c\\n ; return $ [IEVar Nothing (to_ie_post_rn $ noLocA $ greName gre) Nothing] }\\n to_ie _ _ avail@(AvailTC n [_]) -- Exporting the main decl and nothing else\\n | availExportsDecl avail\\n = return [IEThingAbs Nothing (to_ie_post_rn $ noLocA n) Nothing]\\n to_ie rdr_env iface (AvailTC n cs) =\\n case [ xs | avail@(AvailTC x xs) <- mi_exports iface\\n , x == n\\n , availExportsDecl avail -- Note [Partial export]\\n ] of\\n [xs]\\n | all_used xs\\n -> return [IEThingAll (IEThingAllExt Nothing noAnn noAnn noAnn)\\n (NoNamespaceSpecifier noExtField)\\n (to_ie_post_rn $ noLocA n)\\n Nothing]\\n | otherwise\\n -> do { let ns_gres = map (expectJust . lookupGRE_Name rdr_env) cs\\n ns = map greName ns_gres\\n ; return [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n -- Note [Overloaded field import]\\n _other\\n -> do { let infos = map (expectJust . lookupGRE_Name rdr_env) cs\\n (ns_gres,fs_gres) = classifyGREs infos\\n ns = map greName (ns_gres ++ fs_gres)\\n fs = map fieldGREInfo fs_gres\\n ; return $\\n if all_non_overloaded fs\\n then map (\\\\nm -> IEVar Nothing (to_ie_post_rn_var $ noLocA nm) Nothing) ns\\n else [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n where\\n\\n all_used avail_cs = all (`elem` cs) avail_cs\\n\\n all_non_overloaded = all (not . flIsOverloaded . recFieldLabel)\\n\\n combine :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\n combine = map merge . NE.groupAllWith getKey\\n\\n getKey :: LImportDecl GhcRn -> (Bool, Maybe ModuleName, ModuleName)\\n getKey decl =\\n ( isImportDeclQualified . ideclQualified $ idecl -- is this qualified? (important that this be first)\\n , unLoc <$> ideclAs idecl -- what is the qualifier (inside Maybe monad)\\n , unLoc . ideclName $ idecl -- Module Name\\n )\\n where\\n idecl :: ImportDecl GhcRn\\n idecl = unLoc decl\\n\\n merge :: NonEmpty (LImportDecl GhcRn) -> LImportDecl GhcRn\\n merge decls@((L l decl) :| _) = L l (decl { ideclImportList = Just (Exactly, lies) })\\n where lies = concatMap snd $ mapMaybe (ideclImportList . unLoc) $ NE.toList decls\\n\\nclassifyGREs :: [GlobalRdrElt] -> ([GlobalRdrElt], [FieldGlobalRdrElt])\\nclassifyGREs = partition (not . isRecFldGRE)\\n\\nprintMinimalImports :: HscSource -> [ImportDeclUsage] -> RnM ()\\n-- See Note [Printing minimal imports]\\nprintMinimalImports hsc_src imports_w_usage\\n = do { imports\' <- excludeGenerated <$> getMinimalImports imports_w_usage\\n ; this_mod <- getModule\\n ; dflags <- getDynFlags\\n ; liftIO $ withFile (mkFilename dflags this_mod) WriteMode $ \\\\h ->\\n printForUser dflags h neverQualify AllTheWay (vcat (map ppr imports\'))\\n -- The neverQualify is important. We are printing Names\\n -- but they are in the context of an \'import\' decl, and\\n -- we never qualify things inside there\\n -- E.g. import Blag( f, b )\\n -- not import Blag( Blag.f, Blag.g )!\\n }\\n where\\n mkFilename dflags this_mod\\n | Just d <- dumpDir dflags = d basefn\\n | otherwise = basefn\\n where\\n suffix = case hsc_src of\\n HsBootFile -> \\".imports-boot\\"\\n HsSrcFile -> \\".imports\\"\\n HsigFile -> \\".imports\\"\\n basefn = moduleNameString (moduleName this_mod) ++ suffix\\n\\n\\nto_ie_post_rn_var :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn_var (L l n)\\n | isDataOcc $ occName n = L l (IEPattern noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n\\n\\nto_ie_post_rn :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn (L l n)\\n | isTcOcc occ && isSymOcc occ = L l (IEType noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n where occ = occName n\\n\\n{- Note [Do not warn about Prelude hiding]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWe do not warn about\\n import Prelude hiding( x, y )\\nbecause even if nothing else from Prelude is used, it may be essential to hide\\nx,y to avoid name-shadowing warnings. Example (#9061)\\n import Prelude hiding( log )\\n f x = log where log = ()\\n\\nNote [Unused imports]\\n~~~~~~~~~~~~~~~~~~~~~\\nIn `warnUnusedImport`, if we see an import with an explicit list imports, thus\\n import M( a, b )\\nand neither `a` nor `b` is used, we report the entire import decl as unused. We\\ncheck this by looking at the names that it brings into scope scope; if there are\\nno ununused names, don\'t report.\\n\\n(UI1) We don\'t want to complain about `import M()`, because that is often used to bring\\n M\'s /instances/ into scope. That is neatly dealt with by the \\"no unused\\n names\\" (nor unused wildcard imports) criterion.\\n\\n(UI2) We don\'t report a decl as unused if it has an `as Rebindable` qualifier.\\n See (KN1) in Note [Overview of known entities] in GHC.Builtin\\n\\n\\nNote [Printing minimal imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nTo print the minimal imports we walk over all import decls (both user-supplied\\nand generated), trim their import lists, then filter out generated decls.\\n\\nNB that\\n\\n * We do *not* change the \'qualified\' or \'as\' parts!\\n\\n * We do not discard a decl altogether; we might need instances\\n from it. Instead we just trim to an empty import list\\n\\nNote [Partial export]\\n~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have\\n\\n module A( op ) where\\n class C a where\\n op :: a -> a\\n\\n module B where\\n import A\\n f = ..op...\\n\\nThen the minimal import for module B is\\n import A( op )\\nnot\\n import A( C( op ) )\\nwhich we would usually generate if C was exported from B. Hence\\nthe availExportsDecl test when deciding what to generate.\\n\\n\\nNote [Overloaded field import]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nOn the other hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n data T = MkT { foo :: Int }\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( T(foo) )\\nbecause when DuplicateRecordFields is enabled, field selectors are\\nnot in scope without their enclosing datatype.\\n\\nOn the third hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n pattern MkT { foo } = Just foo\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( foo )\\nbecause foo doesn\'t have a parent. This might actually be ambiguous if A\\nexports another field called foo, but there is no good answer to return and this\\nis a very obscure corner, so it seems to be the best we can do. See\\nDRFPatSynExport for a test of this.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Errors}\\n* *\\n************************************************************************\\n-}\\n\\nbadImportItemErr\\n :: ModIface -> ImpDeclSpec -> IE GhcPs\\n -> IsSubordinateError\\n -> [AvailInfo]\\n -> TcRn (NonEmpty ImportLookupReason)\\nbadImportItemErr iface decl_spec ie sub avails = do\\n exts <- importLookupExtensions\\n let import_lookup_bad :: BadImportKind -> ImportLookupReason\\n import_lookup_bad k = ImportLookupBad k iface decl_spec ie exts\\n dflags <- getDynFlags\\n hsc_env <- getTopEnv\\n let rdr_env = mkGlobalRdrEnv\\n $ gresFromAvails hsc_env (Just imp_spec) all_avails\\n pure $ fmap import_lookup_bad (importErrorKind dflags rdr_env)\\n where\\n importErrorKind :: DynFlags -> GlobalRdrEnv -> NonEmpty BadImportKind\\n importErrorKind dflags rdr_env\\n | any checkIfTyCon avails = case sub of\\n IsNotSubordinate -> NE.singleton BadImportAvailTyCon\\n IsSubordinateError { subordinate_err_parent = gre\\n , subordinate_err_unavailable = unavailable\\n , subordinate_err_nontype = nontype\\n , subordinate_err_nondata = nondata }\\n -> NE.fromList $ catMaybes $\\n [ fmap (BadImportNotExportedSubordinates gre) (NE.nonEmpty unavailable)\\n , fmap (BadImportNonTypeSubordinates gre) (NE.nonEmpty nontype)\\n , fmap (BadImportNonDataSubordinates gre) (NE.nonEmpty nondata) ]\\n | any checkIfVarName avails = NE.singleton BadImportAvailVar\\n | Just con <- find checkIfDataCon avails = NE.singleton (BadImportAvailDataCon (availOccName con))\\n | otherwise = NE.singleton (BadImportNotExported suggs)\\n where\\n suggs = similar_suggs ++ fieldSelectorSuggestions rdr_env rdr\\n what_look = case sub of\\n IsNotSubordinate -> WL_TyCon_or_TermVar\\n IsSubordinateError { subordinate_err_parent = gre } ->\\n case greInfo gre of\\n IAmTyCon ClassFlavour\\n -> WL_TyCon_or_TermVar\\n _ -> WL_Term\\n similar_names =\\n similarNameSuggestions (Unbound.LF what_look WL_Global)\\n dflags rdr_env emptyLocalRdrEnv rdr\\n similar_suggs =\\n case NE.nonEmpty $ mapMaybe imported_item $ similar_names of\\n Just similar -> [ SuggestSimilarNames rdr similar ]\\n Nothing -> [ ]\\n\\n -- Only keep imported items, and set the \\"HowInScope\\" to\\n -- \\"Nothing\\" to avoid printing \\"imported from...\\" in the suggestion\\n -- error message.\\n imported_item (SimilarRdrName rdr_name gre (Just (ImportedBy {})))\\n = Just (SimilarRdrName rdr_name gre Nothing)\\n imported_item _ = Nothing\\n\\n checkIfDataCon = checkIfAvailMatches isDataConName\\n checkIfTyCon = checkIfAvailMatches isTyConName\\n checkIfVarName =\\n \\\\case\\n AvailTC{} -> False\\n Avail n -> importedFS == occNameFS (occName n)\\n && (isVarOcc <||> isFieldOcc) (occName n)\\n checkIfAvailMatches namePred =\\n \\\\case\\n AvailTC _ ns ->\\n case find (\\\\n -> importedFS == occNameFS (occName n)) ns of\\n Just n -> namePred n\\n Nothing -> False\\n Avail{} -> False\\n availOccName = occName . availName\\n rdr = ieName ie\\n importedFS = occNameFS $ rdrNameOcc rdr\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n all_avails = mi_exports iface\\n\\nimportLookupExtensions :: TcRn ImportLookupExtensions\\nimportLookupExtensions = do\\n ile_pattern_synonyms <- xoptM LangExt.PatternSynonyms\\n ile_explicit_namespaces <- xoptM LangExt.ExplicitNamespaces\\n return ImportLookupExtensions{ile_pattern_synonyms, ile_explicit_namespaces}\\n\\naddDupDeclErr :: NonEmpty GlobalRdrElt -> TcRn ()\\naddDupDeclErr gres@(gre :| _)\\n -- Report the error at the later location\\n = addErrAt (getSrcSpan (NE.last sorted_names)) $ (TcRnDuplicateDecls (greOccName gre) sorted_names)\\n where\\n sorted_names =\\n NE.sortBy (SrcLoc.leftmost_smallest `on` nameSrcSpan)\\n (fmap greName gres)\\n\\n-- This data decl will parse OK\\n-- data T = a Int\\n-- treating \\"a\\" as the constructor.\\n-- It is really hard to make the parser spot this malformation.\\n-- So the renamer has to check that the constructor is legal\\n--\\n-- We can get an operator as the constructor, even in the prefix form:\\n-- data T = :% Int Int\\n-- from interface files, which always print in prefix form\\n--\\n-- We also allow type constructor names, which are defined by \\"type data\\"\\n-- declarations. See Note [Type data declarations] in GHC.Rename.Module.\\n\\ncheckConName :: RdrName -> TcRn ()\\ncheckConName name\\n = checkErr (isRdrDataCon name || isRdrTc name) (TcRnIllegalDataCon name)\\n", "filetypes": ["haskell"]}}}' 2026-10-16 14:47:00,984 - DEBUG - POST b'http://127.0.0.1:37093/receive_messages' {'content-type': 'application/json', 'x-ycm-hmac': b'Rga7Yd4l4fgfufwYw+0sxzurvznImlBO0MPmgAlS4EY='} b'{"filepath": "/home/enrico/ghc/compiler/GHC/Rename/Names.hs", "line_num": 1, "column_num": 1, "working_dir": "/home/enrico/ghc", "file_data": {"/home/enrico/ghc/compiler/GHC/Rename/Names.hs": {"contents": "{-\\n(c) The GRASP/AQUA Project, Glasgow University, 1992-1998\\n\\nExtracting imported and top-level names in scope\\n-}\\n\\n{-# LANGUAGE NondecreasingIndentation #-}\\n{-# LANGUAGE TypeFamilies #-}\\n\\nmodule GHC.Rename.Names (\\n rnImports, getLocalNonValBinders, newRecordFieldLabel,\\n importsFromIface,\\n ImportUserSpec(..),\\n extendGlobalRdrEnvRn,\\n gresFromAvails,\\n calculateAvails,\\n reportUnusedNames,\\n checkConName,\\n mkChildEnv,\\n findChildren,\\n mkBadExportSubordinate,\\n findImportUsage,\\n getMinimalImports,\\n printMinimalImports,\\n renamePkgQual, renameRawPkgQual,\\n classifyGREs,\\n ImportDeclUsage,\\n rnNamespaceSpecifier\\n ) where\\n\\nimport GHC.Prelude hiding ( head, init, last, tail )\\n\\nimport GHC.Driver.Env\\nimport GHC.Driver.Session\\nimport GHC.Driver.Ppr\\n\\nimport GHC.Rename.Env\\nimport GHC.Rename.Fixity\\nimport GHC.Rename.Utils ( warnUnusedTopBinds )\\nimport GHC.Rename.Unbound\\nimport qualified GHC.Rename.Unbound as Unbound\\n\\nimport GHC.Tc.Errors.Types\\nimport GHC.Tc.Utils.Env\\nimport GHC.Tc.Utils.Monad\\nimport GHC.Tc.Types.LclEnv\\nimport GHC.Tc.Zonk.TcType ( tcInitTidyEnv )\\n\\nimport GHC.Hs\\nimport GHC.Iface.Load ( loadSrcInterface, loadSrcInterface_maybe )\\nimport GHC.Iface.Errors.Types\\n ( IfaceMessage(..), MissingInterfaceError, InterfaceLookingFor(..)\\n , LoadEssentialsReason(..) )\\nimport GHC.Iface.Syntax ( fromIfaceWarnings )\\nimport GHC.Builtin.Modules( pRELUDE_NAME, rEBINDABLE_MOD_NAME )\\nimport GHC.Parser.PostProcess ( setRdrNameSpace )\\nimport GHC.Core.TyCo.Tidy\\nimport GHC.Core.PatSyn\\nimport GHC.Core.TyCon ( TyCon, tyConName )\\nimport qualified GHC.LanguageExtensions as LangExt\\n\\nimport GHC.Utils.Outputable as Outputable\\nimport GHC.Utils.Misc as Utils\\nimport GHC.Utils.Panic\\n\\nimport GHC.Types.Fixity.Env\\nimport GHC.Types.SafeHaskell\\nimport GHC.Types.Name\\nimport GHC.Types.Name.Env\\nimport GHC.Types.Name.Set\\nimport GHC.Types.Name.Reader\\nimport GHC.Types.Avail\\nimport GHC.Types.FieldLabel\\nimport GHC.Types.Hint\\nimport GHC.Types.SourceFile\\nimport GHC.Types.SrcLoc as SrcLoc\\nimport GHC.Types.Basic (TyConFlavour (..), convImportLevel, VisArity)\\nimport GHC.Types.UnresolvedImport\\nimport GHC.Types.Id\\nimport GHC.Types.PkgQual\\nimport GHC.Types.GREInfo (ConInfo(..), ConFieldInfo (..), ConLikeInfo (ConIsData))\\n\\nimport GHC.Unit\\nimport GHC.Unit.Module.Warnings\\nimport GHC.Unit.Module.ModIface\\nimport GHC.Unit.Module.Imported\\nimport GHC.Unit.Module.Deps\\nimport GHC.Unit.Env\\n\\nimport GHC.Data.Bag\\nimport GHC.Data.FastString\\nimport GHC.Data.FastString.Env\\nimport GHC.Data.Maybe\\nimport GHC.Data.List.SetOps ( removeDups )\\n\\nimport Control.Arrow ( second )\\nimport Control.Monad\\nimport Data.Foldable ( for_ )\\nimport Data.IntMap ( IntMap )\\nimport qualified Data.IntMap as IntMap\\nimport Data.Map ( Map )\\nimport qualified Data.Map as Map\\nimport Data.Ord ( comparing )\\nimport Data.Semigroup ( Any(..) )\\nimport qualified Data.Semigroup as S\\nimport Data.List ( partition, find, sortBy )\\nimport Data.List.NonEmpty (NonEmpty(..))\\nimport qualified Data.List.NonEmpty as NE\\nimport Data.Function ( on )\\nimport qualified Data.Set as S\\nimport System.FilePath (())\\nimport System.IO\\n\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{rnImports}\\n* *\\n************************************************************************\\n\\nNote [Tracking Trust Transitively]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen we import a package as well as checking that the direct imports are safe\\naccording to the rules outlined in the Note [Safe Haskell Trust Check] in GHC.Driver.Main\\nwe must also check that these rules hold transitively for all dependent modules\\nand packages. Doing this without caching any trust information would be very\\nslow as we would need to touch all packages and interface files a module depends\\non. To avoid this we make use of the property that if a modules Safe Haskell\\nmode changes, this triggers a recompilation from that module in the dependency\\ngraph. So we can just worry mostly about direct imports.\\n\\nThere is one trust property that can change for a package though without\\nrecompilation being triggered: package trust. So we must check that all\\npackages a module transitively depends on to be trusted are still trusted when\\nwe are compiling this module (as due to recompilation avoidance some modules\\nbelow may not be considered trusted any more without recompilation being\\ntriggered).\\n\\nWe handle this by augmenting the existing transitive list of packages a module M\\ndepends on with a bool for each package that says if it must be trusted when the\\nmodule M is being checked for trust. This list of trust required packages for a\\nsingle import is gathered in the rnImportDecl function and stored in an\\nImportAvails data structure. The union of these trust required packages for all\\nimports is done by the rnImports function using the combine function which calls\\nthe plusImportAvails function that is a union operation for the ImportAvails\\ntype. This gives us in an ImportAvails structure all packages required to be\\ntrusted for the module we are currently compiling. Checking that these packages\\nare still trusted (and that direct imports are trusted) is done in\\nGHC.Driver.Main.checkSafeImports.\\n\\nSee the note below, [Trust Own Package] for a corner case in this method and\\nhow its handled.\\n\\n\\nNote [Trust Own Package]\\n~~~~~~~~~~~~~~~~~~~~~~~~\\nThere is a corner case of package trust checking that the usual transitive check\\ndoesn\'t cover. (For how the usual check operates see the Note [Tracking Trust\\nTransitively] below). The case is when you import a -XSafe module M and M\\nimports a -XTrustworthy module N. If N resides in a different package than M,\\nthen the usual check works as M will record a package dependency on N\'s package\\nand mark it as required to be trusted. If N resides in the same package as M\\nthough, then importing M should require its own package be trusted due to N\\n(since M is -XSafe so doesn\'t create this requirement by itself). The usual\\ncheck fails as a module doesn\'t record a package dependency of its own package.\\nSo instead we now have a bool field in a modules interface file that simply\\nstates if the module requires its own package to be trusted. This field avoids\\nus having to load all interface files that the module depends on to see if one\\nis trustworthy.\\n\\n\\nNote [Trust Transitive Property]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSo there is an interesting design question in regards to transitive trust\\nchecking. Say I have a module B compiled with -XSafe. B is dependent on a bunch\\nof modules and packages, some packages it requires to be trusted as its using\\n-XTrustworthy modules from them. Now if I have a module A that doesn\'t use safe\\nhaskell at all and simply imports B, should A inherit all the trust\\nrequirements from B? Should A now also require that a package p is trusted since\\nB required it?\\n\\nWe currently say no but saying yes also makes sense. The difference is, if a\\nmodule M that doesn\'t use Safe Haskell imports a module N that does, should all\\nthe trusted package requirements be dropped since M didn\'t declare that it cares\\nabout Safe Haskell (so -XSafe is more strongly associated with the module doing\\nthe importing) or should it be done still since the author of the module N that\\nuses Safe Haskell said they cared (so -XSafe is more strongly associated with\\nthe module that was compiled that used it).\\n\\nGoing with yes is a simpler semantics we think and harder for the user to stuff\\nup but it does mean that Safe Haskell will affect users who don\'t care about\\nSafe Haskell as they might grab a package from Cabal which uses safe haskell (say\\nnetwork) and that packages imports -XTrustworthy modules from another package\\n(say bytestring), so requires that package is trusted. The user may now get\\ncompilation errors in code that doesn\'t do anything with Safe Haskell simply\\nbecause they are using the network package. They will have to call \'ghc-pkg\\ntrust network\' to get everything working. Due to this invasive nature of going\\nwith yes we have gone with no for now.\\n-}\\n\\n-- | Process Import Decls. See \'rnImportDecl\' for a description of what\\n-- the return types represent.\\n-- Note: Do the non SOURCE ones first, so that we get a helpful warning\\n-- for SOURCE ones that are unnecessary\\nrnImports :: [(LImportDecl GhcPs, SDoc)]\\n -> RnM ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\nrnImports imports = do\\n tcg_env <- getGblEnv\\n -- NB: want an identity module here, because it\'s OK for a signature\\n -- module to import from its implementor\\n let this_mod = tcg_mod tcg_env\\n let (source, ordinary) = partition (is_source_import . fst) imports\\n is_source_import (d::LImportDecl GhcPs) = ideclSource (unLoc d) == IsBoot\\n stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary\\n stuff2 <- mapAndReportM (rnImportDecl this_mod) source\\n -- Safe Haskell: See Note [Tracking Trust Transitively]\\n let (decls, imp_user_spec, rdr_env, imp_avails) = combine (stuff1 ++ stuff2)\\n -- Update imp_boot_mods if imp_direct_mods mentions any of them\\n let merged_import_avail = clobberSourceImports imp_avails\\n return (decls, imp_user_spec, rdr_env, merged_import_avail)\\n\\n where\\n clobberSourceImports imp_avails =\\n imp_avails { imp_boot_mods = imp_boot_mods\' }\\n where\\n imp_boot_mods\' = mergeInstalledModuleEnv combJ id (const emptyInstalledModuleEnv)\\n (imp_boot_mods imp_avails)\\n (imp_direct_dep_mods imp_avails)\\n\\n combJ (GWIB _ IsBoot) (_, x) = Just x\\n combJ r _ = Just r\\n -- See Note [Combining ImportAvails]\\n combine :: [(LImportDecl GhcRn, ImportUserSpec, GlobalRdrEnv, ImportAvails)]\\n -> ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\n combine ss =\\n let (decls, imp_user_spec, rdr_env, imp_avails, finsts) = foldr\\n plus\\n ([], [], emptyGlobalRdrEnv, emptyImportAvails, emptyModuleSet)\\n ss\\n in (decls, imp_user_spec, rdr_env, imp_avails { imp_finsts = moduleSetElts finsts })\\n\\n plus (decl, us, gbl_env1, imp_avails1)\\n (decls, uss, gbl_env2, imp_avails2, finsts_set)\\n = ( decl:decls,\\n us:uss,\\n gbl_env1 `plusGlobalRdrEnv` gbl_env2,\\n imp_avails1\' `plusImportAvails` imp_avails2,\\n extendModuleSetList finsts_set new_finsts )\\n where\\n imp_avails1\' = imp_avails1 { imp_finsts = [] }\\n new_finsts = imp_finsts imp_avails1\\n\\n{-\\nNote [Combining ImportAvails]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nimp_finsts in ImportAvails is a list of family instance modules\\ntransitively depended on by an import. imp_finsts for a currently\\ncompiled module is a union of all the imp_finsts of imports.\\nComputing the union of two lists of size N is O(N^2) and if we\\ndo it to M imports we end up with O(M*N^2). That can get very\\nexpensive for bigger module hierarchies.\\n\\nUnion can be optimized to O(N log N) if we use a Set.\\nimp_finsts is converted back and forth between dep_finsts, so\\nchanging a type of imp_finsts means either paying for the conversions\\nor changing the type of dep_finsts as well.\\n\\nI\'ve measured that the conversions would cost 20% of allocations on my\\ntest case, so that can be ruled out.\\n\\nChanging the type of dep_finsts forces checkFamInsts to\\nget the module lists in non-deterministic order. If we wanted to restore\\nthe deterministic order, we\'d have to sort there, which is an additional\\ncost. As far as I can tell, using a non-deterministic order is fine there,\\nbut that\'s a brittle nonlocal property which I\'d like to avoid.\\n\\nAdditionally, dep_finsts is read from an interface file, so its \\"natural\\"\\ntype is a list. Which makes it a natural type for imp_finsts.\\n\\nSince rnImports.combine is really the only place that would benefit from\\nit being a Set, it makes sense to optimize the hot loop in rnImports.combine\\nwithout changing the representation.\\n\\nSo here\'s what we do: instead of naively merging ImportAvails with\\nplusImportAvails in a loop, we make plusImportAvails merge empty imp_finsts\\nand compute the union on the side using Sets. When we\'re done, we can\\nconvert it back to a list. One nice side effect of this approach is that\\nif there\'s a lot of overlap in the imp_finsts of imports, the\\nSet doesn\'t really need to grow and we don\'t need to allocate.\\n\\nRunning generateModules from #14693 with DEPTH=16, WIDTH=30 finishes in\\n23s before, and 11s after.\\n-}\\n\\n-- | Given a located import declaration @decl@ from @this_mod@,\\n-- calculate the following pieces of information:\\n--\\n-- 1. An updated \'LImportDecl\', where all unresolved \'RdrName\' in\\n-- the entity lists have been resolved into \'Name\'s,\\n--\\n-- 2. A \'GlobalRdrEnv\' representing the new identifiers that were\\n-- brought into scope (taking into account module qualification\\n-- and hiding),\\n--\\n-- 3. \'ImportAvails\' summarizing the identifiers that were imported\\n-- by this declaration, and\\n--\\n-- 4. A boolean \'AnyHpcUsage\' which is true if the imported module\\n-- used HPC.\\nrnImportDecl :: Module -> (LImportDecl GhcPs, SDoc)\\n -> RnM (LImportDecl GhcRn, ImportUserSpec , GlobalRdrEnv, ImportAvails)\\nrnImportDecl this_mod\\n (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name\\n , ideclPkgQual = raw_pkg_qual\\n , ideclSource = want_boot\\n , ideclSafe = mod_safe\\n , ideclLevelSpec = import_level\\n , ideclQualified = qual_style\\n , ideclExt = XImportDeclPass { ideclOrigin = origin }\\n , ideclAs = as_mod, ideclImportList = imp_details }), import_reason)\\n = setSrcSpanA loc $ do\\n\\n case raw_pkg_qual of\\n NoRawPkgQual -> pure ()\\n RawPkgQual {} -> do\\n pkg_imports <- xoptM LangExt.PackageImports\\n when (not pkg_imports) $ addErr TcRnPackageImportsDisabled\\n\\n let qual_only = isImportDeclQualified qual_style\\n generated = isGeneratedImport origin\\n\\n lookup_scope = importDeclLookupScope origin\\n\\n -- If there\'s an error in loadInterface, (e.g. interface\\n -- file not found) we get lots of spurious errors from \'filterImports\'\\n let imp_mod_name = unLoc loc_imp_mod_name\\n doc = ppr imp_mod_name <+> import_reason\\n\\n hsc_env <- getTopEnv\\n unit_env <- hsc_unit_env <$> getTopEnv\\n let pkg_qual = renameRawPkgQual unit_env imp_mod_name raw_pkg_qual\\n\\n -- Check for self-import, which confuses the typechecker (#9032)\\n -- ghc --make rejects self-import cycles already, but batch-mode may not\\n -- at least not until GHC.IfaceToCore.tcHiBootIface, which is too late to avoid\\n -- typechecker crashes. (Indirect self imports are not caught until\\n -- GHC.IfaceToCore, see #10337 tracking how to make this error better.)\\n --\\n -- Originally, we also allowed \'import {-# SOURCE #-} M\', but this\\n -- caused bug #10182: in one-shot mode, we should never load an hs-boot\\n -- file for the module we are compiling into the EPS. In principle,\\n -- it should be possible to support this mode of use, but we would have to\\n -- extend Provenance to support a local definition in a qualified location.\\n -- For now, we don\'t support it, but see #10336\\n when (imp_mod_name == moduleName this_mod &&\\n (case pkg_qual of -- If we have import \\"\\" M, then we should\\n -- check that \\"\\" is \\"this\\" (which is magic)\\n -- or the name of this_mod\'s package. Yurgh!\\n -- c.f. GHC.findModule, and #9997\\n NoPkgQual -> True\\n ThisPkg uid -> uid == homeUnitId_ (hsc_dflags hsc_env)\\n OtherPkg _ -> False))\\n (addErr (TcRnSelfImport imp_mod_name))\\n\\n -- Check for a missing import list (Opt_WarnMissingImportList also\\n -- checks for T(..) items but that is done in checkDodgyImport below)\\n case imp_details of\\n Just (Exactly, _) -> return () -- Explicit import list\\n _ | generated -> return () -- Do not bleat for generated imports\\n | qual_only -> return ()\\n | otherwise -> addDiagnostic (TcRnNoExplicitImportList imp_mod_name)\\n\\n\\n mb_iface <- loadSrcInterface_maybe doc lookup_scope imp_mod_name want_boot pkg_qual\\n iface <- case mb_iface of\\n Succeeded iface -> return iface\\n Failed err -> failWithTc $\\n importDeclLoadFailure origin imp_mod_name want_boot err\\n\\n -- Compiler sanity check: if the import didn\'t say\\n -- {-# SOURCE #-} we should not get a hi-boot file\\n warnPprTrace ((want_boot == NotBoot) && (mi_boot iface == IsBoot)) \\"rnImportDecl\\" (ppr imp_mod_name) $ do\\n\\n -- Issue a user warning for a redundant {- SOURCE -} import\\n -- NB that we arrange to read all the ordinary imports before\\n -- any of the {- SOURCE -} imports.\\n --\\n -- in --make and GHCi, the compilation manager checks for this,\\n -- and indeed we shouldn\'t do it here because the existence of\\n -- the non-boot module depends on the compilation order, which\\n -- is not deterministic. The hs-boot test can show this up.\\n dflags <- getDynFlags\\n warnIf ((want_boot == IsBoot) && (mi_boot iface == NotBoot) && isOneShot (ghcMode dflags))\\n (TcRnRedundantSourceImport imp_mod_name)\\n when (mod_safe && not (safeImportsOn dflags)) $\\n addErr (TcRnSafeImportsDisabled imp_mod_name)\\n\\n let imp_mod = mi_module iface\\n qual_mod_name = fmap unLoc as_mod `orElse` imp_mod_name\\n imp_spec = ImpDeclSpec { is_mod = imp_mod, is_qual = qual_only,\\n is_dloc = locA loc, is_as = qual_mod_name,\\n is_pkg_qual = pkg_qual, is_isboot = want_boot,\\n is_level = convImportLevel import_level }\\n\\n let filter_imports = do\\n -- filter the imports according to the import declaration\\n (new_imp_details, imp_user_list, gbl_env)\\n <- filterImports hsc_env iface imp_spec imp_details\\n -- for certain error messages, we\\u2019d like to know what could be\\n -- imported here, if everything were imported\\n potential_gres <- (\\\\(_,_,x) -> x) <$> filterImports hsc_env iface imp_spec Nothing\\n return (new_imp_details, imp_user_list, gbl_env, potential_gres)\\n\\n (new_imp_details, imp_user_list, gbl_env, potential_gres) <-\\n case origin of\\n ImplicitEssentialsImport ->\\n -- The implicit GHC.Essentials import does not bring anything into scope.\\n -- See Note [Finding GHC.Essentials] in GHC.Builtin.\\n return (Nothing, ImpUserDependOnly, emptyGlobalRdrEnv, emptyGlobalRdrEnv)\\n UserWrittenImport -> filter_imports\\n ImplicitPreludeImport -> filter_imports\\n PluginImport -> filter_imports\\n\\n let is_hiding | Just (EverythingBut,_) <- imp_details = True\\n | otherwise = False\\n\\n -- should the import be safe?\\n mod_safe\' = mod_safe\\n || (not generated && safeDirectImpsReq dflags)\\n || (generated && safeImplicitImpsReq dflags)\\n\\n hsc_env <- getTopEnv\\n let home_unit = hsc_home_unit hsc_env\\n other_home_units = hsc_all_home_unit_ids hsc_env\\n\\n imported_by\\n | isDependOnlyImport imp_user_list\\n = ImportedBySystem\\n | otherwise\\n = ImportedByUser $ ImportedModsVal\\n { imv_name = is_as imp_spec\\n , imv_span = locA loc\\n , imv_is_safe = mod_safe\'\\n , imv_is_hiding = is_hiding\\n , imv_all_exports = potential_gres\\n , imv_qualified = qual_only\\n , imv_is_level = convImportLevel import_level\\n }\\n imports = calculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by\\n\\n -- Complain if we import a deprecated module\\n case fromIfaceWarnings (mi_warns iface) of\\n WarnAll txt -> addDiagnostic (TcRnDeprecatedModule imp_mod_name txt)\\n _ -> return ()\\n\\n let new_imp_decl = ImportDecl\\n { ideclExt = ideclExt decl\\n , ideclName = ideclName decl\\n , ideclPkgQual = pkg_qual\\n , ideclSource = ideclSource decl\\n , ideclSafe = mod_safe\'\\n , ideclQualified = ideclQualified decl\\n , ideclAs = ideclAs decl\\n , ideclImportList = new_imp_details\\n , ideclLevelSpec = ideclLevelSpec decl\\n }\\n\\n return (L loc new_imp_decl, ImpUserSpec imp_spec imp_user_list, gbl_env, imports)\\n\\n-- | The error message to emit when we failed to load an interface.\\nimportDeclLoadFailure :: ImportDeclOrigin -> ModuleName -> IsBootInterface\\n -> MissingInterfaceError -> TcRnMessage\\nimportDeclLoadFailure ImplicitEssentialsImport _ _ err\\n = TcRnInterfaceError $ CantFindEssentials err LookingForEssentialsModule\\nimportDeclLoadFailure _ mod_name want_boot err\\n = TcRnInterfaceError $ Can\'tFindInterface err $ LookingForModule mod_name want_boot\\n\\n-- | Rename raw package imports\\nrenameRawPkgQual :: UnitEnv -> ModuleName -> RawPkgQual -> PkgQual\\nrenameRawPkgQual unit_env mn = \\\\case\\n NoRawPkgQual -> NoPkgQual\\n RawPkgQual _ fs -> renamePkgQual unit_env mn $ Just fs\\n\\n-- | Rename raw package imports\\nrenamePkgQual :: UnitEnv -> ModuleName -> Maybe FastString -> PkgQual\\nrenamePkgQual unit_env mn mb_pkg = case mb_pkg of\\n Nothing -> NoPkgQual\\n Just pkg_fs\\n | Just uid <- homeUnitId <$> ue_homeUnit unit_env\\n , pkg_fs == fsLit \\"this\\"\\n -> ThisPkg uid\\n\\n | Just (uid, _) <- find (fromMaybe False . fmap (== pkg_fs) . snd) home_names\\n -> ThisPkg uid\\n\\n | Just uid <- resolvePackageImport unit_state mn (PackageName pkg_fs)\\n -> OtherPkg uid\\n\\n | otherwise\\n -> OtherPkg (UnitId pkg_fs)\\n -- not really correct as pkg_fs is unlikely to be a valid unit-id but\\n -- we will report the failure later...\\n where\\n home_names =\\n [ (uid, mkFastString <$> thisPackageName (homeUnitEnv_dflags (ue_findHomeUnitEnv uid unit_env)))\\n | uid <- S.toList hpt_deps\\n ]\\n\\n unit_state = ue_homeUnitState unit_env\\n\\n hpt_deps :: S.Set UnitId\\n hpt_deps = homeUnitDepends unit_state\\n\\n\\n-- | Calculate the \'ImportAvails\' induced by an import of a particular\\n-- interface, but without \'imp_mods\'.\\ncalculateAvails :: HomeUnit\\n -> S.Set UnitId\\n -> ModIface\\n -> IsSafeImport\\n -> IsBootInterface\\n -> ImportedBy\\n -> ImportAvails\\ncalculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by =\\n let imp_mod = mi_module iface\\n imp_sem_mod= mi_semantic_module iface\\n orph_iface = mi_orphan iface\\n has_finsts = mi_finsts iface\\n deps = mi_deps iface\\n trust = getSafeMode $ mi_trust iface\\n trust_pkg = mi_trust_pkg iface\\n is_sig = mi_hsc_src iface == HsigFile\\n\\n -- If the module exports anything defined in this module, just\\n -- ignore it. Reason: otherwise it looks as if there are two\\n -- local definition sites for the thing, and an error gets\\n -- reported. Easiest thing is just to filter them out up\\n -- front. This situation only arises if a module imports\\n -- itself, or another module that imported it. (Necessarily,\\n -- this involves a loop.)\\n --\\n -- We do this *after* filterImports, so that if you say\\n -- module A where\\n -- import B( AType )\\n -- type AType = ...\\n --\\n -- module B( AType ) where\\n -- import {-# SOURCE #-} A( AType )\\n --\\n -- then you won\'t get a \'B does not export AType\' message.\\n\\n\\n -- Compute new transitive dependencies\\n --\\n -- \'dep_orphs\' and \'dep_finsts\' do NOT include the imported module\\n -- itself, but we DO need to include this module in \'imp_orphs\' and\\n -- \'imp_finsts\' if it defines an orphan or instance family; thus the\\n -- orph_iface/has_iface tests.\\n\\n deporphs = dep_orphs deps\\n depfinsts = dep_finsts deps\\n\\n orphans | orph_iface = assertPpr (not (imp_sem_mod `elem` deporphs)) (ppr imp_sem_mod <+> ppr deporphs) $\\n imp_sem_mod : deporphs\\n | otherwise = deporphs\\n\\n finsts | has_finsts = assertPpr (not (imp_sem_mod `elem` depfinsts)) (ppr imp_sem_mod <+> ppr depfinsts) $\\n imp_sem_mod : depfinsts\\n | otherwise = depfinsts\\n\\n -- Trusted packages are a lot like orphans.\\n trusted_pkgs | mod_safe\' = dep_trusted_pkgs deps\\n | otherwise = S.empty\\n\\n\\n pkg = moduleUnit (mi_module iface)\\n ipkg = toUnitId pkg\\n\\n -- Does this import mean we now require our own pkg\\n -- to be trusted? See Note [Trust Own Package]\\n ptrust = trust == Sf_Trustworthy || trust_pkg\\n pkg_trust_req\\n | isHomeUnit home_unit pkg = ptrust\\n | otherwise = False\\n\\n dependent_pkgs = if toUnitId pkg `S.member` other_home_units\\n then S.empty\\n else S.singleton (lvl, ipkg)\\n\\n lvl = case imported_by of\\n ImportedByUser imv -> imv_is_level imv\\n ImportedBySystem -> NormalLevel\\n\\n\\n direct_mods = if toUnitId pkg `S.member` other_home_units\\n then mkPlusModDeps (moduleUnitId imp_mod) lvl (GWIB (moduleName imp_mod) want_boot)\\n else emptyInstalledModuleEnv\\n\\n dep_boot_mods_map = mkModDeps (dep_boot_mods deps)\\n\\n\\n boot_mods\\n -- If we are looking for a boot module, it must be HPT\\n | IsBoot <- want_boot = extendInstalledModuleEnv dep_boot_mods_map (toUnitId <$> imp_mod) (GWIB (moduleName imp_mod) IsBoot)\\n -- Now we are importing A properly, so don\'t go looking for\\n -- A.hs-boot\\n | isHomeUnit home_unit pkg = dep_boot_mods_map\\n -- There\'s no boot files to find in external imports\\n | otherwise = emptyInstalledModuleEnv\\n\\n sig_mods =\\n if is_sig\\n then moduleName imp_mod : dep_sig_mods deps\\n else dep_sig_mods deps\\n\\n\\n in ImportAvails {\\n imp_mods = Map.singleton (mi_module iface) [imported_by],\\n imp_orphs = orphans,\\n imp_finsts = finsts,\\n imp_sig_mods = sig_mods,\\n imp_direct_dep_mods = direct_mods,\\n imp_dep_direct_pkgs = dependent_pkgs,\\n imp_boot_mods = boot_mods,\\n\\n -- Add in the imported modules trusted package\\n -- requirements. ONLY do this though if we import the\\n -- module as a safe import.\\n -- See Note [Tracking Trust Transitively]\\n -- and Note [Trust Transitive Property]\\n imp_trust_pkgs = trusted_pkgs,\\n -- Do we require our own pkg to be trusted?\\n -- See Note [Trust Own Package]\\n imp_trust_own_pkg = pkg_trust_req\\n }\\n\\nmkPlusModDeps :: UnitId -> ImportLevel -> ModuleNameWithIsBoot\\n -> InstalledModuleEnv (S.Set ImportLevel, ModuleNameWithIsBoot)\\nmkPlusModDeps uid st elt = extendInstalledModuleEnv emptyInstalledModuleEnv (mkModule uid (gwib_mod elt)) (S.singleton st, elt)\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{importsFromLocalDecls}\\n* *\\n************************************************************************\\n\\nFrom the top-level declarations of this module produce\\n * the lexical environment\\n * the ImportAvails\\ncreated by its bindings.\\n\\nNote [Top-level Names in Template Haskell decl quotes]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSee also: Note [Interactively-bound Ids in GHCi] in GHC.Driver.Env\\n Note [Looking up Exact RdrNames] in GHC.Rename.Env\\n\\nConsider a Template Haskell declaration quotation like this:\\n module M where\\n f x = h [d| f = 3 |]\\nWhen renaming the declarations inside [d| ...|], we treat the\\ntop level binders specially in two ways\\n\\n1. We give them an Internal Name, not (as usual) an External one.\\n This is done by GHC.Rename.Env.newTopSrcBinder.\\n\\n2. We make them *shadow* the outer bindings.\\n See Note [GlobalRdrEnv shadowing]\\n\\n3. We find out whether we are inside a [d| ... |] by testing the TH\\n level. This is a slight hack, because the level field was really\\n meant for the type checker, and here we are not interested in the\\n fields of Brack, hence the error thunks in thRnBrack.\\n-}\\n\\nextendGlobalRdrEnvRn :: [GlobalRdrElt]\\n -> MiniFixityEnv\\n -> RnM (TcGblEnv, TcLclEnv)\\n-- Updates both the GlobalRdrEnv and the FixityEnv\\n-- We return a new TcLclEnv only because we might have to\\n-- delete some bindings from it;\\n-- see Note [Top-level Names in Template Haskell decl quotes]\\n\\nextendGlobalRdrEnvRn new_gres new_fixities\\n = checkNoErrs $ -- See Note [Fail fast on duplicate definitions]\\n do { (gbl_env, lcl_env) <- getEnvs\\n ; level <- getThLevel\\n ; isGHCi <- getIsGHCi\\n ; let rdr_env = tcg_rdr_env gbl_env\\n fix_env = tcg_fix_env gbl_env\\n th_bndrs = getLclEnvThBndrs lcl_env\\n th_lvl = thLevelIndex level\\n\\n -- Delete new_occs from global and local envs\\n -- If we are in a TemplateHaskell decl bracket,\\n -- we are going to shadow them\\n -- See Note [GlobalRdrEnv shadowing]\\n inBracket = isBrackLevel level\\n\\n lcl_env_TH = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_rdr = minusLocalRdrEnv (tcl_rdr lcl_env) new_gres_env }) lcl_env\\n -- See Note [GlobalRdrEnv shadowing]\\n\\n lcl_env2 | inBracket = lcl_env_TH\\n | otherwise = lcl_env\\n\\n -- Deal with shadowing: see Note [GlobalRdrEnv shadowing]\\n want_shadowing = isGHCi || inBracket\\n rdr_env1 | want_shadowing = shadowNames False rdr_env new_gres_env\\n | otherwise = rdr_env\\n\\n lcl_env3 = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_th_bndrs = extendNameEnvList th_bndrs\\n [ ( n, (TopLevel, th_lvl) )\\n | n <- new_names ] }) lcl_env2\\n\\n ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres\\n\\n ; let fix_env\' = foldl\' extend_fix_env fix_env new_gres\\n gbl_env\' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env\' }\\n\\n ; traceRn \\"extendGlobalRdrEnvRn 2\\" (pprGlobalRdrEnv True rdr_env2)\\n ; return (gbl_env\', lcl_env3) }\\n where\\n new_names = map greName new_gres\\n new_gres_env = mkGlobalRdrEnv new_gres\\n\\n -- If there is a fixity decl for the gre, add it to the fixity env\\n extend_fix_env fix_env gre\\n | Just (L _ fi) <- lookupMiniFixityEnv new_fixities name\\n = extendNameEnv fix_env name (FixItem occ fi)\\n | otherwise\\n = fix_env\\n where\\n name = greName gre\\n occ = greOccName gre\\n\\n add_gre :: GlobalRdrEnv -> GlobalRdrElt -> RnM GlobalRdrEnv\\n -- Extend the GlobalRdrEnv with a LocalDef GRE\\n -- If there is already a LocalDef GRE with the same OccName,\\n -- report an error and discard the new GRE\\n -- This establishes INVARIANT 1 of GlobalRdrEnvs\\n add_gre env gre\\n | not (null dups) -- Same OccName defined twice\\n = do { addDupDeclErr (gre :| dups); return env }\\n\\n | otherwise\\n = return (extendGlobalRdrEnv env gre)\\n where\\n -- See Note [Reporting duplicate local declarations]\\n dups = filter isBadDupGRE\\n $ lookupGRE env (LookupOccName (greOccName gre) (RelevantGREsFOS WantBoth))\\n isBadDupGRE old_gre = isLocalGRE old_gre && greClashesWith gre old_gre\\n\\n{- Note [Fail fast on duplicate definitions]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIf there are duplicate bindings for the same thing, we want to fail\\nfast. Having two bindings for the same thing can cause follow-on errors.\\nExample (test T9975a):\\n data Test = Test { x :: Int }\\n pattern Test wat = Test { x = wat }\\nThis defines \'Test\' twice. The second defn has no field-names; and then\\nwe get an error from Test { x=wat }, saying \\"Test has no field \'x\'\\".\\n\\nEasiest thing is to bale out fast on duplicate definitions, which\\nwe do via `checkNoErrs` on `extendGlobalRdrEnvRn`.\\n\\nNote [Reporting duplicate local declarations]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn general, a single module may not define the same OccName multiple times. This\\nis checked in extendGlobalRdrEnvRn: when adding a new locally-defined GRE to the\\nGlobalRdrEnv we report an error if there are already duplicates in the\\nenvironment. This establishes INVARIANT 1 (see comments on GlobalRdrEnv in\\nGHC.Types.Name.Reader), which says that for a given OccName, all the\\nGlobalRdrElts to which it maps must have distinct \'greName\'s.\\n\\nFor example, the following will be rejected:\\n\\n f x = x\\n g x = x\\n f x = x -- Duplicate!\\n\\nUsers are allowed to introduce new GREs with the same OccName as an imported GRE,\\nas disambiguation is possible through the module system, e.g.:\\n\\n module M where\\n import N (f)\\n f x = x\\n g x = M.f x + N.f x\\n\\nIf both GREs are local, the general rule is that two GREs clash if they have\\nthe same OccName, i.e. they share a textual name and live in the same namespace.\\nHowever, there are additional clashes due to record fields:\\n\\n - a new variable clashes with previously defined record fields\\n which define field selectors,\\n\\n - a new record field shadows:\\n\\n - previously defined variables, if it defines a field selector,\\n - previously defined record fields, unless it is a duplicate record field.\\n\\nThis logic is implemented in the function \'GHC.Types.Name.Reader.greClashesWith\'.\\n\\nSee also Note [Skipping ambiguity errors at use sites of local declarations] in\\nGHC.Rename.Utils.\\n-}\\n\\n\\n{- *********************************************************************\\n* *\\n getLocalDeclBindersd@ returns the names for an HsDecl\\n It\'s used for source code.\\n\\n *** See Note [The Naming story] in GHC.Hs.Decls ****\\n* *\\n********************************************************************* -}\\n\\ngetLocalNonValBinders :: MiniFixityEnv -> HsGroup GhcPs\\n -> RnM ((TcGblEnv, TcLclEnv), NameSet)\\n-- Get all the top-level binders bound the group *except*\\n-- for value bindings, which are treated separately\\n-- Specifically we return AvailInfo for\\n-- * type decls (incl constructors and record selectors)\\n-- * class decls (including class ops)\\n-- * associated types\\n-- * foreign imports\\n-- * value signatures (in hs-boot files only)\\n\\ngetLocalNonValBinders fixity_env\\n (HsGroup { hs_valds = binds,\\n hs_tyclds = tycl_decls,\\n hs_fords = foreign_decls })\\n = do { -- Process all type/class decls *except* family instances\\n ; let inst_decls = tycl_decls >>= group_instds\\n ; dup_fields_ok <- xopt_DuplicateRecordFields <$> getDynFlags\\n ; has_sel <- xopt_FieldSelectors <$> getDynFlags\\n ; tc_gres\\n <- concatMapM\\n (new_tc dup_fields_ok has_sel)\\n (tyClGroupTyClDecls tycl_decls)\\n ; traceRn \\"getLocalNonValBinders 1\\" (ppr tc_gres)\\n ; envs <- extendGlobalRdrEnvRn tc_gres fixity_env\\n ; restoreEnvs envs $ do {\\n -- Bring these things into scope first\\n -- See Note [Looking up family names in family instances]\\n\\n -- Process all family instances\\n -- to bring new data constructors into scope\\n ; nti_gress <- mapM (new_assoc dup_fields_ok has_sel) inst_decls\\n\\n -- Finish off with value binders:\\n -- foreign decls and pattern synonyms for an ordinary module\\n -- type sigs in case of a hs-boot file only\\n ; is_boot <- tcIsHsBootOrSig\\n ; let val_bndrs\\n | is_boot = case binds of\\n ValBinds _ val_binds ->\\n -- In a hs-boot file, the value binders come from the\\n -- *signatures*, and there should be no foreign binders\\n [ L (l2l decl_loc) (unLoc n)\\n | L decl_loc (TypeSig _ _ ns _) <- (val_sigs val_binds), n <- ns]\\n _ -> panic \\"Non-ValBinds in hs-boot group\\"\\n | otherwise = for_hs_bndrs\\n ; val_gres <- mapM new_simple val_bndrs\\n\\n ; let avails = concat nti_gress ++ val_gres\\n new_bndrs = gresToNameSet avails `unionNameSet`\\n gresToNameSet tc_gres\\n ; traceRn \\"getLocalNonValBinders 2\\" (ppr avails)\\n ; envs <- extendGlobalRdrEnvRn avails fixity_env\\n ; return (envs, new_bndrs) } }\\n where\\n for_hs_bndrs :: [LocatedN RdrName]\\n for_hs_bndrs = hsForeignDeclsBinders foreign_decls\\n\\n -- the SrcSpan attached to the input should be the span of the\\n -- declaration, not just the name\\n new_simple :: LocatedN RdrName -> RnM GlobalRdrElt\\n new_simple rdr_name = do { nm <- newTopSrcBinder rdr_name\\n ; return (mkLocalVanillaGRE NoParent nm) }\\n\\n new_tc :: DuplicateRecordFields -> FieldSelectors -> LTyClDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_tc dup_fields_ok has_sel tc_decl -- NOT for type/data instances\\n = do { let TyDeclBinders (main_bndr, tc_flav) at_bndrs sig_bndrs\\n (LConsWithFields cons_with_flds flds) = hsLTyClDeclBinders tc_decl\\n ; tycon_name <- newTopSrcBinder $ la2la main_bndr\\n ; at_names <- mapM (newTopSrcBinder . la2la . fst) at_bndrs\\n ; sig_names <- mapM (newTopSrcBinder . la2la) sig_bndrs\\n ; con_names_with_flds <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst con_names_with_flds) flds\\n ; mapM_ (add_dup_fld_errs flds\') con_names_with_flds\\n ; let tc_gre = mkLocalTyConGRE (fmap (const tycon_name) tc_flav) tycon_name\\n fld_env = mk_fld_env con_names_with_flds flds\'\\n at_gres = zipWith (\\\\ (_, at_flav) at_nm -> mkLocalTyConGRE (fmap (const tycon_name) at_flav) at_nm)\\n at_bndrs at_names\\n sig_gres = map (mkLocalVanillaGRE (ParentIs tycon_name)) sig_names\\n con_gres = map (mkLocalConLikeGRE (ParentIs tycon_name)) fld_env\\n fld_gres = mkLocalFieldGREs (ParentIs tycon_name) fld_env\\n sub_gres = at_gres ++ sig_gres ++ con_gres ++ fld_gres\\n ; traceRn \\"getLocalNonValBinders new_tc\\" $\\n vcat [ text \\"tycon:\\" <+> ppr tycon_name\\n , text \\"tc_gre:\\" <+> ppr tc_gre\\n , text \\"sub_gres:\\" <+> ppr sub_gres ]\\n ; return $ tc_gre : sub_gres }\\n\\n -- Calculate the record field information, which feeds into the GlobalRdrElts\\n -- for DataCons and their fields. It\'s convenient to do this here where\\n -- we are working with a single datatype definition.\\n --\\n -- The information we needed was all set up for us:\\n -- see Note [Collecting record fields in data declarations] in GHC.Hs.Utils.\\n mk_fld_env :: [(Name, Either VisArity [Located Int])] -> IntMap FieldLabel\\n -> [(ConLikeName, ConInfo)]\\n mk_fld_env names flds =\\n [ (DataConName con, ConInfo (ConIsData (map fst names)) fld_info)\\n | (con, con_fl_indxs) <- names\\n , let fld_info = case fmap (map ((flds IntMap.!) . unLoc)) con_fl_indxs of\\n Left 0 -> ConIsNullary\\n Left arity -> ConHasPositionalArgs arity\\n Right [] -> ConIsNullary\\n Right (fld:flds) -> ConHasRecordFields $ fld NE.:| flds ]\\n\\n new_assoc :: DuplicateRecordFields -> FieldSelectors -> LInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_assoc _ _ (L _ (TyFamInstD {})) = return []\\n -- type instances don\'t bind new names\\n\\n new_assoc dup_fields_ok has_sel (L _ (DataFamInstD _ d))\\n = new_di dup_fields_ok has_sel Nothing d\\n new_assoc dup_fields_ok has_sel\\n (L _ (ClsInstD _ (ClsInstDecl { cid_poly_ty = inst_ty\\n , cid_decls = decls })))\\n = do -- First, attempt to grab the name of the class from the instance.\\n -- This step could fail if the instance is not headed by a class,\\n -- such as in the following examples:\\n --\\n -- (1) The class is headed by a bang pattern, such as in\\n -- `instance !Show Int` (#3811c)\\n -- (2) The class is headed by a type variable, such as in\\n -- `instance c` (#16385)\\n --\\n -- If looking up the class name fails, then mb_cls_gre will\\n -- be Nothing.\\n mb_cls_gre <- runMaybeT $ do\\n -- See (1) above\\n L loc cls_rdr <- MaybeT $ pure $ getLHsInstDeclClass_maybe inst_ty\\n -- See (2) above\\n MaybeT $ setSrcSpan (locA loc) $ lookupGlobalOccRn_maybe SameNameSpace cls_rdr\\n -- Assuming the previous step succeeded, process any associated data\\n -- family instances. If the previous step failed, bail out.\\n case mb_cls_gre of\\n Nothing\\n -> pure []\\n Just cls_gre\\n -> let cls_nm = greName cls_gre\\n in concatMapM (new_di dup_fields_ok has_sel (Just cls_nm) . unLoc) (data_fam_insts decls)\\n\\n data_fam_insts decls = concatMap get decls\\n where\\n get (L l (InstD _ (DataFamInstD { dfid_inst = d}))) = [L l d]\\n get _ = []\\n\\n new_di :: DuplicateRecordFields -> FieldSelectors\\n -> Maybe Name -- class name\\n -> DataFamInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_di dup_fields_ok has_sel mb_cls dfid@(DataFamInstDecl { dfid_eqn = ti_decl })\\n = do { main_name <- unLoc <$> lookupFamInstName mb_cls (feqn_tycon ti_decl)\\n ; let LConsWithFields cons_with_flds flds = hsDataFamInstBinders dfid\\n ; sub_names <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst sub_names) flds\\n ; mapM_ (add_dup_fld_errs flds\') sub_names\\n ; let fld_env = mk_fld_env sub_names flds\'\\n con_gres = map (mkLocalConLikeGRE (ParentIs main_name)) fld_env\\n field_gres = mkLocalFieldGREs (ParentIs main_name) fld_env\\n -- NB: the data family name is not bound here,\\n -- so we don\'t return a GlobalRdrElt for it here!\\n ; return $ con_gres ++ field_gres }\\n\\n -- Add errors if a constructor has a duplicate record field.\\n add_dup_fld_errs :: IntMap FieldLabel\\n -> (Name, Either VisArity [Located Int])\\n -> IOEnv (Env TcGblEnv TcLclEnv) ()\\n add_dup_fld_errs all_flds (con, con_flds_or_arity)\\n | Right con_flds <- con_flds_or_arity\\n , let (_, dups) = removeDups (comparing unLoc) con_flds\\n = for_ dups $ \\\\ dup_flds ->\\n -- Report the error at the location of the second occurrence\\n -- of the duplicate field.\\n let loc =\\n case dup_flds of\\n _ :| ( L loc _ : _) -> loc\\n L loc _ :| _ -> loc\\n dup_rdrs = fmap (nameRdrName . flSelector . (all_flds IntMap.!) . unLoc) dup_flds\\n in addErrAt loc $ TcRnDuplicateFieldName (RecordFieldDecl con) dup_rdrs\\n | otherwise\\n = return ()\\n\\nnewRecordFieldLabel :: DuplicateRecordFields -> FieldSelectors -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel\\nnewRecordFieldLabel _ _ [] _ = error \\"newRecordFieldLabel: datatype has no constructors!\\"\\nnewRecordFieldLabel dup_fields_ok has_sel (dc:_) (L loc (FieldOcc _ (L _ fld)))\\n = do { selName <- newTopSrcBinder $ L (l2l loc) $ field\\n ; return $ FieldLabel { flHasDuplicateRecordFields = dup_fields_ok\\n , flHasFieldSelector = has_sel\\n , flSelector = selName } }\\n where\\n fld_occ = rdrNameOcc fld\\n dc_fs = occNameFS $ nameOccName dc\\n field\\n -- Use an Exact RdrName as-is, to preserve the bindings\\n -- of an already renamer-resolved field and its use\\n -- sites. This is needed to correctly support record\\n -- selectors in Template Haskell. See Note [Binders in\\n -- Template Haskell] in \\"GHC.ThToHs\\" and Note [Looking up\\n -- Exact RdrNames] in \\"GHC.Rename.Env\\".\\n | isExact fld\\n = assertPpr (fieldOcc_maybe fld_occ == Just dc_fs)\\n (vcat [ text \\"newRecordFieldLabel: incorrect namespace for exact Name\\" <+> quotes (ppr fld)\\n , text \\"expected namespace:\\" <+> pprNameSpace (fieldName dc_fs)\\n , text \\" actual namespace:\\" <+> pprNameSpace (occNameSpace fld_occ) ])\\n fld\\n\\n -- Field names produced by the parser are namespaced with VarName.\\n -- Here we namespace them according to the first constructor.\\n -- See Note [Record field namespacing] in GHC.Types.Name.Occurrence.\\n | otherwise\\n = mkRdrUnqual $ varToRecFieldOcc dc_fs fld_occ\\n\\n{-\\nNote [Looking up family names in family instances]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider\\n\\n module M where\\n type family T a :: *\\n type instance M.T Int = Bool\\n\\nWe might think that we can simply use \'lookupOccRn\' when processing the type\\ninstance to look up \'M.T\'. Alas, we can\'t! The type family declaration is in\\nthe *same* HsGroup as the type instance declaration. Hence, as we are\\ncurrently collecting the binders declared in that HsGroup, these binders will\\nnot have been added to the global environment yet.\\n\\nSolution is simple: process the type family declarations first, extend\\nthe environment, and then process the type instances.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Filtering imports}\\n* *\\n************************************************************************\\n\\n@filterImports@ takes the @ExportEnv@ telling what the imported module makes\\navailable, and filters it through the import spec (if any).\\n\\nNote [Dealing with imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nFor import M( ies ), we take each AvailInfo from the mi_exports of M, and make\\n\\n imp_occ_env :: OccEnv (NameEnv ImpOccItem)\\n\\nThis map contains one entry for each OccName that M exports, mapping each OccName\\nto the following information:\\n\\n 1. the GlobalRdrElt corresponding to the OccName,\\n 2. whether this GlobalRdrElt was the parent in the AvailInfo we found\\n the OccName in.\\n 3. the GlobalRdrElts that were bundled together in the AvailInfo we found\\n this OccName in (not including the parent),\\n\\nWe need (2) and (3) during the construction of the OccEnv because of associated\\ntypes and bundled pattern synonyms, respectively.\\n(3) is explained in Note [Importing PatternSynonyms].\\n\\nTo explain (2), consider for example:\\n\\n module M where\\n class C a where { data T a }\\n instance C Int where { data T Int = T1 | T2 }\\n instance C Bool where { data T Int = T3 }\\n\\nHere, M\'s exports avails are (recalling the AvailTC invariant from GHC.Types.Avail)\\n\\n C(C,T), T(T,T1,T2,T3)\\n\\nNotice that T appears *twice*, once as a child and once as a parent. From\\nthese two exports, respectively, during construction of the imp_occ_env, we begin\\nby associating the following two elements with the key T:\\n\\n T -> ImpOccItem { imp_item = gre1, imp_bundled = [C,T] , imp_is_parent = False }\\n T -> ImpOccItem { imp_item = gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nwhere `gre1`, `gre2` are two GlobalRdrElts with greName T.\\nWe combine these (in function \'combine\' in \'mkImportOccEnv\') by discarding the\\nnon-parent item, thusly:\\n\\n T -> IE_ITem { imp_item = gre1 `plusGRE` gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nNote the `plusGRE`: this ensures we don\'t drop parent information;\\nsee Note [Preserve parent information when combining import OccEnvs].\\n\\nSo the overall imp_occ_env is:\\n\\n C -> ImpOccItem { imp_item = C, imp_bundled = [T ], imp_is_parent = True }\\n T -> ImpOccItem { imp_item = T , imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n T1 -> ImpOccItem { imp_item = T1, imp_bundled = [T1,T2,T3], imp_is_parent = False }\\n -- similarly for T2, T3\\n\\nNote that the imp_occ_env will have entries for data constructors too,\\nalthough we never look up data constructors.\\n\\nNote [Importing PatternSynonyms]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nAs described in Note [Dealing with imports], associated types can lead to the\\nsame Name appearing twice, both as a child and once as a parent, when\\nconstructing the imp_occ_env. The same thing can happen with pattern synonyms\\nif they are exported bundled with a type.\\n\\nA simplified example, based on #11959:\\n\\n {-# LANGUAGE PatternSynonyms #-}\\n module M (T(P), pattern P) where -- Duplicate export warning, but allowed\\n data T = MkT\\n pattern P = MkT\\n\\nHere we have T(P) and P in export_avails, and respectively construct both\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n P -> ImpOccItem { imp_item = P, imp_bundled = [] , imp_is_parent = False }\\n\\nWe combine these by dropping the one with no siblings, leaving us with:\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n\\nThat is, we simply discard the non-bundled Avail.\\n\\nNote [Importing DuplicateRecordFields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn filterImports, another complicating factor is DuplicateRecordFields.\\nSuppose we have:\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (S(foo), T(foo)) where\\n data S = MkS { foo :: Int }\\n data T = MkT { foo :: Int }\\n\\n module N where\\n import M (foo) -- this is allowed (A)\\n import M (S(foo)) -- this is allowed (B)\\n\\nHere M exports \'foo\' at two different OccNames, with different namespaces for\\nthe two construtors MkS and MkT. Then, when we look up \'foo\' in lookup_names\\nfor case (A), we have a variable foo but must look in all the record field\\nnamespaces to find the two fields (and hence two different Avails).\\nWhereas in case (B) we reach the lookup_ie case for IEThingWith,\\nwhich looks up \'S\' and then finds the unique \'foo\' amongst its children.\\n\\nSee T16745 for a test of this.\\n\\nNote [Preserve parent information when combining import OccEnvs]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen discarding one ImpOccItem in favour of another, as described in\\nNote [Dealing with imports], we must make sure to combine the GREs so that\\nwe don\'t lose information.\\n\\nConsider for example #24084:\\n\\n module M1 where { class C a where { type T a } }\\n module M2 ( module M1 ) where { import M1 }\\n module M3 where { import M2 ( C, T ); instance C () where T () = () }\\n\\nWhen processing the import list of `M3`, we will have two `Avail`s attached\\nto `T`, namely `C(C, T)` and `T(T)`. We combine them in the `combine` function\\nof `mkImportOccEnv`; as described in Note [Dealing with imports] we discard\\n`C(C, T)` in favour of `T(T)`. However, in doing so, we **must not**\\ndiscard the information want that `C` is the parent of `T`. Indeed,\\nlosing track of this information can cause errors when importing,\\nas we could get an error of the form\\n\\n \\u2018T\\u2019 is not a (visible) associated type of class \\u2018C\\u2019\\n\\nThis explains why we use `plusGRE` when combining the two ImpOccItems, even\\nthough we are discarding one in favour of the other.\\n-}\\n\\n-- | All the \'GlobalRdrElt\'s associated with an \'AvailInfo\'.\\ngresFromAvail :: HasDebugCallStack\\n => HscEnv -> Maybe ImportSpec -> AvailInfo -> [GlobalRdrElt]\\ngresFromAvail hsc_env prov avail =\\n [ mk_gre nm info\\n | nm <- availNames avail\\n , let info = lookupGREInfo hsc_env nm ]\\n where\\n\\n mk_gre n info\\n = case prov of\\n -- Nothing => bound locally\\n -- Just is => imported from \'is\'\\n Nothing -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = True, gre_imp = emptyBag\\n , gre_info = info }\\n Just is -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = False, gre_imp = unitBag is\\n , gre_info = info }\\n\\n-- | All the \'GlobalRdrElt\'s associated with a collection of \'AvailInfo\'s.\\ngresFromAvails :: HscEnv -> Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]\\ngresFromAvails hsc_env prov = concatMap (gresFromAvail hsc_env prov)\\n\\nimportsFromIface :: HscEnv -> ModIface -> ImpDeclSpec -> Maybe NameSet -> GlobalRdrEnv\\nimportsFromIface hsc_env iface decl_spec hidden = mkGlobalRdrEnv $ case hidden of\\n Nothing -> all_gres\\n Just hidden_names -> filter (not . (`elemNameSet` hidden_names) . greName) all_gres\\n where\\n all_gres = gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\nrnNamespaceSpecifier :: NamespaceSpecifier GhcPs -> NamespaceSpecifier GhcRn\\nrnNamespaceSpecifier (NoNamespaceSpecifier _) = NoNamespaceSpecifier noExtField\\nrnNamespaceSpecifier (TypeNamespaceSpecifier x) = TypeNamespaceSpecifier x\\nrnNamespaceSpecifier (DataNamespaceSpecifier x) = DataNamespaceSpecifier x\\n\\nfilterImports\\n :: HasDebugCallStack\\n => HscEnv\\n -> ModIface\\n -> ImpDeclSpec\\n -- ^ Import spec\\n -> Maybe (ImportListInterpretation, [LIE GhcPs])\\n -- ^ Whether this is a \\"hiding\\" import list\\n -> RnM (Maybe (ImportListInterpretation, [LIE GhcRn]), -- Import spec w/ Names\\n ImpUserList, -- same, but designed for storage in interfaces\\n GlobalRdrEnv) -- Same again, but in GRE form\\nfilterImports hsc_env iface decl_spec Nothing\\n = return (Nothing, ImpUserAll, importsFromIface hsc_env iface decl_spec Nothing)\\nfilterImports hsc_env iface decl_spec (Just (want_hiding, import_items))\\n = do -- check for errors, convert RdrNames to Names\\n items1 <- mapM lookup_lie import_items\\n\\n let items2 :: [(LIE GhcRn, [GlobalRdrElt])]\\n items2 = concat items1\\n -- NB we may have duplicates, and several items\\n -- for the same parent; e.g N(x) and N(y)\\n\\n (gres, imp_user_list) = case want_hiding of\\n Exactly ->\\n let gres = concatMap (gresFromIE decl_spec) items2\\n gre_env = mkGlobalRdrEnv gres\\n implicit_parents = mkNameSet $ mapMaybe parentOfImplicitlyImportedGRE gres\\n in (gre_env, ImpUserExplicit (gresToAvailInfo $ globalRdrEnvElts $ gre_env) implicit_parents)\\n EverythingBut ->\\n let hidden_names = mkNameSet $ concatMap (map greName . snd) items2\\n in (importsFromIface hsc_env iface decl_spec (Just hidden_names), ImpUserEverythingBut hidden_names)\\n\\n return (Just (want_hiding, map fst items2), imp_user_list, gres)\\n where\\n import_mod = mi_module iface\\n all_avails = mi_exports iface\\n imp_occ_env = mkImportOccEnv hsc_env decl_spec all_avails\\n\\n -- Look up a parent (type constructor, class or data constructor)\\n -- in an import.\\n lookup_parent :: IE GhcPs -> RdrName -> IELookupM ImpOccItem\\n lookup_parent ie rdr =\\n assertPpr (not $ isVarNameSpace ns)\\n (vcat [ text \\"filterImports lookup_parent: unexpected variable\\"\\n , text \\"rdr:\\" <+> ppr rdr\\n , text \\"namespace:\\" <+> pprNameSpace ns ]) $\\n do { xs <- lookup_names ie rdr\\n ; case xs of\\n cax :| [] -> return cax\\n _ -> pprPanic \\"filter_imports lookup_parent ambiguous\\" $\\n vcat [ text \\"rdr:\\" <+> ppr rdr\\n , text \\"lookups:\\" <+> ppr (fmap imp_item xs) ] }\\n -- Looking up non-variables is always unambiguous,\\n -- as there can be at most one corresponding item\\n -- in the imp_occ_env.\\n -- See item (1) of Note [Exporting duplicate declarations]\\n -- in GHC.Tc.Gen.Export.\\n where\\n occ = rdrNameOcc rdr\\n ns = occNameSpace occ\\n\\n -- Look up a RdrName used in an import, returning multiple values if there\\n -- are several fields with the same name exposed by the module\\n lookup_names :: IE GhcPs -> RdrName -> IELookupM (NonEmpty ImpOccItem)\\n lookup_names ie rdr\\n | isQual rdr\\n = failLookupWith (QualImportError rdr)\\n | otherwise\\n = case lookups of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n item:items -> return $ item :| items\\n where\\n lookups = concatMap nonDetNameEnvElts\\n $ lookupImpOccEnv (RelevantGREsFOS WantNormal) imp_occ_env (rdrNameOcc rdr)\\n\\n lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, [GlobalRdrElt])]\\n lookup_lie (L loc ieRdr)\\n = setSrcSpanA loc $\\n do (stuff, warns) <- run_lookup ([],[]) (lookup_ie ieRdr)\\n mapM_ (addTcRnDiagnostic <=< warning_msg) warns\\n return [ (L loc ie, gres) | (ie,gres) <- stuff ]\\n where\\n\\n -- Warn when importing T(..) and no children are brought in scope\\n warning_msg (DodgyImport reason) =\\n pure (TcRnDodgyImports reason)\\n warning_msg MissingImportList =\\n pure (TcRnMissingImportList ieRdr)\\n warning_msg (BadImportW ie sub) = do\\n -- \'BadImportW\' is only constructed below in \'bad_import_w\', in\\n -- the \'EverythingBut\' case, so here we assume a \'hiding\' clause.\\n (reason :| _) <- badImportItemErr iface decl_spec ie sub all_avails\\n pure (TcRnDodgyImports (DodgyImportsHiding reason))\\n warning_msg (DeprecatedExport n w) =\\n pure $ TcRnPragmaWarning\\n PragmaWarningExport\\n { pwarn_occname = occName n\\n , pwarn_impmod = moduleName import_mod }\\n w\\n\\n run_lookup :: a -> IELookupM a -> TcRn a\\n run_lookup def m = case m of\\n Failed err -> do\\n msgs <- lookup_err_msgs err\\n forM_ msgs $ \\\\msg -> addErr (TcRnImportLookup msg)\\n return def\\n Succeeded a -> return a\\n\\n lookup_err_msgs err = case err of\\n BadImport ie sub -> badImportItemErr iface decl_spec ie sub all_avails\\n IllegalImport -> pure $ NE.singleton ImportLookupIllegal\\n QualImportError rdr -> pure $ NE.singleton (ImportLookupQualified rdr)\\n\\n -- For each import item, we convert its RdrNames to Names,\\n -- and at the same time compute all the GlobalRdrElt corresponding\\n -- to what is actually imported by this item.\\n -- Returns Nothing on error.\\n --\\n -- Returns a list because, with DuplicateRecordFields, a naked\\n -- import/export of a record field can correspond to multiple\\n -- different GlobalRdrElts. See Note [Importing DuplicateRecordFields].\\n lookup_ie :: IE GhcPs\\n -> IELookupM ([(IE GhcRn, [GlobalRdrElt])], [IELookupWarning])\\n lookup_ie ie = handle_bad_import $\\n case ie of\\n IEVar _ (L l n) _ -> do\\n -- See Note [Importing DuplicateRecordFields]\\n xs <- lookup_names ie (ieWrappedName n)\\n let gres = map imp_item $ NE.toList xs\\n export_depr_warns\\n | want_hiding == Exactly\\n = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ( [ (IEVar Nothing (L l (replaceWrappedName n name)) noDocstring, [gre])\\n | gre <- gres\\n , let name = greName gre ]\\n , export_depr_warns )\\n\\n IEThingAll x ns_spec (L l tc) _ -> do\\n ImpOccItem { imp_item = gre\\n , imp_bundled = bundled_gres\\n , imp_is_parent = is_par\\n }\\n <- lookup_parent ie $ ieWrappedName tc\\n let name = greName gre\\n\\n child_gres :: [GlobalRdrElt]\\n child_gres\\n | is_par = filterByNamespaceSpecifierGREs ns_spec bundled_gres\\n | otherwise = []\\n\\n imp_list_warn\\n\\n | null child_gres\\n -- e.g. f(..) or T(..) where T is a type synonym\\n = [DodgyImport (DodgyImportsEmptyParent ie ns_spec gre)]\\n\\n -- e.g. import M( T(..) )\\n | not (is_qual decl_spec)\\n = [MissingImportList]\\n\\n | otherwise\\n = []\\n\\n renamed_ie = IEThingAll (x { ieta_warning = Nothing })\\n (rnNamespaceSpecifier ns_spec)\\n (L l (replaceWrappedName tc name))\\n noDocstring\\n export_depr_warn\\n | want_hiding == Exactly\\n = maybeToList $ mk_depr_export_warning gre\\n -- We don\'t want to warn about the children as they\\n -- are not explicitly mentioned; the warning will\\n -- be emitted later on if they are used\\n | otherwise = []\\n\\n return ( [(renamed_ie, gre:child_gres)]\\n , imp_list_warn ++ export_depr_warn)\\n\\n\\n IEThingAbs _ (L l tc\') _\\n | want_hiding == EverythingBut -- hiding ( C )\\n -- Here the \'C\' can be a data constructor\\n -- *or* a type/class, or even both\\n -> let tc = ieWrappedName tc\'\\n tc_name = lookup_parent ie tc\\n dc_name = lookup_parent ie (setRdrNameSpace tc srcDataName)\\n in\\n case catIELookupM [ tc_name, dc_name ] of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n names -> return ( [mkIEThingAbs tc\' l (imp_item name) | name <- names], [])\\n | otherwise\\n -> do ImpOccItem { imp_item = gre } <- lookup_parent ie (ieWrappedName tc\')\\n return ( [mkIEThingAbs tc\' l gre]\\n , maybeToList $ mk_depr_export_warning gre)\\n\\n IEThingWith (deprecation, ann) ltc@(L l rdr_tc) wc rdr_ns _ -> do\\n ImpOccItem { imp_item = gre, imp_bundled = subnames }\\n <- lookup_parent (IEThingAbs Nothing ltc noDocstring) (ieWrappedName rdr_tc)\\n let name = greName gre\\n\\n -- Look up the children in the sub-names of the parent\\n -- See Note [Importing DuplicateRecordFields]\\n let (children_errs, childnames) = lookupChildren subnames rdr_ns\\n\\n bad_import_warns <-\\n if null children_errs then return [] else\\n let items = map lce_wrapped_name children_errs\\n ie = IEThingWith (deprecation, ann) ltc wc items noDocstring\\n -- We are trying to import T( a,b,c,d ), and failed\\n -- to find \'b\' and \'d\'. So we make up an import item\\n -- to report as failing, namely T( b, d ).\\n -- c.f. #15413\\n subordinate_err = mkSubordinateError gre children_errs\\n in bad_import_w ie subordinate_err\\n\\n let name\' = replaceWrappedName rdr_tc name\\n childnames\' = map (to_ie_post_rn . fmap greName) childnames\\n gres = gre : map unLoc childnames\\n export_depr_warns\\n | want_hiding == Exactly = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ([ (IEThingWith (Nothing, ann) (L l name\') wc childnames\' noDocstring\\n ,gres)]\\n , bad_import_warns ++ export_depr_warns)\\n\\n IEWholeNamespace x ns_spec -> do\\n let mod_name = moduleName import_mod\\n names = map greName gres\\n renamed_ie = IEWholeNamespace x { iewn_warning = Nothing\\n , iewn_names = names }\\n (rnNamespaceSpecifier ns_spec)\\n gres = filterByNamespaceSpecifierGREs ns_spec $\\n gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n dodgy_warn\\n | null gres = [DodgyImport (DodgyImportsWildcard mod_name ns_spec)]\\n | otherwise = []\\n return ([(renamed_ie, gres)],\\n dodgy_warn)\\n\\n _other -> failLookupWith IllegalImport\\n -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed...\\n -- all of those constitute errors.\\n\\n where\\n mkIEThingAbs tc l gre\\n = (IEThingAbs Nothing (L l (replaceWrappedName tc n)) noDocstring, [gre])\\n where n = greName gre\\n\\n -- N.B. imports never have docstrings\\n noDocstring = Nothing\\n\\n handle_bad_import m = catchIELookup m $ \\\\case\\n BadImport ie sub -> do\\n ws <- bad_import_w ie sub\\n return ([], ws)\\n err -> failLookupWith err\\n\\n bad_import_w :: IE GhcPs -> IsSubordinateError -> IELookupM [IELookupWarning]\\n bad_import_w ie sub\\n | want_hiding == EverythingBut = return [BadImportW ie sub]\\n | otherwise = failLookupWith (BadImport ie sub)\\n\\n mk_depr_export_warning gre\\n = DeprecatedExport name <$> mi_export_warn_fn iface name\\n where\\n name = greName gre\\n\\n-- | Assuming a subordinate item could not be found, do another lookup for a\\n-- more specific error message.\\nmkBadExportSubordinate :: [GlobalRdrElt] -> LIEWrappedName GhcPs -> BadExportSubordinate\\nmkBadExportSubordinate child_gres n =\\n case lookupChildren child_gres [n] of\\n (LookupChildNonType {lce_nontype_item = g} : _, _) -> BadExportSubordinateNonType g\\n (LookupChildNonData {lce_nondata_item = g} : _, _) -> BadExportSubordinateNonData g\\n _ -> BadExportSubordinateNotFound n\\n\\ntype IELookupM = MaybeErr IELookupError\\n\\ndata IELookupWarning\\n = BadImportW (IE GhcPs) IsSubordinateError\\n | MissingImportList\\n | DodgyImport DodgyImportsReason\\n | DeprecatedExport Name (WarningTxt GhcRn)\\n\\n-- | Is this import/export item a subordinate or not?\\ndata IsSubordinateError\\n = IsSubordinateError { subordinate_err_parent :: !GlobalRdrElt\\n , subordinate_err_unavailable :: [FastString]\\n , subordinate_err_nontype :: [GlobalRdrElt]\\n , subordinate_err_nondata :: [GlobalRdrElt] }\\n | IsNotSubordinate\\n\\nmkSubordinateError :: GlobalRdrElt -> [LookupChildError] -> IsSubordinateError\\nmkSubordinateError gre children_errs = foldr add init_acc children_errs\\n where\\n init_acc :: IsSubordinateError\\n init_acc = IsSubordinateError gre [] [] []\\n\\n add :: LookupChildError -> IsSubordinateError -> IsSubordinateError\\n add children_err sub@IsSubordinateError{} =\\n case children_err of\\n LookupChildNonType{lce_nontype_item = g} ->\\n sub { subordinate_err_nontype = g : subordinate_err_nontype sub }\\n LookupChildNonData{lce_nondata_item = g} ->\\n sub { subordinate_err_nondata = g : subordinate_err_nondata sub }\\n LookupChildNotFound (L _ wname) ->\\n let fs = (occNameFS . rdrNameOcc . ieWrappedName) wname\\n in sub { subordinate_err_unavailable = fs : subordinate_err_unavailable sub }\\n add _ IsNotSubordinate = panic \\"mkSubordinateError: IsNotSubordinate\\"\\n\\ndata IELookupError\\n = QualImportError RdrName\\n | BadImport (IE GhcPs) IsSubordinateError\\n | IllegalImport\\n\\nfailLookupWith :: IELookupError -> IELookupM a\\nfailLookupWith err = Failed err\\n\\ncatchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a\\ncatchIELookup m h = case m of\\n Succeeded r -> return r\\n Failed err -> h err\\n\\ncatIELookupM :: [IELookupM a] -> [a]\\ncatIELookupM ms = [ a | Succeeded a <- ms ]\\n\\n-- | Information associated to an \'AvailInfo\' used in constructing\\n-- an \'OccEnv\' corresponding to imports.\\n--\\n-- See Note [Dealing with imports].\\ndata ImpOccItem\\n = ImpOccItem\\n { imp_item :: GlobalRdrElt\\n -- ^ The import item\\n , imp_bundled :: [GlobalRdrElt]\\n -- ^ Items bundled in the Avail this import item came from,\\n -- not including the import item itself if it is a parent.\\n , imp_is_parent :: Bool\\n -- ^ Is the import item a parent? See Note [Dealing with imports].\\n }\\n\\ninstance Outputable ImpOccItem where\\n ppr (ImpOccItem { imp_item = item, imp_bundled = bundled, imp_is_parent = is_par })\\n = braces $ hsep\\n [ text \\"ImpOccItem\\"\\n , if is_par then text \\"[is_par]\\" else empty\\n , ppr (greName item) <+> ppr (greParent item)\\n , braces $ text \\"bundled:\\" <+> ppr (map greName bundled) ]\\n\\n-- | Make an \'OccEnv\' of all the imports.\\n--\\n-- Complicated by the fact that associated data types and pattern synonyms\\n-- can appear twice. See Note [Dealing with imports].\\nmkImportOccEnv :: HscEnv -> ImpDeclSpec -> [IfaceExport] -> OccEnv (NameEnv ImpOccItem)\\nmkImportOccEnv hsc_env decl_spec all_avails =\\n mkOccEnv_C (plusNameEnv_C combine)\\n [ (occ, mkNameEnv [(nm, item)])\\n | avail <- all_avails\\n , let gres = gresFromAvail hsc_env (Just hiding_spec) avail\\n , gre <- gres\\n , let nm = greName gre\\n occ = greOccName gre\\n (is_parent, bundled) = case avail of\\n AvailTC c _\\n | c == nm -- (Recall the AvailTC invariant from GHC.Types.AvailInfo)\\n -> ( True, drop 1 gres ) -- \\"drop 1\\": don\'t include the parent itself.\\n | otherwise\\n -> ( False, gres )\\n _ -> ( False, [] )\\n item = ImpOccItem\\n { imp_item = gre\\n , imp_bundled = bundled\\n , imp_is_parent = is_parent }\\n ]\\n where\\n\\n hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\n -- See Note [Dealing with imports]\\n -- \'combine\' may be called for associated data types which appear\\n -- twice in the all_avails. In the example, we have two Avails for T,\\n -- namely T(T,T1,T2,T3) and C(C,T), and we combine them by dropping the\\n -- latter, in which T is not the parent.\\n combine :: ImpOccItem -> ImpOccItem -> ImpOccItem\\n combine item1@(ImpOccItem { imp_item = gre1, imp_is_parent = is_parent1 })\\n item2@(ImpOccItem { imp_item = gre2, imp_is_parent = is_parent2 })\\n | is_parent1 || is_parent2\\n , not (isRecFldGRE gre1 || isRecFldGRE gre2) -- NB: does not force GREInfo.\\n , let name1 = greName gre1\\n name2 = greName gre2\\n gre = gre1 `plusGRE` gre2\\n -- See Note [Preserve parent information when combining import OccEnvs]\\n = assertPpr (name1 == name2)\\n (ppr name1 <+> ppr name2) $\\n if is_parent1\\n then item1 { imp_item = gre }\\n else item2 { imp_item = gre }\\n -- Discard C(C,T) in favour of T(T, T1, T2, T3).\\n\\n -- \'combine\' may also be called for pattern synonyms which appear both\\n -- unassociated and associated (see Note [Importing PatternSynonyms]).\\n combine item1@(ImpOccItem { imp_item = c1, imp_bundled = kids1 })\\n item2@(ImpOccItem { imp_item = c2, imp_bundled = kids2 })\\n = assertPpr (greName c1 == greName c2\\n && (not (null kids1 && null kids2)))\\n (ppr c1 <+> ppr c2 <+> ppr kids1 <+> ppr kids2) $\\n if null kids1\\n then item2\\n else item1\\n -- Discard standalone pattern P in favour of T(P).\\n\\n-- | Essentially like @lookupGRE env (LookupOccName occ which_gres)@,\\n-- but working with \'ImpOccItem\'s instead of \'GlobalRdrElt\'s.\\nlookupImpOccEnv :: WhichGREs GREInfo\\n -> OccEnv (NameEnv ImpOccItem) -> OccName -> [NameEnv ImpOccItem]\\nlookupImpOccEnv which_gres env occ =\\n mapMaybe relevant_items $ lookupOccEnv_AllNameSpaces env occ\\n where\\n is_relevant :: ImpOccItem -> Bool\\n is_relevant (ImpOccItem { imp_item = gre }) =\\n greIsRelevant which_gres (occNameSpace occ) gre\\n relevant_items :: NameEnv ImpOccItem -> Maybe (NameEnv ImpOccItem)\\n relevant_items nms\\n | let nms\' = filterNameEnv is_relevant nms\\n = if isEmptyNameEnv nms\'\\n then Nothing\\n else Just nms\'\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{Import/Export Utils}\\n* *\\n************************************************************************\\n-}\\n\\n-- | Given an import\\\\/export spec, appropriately set the @gre_imp@ field\\n-- for the \'GlobalRdrElt\'s.\\ngresFromIE :: ImpDeclSpec -> (LIE GhcRn, [GlobalRdrElt]) -> [GlobalRdrElt]\\ngresFromIE decl_spec (L loc ie, gres)\\n = map set_gre_imp gres\\n where\\n is_explicit = case ie of\\n IEThingAll _ _ name _ -> \\\\n -> n == lieWrappedName name\\n IEWholeNamespace _ _ -> \\\\_ -> False\\n _ -> \\\\_ -> True\\n prov_fn name\\n = ImpSpec { is_decl = decl_spec, is_item = item_spec }\\n where\\n item_spec = ImpSome { is_explicit = is_explicit name\\n , is_iloc = locA loc }\\n set_gre_imp gre@( GRE { gre_name = nm } )\\n = gre { gre_imp = unitBag $ prov_fn nm }\\n\\nparentOfImplicitlyImportedGRE :: Outputable info => GlobalRdrEltX info -> Maybe Name\\nparentOfImplicitlyImportedGRE gre =\\n if any (explicit_import . is_item) $ gre_imp gre\\n then Nothing\\n else greParent_maybe gre\\n where\\n explicit_import :: ImpItemSpec -> Bool\\n explicit_import (ImpAll {}) =\\n pprPanic \\"parentOfImplicitlyImportedGRE: ImpAll\\" (ppr gre)\\n explicit_import (ImpSome { is_explicit }) = is_explicit\\n\\n{- Note [Children for duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider the module\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (F(foo, MkFInt, MkFBool)) where\\n data family F a\\n data instance F Int = MkFInt { foo :: Int }\\n data instance F Bool = MkFBool { foo :: Bool }\\n\\nThe `foo` in the export list refers to *both* selectors! For this\\nreason, lookupChildren builds an environment that maps the FastString\\nto a list of items, rather than a single item.\\n-}\\n\\nmkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]\\nmkChildEnv gres = foldr add emptyNameEnv gres\\n where\\n add gre env = case greParent gre of\\n ParentIs p -> extendNameEnv_Acc (:) Utils.singleton env p gre\\n NoParent -> env\\n\\nfindChildren :: NameEnv [a] -> Name -> [a]\\nfindChildren env n = lookupNameEnv env n `orElse` []\\n\\ndata LookupChildError\\n = LookupChildNotFound { lce_wrapped_name :: !(LIEWrappedName GhcPs) }\\n | LookupChildNonType { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nontype_item :: !GlobalRdrElt }\\n | LookupChildNonData { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nondata_item :: !GlobalRdrElt }\\n\\nlookupChildren :: [GlobalRdrElt]\\n -> [LIEWrappedName GhcPs]\\n -> ( [LookupChildError] -- The ones for which the lookup failed\\n , [LocatedA GlobalRdrElt] )\\n-- (lookupChildren all_kids rdr_items) maps each rdr_item to its\\n-- corresponding Name in all_kids, if the former exists\\n-- The matching is done by FastString, not OccName, so that\\n-- Cls( meth, AssocTy )\\n-- will correctly find AssocTy among the all_kids of Cls, even though\\n-- the RdrName for AssocTy may have a (bogus) DataName namespace\\n-- (Really the rdr_items should be FastStrings in the first place.)\\nlookupChildren all_kids rdr_items = (fails, successes)\\n where\\n mb_xs = map do_one rdr_items\\n fails = [ err | Failed err <- mb_xs ]\\n successes = [ ok | Succeeded oks <- mb_xs, ok <- NE.toList oks ]\\n\\n do_one :: LIEWrappedName GhcPs -> MaybeErr LookupChildError (NonEmpty (LocatedA GlobalRdrElt))\\n do_one item@(L l r) =\\n case r of\\n IEName{}\\n -- IEName (unadorned name) places no restriction on the namespace of\\n -- the imported entity, so we look in both `val_gres` and `typ_gres`.\\n -- In case of conflict (punning), the value namespace takes priority.\\n -- See Note [Prioritise the value namespace in subordinate import lists]\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEType{}\\n -- IEType (\'type\' namespace specifier) restricts the lookup to the\\n -- type namespace, i.e. to `typ_gres`. In case of failure, we check\\n -- `val_gres` to produce a more helpful error message.\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- val_gres -> Failed $ LookupChildNonType item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEData{}\\n -- IEData (\'data\' namespace specifier) restricts the lookup to the\\n -- data namespace, i.e. to `val_gres`. In case of failure, we check\\n -- `typ_gres` to produce a more helpful error message.\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- typ_gres -> Failed $ LookupChildNonData item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEPattern{} -> panic \\"lookupChildren: IEPattern\\" -- Never happens (invalid syntax)\\n IEDefault{} -> panic \\"lookupChildren: IEDefault\\" -- Never happens (invalid syntax)\\n where\\n fs = (occNameFS . rdrNameOcc . ieWrappedName) r\\n gres = fromMaybe [] (lookupFsEnv kid_env fs)\\n (val_gres, typ_gres) = partition (isValNameSpace . greNameSpace) gres\\n\\n -- See Note [Children for duplicate record fields]\\n kid_env :: FastStringEnv [GlobalRdrElt]\\n kid_env = extendFsEnvList_C (++) emptyFsEnv\\n [(occNameFS (occName x), [x]) | x <- all_kids]\\n\\n\\n{- Note [Prioritise the value namespace in subordinate import lists]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider this program that defines a class that has both an associated type\\nnamed (#) and a method named (#)\\n\\n module M_assoc where\\n class C a b where\\n type a # b\\n (#) :: a -> b -> ()\\n module N_assoc where\\n import M_assoc( C((#)) )\\n\\nIn the import declaration, when we see the unadorned name (#) in the subordinate\\nimport list of C, which children should we bring into scope? Our options are:\\n\\n a) only the method (#)\\n b) only the associated type (#)\\n c) both the method and the associated type\\n\\nTo follow the precedent established by top-level items, we go with option (a).\\nIndeed, consider a slightly different program\\n\\n module M_top where\\n type family a # b\\n a # b = ()\\n module N_top where\\n import M_top( (#) )\\n\\nHere the import brings only the function (#) into scope, and one has to say\\n`type (#)` to get the type family.\\n-}\\n\\n-------------------------------\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused names}\\n* *\\n*********************************************************\\n-}\\n\\nreportUnusedNames :: TcGblEnv -> HscSource -> RnM ()\\nreportUnusedNames gbl_env hsc_src\\n = do { keep <- readTcRef (tcg_keep gbl_env)\\n ; traceRn \\"RUN\\" (ppr (tcg_dus gbl_env))\\n ; warnUnusedImportDecls gbl_env hsc_src\\n ; warnUnusedTopBinds $ unused_locals keep\\n ; warnMissingSignatures gbl_env\\n ; warnMissingKindSignatures gbl_env }\\n where\\n used_names :: NameSet -> NameSet\\n used_names keep = findUses (tcg_dus gbl_env) emptyNameSet `unionNameSet` keep\\n -- NB: currently, if f x = g, we only treat \'g\' as used if \'f\' is used\\n -- Hence findUses\\n\\n -- Collect the defined names from the in-scope environment\\n defined_names :: [GlobalRdrElt]\\n defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)\\n\\n kids_env = mkChildEnv defined_names\\n -- This is done in mkExports too; duplicated work\\n\\n gre_is_used :: NameSet -> GlobalRdrElt -> Bool\\n gre_is_used used_names gre0\\n = name `elemNameSet` used_names\\n || any (\\\\ gre -> greName gre `elemNameSet` used_names) (findChildren kids_env name)\\n -- A use of C implies a use of T,\\n -- if C was brought into scope by T(..) or T(C)\\n where\\n name = greName gre0\\n\\n -- Filter out the ones that are\\n -- (a) defined in this module, and\\n -- (b) not defined by a \'deriving\' clause\\n -- The latter have an Internal Name, so we can filter them out easily\\n unused_locals :: NameSet -> [GlobalRdrElt]\\n unused_locals keep =\\n let -- Note that defined_and_used, defined_but_not_used\\n -- are both [GRE]; that\'s why we need defined_and_used\\n -- rather than just used_names\\n _defined_and_used, defined_but_not_used :: [GlobalRdrElt]\\n (_defined_and_used, defined_but_not_used)\\n = partition (gre_is_used (used_names keep)) defined_names\\n\\n in filter is_unused_local defined_but_not_used\\n is_unused_local :: GlobalRdrElt -> Bool\\n is_unused_local gre = isLocalGRE gre\\n && isExternalName (greName gre)\\n\\n{- *********************************************************************\\n* *\\n Missing signatures\\n* *\\n********************************************************************* -}\\n\\n{-\\nNote [Missing signatures]\\n~~~~~~~~~~~~~~~~~~~~~~~~~\\nThere are four warning flags in play:\\n\\n * -Wmissing-exported-signatures\\n Warn about any exported top-level function/value without a type signature.\\n Does not include pattern synonyms.\\n\\n * -Wmissing-signatures\\n Warn about any top-level function/value without a type signature. Does not\\n include pattern synonyms. Takes priority over -Wmissing-exported-signatures.\\n\\n * -Wmissing-exported-pattern-synonym-signatures\\n Warn about any exported pattern synonym without a type signature.\\n\\n * -Wmissing-pattern-synonym-signatures\\n Warn about any pattern synonym without a type signature. Takes priority over\\n -Wmissing-exported-pattern-synonym-signatures.\\n\\n-}\\n\\n-- | Warn the user about top level binders that lack type signatures.\\n-- Called /after/ type inference, so that we can report the\\n-- inferred type of the function\\nwarnMissingSignatures :: TcGblEnv -> RnM ()\\nwarnMissingSignatures gbl_env\\n = do { let exports = availsToNameSet (tcg_exports gbl_env)\\n sig_ns = tcg_sigs gbl_env\\n -- We use sig_ns to exclude top-level bindings that are generated by GHC\\n binds = collectHsBindsBinders CollNoDictBinders $ tcg_binds gbl_env\\n pat_syns = tcg_patsyns gbl_env\\n\\n not_ghc_generated :: Name -> Bool\\n not_ghc_generated name = name `elemNameSet` sig_ns\\n\\n add_binding_warn :: Id -> RnM ()\\n add_binding_warn id =\\n when (not_ghc_generated name) $\\n do { env <- liftZonkM $ tcInitTidyEnv -- Why not use emptyTidyEnv?\\n ; let ty = tidyOpenType env (idType id)\\n missing = MissingTopLevelBindingSig name ty\\n diag = TcRnMissingSignature missing exported\\n ; addDiagnosticAt (getSrcSpan name) diag }\\n where\\n name = idName id\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n add_patsyn_warn :: PatSyn -> RnM ()\\n add_patsyn_warn ps =\\n when (not_ghc_generated name) $\\n addDiagnosticAt (getSrcSpan name)\\n (TcRnMissingSignature missing exported)\\n where\\n name = patSynName ps\\n missing = MissingPatSynSig ps\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n -- Warn about missing signatures\\n -- Do this only when we have a type to offer\\n -- See Note [Missing signatures]\\n ; mapM_ add_binding_warn binds\\n ; mapM_ add_patsyn_warn pat_syns\\n }\\n\\n-- | Warn the user about tycons that lack kind signatures.\\n-- Called /after/ type (and kind) inference, so that we can report the\\n-- inferred kinds.\\nwarnMissingKindSignatures :: TcGblEnv -> RnM ()\\nwarnMissingKindSignatures gbl_env\\n = do { cusks_enabled <- xoptM LangExt.CUSKs\\n ; mapM_ (add_ty_warn cusks_enabled) tcs\\n }\\n where\\n tcs = tcg_tcs gbl_env\\n ksig_ns = tcg_ksigs gbl_env\\n exports = availsToNameSet (tcg_exports gbl_env)\\n\\n has_kind_signature :: Name -> Bool\\n has_kind_signature name = name `elemNameSet` ksig_ns\\n\\n add_ty_warn :: Bool -> TyCon -> RnM ()\\n add_ty_warn cusks_enabled tyCon =\\n when (has_kind_signature name) $\\n addDiagnosticAt (getSrcSpan name) diag\\n where\\n name = tyConName tyCon\\n diag = TcRnMissingSignature missing exported\\n missing = MissingTyConKindSig tyCon cusks_enabled\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused imports}\\n* *\\n*********************************************************\\n\\nThis code finds which import declarations are unused. The\\nspecification and implementation notes are here:\\n https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/unused-imports\\n\\nSee also Note [Choosing the best import declaration] in GHC.Types.Name.Reader\\n-}\\n\\ntype ImportDeclUsage\\n = ( LImportDecl GhcRn -- The import declaration\\n , [GlobalRdrElt] -- What *is* used (normalised)\\n , [Name] -- What is imported but *not* used\\n , [NamespaceSpecifier GhcRn] ) -- Unused wildcards\\n\\nwarnUnusedImportDecls :: TcGblEnv -> HscSource -> RnM ()\\nwarnUnusedImportDecls gbl_env hsc_src\\n = do { uses <- readMutVar (tcg_used_gres gbl_env)\\n ; let imports = tcg_rn_imports gbl_env\\n rdr_env = tcg_rdr_env gbl_env\\n\\n -- We should only warn for unnecessary *user* imports, but deciding\\n -- minimal imports should take generated imports into account\\n ; let usageUserImports = findImportUsage (excludeGenerated imports) uses\\n usageAllImports = findImportUsage imports uses\\n\\n ; traceRn \\"warnUnusedImportDecls\\" $\\n (vcat [ text \\"Uses:\\" <+> ppr uses\\n , text \\"Usage all user imports: \\" <+> ppr usageUserImports\\n , text \\"Usage all imports: \\" <+> ppr usageAllImports])\\n\\n ; mapM_ (warnUnusedImport rdr_env) usageUserImports\\n\\n ; whenGOptM Opt_D_dump_minimal_imports $\\n printMinimalImports hsc_src usageAllImports }\\n\\n-- | Exclude generated imports\\nexcludeGenerated :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\nexcludeGenerated = filterOut (isGeneratedImport . ideclOrigin . ideclExt . unLoc)\\n\\nfindImportUsage :: [LImportDecl GhcRn]\\n -> [GlobalRdrElt]\\n -> [ImportDeclUsage]\\n\\nfindImportUsage imports used_gres\\n = map unused_decl imports\\n where\\n import_usage :: ImportMap\\n import_usage = mkImportMap used_gres\\n\\n unused_decl :: LImportDecl GhcRn -> ImportDeclUsage\\n unused_decl decl@(L _ (ImportDecl { ideclImportList = imps }))\\n = -- pprTrace \\"unused_decl\\" (vcat [ ppr decl\\n -- , text \\"used\\" <+> ppr used_gres\\n -- , text \\"unused\\" <+> ppr unused_names ]) $\\n (decl, used_gres, unused_names, unused_wcs)\\n where\\n used_gres = lookupImportMap decl import_usage\\n\\n used_gre_env = mkGlobalRdrEnv used_gres\\n used_parents = mkNameSet (mapMaybe greParent_maybe used_gres)\\n\\n (unused_names, unused_wcs) -- Not trivial; see eg #7454\\n = case imps of\\n Just (Exactly, imp_ies) ->\\n let unused = foldr (add_unused . unLoc) emptyUnusedNames imp_ies\\n nms = nameSetElemsStable (collectUnusedNames unused)\\n wcs = collectUnusedWildcards unused\\n in (nms, wcs)\\n _other -> ([], []) -- No explicit import list => no unused-name list\\n\\n add_unused :: IE GhcRn -> UnusedNames -> UnusedNames\\n add_unused (IEVar _ n _) acc = add_unused_name (lieWrappedName n) True acc\\n add_unused (IEThingAbs _ n _) acc = add_unused_name (lieWrappedName n) False acc\\n add_unused (IEThingAll _ _ n _) acc = add_unused_all (lieWrappedName n) acc\\n add_unused (IEThingWith _ p wc ns _) acc = add_wc_all (add_unused_with pn xs acc)\\n where pn = lieWrappedName p\\n xs = map lieWrappedName ns\\n add_wc_all = case wc of\\n NoIEWildcard -> id\\n IEWildcard _ -> add_unused_all pn\\n add_unused (IEWholeNamespace x ns_spec) acc = add_unused_wildcard ns_spec (iewn_names x) acc\\n add_unused _ acc = acc\\n\\n add_unused_name :: Name -> Bool -> UnusedNames -> UnusedNames\\n add_unused_name n is_ie_var acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | is_ie_var\\n , isFieldName n\\n -- See Note [Reporting unused imported duplicate record fields]\\n = let\\n fs = getOccFS n\\n (flds, flds_used) = lookupFsEnv acc_fs fs `orElse` (emptyNameSet, Any False)\\n acc_fs\' = extendFsEnv acc_fs fs (extendNameSet flds n, Any used S.<> flds_used)\\n in UnusedNames acc_ns acc_wcs acc_fs\'\\n\\n | used\\n = acc\\n\\n | otherwise\\n = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n where\\n used = isJust $ lookupGRE_Name used_gre_env n\\n\\n add_unused_all :: Name -> UnusedNames -> UnusedNames\\n add_unused_all n acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | Just {} <- lookupGRE_Name used_gre_env n = acc\\n | n `elemNameSet` used_parents = acc\\n | otherwise = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n\\n add_unused_with :: Name -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_with p ns acc\\n | all (`elemNameSet` acc1_ns) ns = add_unused_name p False acc1\\n | otherwise = acc1\\n where\\n acc1@(UnusedNames acc1_ns _ _) = foldr (\\\\n acc\' -> add_unused_name n False acc\') acc ns\\n -- If you use \'signum\' from Num, then the user may well have\\n -- imported Num(signum). We don\'t want to complain that\\n -- Num is not itself mentioned. Hence the two cases in add_unused_with.\\n\\n add_unused_wildcard :: NamespaceSpecifier GhcRn -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_wildcard ns_spec names acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | any_used = acc\\n | otherwise = UnusedNames acc_ns (ns_spec : acc_wcs) acc_fs\\n where\\n -- A wildcard `type ..` or `data ..` is used if at least one of\\n -- the names it expands to is used\\n any_used = any (isJust . lookupGRE_Name used_gre_env) names\\n\\n\\n-- | An accumulator for unused names in an import list.\\n--\\n-- See Note [Reporting unused imported duplicate record fields].\\ndata UnusedNames =\\n UnusedNames\\n { unused_names :: NameSet\\n -- ^ Unused \'Name\'s in an import list, not including record fields\\n -- that are plain \'IEVar\' imports (tracked by \'rec_fld_uses\')\\n -- or wildcard imports (tracked by \'unused_wildcards\').\\n , unused_wildcards :: [NamespaceSpecifier GhcRn]\\n -- ^ Unused wildcards @type ..@ or @data ..@ in an import list.\\n , rec_fld_uses :: FastStringEnv (NameSet, Any)\\n -- ^ Record fields imported without a parent (i.e. an \'IEVar\' import).\\n --\\n -- The \'Any\' value records whether any of the record fields\\n -- sharing the same underlying \'FastString\' have been used.\\n }\\n\\nemptyUnusedNames :: UnusedNames\\nemptyUnusedNames = UnusedNames emptyNameSet [] emptyFsEnv\\n\\ninstance Outputable UnusedNames where\\n ppr (UnusedNames nms wcs flds) =\\n text \\"UnusedNames\\" <+>\\n braces (ppr nms <+> ppr wcs <+> ppr (fmap (second getAny) flds))\\n\\n-- | Collect all unused names from a \'UnusedNames\' value.\\ncollectUnusedNames :: UnusedNames -> NameSet\\ncollectUnusedNames (UnusedNames { unused_names = nms, rec_fld_uses = flds })\\n = nms S.<> unused_flds\\n where\\n unused_flds = nonDetFoldFsEnv collect_unused emptyNameSet flds\\n collect_unused :: (NameSet, Any) -> NameSet -> NameSet\\n collect_unused (nms, Any at_least_one_name_is_used) acc\\n | at_least_one_name_is_used = acc\\n | otherwise = unionNameSet nms acc\\n\\ncollectUnusedWildcards :: UnusedNames -> [NamespaceSpecifier GhcRn]\\ncollectUnusedWildcards = unused_wildcards\\n\\n{- Note [Reporting unused imported duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have (#24035):\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M1 (R1(..), R2(..)) where\\n data R1 = MkR1 { fld :: Int }\\n data R2 = MkR2 { fld :: Int }\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M2 where\\n import M1 (R1(MkR1), R2, fld)\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nIn the import of \'M1\' in \'M2\', the \'fld\' import resolves to two separate GREs,\\nnamely R1(fld) and R2(fld). From the perspective of the renamer, and in particular\\nthe \'findImportUsage\' function, it\'s as if the user had imported the two names\\nseparately (even though no source syntax allows that).\\n\\nThis means that we need to be careful when reporting unused imports: the R2(fld)\\nimport is indeed unused, but because R1(fld) is used, we should not report\\nfld as unused altogether.\\n\\nTo achieve this, we keep track of record field imports without a parent (i.e.\\nusing the IEVar constructor) separately from other import items, using the\\nUnusedNames datatype.\\nOnce we have accumulated usages, we emit warnings for unused record fields\\nwithout parents one whole group (of record fields sharing the same textual name)\\nat a time, and only if *all* of the record fields in the group are unused;\\nsee \'collectUnusedNames\'.\\n\\nNote that this only applies to record fields imported without a parent. If we\\nhad:\\n\\n import M1 (R1(MkR1, fld), R2(fld))\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nthen of course we should report the second \'fld\' as unused.\\n-}\\n\\n\\n{- Note [The ImportMap]\\n~~~~~~~~~~~~~~~~~~~~~~~\\nThe ImportMap is a short-lived intermediate data structure records, for\\neach import declaration, what stuff brought into scope by that\\ndeclaration is actually used in the module.\\n\\nThe [GlobalRdrElt] are the things imported from that decl.\\n-}\\n\\ndata ImportMap = ImportMap\\n { im_imports :: Map RealSrcSpan [GlobalRdrElt]\\n -- ^ See [The ImportMap]\\n -- If loc :-> gres, then\\n -- \'loc\' = the end loc of the bestImport of each GRE in \'gres\'\\n , im_generatedImports :: Map ModuleName [GlobalRdrElt]\\n }\\n\\nmkImportMap :: [GlobalRdrElt] -> ImportMap\\n-- For each of a list of used GREs, find all the import decls that brought\\n-- it into scope; choose one of them (bestImport), and record\\n-- the RdrName in that import decl\'s entry in the ImportMap\\nmkImportMap = foldr insertImportMap $ ImportMap Map.empty Map.empty\\n\\ninsertImportMap :: GlobalRdrElt -> ImportMap -> ImportMap\\ninsertImportMap gre@(GRE { gre_imp = imp_specs }) importMap\\n | RealSrcSpan importSpan _ <- is_dloc best_imp_spec =\\n importMap{im_imports = insertElem importSpan gre $ im_imports importMap}\\n | GeneratedSrcSpan{} <- is_dloc best_imp_spec =\\n importMap{im_generatedImports = insertElem (moduleName $ is_mod best_imp_spec) gre $ im_generatedImports importMap}\\n | otherwise = importMap\\n where\\n best_imp_spec =\\n case bagToList imp_specs of\\n [] -> pprPanic \\"mkImportMap: GRE with no ImportSpecs\\" (ppr gre)\\n is:iss -> is_decl $ bestImport (is NE.:| iss)\\n\\n -- https://github.com/haskell/containers/issues/784\\n insertElem :: Ord k => k -> v -> Map k [v] -> Map k [v]\\n insertElem k v = flip Map.alter k $ \\\\case\\n Just vs -> Just (v : vs)\\n Nothing -> Just [v]\\n\\nlookupImportMap :: LImportDecl GhcRn -> ImportMap -> [GlobalRdrElt]\\nlookupImportMap (L srcSpan ImportDecl{ideclName = L _ modName}) importMap =\\n fromMaybe [] $\\n -- should match logic in insertImportMap\\n case locA srcSpan of\\n RealSrcSpan realSrcSpan _ -> realSrcSpan `Map.lookup` im_imports importMap\\n GeneratedSrcSpan{} -> modName `Map.lookup` im_generatedImports importMap\\n _ -> Nothing\\n\\nlieNames :: LIE (GhcPass p) -> [Located (IdP (GhcPass p))]\\nlieNames = _\\n\\nwarnUnusedImport :: GlobalRdrEnv -> ImportDeclUsage -> RnM ()\\nwarnUnusedImport rdr_env (L loc decl, used, unused, unused_wcs)\\n\\n -- Do not warn for \'import M()\'\\n -- See (UI1) in Note [Unused imports]\\n | Just (Exactly, _) <- ideclImportList decl\\n , null unused && null unused_wcs\\n = return ()\\n\\n -- Note [Do not warn about Prelude hiding]\\n | Just (EverythingBut, hides) <- ideclImportList decl\\n , not (null hides)\\n , pRELUDE_NAME == unLoc (ideclName decl)\\n = return ()\\n\\n -- Do not warn about import X as Rebindable\\n -- See (UI2) in Note [Unused imports]\\n | Just (L _ mod) <- ideclAs decl\\n , mod == rEBINDABLE_MOD_NAME\\n = return ()\\n\\n -- Nothing used; drop entire declaration\\n | null used\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl UnusedImportNone)\\n\\n -- Everything imported is used; nop\\n | null unused && null unused_wcs\\n = return ()\\n\\n -- Some imports are unused: make the `SrcSpan` cover only the unused\\n -- items instead of the whole import statement\\n | Just (_, imports) <- ideclImportList decl\\n , let unused_locs = [ locA loc | L loc ie <- imports\\n , name <- ieNames ie\\n , name `elem` unused ]\\n , loc1 : locs <- unused_locs\\n , let span = foldr1 combineSrcSpans ( loc1 NE.:| locs )\\n = addDiagnosticAt span (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n -- Some imports are unused\\n | otherwise\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n where\\n -- In warning message, pretty-print identifiers unqualified unconditionally\\n -- to improve the consistent for ambiguous/unambiguous identifiers.\\n -- See #14881.\\n possible_field n =\\n case lookupGRE_Name rdr_env n of\\n Just (GRE { gre_par = par, gre_info = IAmRecField info }) ->\\n let fld_occ :: OccName\\n fld_occ = nameOccName $ flSelector $ recFieldLabel info\\n in UnusedImportNameRecField par fld_occ\\n _ -> UnusedImportNameRegular n\\n\\n -- Print unused names in a deterministic (lexicographic) order\\n sort_unused :: [UnusedImportName]\\n sort_unused =\\n [ UnusedImportWildcard wc | wc <- unused_wcs ] ++\\n [ possible_field nm | nm <- sortBy (comparing nameOccName) unused ]\\n\\ngetMinimalImports :: [ImportDeclUsage] -> RnM [LImportDecl GhcRn]\\ngetMinimalImports ie_decls\\n = do { rdr_env <- getGlobalRdrEnv\\n ; fmap combine $ mapM (mk_minimal rdr_env) ie_decls }\\n where\\n mk_minimal rdr_env (L l decl, used_gres, unused, unused_wcs)\\n | null unused && null unused_wcs\\n , Just (Exactly, _) <- ideclImportList decl\\n = return (L l decl)\\n | otherwise\\n = do { let ImportDecl { ideclName = L _ mod_name\\n , ideclSource = is_boot\\n , ideclPkgQual = pkg_qual\\n , ideclExt = XImportDeclPass { ideclOrigin = origin } } = decl\\n ; iface <- loadSrcInterface doc (importDeclLookupScope origin)\\n mod_name is_boot pkg_qual\\n ; let used_avails = gresToAvailInfo used_gres\\n ; lies <- map (L l) <$> concatMapM (to_ie rdr_env iface) used_avails\\n ; return (L l (decl { ideclImportList = Just (Exactly, lies) })) }\\n where\\n doc = text \\"Compute minimal imports for\\" <+> ppr decl\\n\\n to_ie :: GlobalRdrEnv -> ModIface -> AvailInfo -> RnM [IE GhcRn]\\n -- The main trick here is that if we\'re importing all the constructors\\n -- we want to say \\"T(..)\\", but if we\'re importing only a subset we want\\n -- to say \\"T(A,B,C)\\". So we have to find out what the module exports.\\n to_ie rdr_env _ (Avail c) -- Note [Overloaded field import]\\n = do { let\\n gre = expectJust $ lookupGRE_Name rdr_env c\\n ; return $ [IEVar Nothing (to_ie_post_rn $ noLocA $ greName gre) Nothing] }\\n to_ie _ _ avail@(AvailTC n [_]) -- Exporting the main decl and nothing else\\n | availExportsDecl avail\\n = return [IEThingAbs Nothing (to_ie_post_rn $ noLocA n) Nothing]\\n to_ie rdr_env iface (AvailTC n cs) =\\n case [ xs | avail@(AvailTC x xs) <- mi_exports iface\\n , x == n\\n , availExportsDecl avail -- Note [Partial export]\\n ] of\\n [xs]\\n | all_used xs\\n -> return [IEThingAll (IEThingAllExt Nothing noAnn noAnn noAnn)\\n (NoNamespaceSpecifier noExtField)\\n (to_ie_post_rn $ noLocA n)\\n Nothing]\\n | otherwise\\n -> do { let ns_gres = map (expectJust . lookupGRE_Name rdr_env) cs\\n ns = map greName ns_gres\\n ; return [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n -- Note [Overloaded field import]\\n _other\\n -> do { let infos = map (expectJust . lookupGRE_Name rdr_env) cs\\n (ns_gres,fs_gres) = classifyGREs infos\\n ns = map greName (ns_gres ++ fs_gres)\\n fs = map fieldGREInfo fs_gres\\n ; return $\\n if all_non_overloaded fs\\n then map (\\\\nm -> IEVar Nothing (to_ie_post_rn_var $ noLocA nm) Nothing) ns\\n else [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n where\\n\\n all_used avail_cs = all (`elem` cs) avail_cs\\n\\n all_non_overloaded = all (not . flIsOverloaded . recFieldLabel)\\n\\n combine :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\n combine = map merge . NE.groupAllWith getKey\\n\\n getKey :: LImportDecl GhcRn -> (Bool, Maybe ModuleName, ModuleName)\\n getKey decl =\\n ( isImportDeclQualified . ideclQualified $ idecl -- is this qualified? (important that this be first)\\n , unLoc <$> ideclAs idecl -- what is the qualifier (inside Maybe monad)\\n , unLoc . ideclName $ idecl -- Module Name\\n )\\n where\\n idecl :: ImportDecl GhcRn\\n idecl = unLoc decl\\n\\n merge :: NonEmpty (LImportDecl GhcRn) -> LImportDecl GhcRn\\n merge decls@((L l decl) :| _) = L l (decl { ideclImportList = Just (Exactly, lies) })\\n where lies = concatMap snd $ mapMaybe (ideclImportList . unLoc) $ NE.toList decls\\n\\nclassifyGREs :: [GlobalRdrElt] -> ([GlobalRdrElt], [FieldGlobalRdrElt])\\nclassifyGREs = partition (not . isRecFldGRE)\\n\\nprintMinimalImports :: HscSource -> [ImportDeclUsage] -> RnM ()\\n-- See Note [Printing minimal imports]\\nprintMinimalImports hsc_src imports_w_usage\\n = do { imports\' <- excludeGenerated <$> getMinimalImports imports_w_usage\\n ; this_mod <- getModule\\n ; dflags <- getDynFlags\\n ; liftIO $ withFile (mkFilename dflags this_mod) WriteMode $ \\\\h ->\\n printForUser dflags h neverQualify AllTheWay (vcat (map ppr imports\'))\\n -- The neverQualify is important. We are printing Names\\n -- but they are in the context of an \'import\' decl, and\\n -- we never qualify things inside there\\n -- E.g. import Blag( f, b )\\n -- not import Blag( Blag.f, Blag.g )!\\n }\\n where\\n mkFilename dflags this_mod\\n | Just d <- dumpDir dflags = d basefn\\n | otherwise = basefn\\n where\\n suffix = case hsc_src of\\n HsBootFile -> \\".imports-boot\\"\\n HsSrcFile -> \\".imports\\"\\n HsigFile -> \\".imports\\"\\n basefn = moduleNameString (moduleName this_mod) ++ suffix\\n\\n\\nto_ie_post_rn_var :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn_var (L l n)\\n | isDataOcc $ occName n = L l (IEPattern noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n\\n\\nto_ie_post_rn :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn (L l n)\\n | isTcOcc occ && isSymOcc occ = L l (IEType noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n where occ = occName n\\n\\n{- Note [Do not warn about Prelude hiding]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWe do not warn about\\n import Prelude hiding( x, y )\\nbecause even if nothing else from Prelude is used, it may be essential to hide\\nx,y to avoid name-shadowing warnings. Example (#9061)\\n import Prelude hiding( log )\\n f x = log where log = ()\\n\\nNote [Unused imports]\\n~~~~~~~~~~~~~~~~~~~~~\\nIn `warnUnusedImport`, if we see an import with an explicit list imports, thus\\n import M( a, b )\\nand neither `a` nor `b` is used, we report the entire import decl as unused. We\\ncheck this by looking at the names that it brings into scope scope; if there are\\nno ununused names, don\'t report.\\n\\n(UI1) We don\'t want to complain about `import M()`, because that is often used to bring\\n M\'s /instances/ into scope. That is neatly dealt with by the \\"no unused\\n names\\" (nor unused wildcard imports) criterion.\\n\\n(UI2) We don\'t report a decl as unused if it has an `as Rebindable` qualifier.\\n See (KN1) in Note [Overview of known entities] in GHC.Builtin\\n\\n\\nNote [Printing minimal imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nTo print the minimal imports we walk over all import decls (both user-supplied\\nand generated), trim their import lists, then filter out generated decls.\\n\\nNB that\\n\\n * We do *not* change the \'qualified\' or \'as\' parts!\\n\\n * We do not discard a decl altogether; we might need instances\\n from it. Instead we just trim to an empty import list\\n\\nNote [Partial export]\\n~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have\\n\\n module A( op ) where\\n class C a where\\n op :: a -> a\\n\\n module B where\\n import A\\n f = ..op...\\n\\nThen the minimal import for module B is\\n import A( op )\\nnot\\n import A( C( op ) )\\nwhich we would usually generate if C was exported from B. Hence\\nthe availExportsDecl test when deciding what to generate.\\n\\n\\nNote [Overloaded field import]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nOn the other hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n data T = MkT { foo :: Int }\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( T(foo) )\\nbecause when DuplicateRecordFields is enabled, field selectors are\\nnot in scope without their enclosing datatype.\\n\\nOn the third hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n pattern MkT { foo } = Just foo\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( foo )\\nbecause foo doesn\'t have a parent. This might actually be ambiguous if A\\nexports another field called foo, but there is no good answer to return and this\\nis a very obscure corner, so it seems to be the best we can do. See\\nDRFPatSynExport for a test of this.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Errors}\\n* *\\n************************************************************************\\n-}\\n\\nbadImportItemErr\\n :: ModIface -> ImpDeclSpec -> IE GhcPs\\n -> IsSubordinateError\\n -> [AvailInfo]\\n -> TcRn (NonEmpty ImportLookupReason)\\nbadImportItemErr iface decl_spec ie sub avails = do\\n exts <- importLookupExtensions\\n let import_lookup_bad :: BadImportKind -> ImportLookupReason\\n import_lookup_bad k = ImportLookupBad k iface decl_spec ie exts\\n dflags <- getDynFlags\\n hsc_env <- getTopEnv\\n let rdr_env = mkGlobalRdrEnv\\n $ gresFromAvails hsc_env (Just imp_spec) all_avails\\n pure $ fmap import_lookup_bad (importErrorKind dflags rdr_env)\\n where\\n importErrorKind :: DynFlags -> GlobalRdrEnv -> NonEmpty BadImportKind\\n importErrorKind dflags rdr_env\\n | any checkIfTyCon avails = case sub of\\n IsNotSubordinate -> NE.singleton BadImportAvailTyCon\\n IsSubordinateError { subordinate_err_parent = gre\\n , subordinate_err_unavailable = unavailable\\n , subordinate_err_nontype = nontype\\n , subordinate_err_nondata = nondata }\\n -> NE.fromList $ catMaybes $\\n [ fmap (BadImportNotExportedSubordinates gre) (NE.nonEmpty unavailable)\\n , fmap (BadImportNonTypeSubordinates gre) (NE.nonEmpty nontype)\\n , fmap (BadImportNonDataSubordinates gre) (NE.nonEmpty nondata) ]\\n | any checkIfVarName avails = NE.singleton BadImportAvailVar\\n | Just con <- find checkIfDataCon avails = NE.singleton (BadImportAvailDataCon (availOccName con))\\n | otherwise = NE.singleton (BadImportNotExported suggs)\\n where\\n suggs = similar_suggs ++ fieldSelectorSuggestions rdr_env rdr\\n what_look = case sub of\\n IsNotSubordinate -> WL_TyCon_or_TermVar\\n IsSubordinateError { subordinate_err_parent = gre } ->\\n case greInfo gre of\\n IAmTyCon ClassFlavour\\n -> WL_TyCon_or_TermVar\\n _ -> WL_Term\\n similar_names =\\n similarNameSuggestions (Unbound.LF what_look WL_Global)\\n dflags rdr_env emptyLocalRdrEnv rdr\\n similar_suggs =\\n case NE.nonEmpty $ mapMaybe imported_item $ similar_names of\\n Just similar -> [ SuggestSimilarNames rdr similar ]\\n Nothing -> [ ]\\n\\n -- Only keep imported items, and set the \\"HowInScope\\" to\\n -- \\"Nothing\\" to avoid printing \\"imported from...\\" in the suggestion\\n -- error message.\\n imported_item (SimilarRdrName rdr_name gre (Just (ImportedBy {})))\\n = Just (SimilarRdrName rdr_name gre Nothing)\\n imported_item _ = Nothing\\n\\n checkIfDataCon = checkIfAvailMatches isDataConName\\n checkIfTyCon = checkIfAvailMatches isTyConName\\n checkIfVarName =\\n \\\\case\\n AvailTC{} -> False\\n Avail n -> importedFS == occNameFS (occName n)\\n && (isVarOcc <||> isFieldOcc) (occName n)\\n checkIfAvailMatches namePred =\\n \\\\case\\n AvailTC _ ns ->\\n case find (\\\\n -> importedFS == occNameFS (occName n)) ns of\\n Just n -> namePred n\\n Nothing -> False\\n Avail{} -> False\\n availOccName = occName . availName\\n rdr = ieName ie\\n importedFS = occNameFS $ rdrNameOcc rdr\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n all_avails = mi_exports iface\\n\\nimportLookupExtensions :: TcRn ImportLookupExtensions\\nimportLookupExtensions = do\\n ile_pattern_synonyms <- xoptM LangExt.PatternSynonyms\\n ile_explicit_namespaces <- xoptM LangExt.ExplicitNamespaces\\n return ImportLookupExtensions{ile_pattern_synonyms, ile_explicit_namespaces}\\n\\naddDupDeclErr :: NonEmpty GlobalRdrElt -> TcRn ()\\naddDupDeclErr gres@(gre :| _)\\n -- Report the error at the later location\\n = addErrAt (getSrcSpan (NE.last sorted_names)) $ (TcRnDuplicateDecls (greOccName gre) sorted_names)\\n where\\n sorted_names =\\n NE.sortBy (SrcLoc.leftmost_smallest `on` nameSrcSpan)\\n (fmap greName gres)\\n\\n-- This data decl will parse OK\\n-- data T = a Int\\n-- treating \\"a\\" as the constructor.\\n-- It is really hard to make the parser spot this malformation.\\n-- So the renamer has to check that the constructor is legal\\n--\\n-- We can get an operator as the constructor, even in the prefix form:\\n-- data T = :% Int Int\\n-- from interface files, which always print in prefix form\\n--\\n-- We also allow type constructor names, which are defined by \\"type data\\"\\n-- declarations. See Note [Type data declarations] in GHC.Rename.Module.\\n\\ncheckConName :: RdrName -> TcRn ()\\ncheckConName name\\n = checkErr (isRdrDataCon name || isRdrTc name) (TcRnIllegalDataCon name)\\n", "filetypes": ["haskell"]}}}' 2026-10-16 14:47:11,067 - DEBUG - POST b'http://127.0.0.1:37093/receive_messages' {'content-type': 'application/json', 'x-ycm-hmac': b'Rga7Yd4l4fgfufwYw+0sxzurvznImlBO0MPmgAlS4EY='} b'{"filepath": "/home/enrico/ghc/compiler/GHC/Rename/Names.hs", "line_num": 1, "column_num": 1, "working_dir": "/home/enrico/ghc", "file_data": {"/home/enrico/ghc/compiler/GHC/Rename/Names.hs": {"contents": "{-\\n(c) The GRASP/AQUA Project, Glasgow University, 1992-1998\\n\\nExtracting imported and top-level names in scope\\n-}\\n\\n{-# LANGUAGE NondecreasingIndentation #-}\\n{-# LANGUAGE TypeFamilies #-}\\n\\nmodule GHC.Rename.Names (\\n rnImports, getLocalNonValBinders, newRecordFieldLabel,\\n importsFromIface,\\n ImportUserSpec(..),\\n extendGlobalRdrEnvRn,\\n gresFromAvails,\\n calculateAvails,\\n reportUnusedNames,\\n checkConName,\\n mkChildEnv,\\n findChildren,\\n mkBadExportSubordinate,\\n findImportUsage,\\n getMinimalImports,\\n printMinimalImports,\\n renamePkgQual, renameRawPkgQual,\\n classifyGREs,\\n ImportDeclUsage,\\n rnNamespaceSpecifier\\n ) where\\n\\nimport GHC.Prelude hiding ( head, init, last, tail )\\n\\nimport GHC.Driver.Env\\nimport GHC.Driver.Session\\nimport GHC.Driver.Ppr\\n\\nimport GHC.Rename.Env\\nimport GHC.Rename.Fixity\\nimport GHC.Rename.Utils ( warnUnusedTopBinds )\\nimport GHC.Rename.Unbound\\nimport qualified GHC.Rename.Unbound as Unbound\\n\\nimport GHC.Tc.Errors.Types\\nimport GHC.Tc.Utils.Env\\nimport GHC.Tc.Utils.Monad\\nimport GHC.Tc.Types.LclEnv\\nimport GHC.Tc.Zonk.TcType ( tcInitTidyEnv )\\n\\nimport GHC.Hs\\nimport GHC.Iface.Load ( loadSrcInterface, loadSrcInterface_maybe )\\nimport GHC.Iface.Errors.Types\\n ( IfaceMessage(..), MissingInterfaceError, InterfaceLookingFor(..)\\n , LoadEssentialsReason(..) )\\nimport GHC.Iface.Syntax ( fromIfaceWarnings )\\nimport GHC.Builtin.Modules( pRELUDE_NAME, rEBINDABLE_MOD_NAME )\\nimport GHC.Parser.PostProcess ( setRdrNameSpace )\\nimport GHC.Core.TyCo.Tidy\\nimport GHC.Core.PatSyn\\nimport GHC.Core.TyCon ( TyCon, tyConName )\\nimport qualified GHC.LanguageExtensions as LangExt\\n\\nimport GHC.Utils.Outputable as Outputable\\nimport GHC.Utils.Misc as Utils\\nimport GHC.Utils.Panic\\n\\nimport GHC.Types.Fixity.Env\\nimport GHC.Types.SafeHaskell\\nimport GHC.Types.Name\\nimport GHC.Types.Name.Env\\nimport GHC.Types.Name.Set\\nimport GHC.Types.Name.Reader\\nimport GHC.Types.Avail\\nimport GHC.Types.FieldLabel\\nimport GHC.Types.Hint\\nimport GHC.Types.SourceFile\\nimport GHC.Types.SrcLoc as SrcLoc\\nimport GHC.Types.Basic (TyConFlavour (..), convImportLevel, VisArity)\\nimport GHC.Types.UnresolvedImport\\nimport GHC.Types.Id\\nimport GHC.Types.PkgQual\\nimport GHC.Types.GREInfo (ConInfo(..), ConFieldInfo (..), ConLikeInfo (ConIsData))\\n\\nimport GHC.Unit\\nimport GHC.Unit.Module.Warnings\\nimport GHC.Unit.Module.ModIface\\nimport GHC.Unit.Module.Imported\\nimport GHC.Unit.Module.Deps\\nimport GHC.Unit.Env\\n\\nimport GHC.Data.Bag\\nimport GHC.Data.FastString\\nimport GHC.Data.FastString.Env\\nimport GHC.Data.Maybe\\nimport GHC.Data.List.SetOps ( removeDups )\\n\\nimport Control.Arrow ( second )\\nimport Control.Monad\\nimport Data.Foldable ( for_ )\\nimport Data.IntMap ( IntMap )\\nimport qualified Data.IntMap as IntMap\\nimport Data.Map ( Map )\\nimport qualified Data.Map as Map\\nimport Data.Ord ( comparing )\\nimport Data.Semigroup ( Any(..) )\\nimport qualified Data.Semigroup as S\\nimport Data.List ( partition, find, sortBy )\\nimport Data.List.NonEmpty (NonEmpty(..))\\nimport qualified Data.List.NonEmpty as NE\\nimport Data.Function ( on )\\nimport qualified Data.Set as S\\nimport System.FilePath (())\\nimport System.IO\\n\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{rnImports}\\n* *\\n************************************************************************\\n\\nNote [Tracking Trust Transitively]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen we import a package as well as checking that the direct imports are safe\\naccording to the rules outlined in the Note [Safe Haskell Trust Check] in GHC.Driver.Main\\nwe must also check that these rules hold transitively for all dependent modules\\nand packages. Doing this without caching any trust information would be very\\nslow as we would need to touch all packages and interface files a module depends\\non. To avoid this we make use of the property that if a modules Safe Haskell\\nmode changes, this triggers a recompilation from that module in the dependency\\ngraph. So we can just worry mostly about direct imports.\\n\\nThere is one trust property that can change for a package though without\\nrecompilation being triggered: package trust. So we must check that all\\npackages a module transitively depends on to be trusted are still trusted when\\nwe are compiling this module (as due to recompilation avoidance some modules\\nbelow may not be considered trusted any more without recompilation being\\ntriggered).\\n\\nWe handle this by augmenting the existing transitive list of packages a module M\\ndepends on with a bool for each package that says if it must be trusted when the\\nmodule M is being checked for trust. This list of trust required packages for a\\nsingle import is gathered in the rnImportDecl function and stored in an\\nImportAvails data structure. The union of these trust required packages for all\\nimports is done by the rnImports function using the combine function which calls\\nthe plusImportAvails function that is a union operation for the ImportAvails\\ntype. This gives us in an ImportAvails structure all packages required to be\\ntrusted for the module we are currently compiling. Checking that these packages\\nare still trusted (and that direct imports are trusted) is done in\\nGHC.Driver.Main.checkSafeImports.\\n\\nSee the note below, [Trust Own Package] for a corner case in this method and\\nhow its handled.\\n\\n\\nNote [Trust Own Package]\\n~~~~~~~~~~~~~~~~~~~~~~~~\\nThere is a corner case of package trust checking that the usual transitive check\\ndoesn\'t cover. (For how the usual check operates see the Note [Tracking Trust\\nTransitively] below). The case is when you import a -XSafe module M and M\\nimports a -XTrustworthy module N. If N resides in a different package than M,\\nthen the usual check works as M will record a package dependency on N\'s package\\nand mark it as required to be trusted. If N resides in the same package as M\\nthough, then importing M should require its own package be trusted due to N\\n(since M is -XSafe so doesn\'t create this requirement by itself). The usual\\ncheck fails as a module doesn\'t record a package dependency of its own package.\\nSo instead we now have a bool field in a modules interface file that simply\\nstates if the module requires its own package to be trusted. This field avoids\\nus having to load all interface files that the module depends on to see if one\\nis trustworthy.\\n\\n\\nNote [Trust Transitive Property]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSo there is an interesting design question in regards to transitive trust\\nchecking. Say I have a module B compiled with -XSafe. B is dependent on a bunch\\nof modules and packages, some packages it requires to be trusted as its using\\n-XTrustworthy modules from them. Now if I have a module A that doesn\'t use safe\\nhaskell at all and simply imports B, should A inherit all the trust\\nrequirements from B? Should A now also require that a package p is trusted since\\nB required it?\\n\\nWe currently say no but saying yes also makes sense. The difference is, if a\\nmodule M that doesn\'t use Safe Haskell imports a module N that does, should all\\nthe trusted package requirements be dropped since M didn\'t declare that it cares\\nabout Safe Haskell (so -XSafe is more strongly associated with the module doing\\nthe importing) or should it be done still since the author of the module N that\\nuses Safe Haskell said they cared (so -XSafe is more strongly associated with\\nthe module that was compiled that used it).\\n\\nGoing with yes is a simpler semantics we think and harder for the user to stuff\\nup but it does mean that Safe Haskell will affect users who don\'t care about\\nSafe Haskell as they might grab a package from Cabal which uses safe haskell (say\\nnetwork) and that packages imports -XTrustworthy modules from another package\\n(say bytestring), so requires that package is trusted. The user may now get\\ncompilation errors in code that doesn\'t do anything with Safe Haskell simply\\nbecause they are using the network package. They will have to call \'ghc-pkg\\ntrust network\' to get everything working. Due to this invasive nature of going\\nwith yes we have gone with no for now.\\n-}\\n\\n-- | Process Import Decls. See \'rnImportDecl\' for a description of what\\n-- the return types represent.\\n-- Note: Do the non SOURCE ones first, so that we get a helpful warning\\n-- for SOURCE ones that are unnecessary\\nrnImports :: [(LImportDecl GhcPs, SDoc)]\\n -> RnM ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\nrnImports imports = do\\n tcg_env <- getGblEnv\\n -- NB: want an identity module here, because it\'s OK for a signature\\n -- module to import from its implementor\\n let this_mod = tcg_mod tcg_env\\n let (source, ordinary) = partition (is_source_import . fst) imports\\n is_source_import (d::LImportDecl GhcPs) = ideclSource (unLoc d) == IsBoot\\n stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary\\n stuff2 <- mapAndReportM (rnImportDecl this_mod) source\\n -- Safe Haskell: See Note [Tracking Trust Transitively]\\n let (decls, imp_user_spec, rdr_env, imp_avails) = combine (stuff1 ++ stuff2)\\n -- Update imp_boot_mods if imp_direct_mods mentions any of them\\n let merged_import_avail = clobberSourceImports imp_avails\\n return (decls, imp_user_spec, rdr_env, merged_import_avail)\\n\\n where\\n clobberSourceImports imp_avails =\\n imp_avails { imp_boot_mods = imp_boot_mods\' }\\n where\\n imp_boot_mods\' = mergeInstalledModuleEnv combJ id (const emptyInstalledModuleEnv)\\n (imp_boot_mods imp_avails)\\n (imp_direct_dep_mods imp_avails)\\n\\n combJ (GWIB _ IsBoot) (_, x) = Just x\\n combJ r _ = Just r\\n -- See Note [Combining ImportAvails]\\n combine :: [(LImportDecl GhcRn, ImportUserSpec, GlobalRdrEnv, ImportAvails)]\\n -> ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\n combine ss =\\n let (decls, imp_user_spec, rdr_env, imp_avails, finsts) = foldr\\n plus\\n ([], [], emptyGlobalRdrEnv, emptyImportAvails, emptyModuleSet)\\n ss\\n in (decls, imp_user_spec, rdr_env, imp_avails { imp_finsts = moduleSetElts finsts })\\n\\n plus (decl, us, gbl_env1, imp_avails1)\\n (decls, uss, gbl_env2, imp_avails2, finsts_set)\\n = ( decl:decls,\\n us:uss,\\n gbl_env1 `plusGlobalRdrEnv` gbl_env2,\\n imp_avails1\' `plusImportAvails` imp_avails2,\\n extendModuleSetList finsts_set new_finsts )\\n where\\n imp_avails1\' = imp_avails1 { imp_finsts = [] }\\n new_finsts = imp_finsts imp_avails1\\n\\n{-\\nNote [Combining ImportAvails]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nimp_finsts in ImportAvails is a list of family instance modules\\ntransitively depended on by an import. imp_finsts for a currently\\ncompiled module is a union of all the imp_finsts of imports.\\nComputing the union of two lists of size N is O(N^2) and if we\\ndo it to M imports we end up with O(M*N^2). That can get very\\nexpensive for bigger module hierarchies.\\n\\nUnion can be optimized to O(N log N) if we use a Set.\\nimp_finsts is converted back and forth between dep_finsts, so\\nchanging a type of imp_finsts means either paying for the conversions\\nor changing the type of dep_finsts as well.\\n\\nI\'ve measured that the conversions would cost 20% of allocations on my\\ntest case, so that can be ruled out.\\n\\nChanging the type of dep_finsts forces checkFamInsts to\\nget the module lists in non-deterministic order. If we wanted to restore\\nthe deterministic order, we\'d have to sort there, which is an additional\\ncost. As far as I can tell, using a non-deterministic order is fine there,\\nbut that\'s a brittle nonlocal property which I\'d like to avoid.\\n\\nAdditionally, dep_finsts is read from an interface file, so its \\"natural\\"\\ntype is a list. Which makes it a natural type for imp_finsts.\\n\\nSince rnImports.combine is really the only place that would benefit from\\nit being a Set, it makes sense to optimize the hot loop in rnImports.combine\\nwithout changing the representation.\\n\\nSo here\'s what we do: instead of naively merging ImportAvails with\\nplusImportAvails in a loop, we make plusImportAvails merge empty imp_finsts\\nand compute the union on the side using Sets. When we\'re done, we can\\nconvert it back to a list. One nice side effect of this approach is that\\nif there\'s a lot of overlap in the imp_finsts of imports, the\\nSet doesn\'t really need to grow and we don\'t need to allocate.\\n\\nRunning generateModules from #14693 with DEPTH=16, WIDTH=30 finishes in\\n23s before, and 11s after.\\n-}\\n\\n-- | Given a located import declaration @decl@ from @this_mod@,\\n-- calculate the following pieces of information:\\n--\\n-- 1. An updated \'LImportDecl\', where all unresolved \'RdrName\' in\\n-- the entity lists have been resolved into \'Name\'s,\\n--\\n-- 2. A \'GlobalRdrEnv\' representing the new identifiers that were\\n-- brought into scope (taking into account module qualification\\n-- and hiding),\\n--\\n-- 3. \'ImportAvails\' summarizing the identifiers that were imported\\n-- by this declaration, and\\n--\\n-- 4. A boolean \'AnyHpcUsage\' which is true if the imported module\\n-- used HPC.\\nrnImportDecl :: Module -> (LImportDecl GhcPs, SDoc)\\n -> RnM (LImportDecl GhcRn, ImportUserSpec , GlobalRdrEnv, ImportAvails)\\nrnImportDecl this_mod\\n (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name\\n , ideclPkgQual = raw_pkg_qual\\n , ideclSource = want_boot\\n , ideclSafe = mod_safe\\n , ideclLevelSpec = import_level\\n , ideclQualified = qual_style\\n , ideclExt = XImportDeclPass { ideclOrigin = origin }\\n , ideclAs = as_mod, ideclImportList = imp_details }), import_reason)\\n = setSrcSpanA loc $ do\\n\\n case raw_pkg_qual of\\n NoRawPkgQual -> pure ()\\n RawPkgQual {} -> do\\n pkg_imports <- xoptM LangExt.PackageImports\\n when (not pkg_imports) $ addErr TcRnPackageImportsDisabled\\n\\n let qual_only = isImportDeclQualified qual_style\\n generated = isGeneratedImport origin\\n\\n lookup_scope = importDeclLookupScope origin\\n\\n -- If there\'s an error in loadInterface, (e.g. interface\\n -- file not found) we get lots of spurious errors from \'filterImports\'\\n let imp_mod_name = unLoc loc_imp_mod_name\\n doc = ppr imp_mod_name <+> import_reason\\n\\n hsc_env <- getTopEnv\\n unit_env <- hsc_unit_env <$> getTopEnv\\n let pkg_qual = renameRawPkgQual unit_env imp_mod_name raw_pkg_qual\\n\\n -- Check for self-import, which confuses the typechecker (#9032)\\n -- ghc --make rejects self-import cycles already, but batch-mode may not\\n -- at least not until GHC.IfaceToCore.tcHiBootIface, which is too late to avoid\\n -- typechecker crashes. (Indirect self imports are not caught until\\n -- GHC.IfaceToCore, see #10337 tracking how to make this error better.)\\n --\\n -- Originally, we also allowed \'import {-# SOURCE #-} M\', but this\\n -- caused bug #10182: in one-shot mode, we should never load an hs-boot\\n -- file for the module we are compiling into the EPS. In principle,\\n -- it should be possible to support this mode of use, but we would have to\\n -- extend Provenance to support a local definition in a qualified location.\\n -- For now, we don\'t support it, but see #10336\\n when (imp_mod_name == moduleName this_mod &&\\n (case pkg_qual of -- If we have import \\"\\" M, then we should\\n -- check that \\"\\" is \\"this\\" (which is magic)\\n -- or the name of this_mod\'s package. Yurgh!\\n -- c.f. GHC.findModule, and #9997\\n NoPkgQual -> True\\n ThisPkg uid -> uid == homeUnitId_ (hsc_dflags hsc_env)\\n OtherPkg _ -> False))\\n (addErr (TcRnSelfImport imp_mod_name))\\n\\n -- Check for a missing import list (Opt_WarnMissingImportList also\\n -- checks for T(..) items but that is done in checkDodgyImport below)\\n case imp_details of\\n Just (Exactly, _) -> return () -- Explicit import list\\n _ | generated -> return () -- Do not bleat for generated imports\\n | qual_only -> return ()\\n | otherwise -> addDiagnostic (TcRnNoExplicitImportList imp_mod_name)\\n\\n\\n mb_iface <- loadSrcInterface_maybe doc lookup_scope imp_mod_name want_boot pkg_qual\\n iface <- case mb_iface of\\n Succeeded iface -> return iface\\n Failed err -> failWithTc $\\n importDeclLoadFailure origin imp_mod_name want_boot err\\n\\n -- Compiler sanity check: if the import didn\'t say\\n -- {-# SOURCE #-} we should not get a hi-boot file\\n warnPprTrace ((want_boot == NotBoot) && (mi_boot iface == IsBoot)) \\"rnImportDecl\\" (ppr imp_mod_name) $ do\\n\\n -- Issue a user warning for a redundant {- SOURCE -} import\\n -- NB that we arrange to read all the ordinary imports before\\n -- any of the {- SOURCE -} imports.\\n --\\n -- in --make and GHCi, the compilation manager checks for this,\\n -- and indeed we shouldn\'t do it here because the existence of\\n -- the non-boot module depends on the compilation order, which\\n -- is not deterministic. The hs-boot test can show this up.\\n dflags <- getDynFlags\\n warnIf ((want_boot == IsBoot) && (mi_boot iface == NotBoot) && isOneShot (ghcMode dflags))\\n (TcRnRedundantSourceImport imp_mod_name)\\n when (mod_safe && not (safeImportsOn dflags)) $\\n addErr (TcRnSafeImportsDisabled imp_mod_name)\\n\\n let imp_mod = mi_module iface\\n qual_mod_name = fmap unLoc as_mod `orElse` imp_mod_name\\n imp_spec = ImpDeclSpec { is_mod = imp_mod, is_qual = qual_only,\\n is_dloc = locA loc, is_as = qual_mod_name,\\n is_pkg_qual = pkg_qual, is_isboot = want_boot,\\n is_level = convImportLevel import_level }\\n\\n let filter_imports = do\\n -- filter the imports according to the import declaration\\n (new_imp_details, imp_user_list, gbl_env)\\n <- filterImports hsc_env iface imp_spec imp_details\\n -- for certain error messages, we\\u2019d like to know what could be\\n -- imported here, if everything were imported\\n potential_gres <- (\\\\(_,_,x) -> x) <$> filterImports hsc_env iface imp_spec Nothing\\n return (new_imp_details, imp_user_list, gbl_env, potential_gres)\\n\\n (new_imp_details, imp_user_list, gbl_env, potential_gres) <-\\n case origin of\\n ImplicitEssentialsImport ->\\n -- The implicit GHC.Essentials import does not bring anything into scope.\\n -- See Note [Finding GHC.Essentials] in GHC.Builtin.\\n return (Nothing, ImpUserDependOnly, emptyGlobalRdrEnv, emptyGlobalRdrEnv)\\n UserWrittenImport -> filter_imports\\n ImplicitPreludeImport -> filter_imports\\n PluginImport -> filter_imports\\n\\n let is_hiding | Just (EverythingBut,_) <- imp_details = True\\n | otherwise = False\\n\\n -- should the import be safe?\\n mod_safe\' = mod_safe\\n || (not generated && safeDirectImpsReq dflags)\\n || (generated && safeImplicitImpsReq dflags)\\n\\n hsc_env <- getTopEnv\\n let home_unit = hsc_home_unit hsc_env\\n other_home_units = hsc_all_home_unit_ids hsc_env\\n\\n imported_by\\n | isDependOnlyImport imp_user_list\\n = ImportedBySystem\\n | otherwise\\n = ImportedByUser $ ImportedModsVal\\n { imv_name = is_as imp_spec\\n , imv_span = locA loc\\n , imv_is_safe = mod_safe\'\\n , imv_is_hiding = is_hiding\\n , imv_all_exports = potential_gres\\n , imv_qualified = qual_only\\n , imv_is_level = convImportLevel import_level\\n }\\n imports = calculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by\\n\\n -- Complain if we import a deprecated module\\n case fromIfaceWarnings (mi_warns iface) of\\n WarnAll txt -> addDiagnostic (TcRnDeprecatedModule imp_mod_name txt)\\n _ -> return ()\\n\\n let new_imp_decl = ImportDecl\\n { ideclExt = ideclExt decl\\n , ideclName = ideclName decl\\n , ideclPkgQual = pkg_qual\\n , ideclSource = ideclSource decl\\n , ideclSafe = mod_safe\'\\n , ideclQualified = ideclQualified decl\\n , ideclAs = ideclAs decl\\n , ideclImportList = new_imp_details\\n , ideclLevelSpec = ideclLevelSpec decl\\n }\\n\\n return (L loc new_imp_decl, ImpUserSpec imp_spec imp_user_list, gbl_env, imports)\\n\\n-- | The error message to emit when we failed to load an interface.\\nimportDeclLoadFailure :: ImportDeclOrigin -> ModuleName -> IsBootInterface\\n -> MissingInterfaceError -> TcRnMessage\\nimportDeclLoadFailure ImplicitEssentialsImport _ _ err\\n = TcRnInterfaceError $ CantFindEssentials err LookingForEssentialsModule\\nimportDeclLoadFailure _ mod_name want_boot err\\n = TcRnInterfaceError $ Can\'tFindInterface err $ LookingForModule mod_name want_boot\\n\\n-- | Rename raw package imports\\nrenameRawPkgQual :: UnitEnv -> ModuleName -> RawPkgQual -> PkgQual\\nrenameRawPkgQual unit_env mn = \\\\case\\n NoRawPkgQual -> NoPkgQual\\n RawPkgQual _ fs -> renamePkgQual unit_env mn $ Just fs\\n\\n-- | Rename raw package imports\\nrenamePkgQual :: UnitEnv -> ModuleName -> Maybe FastString -> PkgQual\\nrenamePkgQual unit_env mn mb_pkg = case mb_pkg of\\n Nothing -> NoPkgQual\\n Just pkg_fs\\n | Just uid <- homeUnitId <$> ue_homeUnit unit_env\\n , pkg_fs == fsLit \\"this\\"\\n -> ThisPkg uid\\n\\n | Just (uid, _) <- find (fromMaybe False . fmap (== pkg_fs) . snd) home_names\\n -> ThisPkg uid\\n\\n | Just uid <- resolvePackageImport unit_state mn (PackageName pkg_fs)\\n -> OtherPkg uid\\n\\n | otherwise\\n -> OtherPkg (UnitId pkg_fs)\\n -- not really correct as pkg_fs is unlikely to be a valid unit-id but\\n -- we will report the failure later...\\n where\\n home_names =\\n [ (uid, mkFastString <$> thisPackageName (homeUnitEnv_dflags (ue_findHomeUnitEnv uid unit_env)))\\n | uid <- S.toList hpt_deps\\n ]\\n\\n unit_state = ue_homeUnitState unit_env\\n\\n hpt_deps :: S.Set UnitId\\n hpt_deps = homeUnitDepends unit_state\\n\\n\\n-- | Calculate the \'ImportAvails\' induced by an import of a particular\\n-- interface, but without \'imp_mods\'.\\ncalculateAvails :: HomeUnit\\n -> S.Set UnitId\\n -> ModIface\\n -> IsSafeImport\\n -> IsBootInterface\\n -> ImportedBy\\n -> ImportAvails\\ncalculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by =\\n let imp_mod = mi_module iface\\n imp_sem_mod= mi_semantic_module iface\\n orph_iface = mi_orphan iface\\n has_finsts = mi_finsts iface\\n deps = mi_deps iface\\n trust = getSafeMode $ mi_trust iface\\n trust_pkg = mi_trust_pkg iface\\n is_sig = mi_hsc_src iface == HsigFile\\n\\n -- If the module exports anything defined in this module, just\\n -- ignore it. Reason: otherwise it looks as if there are two\\n -- local definition sites for the thing, and an error gets\\n -- reported. Easiest thing is just to filter them out up\\n -- front. This situation only arises if a module imports\\n -- itself, or another module that imported it. (Necessarily,\\n -- this involves a loop.)\\n --\\n -- We do this *after* filterImports, so that if you say\\n -- module A where\\n -- import B( AType )\\n -- type AType = ...\\n --\\n -- module B( AType ) where\\n -- import {-# SOURCE #-} A( AType )\\n --\\n -- then you won\'t get a \'B does not export AType\' message.\\n\\n\\n -- Compute new transitive dependencies\\n --\\n -- \'dep_orphs\' and \'dep_finsts\' do NOT include the imported module\\n -- itself, but we DO need to include this module in \'imp_orphs\' and\\n -- \'imp_finsts\' if it defines an orphan or instance family; thus the\\n -- orph_iface/has_iface tests.\\n\\n deporphs = dep_orphs deps\\n depfinsts = dep_finsts deps\\n\\n orphans | orph_iface = assertPpr (not (imp_sem_mod `elem` deporphs)) (ppr imp_sem_mod <+> ppr deporphs) $\\n imp_sem_mod : deporphs\\n | otherwise = deporphs\\n\\n finsts | has_finsts = assertPpr (not (imp_sem_mod `elem` depfinsts)) (ppr imp_sem_mod <+> ppr depfinsts) $\\n imp_sem_mod : depfinsts\\n | otherwise = depfinsts\\n\\n -- Trusted packages are a lot like orphans.\\n trusted_pkgs | mod_safe\' = dep_trusted_pkgs deps\\n | otherwise = S.empty\\n\\n\\n pkg = moduleUnit (mi_module iface)\\n ipkg = toUnitId pkg\\n\\n -- Does this import mean we now require our own pkg\\n -- to be trusted? See Note [Trust Own Package]\\n ptrust = trust == Sf_Trustworthy || trust_pkg\\n pkg_trust_req\\n | isHomeUnit home_unit pkg = ptrust\\n | otherwise = False\\n\\n dependent_pkgs = if toUnitId pkg `S.member` other_home_units\\n then S.empty\\n else S.singleton (lvl, ipkg)\\n\\n lvl = case imported_by of\\n ImportedByUser imv -> imv_is_level imv\\n ImportedBySystem -> NormalLevel\\n\\n\\n direct_mods = if toUnitId pkg `S.member` other_home_units\\n then mkPlusModDeps (moduleUnitId imp_mod) lvl (GWIB (moduleName imp_mod) want_boot)\\n else emptyInstalledModuleEnv\\n\\n dep_boot_mods_map = mkModDeps (dep_boot_mods deps)\\n\\n\\n boot_mods\\n -- If we are looking for a boot module, it must be HPT\\n | IsBoot <- want_boot = extendInstalledModuleEnv dep_boot_mods_map (toUnitId <$> imp_mod) (GWIB (moduleName imp_mod) IsBoot)\\n -- Now we are importing A properly, so don\'t go looking for\\n -- A.hs-boot\\n | isHomeUnit home_unit pkg = dep_boot_mods_map\\n -- There\'s no boot files to find in external imports\\n | otherwise = emptyInstalledModuleEnv\\n\\n sig_mods =\\n if is_sig\\n then moduleName imp_mod : dep_sig_mods deps\\n else dep_sig_mods deps\\n\\n\\n in ImportAvails {\\n imp_mods = Map.singleton (mi_module iface) [imported_by],\\n imp_orphs = orphans,\\n imp_finsts = finsts,\\n imp_sig_mods = sig_mods,\\n imp_direct_dep_mods = direct_mods,\\n imp_dep_direct_pkgs = dependent_pkgs,\\n imp_boot_mods = boot_mods,\\n\\n -- Add in the imported modules trusted package\\n -- requirements. ONLY do this though if we import the\\n -- module as a safe import.\\n -- See Note [Tracking Trust Transitively]\\n -- and Note [Trust Transitive Property]\\n imp_trust_pkgs = trusted_pkgs,\\n -- Do we require our own pkg to be trusted?\\n -- See Note [Trust Own Package]\\n imp_trust_own_pkg = pkg_trust_req\\n }\\n\\nmkPlusModDeps :: UnitId -> ImportLevel -> ModuleNameWithIsBoot\\n -> InstalledModuleEnv (S.Set ImportLevel, ModuleNameWithIsBoot)\\nmkPlusModDeps uid st elt = extendInstalledModuleEnv emptyInstalledModuleEnv (mkModule uid (gwib_mod elt)) (S.singleton st, elt)\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{importsFromLocalDecls}\\n* *\\n************************************************************************\\n\\nFrom the top-level declarations of this module produce\\n * the lexical environment\\n * the ImportAvails\\ncreated by its bindings.\\n\\nNote [Top-level Names in Template Haskell decl quotes]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSee also: Note [Interactively-bound Ids in GHCi] in GHC.Driver.Env\\n Note [Looking up Exact RdrNames] in GHC.Rename.Env\\n\\nConsider a Template Haskell declaration quotation like this:\\n module M where\\n f x = h [d| f = 3 |]\\nWhen renaming the declarations inside [d| ...|], we treat the\\ntop level binders specially in two ways\\n\\n1. We give them an Internal Name, not (as usual) an External one.\\n This is done by GHC.Rename.Env.newTopSrcBinder.\\n\\n2. We make them *shadow* the outer bindings.\\n See Note [GlobalRdrEnv shadowing]\\n\\n3. We find out whether we are inside a [d| ... |] by testing the TH\\n level. This is a slight hack, because the level field was really\\n meant for the type checker, and here we are not interested in the\\n fields of Brack, hence the error thunks in thRnBrack.\\n-}\\n\\nextendGlobalRdrEnvRn :: [GlobalRdrElt]\\n -> MiniFixityEnv\\n -> RnM (TcGblEnv, TcLclEnv)\\n-- Updates both the GlobalRdrEnv and the FixityEnv\\n-- We return a new TcLclEnv only because we might have to\\n-- delete some bindings from it;\\n-- see Note [Top-level Names in Template Haskell decl quotes]\\n\\nextendGlobalRdrEnvRn new_gres new_fixities\\n = checkNoErrs $ -- See Note [Fail fast on duplicate definitions]\\n do { (gbl_env, lcl_env) <- getEnvs\\n ; level <- getThLevel\\n ; isGHCi <- getIsGHCi\\n ; let rdr_env = tcg_rdr_env gbl_env\\n fix_env = tcg_fix_env gbl_env\\n th_bndrs = getLclEnvThBndrs lcl_env\\n th_lvl = thLevelIndex level\\n\\n -- Delete new_occs from global and local envs\\n -- If we are in a TemplateHaskell decl bracket,\\n -- we are going to shadow them\\n -- See Note [GlobalRdrEnv shadowing]\\n inBracket = isBrackLevel level\\n\\n lcl_env_TH = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_rdr = minusLocalRdrEnv (tcl_rdr lcl_env) new_gres_env }) lcl_env\\n -- See Note [GlobalRdrEnv shadowing]\\n\\n lcl_env2 | inBracket = lcl_env_TH\\n | otherwise = lcl_env\\n\\n -- Deal with shadowing: see Note [GlobalRdrEnv shadowing]\\n want_shadowing = isGHCi || inBracket\\n rdr_env1 | want_shadowing = shadowNames False rdr_env new_gres_env\\n | otherwise = rdr_env\\n\\n lcl_env3 = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_th_bndrs = extendNameEnvList th_bndrs\\n [ ( n, (TopLevel, th_lvl) )\\n | n <- new_names ] }) lcl_env2\\n\\n ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres\\n\\n ; let fix_env\' = foldl\' extend_fix_env fix_env new_gres\\n gbl_env\' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env\' }\\n\\n ; traceRn \\"extendGlobalRdrEnvRn 2\\" (pprGlobalRdrEnv True rdr_env2)\\n ; return (gbl_env\', lcl_env3) }\\n where\\n new_names = map greName new_gres\\n new_gres_env = mkGlobalRdrEnv new_gres\\n\\n -- If there is a fixity decl for the gre, add it to the fixity env\\n extend_fix_env fix_env gre\\n | Just (L _ fi) <- lookupMiniFixityEnv new_fixities name\\n = extendNameEnv fix_env name (FixItem occ fi)\\n | otherwise\\n = fix_env\\n where\\n name = greName gre\\n occ = greOccName gre\\n\\n add_gre :: GlobalRdrEnv -> GlobalRdrElt -> RnM GlobalRdrEnv\\n -- Extend the GlobalRdrEnv with a LocalDef GRE\\n -- If there is already a LocalDef GRE with the same OccName,\\n -- report an error and discard the new GRE\\n -- This establishes INVARIANT 1 of GlobalRdrEnvs\\n add_gre env gre\\n | not (null dups) -- Same OccName defined twice\\n = do { addDupDeclErr (gre :| dups); return env }\\n\\n | otherwise\\n = return (extendGlobalRdrEnv env gre)\\n where\\n -- See Note [Reporting duplicate local declarations]\\n dups = filter isBadDupGRE\\n $ lookupGRE env (LookupOccName (greOccName gre) (RelevantGREsFOS WantBoth))\\n isBadDupGRE old_gre = isLocalGRE old_gre && greClashesWith gre old_gre\\n\\n{- Note [Fail fast on duplicate definitions]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIf there are duplicate bindings for the same thing, we want to fail\\nfast. Having two bindings for the same thing can cause follow-on errors.\\nExample (test T9975a):\\n data Test = Test { x :: Int }\\n pattern Test wat = Test { x = wat }\\nThis defines \'Test\' twice. The second defn has no field-names; and then\\nwe get an error from Test { x=wat }, saying \\"Test has no field \'x\'\\".\\n\\nEasiest thing is to bale out fast on duplicate definitions, which\\nwe do via `checkNoErrs` on `extendGlobalRdrEnvRn`.\\n\\nNote [Reporting duplicate local declarations]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn general, a single module may not define the same OccName multiple times. This\\nis checked in extendGlobalRdrEnvRn: when adding a new locally-defined GRE to the\\nGlobalRdrEnv we report an error if there are already duplicates in the\\nenvironment. This establishes INVARIANT 1 (see comments on GlobalRdrEnv in\\nGHC.Types.Name.Reader), which says that for a given OccName, all the\\nGlobalRdrElts to which it maps must have distinct \'greName\'s.\\n\\nFor example, the following will be rejected:\\n\\n f x = x\\n g x = x\\n f x = x -- Duplicate!\\n\\nUsers are allowed to introduce new GREs with the same OccName as an imported GRE,\\nas disambiguation is possible through the module system, e.g.:\\n\\n module M where\\n import N (f)\\n f x = x\\n g x = M.f x + N.f x\\n\\nIf both GREs are local, the general rule is that two GREs clash if they have\\nthe same OccName, i.e. they share a textual name and live in the same namespace.\\nHowever, there are additional clashes due to record fields:\\n\\n - a new variable clashes with previously defined record fields\\n which define field selectors,\\n\\n - a new record field shadows:\\n\\n - previously defined variables, if it defines a field selector,\\n - previously defined record fields, unless it is a duplicate record field.\\n\\nThis logic is implemented in the function \'GHC.Types.Name.Reader.greClashesWith\'.\\n\\nSee also Note [Skipping ambiguity errors at use sites of local declarations] in\\nGHC.Rename.Utils.\\n-}\\n\\n\\n{- *********************************************************************\\n* *\\n getLocalDeclBindersd@ returns the names for an HsDecl\\n It\'s used for source code.\\n\\n *** See Note [The Naming story] in GHC.Hs.Decls ****\\n* *\\n********************************************************************* -}\\n\\ngetLocalNonValBinders :: MiniFixityEnv -> HsGroup GhcPs\\n -> RnM ((TcGblEnv, TcLclEnv), NameSet)\\n-- Get all the top-level binders bound the group *except*\\n-- for value bindings, which are treated separately\\n-- Specifically we return AvailInfo for\\n-- * type decls (incl constructors and record selectors)\\n-- * class decls (including class ops)\\n-- * associated types\\n-- * foreign imports\\n-- * value signatures (in hs-boot files only)\\n\\ngetLocalNonValBinders fixity_env\\n (HsGroup { hs_valds = binds,\\n hs_tyclds = tycl_decls,\\n hs_fords = foreign_decls })\\n = do { -- Process all type/class decls *except* family instances\\n ; let inst_decls = tycl_decls >>= group_instds\\n ; dup_fields_ok <- xopt_DuplicateRecordFields <$> getDynFlags\\n ; has_sel <- xopt_FieldSelectors <$> getDynFlags\\n ; tc_gres\\n <- concatMapM\\n (new_tc dup_fields_ok has_sel)\\n (tyClGroupTyClDecls tycl_decls)\\n ; traceRn \\"getLocalNonValBinders 1\\" (ppr tc_gres)\\n ; envs <- extendGlobalRdrEnvRn tc_gres fixity_env\\n ; restoreEnvs envs $ do {\\n -- Bring these things into scope first\\n -- See Note [Looking up family names in family instances]\\n\\n -- Process all family instances\\n -- to bring new data constructors into scope\\n ; nti_gress <- mapM (new_assoc dup_fields_ok has_sel) inst_decls\\n\\n -- Finish off with value binders:\\n -- foreign decls and pattern synonyms for an ordinary module\\n -- type sigs in case of a hs-boot file only\\n ; is_boot <- tcIsHsBootOrSig\\n ; let val_bndrs\\n | is_boot = case binds of\\n ValBinds _ val_binds ->\\n -- In a hs-boot file, the value binders come from the\\n -- *signatures*, and there should be no foreign binders\\n [ L (l2l decl_loc) (unLoc n)\\n | L decl_loc (TypeSig _ _ ns _) <- (val_sigs val_binds), n <- ns]\\n _ -> panic \\"Non-ValBinds in hs-boot group\\"\\n | otherwise = for_hs_bndrs\\n ; val_gres <- mapM new_simple val_bndrs\\n\\n ; let avails = concat nti_gress ++ val_gres\\n new_bndrs = gresToNameSet avails `unionNameSet`\\n gresToNameSet tc_gres\\n ; traceRn \\"getLocalNonValBinders 2\\" (ppr avails)\\n ; envs <- extendGlobalRdrEnvRn avails fixity_env\\n ; return (envs, new_bndrs) } }\\n where\\n for_hs_bndrs :: [LocatedN RdrName]\\n for_hs_bndrs = hsForeignDeclsBinders foreign_decls\\n\\n -- the SrcSpan attached to the input should be the span of the\\n -- declaration, not just the name\\n new_simple :: LocatedN RdrName -> RnM GlobalRdrElt\\n new_simple rdr_name = do { nm <- newTopSrcBinder rdr_name\\n ; return (mkLocalVanillaGRE NoParent nm) }\\n\\n new_tc :: DuplicateRecordFields -> FieldSelectors -> LTyClDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_tc dup_fields_ok has_sel tc_decl -- NOT for type/data instances\\n = do { let TyDeclBinders (main_bndr, tc_flav) at_bndrs sig_bndrs\\n (LConsWithFields cons_with_flds flds) = hsLTyClDeclBinders tc_decl\\n ; tycon_name <- newTopSrcBinder $ la2la main_bndr\\n ; at_names <- mapM (newTopSrcBinder . la2la . fst) at_bndrs\\n ; sig_names <- mapM (newTopSrcBinder . la2la) sig_bndrs\\n ; con_names_with_flds <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst con_names_with_flds) flds\\n ; mapM_ (add_dup_fld_errs flds\') con_names_with_flds\\n ; let tc_gre = mkLocalTyConGRE (fmap (const tycon_name) tc_flav) tycon_name\\n fld_env = mk_fld_env con_names_with_flds flds\'\\n at_gres = zipWith (\\\\ (_, at_flav) at_nm -> mkLocalTyConGRE (fmap (const tycon_name) at_flav) at_nm)\\n at_bndrs at_names\\n sig_gres = map (mkLocalVanillaGRE (ParentIs tycon_name)) sig_names\\n con_gres = map (mkLocalConLikeGRE (ParentIs tycon_name)) fld_env\\n fld_gres = mkLocalFieldGREs (ParentIs tycon_name) fld_env\\n sub_gres = at_gres ++ sig_gres ++ con_gres ++ fld_gres\\n ; traceRn \\"getLocalNonValBinders new_tc\\" $\\n vcat [ text \\"tycon:\\" <+> ppr tycon_name\\n , text \\"tc_gre:\\" <+> ppr tc_gre\\n , text \\"sub_gres:\\" <+> ppr sub_gres ]\\n ; return $ tc_gre : sub_gres }\\n\\n -- Calculate the record field information, which feeds into the GlobalRdrElts\\n -- for DataCons and their fields. It\'s convenient to do this here where\\n -- we are working with a single datatype definition.\\n --\\n -- The information we needed was all set up for us:\\n -- see Note [Collecting record fields in data declarations] in GHC.Hs.Utils.\\n mk_fld_env :: [(Name, Either VisArity [Located Int])] -> IntMap FieldLabel\\n -> [(ConLikeName, ConInfo)]\\n mk_fld_env names flds =\\n [ (DataConName con, ConInfo (ConIsData (map fst names)) fld_info)\\n | (con, con_fl_indxs) <- names\\n , let fld_info = case fmap (map ((flds IntMap.!) . unLoc)) con_fl_indxs of\\n Left 0 -> ConIsNullary\\n Left arity -> ConHasPositionalArgs arity\\n Right [] -> ConIsNullary\\n Right (fld:flds) -> ConHasRecordFields $ fld NE.:| flds ]\\n\\n new_assoc :: DuplicateRecordFields -> FieldSelectors -> LInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_assoc _ _ (L _ (TyFamInstD {})) = return []\\n -- type instances don\'t bind new names\\n\\n new_assoc dup_fields_ok has_sel (L _ (DataFamInstD _ d))\\n = new_di dup_fields_ok has_sel Nothing d\\n new_assoc dup_fields_ok has_sel\\n (L _ (ClsInstD _ (ClsInstDecl { cid_poly_ty = inst_ty\\n , cid_decls = decls })))\\n = do -- First, attempt to grab the name of the class from the instance.\\n -- This step could fail if the instance is not headed by a class,\\n -- such as in the following examples:\\n --\\n -- (1) The class is headed by a bang pattern, such as in\\n -- `instance !Show Int` (#3811c)\\n -- (2) The class is headed by a type variable, such as in\\n -- `instance c` (#16385)\\n --\\n -- If looking up the class name fails, then mb_cls_gre will\\n -- be Nothing.\\n mb_cls_gre <- runMaybeT $ do\\n -- See (1) above\\n L loc cls_rdr <- MaybeT $ pure $ getLHsInstDeclClass_maybe inst_ty\\n -- See (2) above\\n MaybeT $ setSrcSpan (locA loc) $ lookupGlobalOccRn_maybe SameNameSpace cls_rdr\\n -- Assuming the previous step succeeded, process any associated data\\n -- family instances. If the previous step failed, bail out.\\n case mb_cls_gre of\\n Nothing\\n -> pure []\\n Just cls_gre\\n -> let cls_nm = greName cls_gre\\n in concatMapM (new_di dup_fields_ok has_sel (Just cls_nm) . unLoc) (data_fam_insts decls)\\n\\n data_fam_insts decls = concatMap get decls\\n where\\n get (L l (InstD _ (DataFamInstD { dfid_inst = d}))) = [L l d]\\n get _ = []\\n\\n new_di :: DuplicateRecordFields -> FieldSelectors\\n -> Maybe Name -- class name\\n -> DataFamInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_di dup_fields_ok has_sel mb_cls dfid@(DataFamInstDecl { dfid_eqn = ti_decl })\\n = do { main_name <- unLoc <$> lookupFamInstName mb_cls (feqn_tycon ti_decl)\\n ; let LConsWithFields cons_with_flds flds = hsDataFamInstBinders dfid\\n ; sub_names <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst sub_names) flds\\n ; mapM_ (add_dup_fld_errs flds\') sub_names\\n ; let fld_env = mk_fld_env sub_names flds\'\\n con_gres = map (mkLocalConLikeGRE (ParentIs main_name)) fld_env\\n field_gres = mkLocalFieldGREs (ParentIs main_name) fld_env\\n -- NB: the data family name is not bound here,\\n -- so we don\'t return a GlobalRdrElt for it here!\\n ; return $ con_gres ++ field_gres }\\n\\n -- Add errors if a constructor has a duplicate record field.\\n add_dup_fld_errs :: IntMap FieldLabel\\n -> (Name, Either VisArity [Located Int])\\n -> IOEnv (Env TcGblEnv TcLclEnv) ()\\n add_dup_fld_errs all_flds (con, con_flds_or_arity)\\n | Right con_flds <- con_flds_or_arity\\n , let (_, dups) = removeDups (comparing unLoc) con_flds\\n = for_ dups $ \\\\ dup_flds ->\\n -- Report the error at the location of the second occurrence\\n -- of the duplicate field.\\n let loc =\\n case dup_flds of\\n _ :| ( L loc _ : _) -> loc\\n L loc _ :| _ -> loc\\n dup_rdrs = fmap (nameRdrName . flSelector . (all_flds IntMap.!) . unLoc) dup_flds\\n in addErrAt loc $ TcRnDuplicateFieldName (RecordFieldDecl con) dup_rdrs\\n | otherwise\\n = return ()\\n\\nnewRecordFieldLabel :: DuplicateRecordFields -> FieldSelectors -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel\\nnewRecordFieldLabel _ _ [] _ = error \\"newRecordFieldLabel: datatype has no constructors!\\"\\nnewRecordFieldLabel dup_fields_ok has_sel (dc:_) (L loc (FieldOcc _ (L _ fld)))\\n = do { selName <- newTopSrcBinder $ L (l2l loc) $ field\\n ; return $ FieldLabel { flHasDuplicateRecordFields = dup_fields_ok\\n , flHasFieldSelector = has_sel\\n , flSelector = selName } }\\n where\\n fld_occ = rdrNameOcc fld\\n dc_fs = occNameFS $ nameOccName dc\\n field\\n -- Use an Exact RdrName as-is, to preserve the bindings\\n -- of an already renamer-resolved field and its use\\n -- sites. This is needed to correctly support record\\n -- selectors in Template Haskell. See Note [Binders in\\n -- Template Haskell] in \\"GHC.ThToHs\\" and Note [Looking up\\n -- Exact RdrNames] in \\"GHC.Rename.Env\\".\\n | isExact fld\\n = assertPpr (fieldOcc_maybe fld_occ == Just dc_fs)\\n (vcat [ text \\"newRecordFieldLabel: incorrect namespace for exact Name\\" <+> quotes (ppr fld)\\n , text \\"expected namespace:\\" <+> pprNameSpace (fieldName dc_fs)\\n , text \\" actual namespace:\\" <+> pprNameSpace (occNameSpace fld_occ) ])\\n fld\\n\\n -- Field names produced by the parser are namespaced with VarName.\\n -- Here we namespace them according to the first constructor.\\n -- See Note [Record field namespacing] in GHC.Types.Name.Occurrence.\\n | otherwise\\n = mkRdrUnqual $ varToRecFieldOcc dc_fs fld_occ\\n\\n{-\\nNote [Looking up family names in family instances]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider\\n\\n module M where\\n type family T a :: *\\n type instance M.T Int = Bool\\n\\nWe might think that we can simply use \'lookupOccRn\' when processing the type\\ninstance to look up \'M.T\'. Alas, we can\'t! The type family declaration is in\\nthe *same* HsGroup as the type instance declaration. Hence, as we are\\ncurrently collecting the binders declared in that HsGroup, these binders will\\nnot have been added to the global environment yet.\\n\\nSolution is simple: process the type family declarations first, extend\\nthe environment, and then process the type instances.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Filtering imports}\\n* *\\n************************************************************************\\n\\n@filterImports@ takes the @ExportEnv@ telling what the imported module makes\\navailable, and filters it through the import spec (if any).\\n\\nNote [Dealing with imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nFor import M( ies ), we take each AvailInfo from the mi_exports of M, and make\\n\\n imp_occ_env :: OccEnv (NameEnv ImpOccItem)\\n\\nThis map contains one entry for each OccName that M exports, mapping each OccName\\nto the following information:\\n\\n 1. the GlobalRdrElt corresponding to the OccName,\\n 2. whether this GlobalRdrElt was the parent in the AvailInfo we found\\n the OccName in.\\n 3. the GlobalRdrElts that were bundled together in the AvailInfo we found\\n this OccName in (not including the parent),\\n\\nWe need (2) and (3) during the construction of the OccEnv because of associated\\ntypes and bundled pattern synonyms, respectively.\\n(3) is explained in Note [Importing PatternSynonyms].\\n\\nTo explain (2), consider for example:\\n\\n module M where\\n class C a where { data T a }\\n instance C Int where { data T Int = T1 | T2 }\\n instance C Bool where { data T Int = T3 }\\n\\nHere, M\'s exports avails are (recalling the AvailTC invariant from GHC.Types.Avail)\\n\\n C(C,T), T(T,T1,T2,T3)\\n\\nNotice that T appears *twice*, once as a child and once as a parent. From\\nthese two exports, respectively, during construction of the imp_occ_env, we begin\\nby associating the following two elements with the key T:\\n\\n T -> ImpOccItem { imp_item = gre1, imp_bundled = [C,T] , imp_is_parent = False }\\n T -> ImpOccItem { imp_item = gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nwhere `gre1`, `gre2` are two GlobalRdrElts with greName T.\\nWe combine these (in function \'combine\' in \'mkImportOccEnv\') by discarding the\\nnon-parent item, thusly:\\n\\n T -> IE_ITem { imp_item = gre1 `plusGRE` gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nNote the `plusGRE`: this ensures we don\'t drop parent information;\\nsee Note [Preserve parent information when combining import OccEnvs].\\n\\nSo the overall imp_occ_env is:\\n\\n C -> ImpOccItem { imp_item = C, imp_bundled = [T ], imp_is_parent = True }\\n T -> ImpOccItem { imp_item = T , imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n T1 -> ImpOccItem { imp_item = T1, imp_bundled = [T1,T2,T3], imp_is_parent = False }\\n -- similarly for T2, T3\\n\\nNote that the imp_occ_env will have entries for data constructors too,\\nalthough we never look up data constructors.\\n\\nNote [Importing PatternSynonyms]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nAs described in Note [Dealing with imports], associated types can lead to the\\nsame Name appearing twice, both as a child and once as a parent, when\\nconstructing the imp_occ_env. The same thing can happen with pattern synonyms\\nif they are exported bundled with a type.\\n\\nA simplified example, based on #11959:\\n\\n {-# LANGUAGE PatternSynonyms #-}\\n module M (T(P), pattern P) where -- Duplicate export warning, but allowed\\n data T = MkT\\n pattern P = MkT\\n\\nHere we have T(P) and P in export_avails, and respectively construct both\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n P -> ImpOccItem { imp_item = P, imp_bundled = [] , imp_is_parent = False }\\n\\nWe combine these by dropping the one with no siblings, leaving us with:\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n\\nThat is, we simply discard the non-bundled Avail.\\n\\nNote [Importing DuplicateRecordFields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn filterImports, another complicating factor is DuplicateRecordFields.\\nSuppose we have:\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (S(foo), T(foo)) where\\n data S = MkS { foo :: Int }\\n data T = MkT { foo :: Int }\\n\\n module N where\\n import M (foo) -- this is allowed (A)\\n import M (S(foo)) -- this is allowed (B)\\n\\nHere M exports \'foo\' at two different OccNames, with different namespaces for\\nthe two construtors MkS and MkT. Then, when we look up \'foo\' in lookup_names\\nfor case (A), we have a variable foo but must look in all the record field\\nnamespaces to find the two fields (and hence two different Avails).\\nWhereas in case (B) we reach the lookup_ie case for IEThingWith,\\nwhich looks up \'S\' and then finds the unique \'foo\' amongst its children.\\n\\nSee T16745 for a test of this.\\n\\nNote [Preserve parent information when combining import OccEnvs]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen discarding one ImpOccItem in favour of another, as described in\\nNote [Dealing with imports], we must make sure to combine the GREs so that\\nwe don\'t lose information.\\n\\nConsider for example #24084:\\n\\n module M1 where { class C a where { type T a } }\\n module M2 ( module M1 ) where { import M1 }\\n module M3 where { import M2 ( C, T ); instance C () where T () = () }\\n\\nWhen processing the import list of `M3`, we will have two `Avail`s attached\\nto `T`, namely `C(C, T)` and `T(T)`. We combine them in the `combine` function\\nof `mkImportOccEnv`; as described in Note [Dealing with imports] we discard\\n`C(C, T)` in favour of `T(T)`. However, in doing so, we **must not**\\ndiscard the information want that `C` is the parent of `T`. Indeed,\\nlosing track of this information can cause errors when importing,\\nas we could get an error of the form\\n\\n \\u2018T\\u2019 is not a (visible) associated type of class \\u2018C\\u2019\\n\\nThis explains why we use `plusGRE` when combining the two ImpOccItems, even\\nthough we are discarding one in favour of the other.\\n-}\\n\\n-- | All the \'GlobalRdrElt\'s associated with an \'AvailInfo\'.\\ngresFromAvail :: HasDebugCallStack\\n => HscEnv -> Maybe ImportSpec -> AvailInfo -> [GlobalRdrElt]\\ngresFromAvail hsc_env prov avail =\\n [ mk_gre nm info\\n | nm <- availNames avail\\n , let info = lookupGREInfo hsc_env nm ]\\n where\\n\\n mk_gre n info\\n = case prov of\\n -- Nothing => bound locally\\n -- Just is => imported from \'is\'\\n Nothing -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = True, gre_imp = emptyBag\\n , gre_info = info }\\n Just is -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = False, gre_imp = unitBag is\\n , gre_info = info }\\n\\n-- | All the \'GlobalRdrElt\'s associated with a collection of \'AvailInfo\'s.\\ngresFromAvails :: HscEnv -> Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]\\ngresFromAvails hsc_env prov = concatMap (gresFromAvail hsc_env prov)\\n\\nimportsFromIface :: HscEnv -> ModIface -> ImpDeclSpec -> Maybe NameSet -> GlobalRdrEnv\\nimportsFromIface hsc_env iface decl_spec hidden = mkGlobalRdrEnv $ case hidden of\\n Nothing -> all_gres\\n Just hidden_names -> filter (not . (`elemNameSet` hidden_names) . greName) all_gres\\n where\\n all_gres = gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\nrnNamespaceSpecifier :: NamespaceSpecifier GhcPs -> NamespaceSpecifier GhcRn\\nrnNamespaceSpecifier (NoNamespaceSpecifier _) = NoNamespaceSpecifier noExtField\\nrnNamespaceSpecifier (TypeNamespaceSpecifier x) = TypeNamespaceSpecifier x\\nrnNamespaceSpecifier (DataNamespaceSpecifier x) = DataNamespaceSpecifier x\\n\\nfilterImports\\n :: HasDebugCallStack\\n => HscEnv\\n -> ModIface\\n -> ImpDeclSpec\\n -- ^ Import spec\\n -> Maybe (ImportListInterpretation, [LIE GhcPs])\\n -- ^ Whether this is a \\"hiding\\" import list\\n -> RnM (Maybe (ImportListInterpretation, [LIE GhcRn]), -- Import spec w/ Names\\n ImpUserList, -- same, but designed for storage in interfaces\\n GlobalRdrEnv) -- Same again, but in GRE form\\nfilterImports hsc_env iface decl_spec Nothing\\n = return (Nothing, ImpUserAll, importsFromIface hsc_env iface decl_spec Nothing)\\nfilterImports hsc_env iface decl_spec (Just (want_hiding, import_items))\\n = do -- check for errors, convert RdrNames to Names\\n items1 <- mapM lookup_lie import_items\\n\\n let items2 :: [(LIE GhcRn, [GlobalRdrElt])]\\n items2 = concat items1\\n -- NB we may have duplicates, and several items\\n -- for the same parent; e.g N(x) and N(y)\\n\\n (gres, imp_user_list) = case want_hiding of\\n Exactly ->\\n let gres = concatMap (gresFromIE decl_spec) items2\\n gre_env = mkGlobalRdrEnv gres\\n implicit_parents = mkNameSet $ mapMaybe parentOfImplicitlyImportedGRE gres\\n in (gre_env, ImpUserExplicit (gresToAvailInfo $ globalRdrEnvElts $ gre_env) implicit_parents)\\n EverythingBut ->\\n let hidden_names = mkNameSet $ concatMap (map greName . snd) items2\\n in (importsFromIface hsc_env iface decl_spec (Just hidden_names), ImpUserEverythingBut hidden_names)\\n\\n return (Just (want_hiding, map fst items2), imp_user_list, gres)\\n where\\n import_mod = mi_module iface\\n all_avails = mi_exports iface\\n imp_occ_env = mkImportOccEnv hsc_env decl_spec all_avails\\n\\n -- Look up a parent (type constructor, class or data constructor)\\n -- in an import.\\n lookup_parent :: IE GhcPs -> RdrName -> IELookupM ImpOccItem\\n lookup_parent ie rdr =\\n assertPpr (not $ isVarNameSpace ns)\\n (vcat [ text \\"filterImports lookup_parent: unexpected variable\\"\\n , text \\"rdr:\\" <+> ppr rdr\\n , text \\"namespace:\\" <+> pprNameSpace ns ]) $\\n do { xs <- lookup_names ie rdr\\n ; case xs of\\n cax :| [] -> return cax\\n _ -> pprPanic \\"filter_imports lookup_parent ambiguous\\" $\\n vcat [ text \\"rdr:\\" <+> ppr rdr\\n , text \\"lookups:\\" <+> ppr (fmap imp_item xs) ] }\\n -- Looking up non-variables is always unambiguous,\\n -- as there can be at most one corresponding item\\n -- in the imp_occ_env.\\n -- See item (1) of Note [Exporting duplicate declarations]\\n -- in GHC.Tc.Gen.Export.\\n where\\n occ = rdrNameOcc rdr\\n ns = occNameSpace occ\\n\\n -- Look up a RdrName used in an import, returning multiple values if there\\n -- are several fields with the same name exposed by the module\\n lookup_names :: IE GhcPs -> RdrName -> IELookupM (NonEmpty ImpOccItem)\\n lookup_names ie rdr\\n | isQual rdr\\n = failLookupWith (QualImportError rdr)\\n | otherwise\\n = case lookups of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n item:items -> return $ item :| items\\n where\\n lookups = concatMap nonDetNameEnvElts\\n $ lookupImpOccEnv (RelevantGREsFOS WantNormal) imp_occ_env (rdrNameOcc rdr)\\n\\n lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, [GlobalRdrElt])]\\n lookup_lie (L loc ieRdr)\\n = setSrcSpanA loc $\\n do (stuff, warns) <- run_lookup ([],[]) (lookup_ie ieRdr)\\n mapM_ (addTcRnDiagnostic <=< warning_msg) warns\\n return [ (L loc ie, gres) | (ie,gres) <- stuff ]\\n where\\n\\n -- Warn when importing T(..) and no children are brought in scope\\n warning_msg (DodgyImport reason) =\\n pure (TcRnDodgyImports reason)\\n warning_msg MissingImportList =\\n pure (TcRnMissingImportList ieRdr)\\n warning_msg (BadImportW ie sub) = do\\n -- \'BadImportW\' is only constructed below in \'bad_import_w\', in\\n -- the \'EverythingBut\' case, so here we assume a \'hiding\' clause.\\n (reason :| _) <- badImportItemErr iface decl_spec ie sub all_avails\\n pure (TcRnDodgyImports (DodgyImportsHiding reason))\\n warning_msg (DeprecatedExport n w) =\\n pure $ TcRnPragmaWarning\\n PragmaWarningExport\\n { pwarn_occname = occName n\\n , pwarn_impmod = moduleName import_mod }\\n w\\n\\n run_lookup :: a -> IELookupM a -> TcRn a\\n run_lookup def m = case m of\\n Failed err -> do\\n msgs <- lookup_err_msgs err\\n forM_ msgs $ \\\\msg -> addErr (TcRnImportLookup msg)\\n return def\\n Succeeded a -> return a\\n\\n lookup_err_msgs err = case err of\\n BadImport ie sub -> badImportItemErr iface decl_spec ie sub all_avails\\n IllegalImport -> pure $ NE.singleton ImportLookupIllegal\\n QualImportError rdr -> pure $ NE.singleton (ImportLookupQualified rdr)\\n\\n -- For each import item, we convert its RdrNames to Names,\\n -- and at the same time compute all the GlobalRdrElt corresponding\\n -- to what is actually imported by this item.\\n -- Returns Nothing on error.\\n --\\n -- Returns a list because, with DuplicateRecordFields, a naked\\n -- import/export of a record field can correspond to multiple\\n -- different GlobalRdrElts. See Note [Importing DuplicateRecordFields].\\n lookup_ie :: IE GhcPs\\n -> IELookupM ([(IE GhcRn, [GlobalRdrElt])], [IELookupWarning])\\n lookup_ie ie = handle_bad_import $\\n case ie of\\n IEVar _ (L l n) _ -> do\\n -- See Note [Importing DuplicateRecordFields]\\n xs <- lookup_names ie (ieWrappedName n)\\n let gres = map imp_item $ NE.toList xs\\n export_depr_warns\\n | want_hiding == Exactly\\n = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ( [ (IEVar Nothing (L l (replaceWrappedName n name)) noDocstring, [gre])\\n | gre <- gres\\n , let name = greName gre ]\\n , export_depr_warns )\\n\\n IEThingAll x ns_spec (L l tc) _ -> do\\n ImpOccItem { imp_item = gre\\n , imp_bundled = bundled_gres\\n , imp_is_parent = is_par\\n }\\n <- lookup_parent ie $ ieWrappedName tc\\n let name = greName gre\\n\\n child_gres :: [GlobalRdrElt]\\n child_gres\\n | is_par = filterByNamespaceSpecifierGREs ns_spec bundled_gres\\n | otherwise = []\\n\\n imp_list_warn\\n\\n | null child_gres\\n -- e.g. f(..) or T(..) where T is a type synonym\\n = [DodgyImport (DodgyImportsEmptyParent ie ns_spec gre)]\\n\\n -- e.g. import M( T(..) )\\n | not (is_qual decl_spec)\\n = [MissingImportList]\\n\\n | otherwise\\n = []\\n\\n renamed_ie = IEThingAll (x { ieta_warning = Nothing })\\n (rnNamespaceSpecifier ns_spec)\\n (L l (replaceWrappedName tc name))\\n noDocstring\\n export_depr_warn\\n | want_hiding == Exactly\\n = maybeToList $ mk_depr_export_warning gre\\n -- We don\'t want to warn about the children as they\\n -- are not explicitly mentioned; the warning will\\n -- be emitted later on if they are used\\n | otherwise = []\\n\\n return ( [(renamed_ie, gre:child_gres)]\\n , imp_list_warn ++ export_depr_warn)\\n\\n\\n IEThingAbs _ (L l tc\') _\\n | want_hiding == EverythingBut -- hiding ( C )\\n -- Here the \'C\' can be a data constructor\\n -- *or* a type/class, or even both\\n -> let tc = ieWrappedName tc\'\\n tc_name = lookup_parent ie tc\\n dc_name = lookup_parent ie (setRdrNameSpace tc srcDataName)\\n in\\n case catIELookupM [ tc_name, dc_name ] of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n names -> return ( [mkIEThingAbs tc\' l (imp_item name) | name <- names], [])\\n | otherwise\\n -> do ImpOccItem { imp_item = gre } <- lookup_parent ie (ieWrappedName tc\')\\n return ( [mkIEThingAbs tc\' l gre]\\n , maybeToList $ mk_depr_export_warning gre)\\n\\n IEThingWith (deprecation, ann) ltc@(L l rdr_tc) wc rdr_ns _ -> do\\n ImpOccItem { imp_item = gre, imp_bundled = subnames }\\n <- lookup_parent (IEThingAbs Nothing ltc noDocstring) (ieWrappedName rdr_tc)\\n let name = greName gre\\n\\n -- Look up the children in the sub-names of the parent\\n -- See Note [Importing DuplicateRecordFields]\\n let (children_errs, childnames) = lookupChildren subnames rdr_ns\\n\\n bad_import_warns <-\\n if null children_errs then return [] else\\n let items = map lce_wrapped_name children_errs\\n ie = IEThingWith (deprecation, ann) ltc wc items noDocstring\\n -- We are trying to import T( a,b,c,d ), and failed\\n -- to find \'b\' and \'d\'. So we make up an import item\\n -- to report as failing, namely T( b, d ).\\n -- c.f. #15413\\n subordinate_err = mkSubordinateError gre children_errs\\n in bad_import_w ie subordinate_err\\n\\n let name\' = replaceWrappedName rdr_tc name\\n childnames\' = map (to_ie_post_rn . fmap greName) childnames\\n gres = gre : map unLoc childnames\\n export_depr_warns\\n | want_hiding == Exactly = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ([ (IEThingWith (Nothing, ann) (L l name\') wc childnames\' noDocstring\\n ,gres)]\\n , bad_import_warns ++ export_depr_warns)\\n\\n IEWholeNamespace x ns_spec -> do\\n let mod_name = moduleName import_mod\\n names = map greName gres\\n renamed_ie = IEWholeNamespace x { iewn_warning = Nothing\\n , iewn_names = names }\\n (rnNamespaceSpecifier ns_spec)\\n gres = filterByNamespaceSpecifierGREs ns_spec $\\n gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n dodgy_warn\\n | null gres = [DodgyImport (DodgyImportsWildcard mod_name ns_spec)]\\n | otherwise = []\\n return ([(renamed_ie, gres)],\\n dodgy_warn)\\n\\n _other -> failLookupWith IllegalImport\\n -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed...\\n -- all of those constitute errors.\\n\\n where\\n mkIEThingAbs tc l gre\\n = (IEThingAbs Nothing (L l (replaceWrappedName tc n)) noDocstring, [gre])\\n where n = greName gre\\n\\n -- N.B. imports never have docstrings\\n noDocstring = Nothing\\n\\n handle_bad_import m = catchIELookup m $ \\\\case\\n BadImport ie sub -> do\\n ws <- bad_import_w ie sub\\n return ([], ws)\\n err -> failLookupWith err\\n\\n bad_import_w :: IE GhcPs -> IsSubordinateError -> IELookupM [IELookupWarning]\\n bad_import_w ie sub\\n | want_hiding == EverythingBut = return [BadImportW ie sub]\\n | otherwise = failLookupWith (BadImport ie sub)\\n\\n mk_depr_export_warning gre\\n = DeprecatedExport name <$> mi_export_warn_fn iface name\\n where\\n name = greName gre\\n\\n-- | Assuming a subordinate item could not be found, do another lookup for a\\n-- more specific error message.\\nmkBadExportSubordinate :: [GlobalRdrElt] -> LIEWrappedName GhcPs -> BadExportSubordinate\\nmkBadExportSubordinate child_gres n =\\n case lookupChildren child_gres [n] of\\n (LookupChildNonType {lce_nontype_item = g} : _, _) -> BadExportSubordinateNonType g\\n (LookupChildNonData {lce_nondata_item = g} : _, _) -> BadExportSubordinateNonData g\\n _ -> BadExportSubordinateNotFound n\\n\\ntype IELookupM = MaybeErr IELookupError\\n\\ndata IELookupWarning\\n = BadImportW (IE GhcPs) IsSubordinateError\\n | MissingImportList\\n | DodgyImport DodgyImportsReason\\n | DeprecatedExport Name (WarningTxt GhcRn)\\n\\n-- | Is this import/export item a subordinate or not?\\ndata IsSubordinateError\\n = IsSubordinateError { subordinate_err_parent :: !GlobalRdrElt\\n , subordinate_err_unavailable :: [FastString]\\n , subordinate_err_nontype :: [GlobalRdrElt]\\n , subordinate_err_nondata :: [GlobalRdrElt] }\\n | IsNotSubordinate\\n\\nmkSubordinateError :: GlobalRdrElt -> [LookupChildError] -> IsSubordinateError\\nmkSubordinateError gre children_errs = foldr add init_acc children_errs\\n where\\n init_acc :: IsSubordinateError\\n init_acc = IsSubordinateError gre [] [] []\\n\\n add :: LookupChildError -> IsSubordinateError -> IsSubordinateError\\n add children_err sub@IsSubordinateError{} =\\n case children_err of\\n LookupChildNonType{lce_nontype_item = g} ->\\n sub { subordinate_err_nontype = g : subordinate_err_nontype sub }\\n LookupChildNonData{lce_nondata_item = g} ->\\n sub { subordinate_err_nondata = g : subordinate_err_nondata sub }\\n LookupChildNotFound (L _ wname) ->\\n let fs = (occNameFS . rdrNameOcc . ieWrappedName) wname\\n in sub { subordinate_err_unavailable = fs : subordinate_err_unavailable sub }\\n add _ IsNotSubordinate = panic \\"mkSubordinateError: IsNotSubordinate\\"\\n\\ndata IELookupError\\n = QualImportError RdrName\\n | BadImport (IE GhcPs) IsSubordinateError\\n | IllegalImport\\n\\nfailLookupWith :: IELookupError -> IELookupM a\\nfailLookupWith err = Failed err\\n\\ncatchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a\\ncatchIELookup m h = case m of\\n Succeeded r -> return r\\n Failed err -> h err\\n\\ncatIELookupM :: [IELookupM a] -> [a]\\ncatIELookupM ms = [ a | Succeeded a <- ms ]\\n\\n-- | Information associated to an \'AvailInfo\' used in constructing\\n-- an \'OccEnv\' corresponding to imports.\\n--\\n-- See Note [Dealing with imports].\\ndata ImpOccItem\\n = ImpOccItem\\n { imp_item :: GlobalRdrElt\\n -- ^ The import item\\n , imp_bundled :: [GlobalRdrElt]\\n -- ^ Items bundled in the Avail this import item came from,\\n -- not including the import item itself if it is a parent.\\n , imp_is_parent :: Bool\\n -- ^ Is the import item a parent? See Note [Dealing with imports].\\n }\\n\\ninstance Outputable ImpOccItem where\\n ppr (ImpOccItem { imp_item = item, imp_bundled = bundled, imp_is_parent = is_par })\\n = braces $ hsep\\n [ text \\"ImpOccItem\\"\\n , if is_par then text \\"[is_par]\\" else empty\\n , ppr (greName item) <+> ppr (greParent item)\\n , braces $ text \\"bundled:\\" <+> ppr (map greName bundled) ]\\n\\n-- | Make an \'OccEnv\' of all the imports.\\n--\\n-- Complicated by the fact that associated data types and pattern synonyms\\n-- can appear twice. See Note [Dealing with imports].\\nmkImportOccEnv :: HscEnv -> ImpDeclSpec -> [IfaceExport] -> OccEnv (NameEnv ImpOccItem)\\nmkImportOccEnv hsc_env decl_spec all_avails =\\n mkOccEnv_C (plusNameEnv_C combine)\\n [ (occ, mkNameEnv [(nm, item)])\\n | avail <- all_avails\\n , let gres = gresFromAvail hsc_env (Just hiding_spec) avail\\n , gre <- gres\\n , let nm = greName gre\\n occ = greOccName gre\\n (is_parent, bundled) = case avail of\\n AvailTC c _\\n | c == nm -- (Recall the AvailTC invariant from GHC.Types.AvailInfo)\\n -> ( True, drop 1 gres ) -- \\"drop 1\\": don\'t include the parent itself.\\n | otherwise\\n -> ( False, gres )\\n _ -> ( False, [] )\\n item = ImpOccItem\\n { imp_item = gre\\n , imp_bundled = bundled\\n , imp_is_parent = is_parent }\\n ]\\n where\\n\\n hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\n -- See Note [Dealing with imports]\\n -- \'combine\' may be called for associated data types which appear\\n -- twice in the all_avails. In the example, we have two Avails for T,\\n -- namely T(T,T1,T2,T3) and C(C,T), and we combine them by dropping the\\n -- latter, in which T is not the parent.\\n combine :: ImpOccItem -> ImpOccItem -> ImpOccItem\\n combine item1@(ImpOccItem { imp_item = gre1, imp_is_parent = is_parent1 })\\n item2@(ImpOccItem { imp_item = gre2, imp_is_parent = is_parent2 })\\n | is_parent1 || is_parent2\\n , not (isRecFldGRE gre1 || isRecFldGRE gre2) -- NB: does not force GREInfo.\\n , let name1 = greName gre1\\n name2 = greName gre2\\n gre = gre1 `plusGRE` gre2\\n -- See Note [Preserve parent information when combining import OccEnvs]\\n = assertPpr (name1 == name2)\\n (ppr name1 <+> ppr name2) $\\n if is_parent1\\n then item1 { imp_item = gre }\\n else item2 { imp_item = gre }\\n -- Discard C(C,T) in favour of T(T, T1, T2, T3).\\n\\n -- \'combine\' may also be called for pattern synonyms which appear both\\n -- unassociated and associated (see Note [Importing PatternSynonyms]).\\n combine item1@(ImpOccItem { imp_item = c1, imp_bundled = kids1 })\\n item2@(ImpOccItem { imp_item = c2, imp_bundled = kids2 })\\n = assertPpr (greName c1 == greName c2\\n && (not (null kids1 && null kids2)))\\n (ppr c1 <+> ppr c2 <+> ppr kids1 <+> ppr kids2) $\\n if null kids1\\n then item2\\n else item1\\n -- Discard standalone pattern P in favour of T(P).\\n\\n-- | Essentially like @lookupGRE env (LookupOccName occ which_gres)@,\\n-- but working with \'ImpOccItem\'s instead of \'GlobalRdrElt\'s.\\nlookupImpOccEnv :: WhichGREs GREInfo\\n -> OccEnv (NameEnv ImpOccItem) -> OccName -> [NameEnv ImpOccItem]\\nlookupImpOccEnv which_gres env occ =\\n mapMaybe relevant_items $ lookupOccEnv_AllNameSpaces env occ\\n where\\n is_relevant :: ImpOccItem -> Bool\\n is_relevant (ImpOccItem { imp_item = gre }) =\\n greIsRelevant which_gres (occNameSpace occ) gre\\n relevant_items :: NameEnv ImpOccItem -> Maybe (NameEnv ImpOccItem)\\n relevant_items nms\\n | let nms\' = filterNameEnv is_relevant nms\\n = if isEmptyNameEnv nms\'\\n then Nothing\\n else Just nms\'\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{Import/Export Utils}\\n* *\\n************************************************************************\\n-}\\n\\n-- | Given an import\\\\/export spec, appropriately set the @gre_imp@ field\\n-- for the \'GlobalRdrElt\'s.\\ngresFromIE :: ImpDeclSpec -> (LIE GhcRn, [GlobalRdrElt]) -> [GlobalRdrElt]\\ngresFromIE decl_spec (L loc ie, gres)\\n = map set_gre_imp gres\\n where\\n is_explicit = case ie of\\n IEThingAll _ _ name _ -> \\\\n -> n == lieWrappedName name\\n IEWholeNamespace _ _ -> \\\\_ -> False\\n _ -> \\\\_ -> True\\n prov_fn name\\n = ImpSpec { is_decl = decl_spec, is_item = item_spec }\\n where\\n item_spec = ImpSome { is_explicit = is_explicit name\\n , is_iloc = locA loc }\\n set_gre_imp gre@( GRE { gre_name = nm } )\\n = gre { gre_imp = unitBag $ prov_fn nm }\\n\\nparentOfImplicitlyImportedGRE :: Outputable info => GlobalRdrEltX info -> Maybe Name\\nparentOfImplicitlyImportedGRE gre =\\n if any (explicit_import . is_item) $ gre_imp gre\\n then Nothing\\n else greParent_maybe gre\\n where\\n explicit_import :: ImpItemSpec -> Bool\\n explicit_import (ImpAll {}) =\\n pprPanic \\"parentOfImplicitlyImportedGRE: ImpAll\\" (ppr gre)\\n explicit_import (ImpSome { is_explicit }) = is_explicit\\n\\n{- Note [Children for duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider the module\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (F(foo, MkFInt, MkFBool)) where\\n data family F a\\n data instance F Int = MkFInt { foo :: Int }\\n data instance F Bool = MkFBool { foo :: Bool }\\n\\nThe `foo` in the export list refers to *both* selectors! For this\\nreason, lookupChildren builds an environment that maps the FastString\\nto a list of items, rather than a single item.\\n-}\\n\\nmkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]\\nmkChildEnv gres = foldr add emptyNameEnv gres\\n where\\n add gre env = case greParent gre of\\n ParentIs p -> extendNameEnv_Acc (:) Utils.singleton env p gre\\n NoParent -> env\\n\\nfindChildren :: NameEnv [a] -> Name -> [a]\\nfindChildren env n = lookupNameEnv env n `orElse` []\\n\\ndata LookupChildError\\n = LookupChildNotFound { lce_wrapped_name :: !(LIEWrappedName GhcPs) }\\n | LookupChildNonType { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nontype_item :: !GlobalRdrElt }\\n | LookupChildNonData { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nondata_item :: !GlobalRdrElt }\\n\\nlookupChildren :: [GlobalRdrElt]\\n -> [LIEWrappedName GhcPs]\\n -> ( [LookupChildError] -- The ones for which the lookup failed\\n , [LocatedA GlobalRdrElt] )\\n-- (lookupChildren all_kids rdr_items) maps each rdr_item to its\\n-- corresponding Name in all_kids, if the former exists\\n-- The matching is done by FastString, not OccName, so that\\n-- Cls( meth, AssocTy )\\n-- will correctly find AssocTy among the all_kids of Cls, even though\\n-- the RdrName for AssocTy may have a (bogus) DataName namespace\\n-- (Really the rdr_items should be FastStrings in the first place.)\\nlookupChildren all_kids rdr_items = (fails, successes)\\n where\\n mb_xs = map do_one rdr_items\\n fails = [ err | Failed err <- mb_xs ]\\n successes = [ ok | Succeeded oks <- mb_xs, ok <- NE.toList oks ]\\n\\n do_one :: LIEWrappedName GhcPs -> MaybeErr LookupChildError (NonEmpty (LocatedA GlobalRdrElt))\\n do_one item@(L l r) =\\n case r of\\n IEName{}\\n -- IEName (unadorned name) places no restriction on the namespace of\\n -- the imported entity, so we look in both `val_gres` and `typ_gres`.\\n -- In case of conflict (punning), the value namespace takes priority.\\n -- See Note [Prioritise the value namespace in subordinate import lists]\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEType{}\\n -- IEType (\'type\' namespace specifier) restricts the lookup to the\\n -- type namespace, i.e. to `typ_gres`. In case of failure, we check\\n -- `val_gres` to produce a more helpful error message.\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- val_gres -> Failed $ LookupChildNonType item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEData{}\\n -- IEData (\'data\' namespace specifier) restricts the lookup to the\\n -- data namespace, i.e. to `val_gres`. In case of failure, we check\\n -- `typ_gres` to produce a more helpful error message.\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- typ_gres -> Failed $ LookupChildNonData item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEPattern{} -> panic \\"lookupChildren: IEPattern\\" -- Never happens (invalid syntax)\\n IEDefault{} -> panic \\"lookupChildren: IEDefault\\" -- Never happens (invalid syntax)\\n where\\n fs = (occNameFS . rdrNameOcc . ieWrappedName) r\\n gres = fromMaybe [] (lookupFsEnv kid_env fs)\\n (val_gres, typ_gres) = partition (isValNameSpace . greNameSpace) gres\\n\\n -- See Note [Children for duplicate record fields]\\n kid_env :: FastStringEnv [GlobalRdrElt]\\n kid_env = extendFsEnvList_C (++) emptyFsEnv\\n [(occNameFS (occName x), [x]) | x <- all_kids]\\n\\n\\n{- Note [Prioritise the value namespace in subordinate import lists]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider this program that defines a class that has both an associated type\\nnamed (#) and a method named (#)\\n\\n module M_assoc where\\n class C a b where\\n type a # b\\n (#) :: a -> b -> ()\\n module N_assoc where\\n import M_assoc( C((#)) )\\n\\nIn the import declaration, when we see the unadorned name (#) in the subordinate\\nimport list of C, which children should we bring into scope? Our options are:\\n\\n a) only the method (#)\\n b) only the associated type (#)\\n c) both the method and the associated type\\n\\nTo follow the precedent established by top-level items, we go with option (a).\\nIndeed, consider a slightly different program\\n\\n module M_top where\\n type family a # b\\n a # b = ()\\n module N_top where\\n import M_top( (#) )\\n\\nHere the import brings only the function (#) into scope, and one has to say\\n`type (#)` to get the type family.\\n-}\\n\\n-------------------------------\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused names}\\n* *\\n*********************************************************\\n-}\\n\\nreportUnusedNames :: TcGblEnv -> HscSource -> RnM ()\\nreportUnusedNames gbl_env hsc_src\\n = do { keep <- readTcRef (tcg_keep gbl_env)\\n ; traceRn \\"RUN\\" (ppr (tcg_dus gbl_env))\\n ; warnUnusedImportDecls gbl_env hsc_src\\n ; warnUnusedTopBinds $ unused_locals keep\\n ; warnMissingSignatures gbl_env\\n ; warnMissingKindSignatures gbl_env }\\n where\\n used_names :: NameSet -> NameSet\\n used_names keep = findUses (tcg_dus gbl_env) emptyNameSet `unionNameSet` keep\\n -- NB: currently, if f x = g, we only treat \'g\' as used if \'f\' is used\\n -- Hence findUses\\n\\n -- Collect the defined names from the in-scope environment\\n defined_names :: [GlobalRdrElt]\\n defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)\\n\\n kids_env = mkChildEnv defined_names\\n -- This is done in mkExports too; duplicated work\\n\\n gre_is_used :: NameSet -> GlobalRdrElt -> Bool\\n gre_is_used used_names gre0\\n = name `elemNameSet` used_names\\n || any (\\\\ gre -> greName gre `elemNameSet` used_names) (findChildren kids_env name)\\n -- A use of C implies a use of T,\\n -- if C was brought into scope by T(..) or T(C)\\n where\\n name = greName gre0\\n\\n -- Filter out the ones that are\\n -- (a) defined in this module, and\\n -- (b) not defined by a \'deriving\' clause\\n -- The latter have an Internal Name, so we can filter them out easily\\n unused_locals :: NameSet -> [GlobalRdrElt]\\n unused_locals keep =\\n let -- Note that defined_and_used, defined_but_not_used\\n -- are both [GRE]; that\'s why we need defined_and_used\\n -- rather than just used_names\\n _defined_and_used, defined_but_not_used :: [GlobalRdrElt]\\n (_defined_and_used, defined_but_not_used)\\n = partition (gre_is_used (used_names keep)) defined_names\\n\\n in filter is_unused_local defined_but_not_used\\n is_unused_local :: GlobalRdrElt -> Bool\\n is_unused_local gre = isLocalGRE gre\\n && isExternalName (greName gre)\\n\\n{- *********************************************************************\\n* *\\n Missing signatures\\n* *\\n********************************************************************* -}\\n\\n{-\\nNote [Missing signatures]\\n~~~~~~~~~~~~~~~~~~~~~~~~~\\nThere are four warning flags in play:\\n\\n * -Wmissing-exported-signatures\\n Warn about any exported top-level function/value without a type signature.\\n Does not include pattern synonyms.\\n\\n * -Wmissing-signatures\\n Warn about any top-level function/value without a type signature. Does not\\n include pattern synonyms. Takes priority over -Wmissing-exported-signatures.\\n\\n * -Wmissing-exported-pattern-synonym-signatures\\n Warn about any exported pattern synonym without a type signature.\\n\\n * -Wmissing-pattern-synonym-signatures\\n Warn about any pattern synonym without a type signature. Takes priority over\\n -Wmissing-exported-pattern-synonym-signatures.\\n\\n-}\\n\\n-- | Warn the user about top level binders that lack type signatures.\\n-- Called /after/ type inference, so that we can report the\\n-- inferred type of the function\\nwarnMissingSignatures :: TcGblEnv -> RnM ()\\nwarnMissingSignatures gbl_env\\n = do { let exports = availsToNameSet (tcg_exports gbl_env)\\n sig_ns = tcg_sigs gbl_env\\n -- We use sig_ns to exclude top-level bindings that are generated by GHC\\n binds = collectHsBindsBinders CollNoDictBinders $ tcg_binds gbl_env\\n pat_syns = tcg_patsyns gbl_env\\n\\n not_ghc_generated :: Name -> Bool\\n not_ghc_generated name = name `elemNameSet` sig_ns\\n\\n add_binding_warn :: Id -> RnM ()\\n add_binding_warn id =\\n when (not_ghc_generated name) $\\n do { env <- liftZonkM $ tcInitTidyEnv -- Why not use emptyTidyEnv?\\n ; let ty = tidyOpenType env (idType id)\\n missing = MissingTopLevelBindingSig name ty\\n diag = TcRnMissingSignature missing exported\\n ; addDiagnosticAt (getSrcSpan name) diag }\\n where\\n name = idName id\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n add_patsyn_warn :: PatSyn -> RnM ()\\n add_patsyn_warn ps =\\n when (not_ghc_generated name) $\\n addDiagnosticAt (getSrcSpan name)\\n (TcRnMissingSignature missing exported)\\n where\\n name = patSynName ps\\n missing = MissingPatSynSig ps\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n -- Warn about missing signatures\\n -- Do this only when we have a type to offer\\n -- See Note [Missing signatures]\\n ; mapM_ add_binding_warn binds\\n ; mapM_ add_patsyn_warn pat_syns\\n }\\n\\n-- | Warn the user about tycons that lack kind signatures.\\n-- Called /after/ type (and kind) inference, so that we can report the\\n-- inferred kinds.\\nwarnMissingKindSignatures :: TcGblEnv -> RnM ()\\nwarnMissingKindSignatures gbl_env\\n = do { cusks_enabled <- xoptM LangExt.CUSKs\\n ; mapM_ (add_ty_warn cusks_enabled) tcs\\n }\\n where\\n tcs = tcg_tcs gbl_env\\n ksig_ns = tcg_ksigs gbl_env\\n exports = availsToNameSet (tcg_exports gbl_env)\\n\\n has_kind_signature :: Name -> Bool\\n has_kind_signature name = name `elemNameSet` ksig_ns\\n\\n add_ty_warn :: Bool -> TyCon -> RnM ()\\n add_ty_warn cusks_enabled tyCon =\\n when (has_kind_signature name) $\\n addDiagnosticAt (getSrcSpan name) diag\\n where\\n name = tyConName tyCon\\n diag = TcRnMissingSignature missing exported\\n missing = MissingTyConKindSig tyCon cusks_enabled\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused imports}\\n* *\\n*********************************************************\\n\\nThis code finds which import declarations are unused. The\\nspecification and implementation notes are here:\\n https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/unused-imports\\n\\nSee also Note [Choosing the best import declaration] in GHC.Types.Name.Reader\\n-}\\n\\ntype ImportDeclUsage\\n = ( LImportDecl GhcRn -- The import declaration\\n , [GlobalRdrElt] -- What *is* used (normalised)\\n , [Name] -- What is imported but *not* used\\n , [NamespaceSpecifier GhcRn] ) -- Unused wildcards\\n\\nwarnUnusedImportDecls :: TcGblEnv -> HscSource -> RnM ()\\nwarnUnusedImportDecls gbl_env hsc_src\\n = do { uses <- readMutVar (tcg_used_gres gbl_env)\\n ; let imports = tcg_rn_imports gbl_env\\n rdr_env = tcg_rdr_env gbl_env\\n\\n -- We should only warn for unnecessary *user* imports, but deciding\\n -- minimal imports should take generated imports into account\\n ; let usageUserImports = findImportUsage (excludeGenerated imports) uses\\n usageAllImports = findImportUsage imports uses\\n\\n ; traceRn \\"warnUnusedImportDecls\\" $\\n (vcat [ text \\"Uses:\\" <+> ppr uses\\n , text \\"Usage all user imports: \\" <+> ppr usageUserImports\\n , text \\"Usage all imports: \\" <+> ppr usageAllImports])\\n\\n ; mapM_ (warnUnusedImport rdr_env) usageUserImports\\n\\n ; whenGOptM Opt_D_dump_minimal_imports $\\n printMinimalImports hsc_src usageAllImports }\\n\\n-- | Exclude generated imports\\nexcludeGenerated :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\nexcludeGenerated = filterOut (isGeneratedImport . ideclOrigin . ideclExt . unLoc)\\n\\nfindImportUsage :: [LImportDecl GhcRn]\\n -> [GlobalRdrElt]\\n -> [ImportDeclUsage]\\n\\nfindImportUsage imports used_gres\\n = map unused_decl imports\\n where\\n import_usage :: ImportMap\\n import_usage = mkImportMap used_gres\\n\\n unused_decl :: LImportDecl GhcRn -> ImportDeclUsage\\n unused_decl decl@(L _ (ImportDecl { ideclImportList = imps }))\\n = -- pprTrace \\"unused_decl\\" (vcat [ ppr decl\\n -- , text \\"used\\" <+> ppr used_gres\\n -- , text \\"unused\\" <+> ppr unused_names ]) $\\n (decl, used_gres, unused_names, unused_wcs)\\n where\\n used_gres = lookupImportMap decl import_usage\\n\\n used_gre_env = mkGlobalRdrEnv used_gres\\n used_parents = mkNameSet (mapMaybe greParent_maybe used_gres)\\n\\n (unused_names, unused_wcs) -- Not trivial; see eg #7454\\n = case imps of\\n Just (Exactly, imp_ies) ->\\n let unused = foldr (add_unused . unLoc) emptyUnusedNames imp_ies\\n nms = nameSetElemsStable (collectUnusedNames unused)\\n wcs = collectUnusedWildcards unused\\n in (nms, wcs)\\n _other -> ([], []) -- No explicit import list => no unused-name list\\n\\n add_unused :: IE GhcRn -> UnusedNames -> UnusedNames\\n add_unused (IEVar _ n _) acc = add_unused_name (lieWrappedName n) True acc\\n add_unused (IEThingAbs _ n _) acc = add_unused_name (lieWrappedName n) False acc\\n add_unused (IEThingAll _ _ n _) acc = add_unused_all (lieWrappedName n) acc\\n add_unused (IEThingWith _ p wc ns _) acc = add_wc_all (add_unused_with pn xs acc)\\n where pn = lieWrappedName p\\n xs = map lieWrappedName ns\\n add_wc_all = case wc of\\n NoIEWildcard -> id\\n IEWildcard _ -> add_unused_all pn\\n add_unused (IEWholeNamespace x ns_spec) acc = add_unused_wildcard ns_spec (iewn_names x) acc\\n add_unused _ acc = acc\\n\\n add_unused_name :: Name -> Bool -> UnusedNames -> UnusedNames\\n add_unused_name n is_ie_var acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | is_ie_var\\n , isFieldName n\\n -- See Note [Reporting unused imported duplicate record fields]\\n = let\\n fs = getOccFS n\\n (flds, flds_used) = lookupFsEnv acc_fs fs `orElse` (emptyNameSet, Any False)\\n acc_fs\' = extendFsEnv acc_fs fs (extendNameSet flds n, Any used S.<> flds_used)\\n in UnusedNames acc_ns acc_wcs acc_fs\'\\n\\n | used\\n = acc\\n\\n | otherwise\\n = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n where\\n used = isJust $ lookupGRE_Name used_gre_env n\\n\\n add_unused_all :: Name -> UnusedNames -> UnusedNames\\n add_unused_all n acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | Just {} <- lookupGRE_Name used_gre_env n = acc\\n | n `elemNameSet` used_parents = acc\\n | otherwise = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n\\n add_unused_with :: Name -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_with p ns acc\\n | all (`elemNameSet` acc1_ns) ns = add_unused_name p False acc1\\n | otherwise = acc1\\n where\\n acc1@(UnusedNames acc1_ns _ _) = foldr (\\\\n acc\' -> add_unused_name n False acc\') acc ns\\n -- If you use \'signum\' from Num, then the user may well have\\n -- imported Num(signum). We don\'t want to complain that\\n -- Num is not itself mentioned. Hence the two cases in add_unused_with.\\n\\n add_unused_wildcard :: NamespaceSpecifier GhcRn -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_wildcard ns_spec names acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | any_used = acc\\n | otherwise = UnusedNames acc_ns (ns_spec : acc_wcs) acc_fs\\n where\\n -- A wildcard `type ..` or `data ..` is used if at least one of\\n -- the names it expands to is used\\n any_used = any (isJust . lookupGRE_Name used_gre_env) names\\n\\n\\n-- | An accumulator for unused names in an import list.\\n--\\n-- See Note [Reporting unused imported duplicate record fields].\\ndata UnusedNames =\\n UnusedNames\\n { unused_names :: NameSet\\n -- ^ Unused \'Name\'s in an import list, not including record fields\\n -- that are plain \'IEVar\' imports (tracked by \'rec_fld_uses\')\\n -- or wildcard imports (tracked by \'unused_wildcards\').\\n , unused_wildcards :: [NamespaceSpecifier GhcRn]\\n -- ^ Unused wildcards @type ..@ or @data ..@ in an import list.\\n , rec_fld_uses :: FastStringEnv (NameSet, Any)\\n -- ^ Record fields imported without a parent (i.e. an \'IEVar\' import).\\n --\\n -- The \'Any\' value records whether any of the record fields\\n -- sharing the same underlying \'FastString\' have been used.\\n }\\n\\nemptyUnusedNames :: UnusedNames\\nemptyUnusedNames = UnusedNames emptyNameSet [] emptyFsEnv\\n\\ninstance Outputable UnusedNames where\\n ppr (UnusedNames nms wcs flds) =\\n text \\"UnusedNames\\" <+>\\n braces (ppr nms <+> ppr wcs <+> ppr (fmap (second getAny) flds))\\n\\n-- | Collect all unused names from a \'UnusedNames\' value.\\ncollectUnusedNames :: UnusedNames -> NameSet\\ncollectUnusedNames (UnusedNames { unused_names = nms, rec_fld_uses = flds })\\n = nms S.<> unused_flds\\n where\\n unused_flds = nonDetFoldFsEnv collect_unused emptyNameSet flds\\n collect_unused :: (NameSet, Any) -> NameSet -> NameSet\\n collect_unused (nms, Any at_least_one_name_is_used) acc\\n | at_least_one_name_is_used = acc\\n | otherwise = unionNameSet nms acc\\n\\ncollectUnusedWildcards :: UnusedNames -> [NamespaceSpecifier GhcRn]\\ncollectUnusedWildcards = unused_wildcards\\n\\n{- Note [Reporting unused imported duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have (#24035):\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M1 (R1(..), R2(..)) where\\n data R1 = MkR1 { fld :: Int }\\n data R2 = MkR2 { fld :: Int }\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M2 where\\n import M1 (R1(MkR1), R2, fld)\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nIn the import of \'M1\' in \'M2\', the \'fld\' import resolves to two separate GREs,\\nnamely R1(fld) and R2(fld). From the perspective of the renamer, and in particular\\nthe \'findImportUsage\' function, it\'s as if the user had imported the two names\\nseparately (even though no source syntax allows that).\\n\\nThis means that we need to be careful when reporting unused imports: the R2(fld)\\nimport is indeed unused, but because R1(fld) is used, we should not report\\nfld as unused altogether.\\n\\nTo achieve this, we keep track of record field imports without a parent (i.e.\\nusing the IEVar constructor) separately from other import items, using the\\nUnusedNames datatype.\\nOnce we have accumulated usages, we emit warnings for unused record fields\\nwithout parents one whole group (of record fields sharing the same textual name)\\nat a time, and only if *all* of the record fields in the group are unused;\\nsee \'collectUnusedNames\'.\\n\\nNote that this only applies to record fields imported without a parent. If we\\nhad:\\n\\n import M1 (R1(MkR1, fld), R2(fld))\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nthen of course we should report the second \'fld\' as unused.\\n-}\\n\\n\\n{- Note [The ImportMap]\\n~~~~~~~~~~~~~~~~~~~~~~~\\nThe ImportMap is a short-lived intermediate data structure records, for\\neach import declaration, what stuff brought into scope by that\\ndeclaration is actually used in the module.\\n\\nThe [GlobalRdrElt] are the things imported from that decl.\\n-}\\n\\ndata ImportMap = ImportMap\\n { im_imports :: Map RealSrcSpan [GlobalRdrElt]\\n -- ^ See [The ImportMap]\\n -- If loc :-> gres, then\\n -- \'loc\' = the end loc of the bestImport of each GRE in \'gres\'\\n , im_generatedImports :: Map ModuleName [GlobalRdrElt]\\n }\\n\\nmkImportMap :: [GlobalRdrElt] -> ImportMap\\n-- For each of a list of used GREs, find all the import decls that brought\\n-- it into scope; choose one of them (bestImport), and record\\n-- the RdrName in that import decl\'s entry in the ImportMap\\nmkImportMap = foldr insertImportMap $ ImportMap Map.empty Map.empty\\n\\ninsertImportMap :: GlobalRdrElt -> ImportMap -> ImportMap\\ninsertImportMap gre@(GRE { gre_imp = imp_specs }) importMap\\n | RealSrcSpan importSpan _ <- is_dloc best_imp_spec =\\n importMap{im_imports = insertElem importSpan gre $ im_imports importMap}\\n | GeneratedSrcSpan{} <- is_dloc best_imp_spec =\\n importMap{im_generatedImports = insertElem (moduleName $ is_mod best_imp_spec) gre $ im_generatedImports importMap}\\n | otherwise = importMap\\n where\\n best_imp_spec =\\n case bagToList imp_specs of\\n [] -> pprPanic \\"mkImportMap: GRE with no ImportSpecs\\" (ppr gre)\\n is:iss -> is_decl $ bestImport (is NE.:| iss)\\n\\n -- https://github.com/haskell/containers/issues/784\\n insertElem :: Ord k => k -> v -> Map k [v] -> Map k [v]\\n insertElem k v = flip Map.alter k $ \\\\case\\n Just vs -> Just (v : vs)\\n Nothing -> Just [v]\\n\\nlookupImportMap :: LImportDecl GhcRn -> ImportMap -> [GlobalRdrElt]\\nlookupImportMap (L srcSpan ImportDecl{ideclName = L _ modName}) importMap =\\n fromMaybe [] $\\n -- should match logic in insertImportMap\\n case locA srcSpan of\\n RealSrcSpan realSrcSpan _ -> realSrcSpan `Map.lookup` im_imports importMap\\n GeneratedSrcSpan{} -> modName `Map.lookup` im_generatedImports importMap\\n _ -> Nothing\\n\\nlieNames :: LIE (GhcPass p) -> [Located (IdP (GhcPass p))]\\nlieNames = _\\n\\nwarnUnusedImport :: GlobalRdrEnv -> ImportDeclUsage -> RnM ()\\nwarnUnusedImport rdr_env (L loc decl, used, unused, unused_wcs)\\n\\n -- Do not warn for \'import M()\'\\n -- See (UI1) in Note [Unused imports]\\n | Just (Exactly, _) <- ideclImportList decl\\n , null unused && null unused_wcs\\n = return ()\\n\\n -- Note [Do not warn about Prelude hiding]\\n | Just (EverythingBut, hides) <- ideclImportList decl\\n , not (null hides)\\n , pRELUDE_NAME == unLoc (ideclName decl)\\n = return ()\\n\\n -- Do not warn about import X as Rebindable\\n -- See (UI2) in Note [Unused imports]\\n | Just (L _ mod) <- ideclAs decl\\n , mod == rEBINDABLE_MOD_NAME\\n = return ()\\n\\n -- Nothing used; drop entire declaration\\n | null used\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl UnusedImportNone)\\n\\n -- Everything imported is used; nop\\n | null unused && null unused_wcs\\n = return ()\\n\\n -- Some imports are unused: make the `SrcSpan` cover only the unused\\n -- items instead of the whole import statement\\n | Just (_, imports) <- ideclImportList decl\\n , let unused_locs = [ locA loc | L loc ie <- imports\\n , name <- ieNames ie\\n , name `elem` unused ]\\n , loc1 : locs <- unused_locs\\n , let span = foldr1 combineSrcSpans ( loc1 NE.:| locs )\\n = addDiagnosticAt span (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n -- Some imports are unused\\n | otherwise\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n where\\n -- In warning message, pretty-print identifiers unqualified unconditionally\\n -- to improve the consistent for ambiguous/unambiguous identifiers.\\n -- See #14881.\\n possible_field n =\\n case lookupGRE_Name rdr_env n of\\n Just (GRE { gre_par = par, gre_info = IAmRecField info }) ->\\n let fld_occ :: OccName\\n fld_occ = nameOccName $ flSelector $ recFieldLabel info\\n in UnusedImportNameRecField par fld_occ\\n _ -> UnusedImportNameRegular n\\n\\n -- Print unused names in a deterministic (lexicographic) order\\n sort_unused :: [UnusedImportName]\\n sort_unused =\\n [ UnusedImportWildcard wc | wc <- unused_wcs ] ++\\n [ possible_field nm | nm <- sortBy (comparing nameOccName) unused ]\\n\\ngetMinimalImports :: [ImportDeclUsage] -> RnM [LImportDecl GhcRn]\\ngetMinimalImports ie_decls\\n = do { rdr_env <- getGlobalRdrEnv\\n ; fmap combine $ mapM (mk_minimal rdr_env) ie_decls }\\n where\\n mk_minimal rdr_env (L l decl, used_gres, unused, unused_wcs)\\n | null unused && null unused_wcs\\n , Just (Exactly, _) <- ideclImportList decl\\n = return (L l decl)\\n | otherwise\\n = do { let ImportDecl { ideclName = L _ mod_name\\n , ideclSource = is_boot\\n , ideclPkgQual = pkg_qual\\n , ideclExt = XImportDeclPass { ideclOrigin = origin } } = decl\\n ; iface <- loadSrcInterface doc (importDeclLookupScope origin)\\n mod_name is_boot pkg_qual\\n ; let used_avails = gresToAvailInfo used_gres\\n ; lies <- map (L l) <$> concatMapM (to_ie rdr_env iface) used_avails\\n ; return (L l (decl { ideclImportList = Just (Exactly, lies) })) }\\n where\\n doc = text \\"Compute minimal imports for\\" <+> ppr decl\\n\\n to_ie :: GlobalRdrEnv -> ModIface -> AvailInfo -> RnM [IE GhcRn]\\n -- The main trick here is that if we\'re importing all the constructors\\n -- we want to say \\"T(..)\\", but if we\'re importing only a subset we want\\n -- to say \\"T(A,B,C)\\". So we have to find out what the module exports.\\n to_ie rdr_env _ (Avail c) -- Note [Overloaded field import]\\n = do { let\\n gre = expectJust $ lookupGRE_Name rdr_env c\\n ; return $ [IEVar Nothing (to_ie_post_rn $ noLocA $ greName gre) Nothing] }\\n to_ie _ _ avail@(AvailTC n [_]) -- Exporting the main decl and nothing else\\n | availExportsDecl avail\\n = return [IEThingAbs Nothing (to_ie_post_rn $ noLocA n) Nothing]\\n to_ie rdr_env iface (AvailTC n cs) =\\n case [ xs | avail@(AvailTC x xs) <- mi_exports iface\\n , x == n\\n , availExportsDecl avail -- Note [Partial export]\\n ] of\\n [xs]\\n | all_used xs\\n -> return [IEThingAll (IEThingAllExt Nothing noAnn noAnn noAnn)\\n (NoNamespaceSpecifier noExtField)\\n (to_ie_post_rn $ noLocA n)\\n Nothing]\\n | otherwise\\n -> do { let ns_gres = map (expectJust . lookupGRE_Name rdr_env) cs\\n ns = map greName ns_gres\\n ; return [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n -- Note [Overloaded field import]\\n _other\\n -> do { let infos = map (expectJust . lookupGRE_Name rdr_env) cs\\n (ns_gres,fs_gres) = classifyGREs infos\\n ns = map greName (ns_gres ++ fs_gres)\\n fs = map fieldGREInfo fs_gres\\n ; return $\\n if all_non_overloaded fs\\n then map (\\\\nm -> IEVar Nothing (to_ie_post_rn_var $ noLocA nm) Nothing) ns\\n else [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n where\\n\\n all_used avail_cs = all (`elem` cs) avail_cs\\n\\n all_non_overloaded = all (not . flIsOverloaded . recFieldLabel)\\n\\n combine :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\n combine = map merge . NE.groupAllWith getKey\\n\\n getKey :: LImportDecl GhcRn -> (Bool, Maybe ModuleName, ModuleName)\\n getKey decl =\\n ( isImportDeclQualified . ideclQualified $ idecl -- is this qualified? (important that this be first)\\n , unLoc <$> ideclAs idecl -- what is the qualifier (inside Maybe monad)\\n , unLoc . ideclName $ idecl -- Module Name\\n )\\n where\\n idecl :: ImportDecl GhcRn\\n idecl = unLoc decl\\n\\n merge :: NonEmpty (LImportDecl GhcRn) -> LImportDecl GhcRn\\n merge decls@((L l decl) :| _) = L l (decl { ideclImportList = Just (Exactly, lies) })\\n where lies = concatMap snd $ mapMaybe (ideclImportList . unLoc) $ NE.toList decls\\n\\nclassifyGREs :: [GlobalRdrElt] -> ([GlobalRdrElt], [FieldGlobalRdrElt])\\nclassifyGREs = partition (not . isRecFldGRE)\\n\\nprintMinimalImports :: HscSource -> [ImportDeclUsage] -> RnM ()\\n-- See Note [Printing minimal imports]\\nprintMinimalImports hsc_src imports_w_usage\\n = do { imports\' <- excludeGenerated <$> getMinimalImports imports_w_usage\\n ; this_mod <- getModule\\n ; dflags <- getDynFlags\\n ; liftIO $ withFile (mkFilename dflags this_mod) WriteMode $ \\\\h ->\\n printForUser dflags h neverQualify AllTheWay (vcat (map ppr imports\'))\\n -- The neverQualify is important. We are printing Names\\n -- but they are in the context of an \'import\' decl, and\\n -- we never qualify things inside there\\n -- E.g. import Blag( f, b )\\n -- not import Blag( Blag.f, Blag.g )!\\n }\\n where\\n mkFilename dflags this_mod\\n | Just d <- dumpDir dflags = d basefn\\n | otherwise = basefn\\n where\\n suffix = case hsc_src of\\n HsBootFile -> \\".imports-boot\\"\\n HsSrcFile -> \\".imports\\"\\n HsigFile -> \\".imports\\"\\n basefn = moduleNameString (moduleName this_mod) ++ suffix\\n\\n\\nto_ie_post_rn_var :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn_var (L l n)\\n | isDataOcc $ occName n = L l (IEPattern noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n\\n\\nto_ie_post_rn :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn (L l n)\\n | isTcOcc occ && isSymOcc occ = L l (IEType noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n where occ = occName n\\n\\n{- Note [Do not warn about Prelude hiding]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWe do not warn about\\n import Prelude hiding( x, y )\\nbecause even if nothing else from Prelude is used, it may be essential to hide\\nx,y to avoid name-shadowing warnings. Example (#9061)\\n import Prelude hiding( log )\\n f x = log where log = ()\\n\\nNote [Unused imports]\\n~~~~~~~~~~~~~~~~~~~~~\\nIn `warnUnusedImport`, if we see an import with an explicit list imports, thus\\n import M( a, b )\\nand neither `a` nor `b` is used, we report the entire import decl as unused. We\\ncheck this by looking at the names that it brings into scope scope; if there are\\nno ununused names, don\'t report.\\n\\n(UI1) We don\'t want to complain about `import M()`, because that is often used to bring\\n M\'s /instances/ into scope. That is neatly dealt with by the \\"no unused\\n names\\" (nor unused wildcard imports) criterion.\\n\\n(UI2) We don\'t report a decl as unused if it has an `as Rebindable` qualifier.\\n See (KN1) in Note [Overview of known entities] in GHC.Builtin\\n\\n\\nNote [Printing minimal imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nTo print the minimal imports we walk over all import decls (both user-supplied\\nand generated), trim their import lists, then filter out generated decls.\\n\\nNB that\\n\\n * We do *not* change the \'qualified\' or \'as\' parts!\\n\\n * We do not discard a decl altogether; we might need instances\\n from it. Instead we just trim to an empty import list\\n\\nNote [Partial export]\\n~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have\\n\\n module A( op ) where\\n class C a where\\n op :: a -> a\\n\\n module B where\\n import A\\n f = ..op...\\n\\nThen the minimal import for module B is\\n import A( op )\\nnot\\n import A( C( op ) )\\nwhich we would usually generate if C was exported from B. Hence\\nthe availExportsDecl test when deciding what to generate.\\n\\n\\nNote [Overloaded field import]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nOn the other hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n data T = MkT { foo :: Int }\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( T(foo) )\\nbecause when DuplicateRecordFields is enabled, field selectors are\\nnot in scope without their enclosing datatype.\\n\\nOn the third hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n pattern MkT { foo } = Just foo\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( foo )\\nbecause foo doesn\'t have a parent. This might actually be ambiguous if A\\nexports another field called foo, but there is no good answer to return and this\\nis a very obscure corner, so it seems to be the best we can do. See\\nDRFPatSynExport for a test of this.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Errors}\\n* *\\n************************************************************************\\n-}\\n\\nbadImportItemErr\\n :: ModIface -> ImpDeclSpec -> IE GhcPs\\n -> IsSubordinateError\\n -> [AvailInfo]\\n -> TcRn (NonEmpty ImportLookupReason)\\nbadImportItemErr iface decl_spec ie sub avails = do\\n exts <- importLookupExtensions\\n let import_lookup_bad :: BadImportKind -> ImportLookupReason\\n import_lookup_bad k = ImportLookupBad k iface decl_spec ie exts\\n dflags <- getDynFlags\\n hsc_env <- getTopEnv\\n let rdr_env = mkGlobalRdrEnv\\n $ gresFromAvails hsc_env (Just imp_spec) all_avails\\n pure $ fmap import_lookup_bad (importErrorKind dflags rdr_env)\\n where\\n importErrorKind :: DynFlags -> GlobalRdrEnv -> NonEmpty BadImportKind\\n importErrorKind dflags rdr_env\\n | any checkIfTyCon avails = case sub of\\n IsNotSubordinate -> NE.singleton BadImportAvailTyCon\\n IsSubordinateError { subordinate_err_parent = gre\\n , subordinate_err_unavailable = unavailable\\n , subordinate_err_nontype = nontype\\n , subordinate_err_nondata = nondata }\\n -> NE.fromList $ catMaybes $\\n [ fmap (BadImportNotExportedSubordinates gre) (NE.nonEmpty unavailable)\\n , fmap (BadImportNonTypeSubordinates gre) (NE.nonEmpty nontype)\\n , fmap (BadImportNonDataSubordinates gre) (NE.nonEmpty nondata) ]\\n | any checkIfVarName avails = NE.singleton BadImportAvailVar\\n | Just con <- find checkIfDataCon avails = NE.singleton (BadImportAvailDataCon (availOccName con))\\n | otherwise = NE.singleton (BadImportNotExported suggs)\\n where\\n suggs = similar_suggs ++ fieldSelectorSuggestions rdr_env rdr\\n what_look = case sub of\\n IsNotSubordinate -> WL_TyCon_or_TermVar\\n IsSubordinateError { subordinate_err_parent = gre } ->\\n case greInfo gre of\\n IAmTyCon ClassFlavour\\n -> WL_TyCon_or_TermVar\\n _ -> WL_Term\\n similar_names =\\n similarNameSuggestions (Unbound.LF what_look WL_Global)\\n dflags rdr_env emptyLocalRdrEnv rdr\\n similar_suggs =\\n case NE.nonEmpty $ mapMaybe imported_item $ similar_names of\\n Just similar -> [ SuggestSimilarNames rdr similar ]\\n Nothing -> [ ]\\n\\n -- Only keep imported items, and set the \\"HowInScope\\" to\\n -- \\"Nothing\\" to avoid printing \\"imported from...\\" in the suggestion\\n -- error message.\\n imported_item (SimilarRdrName rdr_name gre (Just (ImportedBy {})))\\n = Just (SimilarRdrName rdr_name gre Nothing)\\n imported_item _ = Nothing\\n\\n checkIfDataCon = checkIfAvailMatches isDataConName\\n checkIfTyCon = checkIfAvailMatches isTyConName\\n checkIfVarName =\\n \\\\case\\n AvailTC{} -> False\\n Avail n -> importedFS == occNameFS (occName n)\\n && (isVarOcc <||> isFieldOcc) (occName n)\\n checkIfAvailMatches namePred =\\n \\\\case\\n AvailTC _ ns ->\\n case find (\\\\n -> importedFS == occNameFS (occName n)) ns of\\n Just n -> namePred n\\n Nothing -> False\\n Avail{} -> False\\n availOccName = occName . availName\\n rdr = ieName ie\\n importedFS = occNameFS $ rdrNameOcc rdr\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n all_avails = mi_exports iface\\n\\nimportLookupExtensions :: TcRn ImportLookupExtensions\\nimportLookupExtensions = do\\n ile_pattern_synonyms <- xoptM LangExt.PatternSynonyms\\n ile_explicit_namespaces <- xoptM LangExt.ExplicitNamespaces\\n return ImportLookupExtensions{ile_pattern_synonyms, ile_explicit_namespaces}\\n\\naddDupDeclErr :: NonEmpty GlobalRdrElt -> TcRn ()\\naddDupDeclErr gres@(gre :| _)\\n -- Report the error at the later location\\n = addErrAt (getSrcSpan (NE.last sorted_names)) $ (TcRnDuplicateDecls (greOccName gre) sorted_names)\\n where\\n sorted_names =\\n NE.sortBy (SrcLoc.leftmost_smallest `on` nameSrcSpan)\\n (fmap greName gres)\\n\\n-- This data decl will parse OK\\n-- data T = a Int\\n-- treating \\"a\\" as the constructor.\\n-- It is really hard to make the parser spot this malformation.\\n-- So the renamer has to check that the constructor is legal\\n--\\n-- We can get an operator as the constructor, even in the prefix form:\\n-- data T = :% Int Int\\n-- from interface files, which always print in prefix form\\n--\\n-- We also allow type constructor names, which are defined by \\"type data\\"\\n-- declarations. See Note [Type data declarations] in GHC.Rename.Module.\\n\\ncheckConName :: RdrName -> TcRn ()\\ncheckConName name\\n = checkErr (isRdrDataCon name || isRdrTc name) (TcRnIllegalDataCon name)\\n", "filetypes": ["haskell"]}}}' 2026-10-16 14:47:21,155 - DEBUG - POST b'http://127.0.0.1:37093/receive_messages' {'content-type': 'application/json', 'x-ycm-hmac': b'Rga7Yd4l4fgfufwYw+0sxzurvznImlBO0MPmgAlS4EY='} b'{"filepath": "/home/enrico/ghc/compiler/GHC/Rename/Names.hs", "line_num": 1, "column_num": 1, "working_dir": "/home/enrico/ghc", "file_data": {"/home/enrico/ghc/compiler/GHC/Rename/Names.hs": {"contents": "{-\\n(c) The GRASP/AQUA Project, Glasgow University, 1992-1998\\n\\nExtracting imported and top-level names in scope\\n-}\\n\\n{-# LANGUAGE NondecreasingIndentation #-}\\n{-# LANGUAGE TypeFamilies #-}\\n\\nmodule GHC.Rename.Names (\\n rnImports, getLocalNonValBinders, newRecordFieldLabel,\\n importsFromIface,\\n ImportUserSpec(..),\\n extendGlobalRdrEnvRn,\\n gresFromAvails,\\n calculateAvails,\\n reportUnusedNames,\\n checkConName,\\n mkChildEnv,\\n findChildren,\\n mkBadExportSubordinate,\\n findImportUsage,\\n getMinimalImports,\\n printMinimalImports,\\n renamePkgQual, renameRawPkgQual,\\n classifyGREs,\\n ImportDeclUsage,\\n rnNamespaceSpecifier\\n ) where\\n\\nimport GHC.Prelude hiding ( head, init, last, tail )\\n\\nimport GHC.Driver.Env\\nimport GHC.Driver.Session\\nimport GHC.Driver.Ppr\\n\\nimport GHC.Rename.Env\\nimport GHC.Rename.Fixity\\nimport GHC.Rename.Utils ( warnUnusedTopBinds )\\nimport GHC.Rename.Unbound\\nimport qualified GHC.Rename.Unbound as Unbound\\n\\nimport GHC.Tc.Errors.Types\\nimport GHC.Tc.Utils.Env\\nimport GHC.Tc.Utils.Monad\\nimport GHC.Tc.Types.LclEnv\\nimport GHC.Tc.Zonk.TcType ( tcInitTidyEnv )\\n\\nimport GHC.Hs\\nimport GHC.Iface.Load ( loadSrcInterface, loadSrcInterface_maybe )\\nimport GHC.Iface.Errors.Types\\n ( IfaceMessage(..), MissingInterfaceError, InterfaceLookingFor(..)\\n , LoadEssentialsReason(..) )\\nimport GHC.Iface.Syntax ( fromIfaceWarnings )\\nimport GHC.Builtin.Modules( pRELUDE_NAME, rEBINDABLE_MOD_NAME )\\nimport GHC.Parser.PostProcess ( setRdrNameSpace )\\nimport GHC.Core.TyCo.Tidy\\nimport GHC.Core.PatSyn\\nimport GHC.Core.TyCon ( TyCon, tyConName )\\nimport qualified GHC.LanguageExtensions as LangExt\\n\\nimport GHC.Utils.Outputable as Outputable\\nimport GHC.Utils.Misc as Utils\\nimport GHC.Utils.Panic\\n\\nimport GHC.Types.Fixity.Env\\nimport GHC.Types.SafeHaskell\\nimport GHC.Types.Name\\nimport GHC.Types.Name.Env\\nimport GHC.Types.Name.Set\\nimport GHC.Types.Name.Reader\\nimport GHC.Types.Avail\\nimport GHC.Types.FieldLabel\\nimport GHC.Types.Hint\\nimport GHC.Types.SourceFile\\nimport GHC.Types.SrcLoc as SrcLoc\\nimport GHC.Types.Basic (TyConFlavour (..), convImportLevel, VisArity)\\nimport GHC.Types.UnresolvedImport\\nimport GHC.Types.Id\\nimport GHC.Types.PkgQual\\nimport GHC.Types.GREInfo (ConInfo(..), ConFieldInfo (..), ConLikeInfo (ConIsData))\\n\\nimport GHC.Unit\\nimport GHC.Unit.Module.Warnings\\nimport GHC.Unit.Module.ModIface\\nimport GHC.Unit.Module.Imported\\nimport GHC.Unit.Module.Deps\\nimport GHC.Unit.Env\\n\\nimport GHC.Data.Bag\\nimport GHC.Data.FastString\\nimport GHC.Data.FastString.Env\\nimport GHC.Data.Maybe\\nimport GHC.Data.List.SetOps ( removeDups )\\n\\nimport Control.Arrow ( second )\\nimport Control.Monad\\nimport Data.Foldable ( for_ )\\nimport Data.IntMap ( IntMap )\\nimport qualified Data.IntMap as IntMap\\nimport Data.Map ( Map )\\nimport qualified Data.Map as Map\\nimport Data.Ord ( comparing )\\nimport Data.Semigroup ( Any(..) )\\nimport qualified Data.Semigroup as S\\nimport Data.List ( partition, find, sortBy )\\nimport Data.List.NonEmpty (NonEmpty(..))\\nimport qualified Data.List.NonEmpty as NE\\nimport Data.Function ( on )\\nimport qualified Data.Set as S\\nimport System.FilePath (())\\nimport System.IO\\n\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{rnImports}\\n* *\\n************************************************************************\\n\\nNote [Tracking Trust Transitively]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen we import a package as well as checking that the direct imports are safe\\naccording to the rules outlined in the Note [Safe Haskell Trust Check] in GHC.Driver.Main\\nwe must also check that these rules hold transitively for all dependent modules\\nand packages. Doing this without caching any trust information would be very\\nslow as we would need to touch all packages and interface files a module depends\\non. To avoid this we make use of the property that if a modules Safe Haskell\\nmode changes, this triggers a recompilation from that module in the dependency\\ngraph. So we can just worry mostly about direct imports.\\n\\nThere is one trust property that can change for a package though without\\nrecompilation being triggered: package trust. So we must check that all\\npackages a module transitively depends on to be trusted are still trusted when\\nwe are compiling this module (as due to recompilation avoidance some modules\\nbelow may not be considered trusted any more without recompilation being\\ntriggered).\\n\\nWe handle this by augmenting the existing transitive list of packages a module M\\ndepends on with a bool for each package that says if it must be trusted when the\\nmodule M is being checked for trust. This list of trust required packages for a\\nsingle import is gathered in the rnImportDecl function and stored in an\\nImportAvails data structure. The union of these trust required packages for all\\nimports is done by the rnImports function using the combine function which calls\\nthe plusImportAvails function that is a union operation for the ImportAvails\\ntype. This gives us in an ImportAvails structure all packages required to be\\ntrusted for the module we are currently compiling. Checking that these packages\\nare still trusted (and that direct imports are trusted) is done in\\nGHC.Driver.Main.checkSafeImports.\\n\\nSee the note below, [Trust Own Package] for a corner case in this method and\\nhow its handled.\\n\\n\\nNote [Trust Own Package]\\n~~~~~~~~~~~~~~~~~~~~~~~~\\nThere is a corner case of package trust checking that the usual transitive check\\ndoesn\'t cover. (For how the usual check operates see the Note [Tracking Trust\\nTransitively] below). The case is when you import a -XSafe module M and M\\nimports a -XTrustworthy module N. If N resides in a different package than M,\\nthen the usual check works as M will record a package dependency on N\'s package\\nand mark it as required to be trusted. If N resides in the same package as M\\nthough, then importing M should require its own package be trusted due to N\\n(since M is -XSafe so doesn\'t create this requirement by itself). The usual\\ncheck fails as a module doesn\'t record a package dependency of its own package.\\nSo instead we now have a bool field in a modules interface file that simply\\nstates if the module requires its own package to be trusted. This field avoids\\nus having to load all interface files that the module depends on to see if one\\nis trustworthy.\\n\\n\\nNote [Trust Transitive Property]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSo there is an interesting design question in regards to transitive trust\\nchecking. Say I have a module B compiled with -XSafe. B is dependent on a bunch\\nof modules and packages, some packages it requires to be trusted as its using\\n-XTrustworthy modules from them. Now if I have a module A that doesn\'t use safe\\nhaskell at all and simply imports B, should A inherit all the trust\\nrequirements from B? Should A now also require that a package p is trusted since\\nB required it?\\n\\nWe currently say no but saying yes also makes sense. The difference is, if a\\nmodule M that doesn\'t use Safe Haskell imports a module N that does, should all\\nthe trusted package requirements be dropped since M didn\'t declare that it cares\\nabout Safe Haskell (so -XSafe is more strongly associated with the module doing\\nthe importing) or should it be done still since the author of the module N that\\nuses Safe Haskell said they cared (so -XSafe is more strongly associated with\\nthe module that was compiled that used it).\\n\\nGoing with yes is a simpler semantics we think and harder for the user to stuff\\nup but it does mean that Safe Haskell will affect users who don\'t care about\\nSafe Haskell as they might grab a package from Cabal which uses safe haskell (say\\nnetwork) and that packages imports -XTrustworthy modules from another package\\n(say bytestring), so requires that package is trusted. The user may now get\\ncompilation errors in code that doesn\'t do anything with Safe Haskell simply\\nbecause they are using the network package. They will have to call \'ghc-pkg\\ntrust network\' to get everything working. Due to this invasive nature of going\\nwith yes we have gone with no for now.\\n-}\\n\\n-- | Process Import Decls. See \'rnImportDecl\' for a description of what\\n-- the return types represent.\\n-- Note: Do the non SOURCE ones first, so that we get a helpful warning\\n-- for SOURCE ones that are unnecessary\\nrnImports :: [(LImportDecl GhcPs, SDoc)]\\n -> RnM ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\nrnImports imports = do\\n tcg_env <- getGblEnv\\n -- NB: want an identity module here, because it\'s OK for a signature\\n -- module to import from its implementor\\n let this_mod = tcg_mod tcg_env\\n let (source, ordinary) = partition (is_source_import . fst) imports\\n is_source_import (d::LImportDecl GhcPs) = ideclSource (unLoc d) == IsBoot\\n stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary\\n stuff2 <- mapAndReportM (rnImportDecl this_mod) source\\n -- Safe Haskell: See Note [Tracking Trust Transitively]\\n let (decls, imp_user_spec, rdr_env, imp_avails) = combine (stuff1 ++ stuff2)\\n -- Update imp_boot_mods if imp_direct_mods mentions any of them\\n let merged_import_avail = clobberSourceImports imp_avails\\n return (decls, imp_user_spec, rdr_env, merged_import_avail)\\n\\n where\\n clobberSourceImports imp_avails =\\n imp_avails { imp_boot_mods = imp_boot_mods\' }\\n where\\n imp_boot_mods\' = mergeInstalledModuleEnv combJ id (const emptyInstalledModuleEnv)\\n (imp_boot_mods imp_avails)\\n (imp_direct_dep_mods imp_avails)\\n\\n combJ (GWIB _ IsBoot) (_, x) = Just x\\n combJ r _ = Just r\\n -- See Note [Combining ImportAvails]\\n combine :: [(LImportDecl GhcRn, ImportUserSpec, GlobalRdrEnv, ImportAvails)]\\n -> ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\n combine ss =\\n let (decls, imp_user_spec, rdr_env, imp_avails, finsts) = foldr\\n plus\\n ([], [], emptyGlobalRdrEnv, emptyImportAvails, emptyModuleSet)\\n ss\\n in (decls, imp_user_spec, rdr_env, imp_avails { imp_finsts = moduleSetElts finsts })\\n\\n plus (decl, us, gbl_env1, imp_avails1)\\n (decls, uss, gbl_env2, imp_avails2, finsts_set)\\n = ( decl:decls,\\n us:uss,\\n gbl_env1 `plusGlobalRdrEnv` gbl_env2,\\n imp_avails1\' `plusImportAvails` imp_avails2,\\n extendModuleSetList finsts_set new_finsts )\\n where\\n imp_avails1\' = imp_avails1 { imp_finsts = [] }\\n new_finsts = imp_finsts imp_avails1\\n\\n{-\\nNote [Combining ImportAvails]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nimp_finsts in ImportAvails is a list of family instance modules\\ntransitively depended on by an import. imp_finsts for a currently\\ncompiled module is a union of all the imp_finsts of imports.\\nComputing the union of two lists of size N is O(N^2) and if we\\ndo it to M imports we end up with O(M*N^2). That can get very\\nexpensive for bigger module hierarchies.\\n\\nUnion can be optimized to O(N log N) if we use a Set.\\nimp_finsts is converted back and forth between dep_finsts, so\\nchanging a type of imp_finsts means either paying for the conversions\\nor changing the type of dep_finsts as well.\\n\\nI\'ve measured that the conversions would cost 20% of allocations on my\\ntest case, so that can be ruled out.\\n\\nChanging the type of dep_finsts forces checkFamInsts to\\nget the module lists in non-deterministic order. If we wanted to restore\\nthe deterministic order, we\'d have to sort there, which is an additional\\ncost. As far as I can tell, using a non-deterministic order is fine there,\\nbut that\'s a brittle nonlocal property which I\'d like to avoid.\\n\\nAdditionally, dep_finsts is read from an interface file, so its \\"natural\\"\\ntype is a list. Which makes it a natural type for imp_finsts.\\n\\nSince rnImports.combine is really the only place that would benefit from\\nit being a Set, it makes sense to optimize the hot loop in rnImports.combine\\nwithout changing the representation.\\n\\nSo here\'s what we do: instead of naively merging ImportAvails with\\nplusImportAvails in a loop, we make plusImportAvails merge empty imp_finsts\\nand compute the union on the side using Sets. When we\'re done, we can\\nconvert it back to a list. One nice side effect of this approach is that\\nif there\'s a lot of overlap in the imp_finsts of imports, the\\nSet doesn\'t really need to grow and we don\'t need to allocate.\\n\\nRunning generateModules from #14693 with DEPTH=16, WIDTH=30 finishes in\\n23s before, and 11s after.\\n-}\\n\\n-- | Given a located import declaration @decl@ from @this_mod@,\\n-- calculate the following pieces of information:\\n--\\n-- 1. An updated \'LImportDecl\', where all unresolved \'RdrName\' in\\n-- the entity lists have been resolved into \'Name\'s,\\n--\\n-- 2. A \'GlobalRdrEnv\' representing the new identifiers that were\\n-- brought into scope (taking into account module qualification\\n-- and hiding),\\n--\\n-- 3. \'ImportAvails\' summarizing the identifiers that were imported\\n-- by this declaration, and\\n--\\n-- 4. A boolean \'AnyHpcUsage\' which is true if the imported module\\n-- used HPC.\\nrnImportDecl :: Module -> (LImportDecl GhcPs, SDoc)\\n -> RnM (LImportDecl GhcRn, ImportUserSpec , GlobalRdrEnv, ImportAvails)\\nrnImportDecl this_mod\\n (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name\\n , ideclPkgQual = raw_pkg_qual\\n , ideclSource = want_boot\\n , ideclSafe = mod_safe\\n , ideclLevelSpec = import_level\\n , ideclQualified = qual_style\\n , ideclExt = XImportDeclPass { ideclOrigin = origin }\\n , ideclAs = as_mod, ideclImportList = imp_details }), import_reason)\\n = setSrcSpanA loc $ do\\n\\n case raw_pkg_qual of\\n NoRawPkgQual -> pure ()\\n RawPkgQual {} -> do\\n pkg_imports <- xoptM LangExt.PackageImports\\n when (not pkg_imports) $ addErr TcRnPackageImportsDisabled\\n\\n let qual_only = isImportDeclQualified qual_style\\n generated = isGeneratedImport origin\\n\\n lookup_scope = importDeclLookupScope origin\\n\\n -- If there\'s an error in loadInterface, (e.g. interface\\n -- file not found) we get lots of spurious errors from \'filterImports\'\\n let imp_mod_name = unLoc loc_imp_mod_name\\n doc = ppr imp_mod_name <+> import_reason\\n\\n hsc_env <- getTopEnv\\n unit_env <- hsc_unit_env <$> getTopEnv\\n let pkg_qual = renameRawPkgQual unit_env imp_mod_name raw_pkg_qual\\n\\n -- Check for self-import, which confuses the typechecker (#9032)\\n -- ghc --make rejects self-import cycles already, but batch-mode may not\\n -- at least not until GHC.IfaceToCore.tcHiBootIface, which is too late to avoid\\n -- typechecker crashes. (Indirect self imports are not caught until\\n -- GHC.IfaceToCore, see #10337 tracking how to make this error better.)\\n --\\n -- Originally, we also allowed \'import {-# SOURCE #-} M\', but this\\n -- caused bug #10182: in one-shot mode, we should never load an hs-boot\\n -- file for the module we are compiling into the EPS. In principle,\\n -- it should be possible to support this mode of use, but we would have to\\n -- extend Provenance to support a local definition in a qualified location.\\n -- For now, we don\'t support it, but see #10336\\n when (imp_mod_name == moduleName this_mod &&\\n (case pkg_qual of -- If we have import \\"\\" M, then we should\\n -- check that \\"\\" is \\"this\\" (which is magic)\\n -- or the name of this_mod\'s package. Yurgh!\\n -- c.f. GHC.findModule, and #9997\\n NoPkgQual -> True\\n ThisPkg uid -> uid == homeUnitId_ (hsc_dflags hsc_env)\\n OtherPkg _ -> False))\\n (addErr (TcRnSelfImport imp_mod_name))\\n\\n -- Check for a missing import list (Opt_WarnMissingImportList also\\n -- checks for T(..) items but that is done in checkDodgyImport below)\\n case imp_details of\\n Just (Exactly, _) -> return () -- Explicit import list\\n _ | generated -> return () -- Do not bleat for generated imports\\n | qual_only -> return ()\\n | otherwise -> addDiagnostic (TcRnNoExplicitImportList imp_mod_name)\\n\\n\\n mb_iface <- loadSrcInterface_maybe doc lookup_scope imp_mod_name want_boot pkg_qual\\n iface <- case mb_iface of\\n Succeeded iface -> return iface\\n Failed err -> failWithTc $\\n importDeclLoadFailure origin imp_mod_name want_boot err\\n\\n -- Compiler sanity check: if the import didn\'t say\\n -- {-# SOURCE #-} we should not get a hi-boot file\\n warnPprTrace ((want_boot == NotBoot) && (mi_boot iface == IsBoot)) \\"rnImportDecl\\" (ppr imp_mod_name) $ do\\n\\n -- Issue a user warning for a redundant {- SOURCE -} import\\n -- NB that we arrange to read all the ordinary imports before\\n -- any of the {- SOURCE -} imports.\\n --\\n -- in --make and GHCi, the compilation manager checks for this,\\n -- and indeed we shouldn\'t do it here because the existence of\\n -- the non-boot module depends on the compilation order, which\\n -- is not deterministic. The hs-boot test can show this up.\\n dflags <- getDynFlags\\n warnIf ((want_boot == IsBoot) && (mi_boot iface == NotBoot) && isOneShot (ghcMode dflags))\\n (TcRnRedundantSourceImport imp_mod_name)\\n when (mod_safe && not (safeImportsOn dflags)) $\\n addErr (TcRnSafeImportsDisabled imp_mod_name)\\n\\n let imp_mod = mi_module iface\\n qual_mod_name = fmap unLoc as_mod `orElse` imp_mod_name\\n imp_spec = ImpDeclSpec { is_mod = imp_mod, is_qual = qual_only,\\n is_dloc = locA loc, is_as = qual_mod_name,\\n is_pkg_qual = pkg_qual, is_isboot = want_boot,\\n is_level = convImportLevel import_level }\\n\\n let filter_imports = do\\n -- filter the imports according to the import declaration\\n (new_imp_details, imp_user_list, gbl_env)\\n <- filterImports hsc_env iface imp_spec imp_details\\n -- for certain error messages, we\\u2019d like to know what could be\\n -- imported here, if everything were imported\\n potential_gres <- (\\\\(_,_,x) -> x) <$> filterImports hsc_env iface imp_spec Nothing\\n return (new_imp_details, imp_user_list, gbl_env, potential_gres)\\n\\n (new_imp_details, imp_user_list, gbl_env, potential_gres) <-\\n case origin of\\n ImplicitEssentialsImport ->\\n -- The implicit GHC.Essentials import does not bring anything into scope.\\n -- See Note [Finding GHC.Essentials] in GHC.Builtin.\\n return (Nothing, ImpUserDependOnly, emptyGlobalRdrEnv, emptyGlobalRdrEnv)\\n UserWrittenImport -> filter_imports\\n ImplicitPreludeImport -> filter_imports\\n PluginImport -> filter_imports\\n\\n let is_hiding | Just (EverythingBut,_) <- imp_details = True\\n | otherwise = False\\n\\n -- should the import be safe?\\n mod_safe\' = mod_safe\\n || (not generated && safeDirectImpsReq dflags)\\n || (generated && safeImplicitImpsReq dflags)\\n\\n hsc_env <- getTopEnv\\n let home_unit = hsc_home_unit hsc_env\\n other_home_units = hsc_all_home_unit_ids hsc_env\\n\\n imported_by\\n | isDependOnlyImport imp_user_list\\n = ImportedBySystem\\n | otherwise\\n = ImportedByUser $ ImportedModsVal\\n { imv_name = is_as imp_spec\\n , imv_span = locA loc\\n , imv_is_safe = mod_safe\'\\n , imv_is_hiding = is_hiding\\n , imv_all_exports = potential_gres\\n , imv_qualified = qual_only\\n , imv_is_level = convImportLevel import_level\\n }\\n imports = calculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by\\n\\n -- Complain if we import a deprecated module\\n case fromIfaceWarnings (mi_warns iface) of\\n WarnAll txt -> addDiagnostic (TcRnDeprecatedModule imp_mod_name txt)\\n _ -> return ()\\n\\n let new_imp_decl = ImportDecl\\n { ideclExt = ideclExt decl\\n , ideclName = ideclName decl\\n , ideclPkgQual = pkg_qual\\n , ideclSource = ideclSource decl\\n , ideclSafe = mod_safe\'\\n , ideclQualified = ideclQualified decl\\n , ideclAs = ideclAs decl\\n , ideclImportList = new_imp_details\\n , ideclLevelSpec = ideclLevelSpec decl\\n }\\n\\n return (L loc new_imp_decl, ImpUserSpec imp_spec imp_user_list, gbl_env, imports)\\n\\n-- | The error message to emit when we failed to load an interface.\\nimportDeclLoadFailure :: ImportDeclOrigin -> ModuleName -> IsBootInterface\\n -> MissingInterfaceError -> TcRnMessage\\nimportDeclLoadFailure ImplicitEssentialsImport _ _ err\\n = TcRnInterfaceError $ CantFindEssentials err LookingForEssentialsModule\\nimportDeclLoadFailure _ mod_name want_boot err\\n = TcRnInterfaceError $ Can\'tFindInterface err $ LookingForModule mod_name want_boot\\n\\n-- | Rename raw package imports\\nrenameRawPkgQual :: UnitEnv -> ModuleName -> RawPkgQual -> PkgQual\\nrenameRawPkgQual unit_env mn = \\\\case\\n NoRawPkgQual -> NoPkgQual\\n RawPkgQual _ fs -> renamePkgQual unit_env mn $ Just fs\\n\\n-- | Rename raw package imports\\nrenamePkgQual :: UnitEnv -> ModuleName -> Maybe FastString -> PkgQual\\nrenamePkgQual unit_env mn mb_pkg = case mb_pkg of\\n Nothing -> NoPkgQual\\n Just pkg_fs\\n | Just uid <- homeUnitId <$> ue_homeUnit unit_env\\n , pkg_fs == fsLit \\"this\\"\\n -> ThisPkg uid\\n\\n | Just (uid, _) <- find (fromMaybe False . fmap (== pkg_fs) . snd) home_names\\n -> ThisPkg uid\\n\\n | Just uid <- resolvePackageImport unit_state mn (PackageName pkg_fs)\\n -> OtherPkg uid\\n\\n | otherwise\\n -> OtherPkg (UnitId pkg_fs)\\n -- not really correct as pkg_fs is unlikely to be a valid unit-id but\\n -- we will report the failure later...\\n where\\n home_names =\\n [ (uid, mkFastString <$> thisPackageName (homeUnitEnv_dflags (ue_findHomeUnitEnv uid unit_env)))\\n | uid <- S.toList hpt_deps\\n ]\\n\\n unit_state = ue_homeUnitState unit_env\\n\\n hpt_deps :: S.Set UnitId\\n hpt_deps = homeUnitDepends unit_state\\n\\n\\n-- | Calculate the \'ImportAvails\' induced by an import of a particular\\n-- interface, but without \'imp_mods\'.\\ncalculateAvails :: HomeUnit\\n -> S.Set UnitId\\n -> ModIface\\n -> IsSafeImport\\n -> IsBootInterface\\n -> ImportedBy\\n -> ImportAvails\\ncalculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by =\\n let imp_mod = mi_module iface\\n imp_sem_mod= mi_semantic_module iface\\n orph_iface = mi_orphan iface\\n has_finsts = mi_finsts iface\\n deps = mi_deps iface\\n trust = getSafeMode $ mi_trust iface\\n trust_pkg = mi_trust_pkg iface\\n is_sig = mi_hsc_src iface == HsigFile\\n\\n -- If the module exports anything defined in this module, just\\n -- ignore it. Reason: otherwise it looks as if there are two\\n -- local definition sites for the thing, and an error gets\\n -- reported. Easiest thing is just to filter them out up\\n -- front. This situation only arises if a module imports\\n -- itself, or another module that imported it. (Necessarily,\\n -- this involves a loop.)\\n --\\n -- We do this *after* filterImports, so that if you say\\n -- module A where\\n -- import B( AType )\\n -- type AType = ...\\n --\\n -- module B( AType ) where\\n -- import {-# SOURCE #-} A( AType )\\n --\\n -- then you won\'t get a \'B does not export AType\' message.\\n\\n\\n -- Compute new transitive dependencies\\n --\\n -- \'dep_orphs\' and \'dep_finsts\' do NOT include the imported module\\n -- itself, but we DO need to include this module in \'imp_orphs\' and\\n -- \'imp_finsts\' if it defines an orphan or instance family; thus the\\n -- orph_iface/has_iface tests.\\n\\n deporphs = dep_orphs deps\\n depfinsts = dep_finsts deps\\n\\n orphans | orph_iface = assertPpr (not (imp_sem_mod `elem` deporphs)) (ppr imp_sem_mod <+> ppr deporphs) $\\n imp_sem_mod : deporphs\\n | otherwise = deporphs\\n\\n finsts | has_finsts = assertPpr (not (imp_sem_mod `elem` depfinsts)) (ppr imp_sem_mod <+> ppr depfinsts) $\\n imp_sem_mod : depfinsts\\n | otherwise = depfinsts\\n\\n -- Trusted packages are a lot like orphans.\\n trusted_pkgs | mod_safe\' = dep_trusted_pkgs deps\\n | otherwise = S.empty\\n\\n\\n pkg = moduleUnit (mi_module iface)\\n ipkg = toUnitId pkg\\n\\n -- Does this import mean we now require our own pkg\\n -- to be trusted? See Note [Trust Own Package]\\n ptrust = trust == Sf_Trustworthy || trust_pkg\\n pkg_trust_req\\n | isHomeUnit home_unit pkg = ptrust\\n | otherwise = False\\n\\n dependent_pkgs = if toUnitId pkg `S.member` other_home_units\\n then S.empty\\n else S.singleton (lvl, ipkg)\\n\\n lvl = case imported_by of\\n ImportedByUser imv -> imv_is_level imv\\n ImportedBySystem -> NormalLevel\\n\\n\\n direct_mods = if toUnitId pkg `S.member` other_home_units\\n then mkPlusModDeps (moduleUnitId imp_mod) lvl (GWIB (moduleName imp_mod) want_boot)\\n else emptyInstalledModuleEnv\\n\\n dep_boot_mods_map = mkModDeps (dep_boot_mods deps)\\n\\n\\n boot_mods\\n -- If we are looking for a boot module, it must be HPT\\n | IsBoot <- want_boot = extendInstalledModuleEnv dep_boot_mods_map (toUnitId <$> imp_mod) (GWIB (moduleName imp_mod) IsBoot)\\n -- Now we are importing A properly, so don\'t go looking for\\n -- A.hs-boot\\n | isHomeUnit home_unit pkg = dep_boot_mods_map\\n -- There\'s no boot files to find in external imports\\n | otherwise = emptyInstalledModuleEnv\\n\\n sig_mods =\\n if is_sig\\n then moduleName imp_mod : dep_sig_mods deps\\n else dep_sig_mods deps\\n\\n\\n in ImportAvails {\\n imp_mods = Map.singleton (mi_module iface) [imported_by],\\n imp_orphs = orphans,\\n imp_finsts = finsts,\\n imp_sig_mods = sig_mods,\\n imp_direct_dep_mods = direct_mods,\\n imp_dep_direct_pkgs = dependent_pkgs,\\n imp_boot_mods = boot_mods,\\n\\n -- Add in the imported modules trusted package\\n -- requirements. ONLY do this though if we import the\\n -- module as a safe import.\\n -- See Note [Tracking Trust Transitively]\\n -- and Note [Trust Transitive Property]\\n imp_trust_pkgs = trusted_pkgs,\\n -- Do we require our own pkg to be trusted?\\n -- See Note [Trust Own Package]\\n imp_trust_own_pkg = pkg_trust_req\\n }\\n\\nmkPlusModDeps :: UnitId -> ImportLevel -> ModuleNameWithIsBoot\\n -> InstalledModuleEnv (S.Set ImportLevel, ModuleNameWithIsBoot)\\nmkPlusModDeps uid st elt = extendInstalledModuleEnv emptyInstalledModuleEnv (mkModule uid (gwib_mod elt)) (S.singleton st, elt)\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{importsFromLocalDecls}\\n* *\\n************************************************************************\\n\\nFrom the top-level declarations of this module produce\\n * the lexical environment\\n * the ImportAvails\\ncreated by its bindings.\\n\\nNote [Top-level Names in Template Haskell decl quotes]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSee also: Note [Interactively-bound Ids in GHCi] in GHC.Driver.Env\\n Note [Looking up Exact RdrNames] in GHC.Rename.Env\\n\\nConsider a Template Haskell declaration quotation like this:\\n module M where\\n f x = h [d| f = 3 |]\\nWhen renaming the declarations inside [d| ...|], we treat the\\ntop level binders specially in two ways\\n\\n1. We give them an Internal Name, not (as usual) an External one.\\n This is done by GHC.Rename.Env.newTopSrcBinder.\\n\\n2. We make them *shadow* the outer bindings.\\n See Note [GlobalRdrEnv shadowing]\\n\\n3. We find out whether we are inside a [d| ... |] by testing the TH\\n level. This is a slight hack, because the level field was really\\n meant for the type checker, and here we are not interested in the\\n fields of Brack, hence the error thunks in thRnBrack.\\n-}\\n\\nextendGlobalRdrEnvRn :: [GlobalRdrElt]\\n -> MiniFixityEnv\\n -> RnM (TcGblEnv, TcLclEnv)\\n-- Updates both the GlobalRdrEnv and the FixityEnv\\n-- We return a new TcLclEnv only because we might have to\\n-- delete some bindings from it;\\n-- see Note [Top-level Names in Template Haskell decl quotes]\\n\\nextendGlobalRdrEnvRn new_gres new_fixities\\n = checkNoErrs $ -- See Note [Fail fast on duplicate definitions]\\n do { (gbl_env, lcl_env) <- getEnvs\\n ; level <- getThLevel\\n ; isGHCi <- getIsGHCi\\n ; let rdr_env = tcg_rdr_env gbl_env\\n fix_env = tcg_fix_env gbl_env\\n th_bndrs = getLclEnvThBndrs lcl_env\\n th_lvl = thLevelIndex level\\n\\n -- Delete new_occs from global and local envs\\n -- If we are in a TemplateHaskell decl bracket,\\n -- we are going to shadow them\\n -- See Note [GlobalRdrEnv shadowing]\\n inBracket = isBrackLevel level\\n\\n lcl_env_TH = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_rdr = minusLocalRdrEnv (tcl_rdr lcl_env) new_gres_env }) lcl_env\\n -- See Note [GlobalRdrEnv shadowing]\\n\\n lcl_env2 | inBracket = lcl_env_TH\\n | otherwise = lcl_env\\n\\n -- Deal with shadowing: see Note [GlobalRdrEnv shadowing]\\n want_shadowing = isGHCi || inBracket\\n rdr_env1 | want_shadowing = shadowNames False rdr_env new_gres_env\\n | otherwise = rdr_env\\n\\n lcl_env3 = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_th_bndrs = extendNameEnvList th_bndrs\\n [ ( n, (TopLevel, th_lvl) )\\n | n <- new_names ] }) lcl_env2\\n\\n ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres\\n\\n ; let fix_env\' = foldl\' extend_fix_env fix_env new_gres\\n gbl_env\' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env\' }\\n\\n ; traceRn \\"extendGlobalRdrEnvRn 2\\" (pprGlobalRdrEnv True rdr_env2)\\n ; return (gbl_env\', lcl_env3) }\\n where\\n new_names = map greName new_gres\\n new_gres_env = mkGlobalRdrEnv new_gres\\n\\n -- If there is a fixity decl for the gre, add it to the fixity env\\n extend_fix_env fix_env gre\\n | Just (L _ fi) <- lookupMiniFixityEnv new_fixities name\\n = extendNameEnv fix_env name (FixItem occ fi)\\n | otherwise\\n = fix_env\\n where\\n name = greName gre\\n occ = greOccName gre\\n\\n add_gre :: GlobalRdrEnv -> GlobalRdrElt -> RnM GlobalRdrEnv\\n -- Extend the GlobalRdrEnv with a LocalDef GRE\\n -- If there is already a LocalDef GRE with the same OccName,\\n -- report an error and discard the new GRE\\n -- This establishes INVARIANT 1 of GlobalRdrEnvs\\n add_gre env gre\\n | not (null dups) -- Same OccName defined twice\\n = do { addDupDeclErr (gre :| dups); return env }\\n\\n | otherwise\\n = return (extendGlobalRdrEnv env gre)\\n where\\n -- See Note [Reporting duplicate local declarations]\\n dups = filter isBadDupGRE\\n $ lookupGRE env (LookupOccName (greOccName gre) (RelevantGREsFOS WantBoth))\\n isBadDupGRE old_gre = isLocalGRE old_gre && greClashesWith gre old_gre\\n\\n{- Note [Fail fast on duplicate definitions]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIf there are duplicate bindings for the same thing, we want to fail\\nfast. Having two bindings for the same thing can cause follow-on errors.\\nExample (test T9975a):\\n data Test = Test { x :: Int }\\n pattern Test wat = Test { x = wat }\\nThis defines \'Test\' twice. The second defn has no field-names; and then\\nwe get an error from Test { x=wat }, saying \\"Test has no field \'x\'\\".\\n\\nEasiest thing is to bale out fast on duplicate definitions, which\\nwe do via `checkNoErrs` on `extendGlobalRdrEnvRn`.\\n\\nNote [Reporting duplicate local declarations]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn general, a single module may not define the same OccName multiple times. This\\nis checked in extendGlobalRdrEnvRn: when adding a new locally-defined GRE to the\\nGlobalRdrEnv we report an error if there are already duplicates in the\\nenvironment. This establishes INVARIANT 1 (see comments on GlobalRdrEnv in\\nGHC.Types.Name.Reader), which says that for a given OccName, all the\\nGlobalRdrElts to which it maps must have distinct \'greName\'s.\\n\\nFor example, the following will be rejected:\\n\\n f x = x\\n g x = x\\n f x = x -- Duplicate!\\n\\nUsers are allowed to introduce new GREs with the same OccName as an imported GRE,\\nas disambiguation is possible through the module system, e.g.:\\n\\n module M where\\n import N (f)\\n f x = x\\n g x = M.f x + N.f x\\n\\nIf both GREs are local, the general rule is that two GREs clash if they have\\nthe same OccName, i.e. they share a textual name and live in the same namespace.\\nHowever, there are additional clashes due to record fields:\\n\\n - a new variable clashes with previously defined record fields\\n which define field selectors,\\n\\n - a new record field shadows:\\n\\n - previously defined variables, if it defines a field selector,\\n - previously defined record fields, unless it is a duplicate record field.\\n\\nThis logic is implemented in the function \'GHC.Types.Name.Reader.greClashesWith\'.\\n\\nSee also Note [Skipping ambiguity errors at use sites of local declarations] in\\nGHC.Rename.Utils.\\n-}\\n\\n\\n{- *********************************************************************\\n* *\\n getLocalDeclBindersd@ returns the names for an HsDecl\\n It\'s used for source code.\\n\\n *** See Note [The Naming story] in GHC.Hs.Decls ****\\n* *\\n********************************************************************* -}\\n\\ngetLocalNonValBinders :: MiniFixityEnv -> HsGroup GhcPs\\n -> RnM ((TcGblEnv, TcLclEnv), NameSet)\\n-- Get all the top-level binders bound the group *except*\\n-- for value bindings, which are treated separately\\n-- Specifically we return AvailInfo for\\n-- * type decls (incl constructors and record selectors)\\n-- * class decls (including class ops)\\n-- * associated types\\n-- * foreign imports\\n-- * value signatures (in hs-boot files only)\\n\\ngetLocalNonValBinders fixity_env\\n (HsGroup { hs_valds = binds,\\n hs_tyclds = tycl_decls,\\n hs_fords = foreign_decls })\\n = do { -- Process all type/class decls *except* family instances\\n ; let inst_decls = tycl_decls >>= group_instds\\n ; dup_fields_ok <- xopt_DuplicateRecordFields <$> getDynFlags\\n ; has_sel <- xopt_FieldSelectors <$> getDynFlags\\n ; tc_gres\\n <- concatMapM\\n (new_tc dup_fields_ok has_sel)\\n (tyClGroupTyClDecls tycl_decls)\\n ; traceRn \\"getLocalNonValBinders 1\\" (ppr tc_gres)\\n ; envs <- extendGlobalRdrEnvRn tc_gres fixity_env\\n ; restoreEnvs envs $ do {\\n -- Bring these things into scope first\\n -- See Note [Looking up family names in family instances]\\n\\n -- Process all family instances\\n -- to bring new data constructors into scope\\n ; nti_gress <- mapM (new_assoc dup_fields_ok has_sel) inst_decls\\n\\n -- Finish off with value binders:\\n -- foreign decls and pattern synonyms for an ordinary module\\n -- type sigs in case of a hs-boot file only\\n ; is_boot <- tcIsHsBootOrSig\\n ; let val_bndrs\\n | is_boot = case binds of\\n ValBinds _ val_binds ->\\n -- In a hs-boot file, the value binders come from the\\n -- *signatures*, and there should be no foreign binders\\n [ L (l2l decl_loc) (unLoc n)\\n | L decl_loc (TypeSig _ _ ns _) <- (val_sigs val_binds), n <- ns]\\n _ -> panic \\"Non-ValBinds in hs-boot group\\"\\n | otherwise = for_hs_bndrs\\n ; val_gres <- mapM new_simple val_bndrs\\n\\n ; let avails = concat nti_gress ++ val_gres\\n new_bndrs = gresToNameSet avails `unionNameSet`\\n gresToNameSet tc_gres\\n ; traceRn \\"getLocalNonValBinders 2\\" (ppr avails)\\n ; envs <- extendGlobalRdrEnvRn avails fixity_env\\n ; return (envs, new_bndrs) } }\\n where\\n for_hs_bndrs :: [LocatedN RdrName]\\n for_hs_bndrs = hsForeignDeclsBinders foreign_decls\\n\\n -- the SrcSpan attached to the input should be the span of the\\n -- declaration, not just the name\\n new_simple :: LocatedN RdrName -> RnM GlobalRdrElt\\n new_simple rdr_name = do { nm <- newTopSrcBinder rdr_name\\n ; return (mkLocalVanillaGRE NoParent nm) }\\n\\n new_tc :: DuplicateRecordFields -> FieldSelectors -> LTyClDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_tc dup_fields_ok has_sel tc_decl -- NOT for type/data instances\\n = do { let TyDeclBinders (main_bndr, tc_flav) at_bndrs sig_bndrs\\n (LConsWithFields cons_with_flds flds) = hsLTyClDeclBinders tc_decl\\n ; tycon_name <- newTopSrcBinder $ la2la main_bndr\\n ; at_names <- mapM (newTopSrcBinder . la2la . fst) at_bndrs\\n ; sig_names <- mapM (newTopSrcBinder . la2la) sig_bndrs\\n ; con_names_with_flds <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst con_names_with_flds) flds\\n ; mapM_ (add_dup_fld_errs flds\') con_names_with_flds\\n ; let tc_gre = mkLocalTyConGRE (fmap (const tycon_name) tc_flav) tycon_name\\n fld_env = mk_fld_env con_names_with_flds flds\'\\n at_gres = zipWith (\\\\ (_, at_flav) at_nm -> mkLocalTyConGRE (fmap (const tycon_name) at_flav) at_nm)\\n at_bndrs at_names\\n sig_gres = map (mkLocalVanillaGRE (ParentIs tycon_name)) sig_names\\n con_gres = map (mkLocalConLikeGRE (ParentIs tycon_name)) fld_env\\n fld_gres = mkLocalFieldGREs (ParentIs tycon_name) fld_env\\n sub_gres = at_gres ++ sig_gres ++ con_gres ++ fld_gres\\n ; traceRn \\"getLocalNonValBinders new_tc\\" $\\n vcat [ text \\"tycon:\\" <+> ppr tycon_name\\n , text \\"tc_gre:\\" <+> ppr tc_gre\\n , text \\"sub_gres:\\" <+> ppr sub_gres ]\\n ; return $ tc_gre : sub_gres }\\n\\n -- Calculate the record field information, which feeds into the GlobalRdrElts\\n -- for DataCons and their fields. It\'s convenient to do this here where\\n -- we are working with a single datatype definition.\\n --\\n -- The information we needed was all set up for us:\\n -- see Note [Collecting record fields in data declarations] in GHC.Hs.Utils.\\n mk_fld_env :: [(Name, Either VisArity [Located Int])] -> IntMap FieldLabel\\n -> [(ConLikeName, ConInfo)]\\n mk_fld_env names flds =\\n [ (DataConName con, ConInfo (ConIsData (map fst names)) fld_info)\\n | (con, con_fl_indxs) <- names\\n , let fld_info = case fmap (map ((flds IntMap.!) . unLoc)) con_fl_indxs of\\n Left 0 -> ConIsNullary\\n Left arity -> ConHasPositionalArgs arity\\n Right [] -> ConIsNullary\\n Right (fld:flds) -> ConHasRecordFields $ fld NE.:| flds ]\\n\\n new_assoc :: DuplicateRecordFields -> FieldSelectors -> LInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_assoc _ _ (L _ (TyFamInstD {})) = return []\\n -- type instances don\'t bind new names\\n\\n new_assoc dup_fields_ok has_sel (L _ (DataFamInstD _ d))\\n = new_di dup_fields_ok has_sel Nothing d\\n new_assoc dup_fields_ok has_sel\\n (L _ (ClsInstD _ (ClsInstDecl { cid_poly_ty = inst_ty\\n , cid_decls = decls })))\\n = do -- First, attempt to grab the name of the class from the instance.\\n -- This step could fail if the instance is not headed by a class,\\n -- such as in the following examples:\\n --\\n -- (1) The class is headed by a bang pattern, such as in\\n -- `instance !Show Int` (#3811c)\\n -- (2) The class is headed by a type variable, such as in\\n -- `instance c` (#16385)\\n --\\n -- If looking up the class name fails, then mb_cls_gre will\\n -- be Nothing.\\n mb_cls_gre <- runMaybeT $ do\\n -- See (1) above\\n L loc cls_rdr <- MaybeT $ pure $ getLHsInstDeclClass_maybe inst_ty\\n -- See (2) above\\n MaybeT $ setSrcSpan (locA loc) $ lookupGlobalOccRn_maybe SameNameSpace cls_rdr\\n -- Assuming the previous step succeeded, process any associated data\\n -- family instances. If the previous step failed, bail out.\\n case mb_cls_gre of\\n Nothing\\n -> pure []\\n Just cls_gre\\n -> let cls_nm = greName cls_gre\\n in concatMapM (new_di dup_fields_ok has_sel (Just cls_nm) . unLoc) (data_fam_insts decls)\\n\\n data_fam_insts decls = concatMap get decls\\n where\\n get (L l (InstD _ (DataFamInstD { dfid_inst = d}))) = [L l d]\\n get _ = []\\n\\n new_di :: DuplicateRecordFields -> FieldSelectors\\n -> Maybe Name -- class name\\n -> DataFamInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_di dup_fields_ok has_sel mb_cls dfid@(DataFamInstDecl { dfid_eqn = ti_decl })\\n = do { main_name <- unLoc <$> lookupFamInstName mb_cls (feqn_tycon ti_decl)\\n ; let LConsWithFields cons_with_flds flds = hsDataFamInstBinders dfid\\n ; sub_names <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst sub_names) flds\\n ; mapM_ (add_dup_fld_errs flds\') sub_names\\n ; let fld_env = mk_fld_env sub_names flds\'\\n con_gres = map (mkLocalConLikeGRE (ParentIs main_name)) fld_env\\n field_gres = mkLocalFieldGREs (ParentIs main_name) fld_env\\n -- NB: the data family name is not bound here,\\n -- so we don\'t return a GlobalRdrElt for it here!\\n ; return $ con_gres ++ field_gres }\\n\\n -- Add errors if a constructor has a duplicate record field.\\n add_dup_fld_errs :: IntMap FieldLabel\\n -> (Name, Either VisArity [Located Int])\\n -> IOEnv (Env TcGblEnv TcLclEnv) ()\\n add_dup_fld_errs all_flds (con, con_flds_or_arity)\\n | Right con_flds <- con_flds_or_arity\\n , let (_, dups) = removeDups (comparing unLoc) con_flds\\n = for_ dups $ \\\\ dup_flds ->\\n -- Report the error at the location of the second occurrence\\n -- of the duplicate field.\\n let loc =\\n case dup_flds of\\n _ :| ( L loc _ : _) -> loc\\n L loc _ :| _ -> loc\\n dup_rdrs = fmap (nameRdrName . flSelector . (all_flds IntMap.!) . unLoc) dup_flds\\n in addErrAt loc $ TcRnDuplicateFieldName (RecordFieldDecl con) dup_rdrs\\n | otherwise\\n = return ()\\n\\nnewRecordFieldLabel :: DuplicateRecordFields -> FieldSelectors -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel\\nnewRecordFieldLabel _ _ [] _ = error \\"newRecordFieldLabel: datatype has no constructors!\\"\\nnewRecordFieldLabel dup_fields_ok has_sel (dc:_) (L loc (FieldOcc _ (L _ fld)))\\n = do { selName <- newTopSrcBinder $ L (l2l loc) $ field\\n ; return $ FieldLabel { flHasDuplicateRecordFields = dup_fields_ok\\n , flHasFieldSelector = has_sel\\n , flSelector = selName } }\\n where\\n fld_occ = rdrNameOcc fld\\n dc_fs = occNameFS $ nameOccName dc\\n field\\n -- Use an Exact RdrName as-is, to preserve the bindings\\n -- of an already renamer-resolved field and its use\\n -- sites. This is needed to correctly support record\\n -- selectors in Template Haskell. See Note [Binders in\\n -- Template Haskell] in \\"GHC.ThToHs\\" and Note [Looking up\\n -- Exact RdrNames] in \\"GHC.Rename.Env\\".\\n | isExact fld\\n = assertPpr (fieldOcc_maybe fld_occ == Just dc_fs)\\n (vcat [ text \\"newRecordFieldLabel: incorrect namespace for exact Name\\" <+> quotes (ppr fld)\\n , text \\"expected namespace:\\" <+> pprNameSpace (fieldName dc_fs)\\n , text \\" actual namespace:\\" <+> pprNameSpace (occNameSpace fld_occ) ])\\n fld\\n\\n -- Field names produced by the parser are namespaced with VarName.\\n -- Here we namespace them according to the first constructor.\\n -- See Note [Record field namespacing] in GHC.Types.Name.Occurrence.\\n | otherwise\\n = mkRdrUnqual $ varToRecFieldOcc dc_fs fld_occ\\n\\n{-\\nNote [Looking up family names in family instances]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider\\n\\n module M where\\n type family T a :: *\\n type instance M.T Int = Bool\\n\\nWe might think that we can simply use \'lookupOccRn\' when processing the type\\ninstance to look up \'M.T\'. Alas, we can\'t! The type family declaration is in\\nthe *same* HsGroup as the type instance declaration. Hence, as we are\\ncurrently collecting the binders declared in that HsGroup, these binders will\\nnot have been added to the global environment yet.\\n\\nSolution is simple: process the type family declarations first, extend\\nthe environment, and then process the type instances.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Filtering imports}\\n* *\\n************************************************************************\\n\\n@filterImports@ takes the @ExportEnv@ telling what the imported module makes\\navailable, and filters it through the import spec (if any).\\n\\nNote [Dealing with imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nFor import M( ies ), we take each AvailInfo from the mi_exports of M, and make\\n\\n imp_occ_env :: OccEnv (NameEnv ImpOccItem)\\n\\nThis map contains one entry for each OccName that M exports, mapping each OccName\\nto the following information:\\n\\n 1. the GlobalRdrElt corresponding to the OccName,\\n 2. whether this GlobalRdrElt was the parent in the AvailInfo we found\\n the OccName in.\\n 3. the GlobalRdrElts that were bundled together in the AvailInfo we found\\n this OccName in (not including the parent),\\n\\nWe need (2) and (3) during the construction of the OccEnv because of associated\\ntypes and bundled pattern synonyms, respectively.\\n(3) is explained in Note [Importing PatternSynonyms].\\n\\nTo explain (2), consider for example:\\n\\n module M where\\n class C a where { data T a }\\n instance C Int where { data T Int = T1 | T2 }\\n instance C Bool where { data T Int = T3 }\\n\\nHere, M\'s exports avails are (recalling the AvailTC invariant from GHC.Types.Avail)\\n\\n C(C,T), T(T,T1,T2,T3)\\n\\nNotice that T appears *twice*, once as a child and once as a parent. From\\nthese two exports, respectively, during construction of the imp_occ_env, we begin\\nby associating the following two elements with the key T:\\n\\n T -> ImpOccItem { imp_item = gre1, imp_bundled = [C,T] , imp_is_parent = False }\\n T -> ImpOccItem { imp_item = gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nwhere `gre1`, `gre2` are two GlobalRdrElts with greName T.\\nWe combine these (in function \'combine\' in \'mkImportOccEnv\') by discarding the\\nnon-parent item, thusly:\\n\\n T -> IE_ITem { imp_item = gre1 `plusGRE` gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nNote the `plusGRE`: this ensures we don\'t drop parent information;\\nsee Note [Preserve parent information when combining import OccEnvs].\\n\\nSo the overall imp_occ_env is:\\n\\n C -> ImpOccItem { imp_item = C, imp_bundled = [T ], imp_is_parent = True }\\n T -> ImpOccItem { imp_item = T , imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n T1 -> ImpOccItem { imp_item = T1, imp_bundled = [T1,T2,T3], imp_is_parent = False }\\n -- similarly for T2, T3\\n\\nNote that the imp_occ_env will have entries for data constructors too,\\nalthough we never look up data constructors.\\n\\nNote [Importing PatternSynonyms]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nAs described in Note [Dealing with imports], associated types can lead to the\\nsame Name appearing twice, both as a child and once as a parent, when\\nconstructing the imp_occ_env. The same thing can happen with pattern synonyms\\nif they are exported bundled with a type.\\n\\nA simplified example, based on #11959:\\n\\n {-# LANGUAGE PatternSynonyms #-}\\n module M (T(P), pattern P) where -- Duplicate export warning, but allowed\\n data T = MkT\\n pattern P = MkT\\n\\nHere we have T(P) and P in export_avails, and respectively construct both\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n P -> ImpOccItem { imp_item = P, imp_bundled = [] , imp_is_parent = False }\\n\\nWe combine these by dropping the one with no siblings, leaving us with:\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n\\nThat is, we simply discard the non-bundled Avail.\\n\\nNote [Importing DuplicateRecordFields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn filterImports, another complicating factor is DuplicateRecordFields.\\nSuppose we have:\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (S(foo), T(foo)) where\\n data S = MkS { foo :: Int }\\n data T = MkT { foo :: Int }\\n\\n module N where\\n import M (foo) -- this is allowed (A)\\n import M (S(foo)) -- this is allowed (B)\\n\\nHere M exports \'foo\' at two different OccNames, with different namespaces for\\nthe two construtors MkS and MkT. Then, when we look up \'foo\' in lookup_names\\nfor case (A), we have a variable foo but must look in all the record field\\nnamespaces to find the two fields (and hence two different Avails).\\nWhereas in case (B) we reach the lookup_ie case for IEThingWith,\\nwhich looks up \'S\' and then finds the unique \'foo\' amongst its children.\\n\\nSee T16745 for a test of this.\\n\\nNote [Preserve parent information when combining import OccEnvs]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen discarding one ImpOccItem in favour of another, as described in\\nNote [Dealing with imports], we must make sure to combine the GREs so that\\nwe don\'t lose information.\\n\\nConsider for example #24084:\\n\\n module M1 where { class C a where { type T a } }\\n module M2 ( module M1 ) where { import M1 }\\n module M3 where { import M2 ( C, T ); instance C () where T () = () }\\n\\nWhen processing the import list of `M3`, we will have two `Avail`s attached\\nto `T`, namely `C(C, T)` and `T(T)`. We combine them in the `combine` function\\nof `mkImportOccEnv`; as described in Note [Dealing with imports] we discard\\n`C(C, T)` in favour of `T(T)`. However, in doing so, we **must not**\\ndiscard the information want that `C` is the parent of `T`. Indeed,\\nlosing track of this information can cause errors when importing,\\nas we could get an error of the form\\n\\n \\u2018T\\u2019 is not a (visible) associated type of class \\u2018C\\u2019\\n\\nThis explains why we use `plusGRE` when combining the two ImpOccItems, even\\nthough we are discarding one in favour of the other.\\n-}\\n\\n-- | All the \'GlobalRdrElt\'s associated with an \'AvailInfo\'.\\ngresFromAvail :: HasDebugCallStack\\n => HscEnv -> Maybe ImportSpec -> AvailInfo -> [GlobalRdrElt]\\ngresFromAvail hsc_env prov avail =\\n [ mk_gre nm info\\n | nm <- availNames avail\\n , let info = lookupGREInfo hsc_env nm ]\\n where\\n\\n mk_gre n info\\n = case prov of\\n -- Nothing => bound locally\\n -- Just is => imported from \'is\'\\n Nothing -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = True, gre_imp = emptyBag\\n , gre_info = info }\\n Just is -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = False, gre_imp = unitBag is\\n , gre_info = info }\\n\\n-- | All the \'GlobalRdrElt\'s associated with a collection of \'AvailInfo\'s.\\ngresFromAvails :: HscEnv -> Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]\\ngresFromAvails hsc_env prov = concatMap (gresFromAvail hsc_env prov)\\n\\nimportsFromIface :: HscEnv -> ModIface -> ImpDeclSpec -> Maybe NameSet -> GlobalRdrEnv\\nimportsFromIface hsc_env iface decl_spec hidden = mkGlobalRdrEnv $ case hidden of\\n Nothing -> all_gres\\n Just hidden_names -> filter (not . (`elemNameSet` hidden_names) . greName) all_gres\\n where\\n all_gres = gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\nrnNamespaceSpecifier :: NamespaceSpecifier GhcPs -> NamespaceSpecifier GhcRn\\nrnNamespaceSpecifier (NoNamespaceSpecifier _) = NoNamespaceSpecifier noExtField\\nrnNamespaceSpecifier (TypeNamespaceSpecifier x) = TypeNamespaceSpecifier x\\nrnNamespaceSpecifier (DataNamespaceSpecifier x) = DataNamespaceSpecifier x\\n\\nfilterImports\\n :: HasDebugCallStack\\n => HscEnv\\n -> ModIface\\n -> ImpDeclSpec\\n -- ^ Import spec\\n -> Maybe (ImportListInterpretation, [LIE GhcPs])\\n -- ^ Whether this is a \\"hiding\\" import list\\n -> RnM (Maybe (ImportListInterpretation, [LIE GhcRn]), -- Import spec w/ Names\\n ImpUserList, -- same, but designed for storage in interfaces\\n GlobalRdrEnv) -- Same again, but in GRE form\\nfilterImports hsc_env iface decl_spec Nothing\\n = return (Nothing, ImpUserAll, importsFromIface hsc_env iface decl_spec Nothing)\\nfilterImports hsc_env iface decl_spec (Just (want_hiding, import_items))\\n = do -- check for errors, convert RdrNames to Names\\n items1 <- mapM lookup_lie import_items\\n\\n let items2 :: [(LIE GhcRn, [GlobalRdrElt])]\\n items2 = concat items1\\n -- NB we may have duplicates, and several items\\n -- for the same parent; e.g N(x) and N(y)\\n\\n (gres, imp_user_list) = case want_hiding of\\n Exactly ->\\n let gres = concatMap (gresFromIE decl_spec) items2\\n gre_env = mkGlobalRdrEnv gres\\n implicit_parents = mkNameSet $ mapMaybe parentOfImplicitlyImportedGRE gres\\n in (gre_env, ImpUserExplicit (gresToAvailInfo $ globalRdrEnvElts $ gre_env) implicit_parents)\\n EverythingBut ->\\n let hidden_names = mkNameSet $ concatMap (map greName . snd) items2\\n in (importsFromIface hsc_env iface decl_spec (Just hidden_names), ImpUserEverythingBut hidden_names)\\n\\n return (Just (want_hiding, map fst items2), imp_user_list, gres)\\n where\\n import_mod = mi_module iface\\n all_avails = mi_exports iface\\n imp_occ_env = mkImportOccEnv hsc_env decl_spec all_avails\\n\\n -- Look up a parent (type constructor, class or data constructor)\\n -- in an import.\\n lookup_parent :: IE GhcPs -> RdrName -> IELookupM ImpOccItem\\n lookup_parent ie rdr =\\n assertPpr (not $ isVarNameSpace ns)\\n (vcat [ text \\"filterImports lookup_parent: unexpected variable\\"\\n , text \\"rdr:\\" <+> ppr rdr\\n , text \\"namespace:\\" <+> pprNameSpace ns ]) $\\n do { xs <- lookup_names ie rdr\\n ; case xs of\\n cax :| [] -> return cax\\n _ -> pprPanic \\"filter_imports lookup_parent ambiguous\\" $\\n vcat [ text \\"rdr:\\" <+> ppr rdr\\n , text \\"lookups:\\" <+> ppr (fmap imp_item xs) ] }\\n -- Looking up non-variables is always unambiguous,\\n -- as there can be at most one corresponding item\\n -- in the imp_occ_env.\\n -- See item (1) of Note [Exporting duplicate declarations]\\n -- in GHC.Tc.Gen.Export.\\n where\\n occ = rdrNameOcc rdr\\n ns = occNameSpace occ\\n\\n -- Look up a RdrName used in an import, returning multiple values if there\\n -- are several fields with the same name exposed by the module\\n lookup_names :: IE GhcPs -> RdrName -> IELookupM (NonEmpty ImpOccItem)\\n lookup_names ie rdr\\n | isQual rdr\\n = failLookupWith (QualImportError rdr)\\n | otherwise\\n = case lookups of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n item:items -> return $ item :| items\\n where\\n lookups = concatMap nonDetNameEnvElts\\n $ lookupImpOccEnv (RelevantGREsFOS WantNormal) imp_occ_env (rdrNameOcc rdr)\\n\\n lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, [GlobalRdrElt])]\\n lookup_lie (L loc ieRdr)\\n = setSrcSpanA loc $\\n do (stuff, warns) <- run_lookup ([],[]) (lookup_ie ieRdr)\\n mapM_ (addTcRnDiagnostic <=< warning_msg) warns\\n return [ (L loc ie, gres) | (ie,gres) <- stuff ]\\n where\\n\\n -- Warn when importing T(..) and no children are brought in scope\\n warning_msg (DodgyImport reason) =\\n pure (TcRnDodgyImports reason)\\n warning_msg MissingImportList =\\n pure (TcRnMissingImportList ieRdr)\\n warning_msg (BadImportW ie sub) = do\\n -- \'BadImportW\' is only constructed below in \'bad_import_w\', in\\n -- the \'EverythingBut\' case, so here we assume a \'hiding\' clause.\\n (reason :| _) <- badImportItemErr iface decl_spec ie sub all_avails\\n pure (TcRnDodgyImports (DodgyImportsHiding reason))\\n warning_msg (DeprecatedExport n w) =\\n pure $ TcRnPragmaWarning\\n PragmaWarningExport\\n { pwarn_occname = occName n\\n , pwarn_impmod = moduleName import_mod }\\n w\\n\\n run_lookup :: a -> IELookupM a -> TcRn a\\n run_lookup def m = case m of\\n Failed err -> do\\n msgs <- lookup_err_msgs err\\n forM_ msgs $ \\\\msg -> addErr (TcRnImportLookup msg)\\n return def\\n Succeeded a -> return a\\n\\n lookup_err_msgs err = case err of\\n BadImport ie sub -> badImportItemErr iface decl_spec ie sub all_avails\\n IllegalImport -> pure $ NE.singleton ImportLookupIllegal\\n QualImportError rdr -> pure $ NE.singleton (ImportLookupQualified rdr)\\n\\n -- For each import item, we convert its RdrNames to Names,\\n -- and at the same time compute all the GlobalRdrElt corresponding\\n -- to what is actually imported by this item.\\n -- Returns Nothing on error.\\n --\\n -- Returns a list because, with DuplicateRecordFields, a naked\\n -- import/export of a record field can correspond to multiple\\n -- different GlobalRdrElts. See Note [Importing DuplicateRecordFields].\\n lookup_ie :: IE GhcPs\\n -> IELookupM ([(IE GhcRn, [GlobalRdrElt])], [IELookupWarning])\\n lookup_ie ie = handle_bad_import $\\n case ie of\\n IEVar _ (L l n) _ -> do\\n -- See Note [Importing DuplicateRecordFields]\\n xs <- lookup_names ie (ieWrappedName n)\\n let gres = map imp_item $ NE.toList xs\\n export_depr_warns\\n | want_hiding == Exactly\\n = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ( [ (IEVar Nothing (L l (replaceWrappedName n name)) noDocstring, [gre])\\n | gre <- gres\\n , let name = greName gre ]\\n , export_depr_warns )\\n\\n IEThingAll x ns_spec (L l tc) _ -> do\\n ImpOccItem { imp_item = gre\\n , imp_bundled = bundled_gres\\n , imp_is_parent = is_par\\n }\\n <- lookup_parent ie $ ieWrappedName tc\\n let name = greName gre\\n\\n child_gres :: [GlobalRdrElt]\\n child_gres\\n | is_par = filterByNamespaceSpecifierGREs ns_spec bundled_gres\\n | otherwise = []\\n\\n imp_list_warn\\n\\n | null child_gres\\n -- e.g. f(..) or T(..) where T is a type synonym\\n = [DodgyImport (DodgyImportsEmptyParent ie ns_spec gre)]\\n\\n -- e.g. import M( T(..) )\\n | not (is_qual decl_spec)\\n = [MissingImportList]\\n\\n | otherwise\\n = []\\n\\n renamed_ie = IEThingAll (x { ieta_warning = Nothing })\\n (rnNamespaceSpecifier ns_spec)\\n (L l (replaceWrappedName tc name))\\n noDocstring\\n export_depr_warn\\n | want_hiding == Exactly\\n = maybeToList $ mk_depr_export_warning gre\\n -- We don\'t want to warn about the children as they\\n -- are not explicitly mentioned; the warning will\\n -- be emitted later on if they are used\\n | otherwise = []\\n\\n return ( [(renamed_ie, gre:child_gres)]\\n , imp_list_warn ++ export_depr_warn)\\n\\n\\n IEThingAbs _ (L l tc\') _\\n | want_hiding == EverythingBut -- hiding ( C )\\n -- Here the \'C\' can be a data constructor\\n -- *or* a type/class, or even both\\n -> let tc = ieWrappedName tc\'\\n tc_name = lookup_parent ie tc\\n dc_name = lookup_parent ie (setRdrNameSpace tc srcDataName)\\n in\\n case catIELookupM [ tc_name, dc_name ] of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n names -> return ( [mkIEThingAbs tc\' l (imp_item name) | name <- names], [])\\n | otherwise\\n -> do ImpOccItem { imp_item = gre } <- lookup_parent ie (ieWrappedName tc\')\\n return ( [mkIEThingAbs tc\' l gre]\\n , maybeToList $ mk_depr_export_warning gre)\\n\\n IEThingWith (deprecation, ann) ltc@(L l rdr_tc) wc rdr_ns _ -> do\\n ImpOccItem { imp_item = gre, imp_bundled = subnames }\\n <- lookup_parent (IEThingAbs Nothing ltc noDocstring) (ieWrappedName rdr_tc)\\n let name = greName gre\\n\\n -- Look up the children in the sub-names of the parent\\n -- See Note [Importing DuplicateRecordFields]\\n let (children_errs, childnames) = lookupChildren subnames rdr_ns\\n\\n bad_import_warns <-\\n if null children_errs then return [] else\\n let items = map lce_wrapped_name children_errs\\n ie = IEThingWith (deprecation, ann) ltc wc items noDocstring\\n -- We are trying to import T( a,b,c,d ), and failed\\n -- to find \'b\' and \'d\'. So we make up an import item\\n -- to report as failing, namely T( b, d ).\\n -- c.f. #15413\\n subordinate_err = mkSubordinateError gre children_errs\\n in bad_import_w ie subordinate_err\\n\\n let name\' = replaceWrappedName rdr_tc name\\n childnames\' = map (to_ie_post_rn . fmap greName) childnames\\n gres = gre : map unLoc childnames\\n export_depr_warns\\n | want_hiding == Exactly = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ([ (IEThingWith (Nothing, ann) (L l name\') wc childnames\' noDocstring\\n ,gres)]\\n , bad_import_warns ++ export_depr_warns)\\n\\n IEWholeNamespace x ns_spec -> do\\n let mod_name = moduleName import_mod\\n names = map greName gres\\n renamed_ie = IEWholeNamespace x { iewn_warning = Nothing\\n , iewn_names = names }\\n (rnNamespaceSpecifier ns_spec)\\n gres = filterByNamespaceSpecifierGREs ns_spec $\\n gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n dodgy_warn\\n | null gres = [DodgyImport (DodgyImportsWildcard mod_name ns_spec)]\\n | otherwise = []\\n return ([(renamed_ie, gres)],\\n dodgy_warn)\\n\\n _other -> failLookupWith IllegalImport\\n -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed...\\n -- all of those constitute errors.\\n\\n where\\n mkIEThingAbs tc l gre\\n = (IEThingAbs Nothing (L l (replaceWrappedName tc n)) noDocstring, [gre])\\n where n = greName gre\\n\\n -- N.B. imports never have docstrings\\n noDocstring = Nothing\\n\\n handle_bad_import m = catchIELookup m $ \\\\case\\n BadImport ie sub -> do\\n ws <- bad_import_w ie sub\\n return ([], ws)\\n err -> failLookupWith err\\n\\n bad_import_w :: IE GhcPs -> IsSubordinateError -> IELookupM [IELookupWarning]\\n bad_import_w ie sub\\n | want_hiding == EverythingBut = return [BadImportW ie sub]\\n | otherwise = failLookupWith (BadImport ie sub)\\n\\n mk_depr_export_warning gre\\n = DeprecatedExport name <$> mi_export_warn_fn iface name\\n where\\n name = greName gre\\n\\n-- | Assuming a subordinate item could not be found, do another lookup for a\\n-- more specific error message.\\nmkBadExportSubordinate :: [GlobalRdrElt] -> LIEWrappedName GhcPs -> BadExportSubordinate\\nmkBadExportSubordinate child_gres n =\\n case lookupChildren child_gres [n] of\\n (LookupChildNonType {lce_nontype_item = g} : _, _) -> BadExportSubordinateNonType g\\n (LookupChildNonData {lce_nondata_item = g} : _, _) -> BadExportSubordinateNonData g\\n _ -> BadExportSubordinateNotFound n\\n\\ntype IELookupM = MaybeErr IELookupError\\n\\ndata IELookupWarning\\n = BadImportW (IE GhcPs) IsSubordinateError\\n | MissingImportList\\n | DodgyImport DodgyImportsReason\\n | DeprecatedExport Name (WarningTxt GhcRn)\\n\\n-- | Is this import/export item a subordinate or not?\\ndata IsSubordinateError\\n = IsSubordinateError { subordinate_err_parent :: !GlobalRdrElt\\n , subordinate_err_unavailable :: [FastString]\\n , subordinate_err_nontype :: [GlobalRdrElt]\\n , subordinate_err_nondata :: [GlobalRdrElt] }\\n | IsNotSubordinate\\n\\nmkSubordinateError :: GlobalRdrElt -> [LookupChildError] -> IsSubordinateError\\nmkSubordinateError gre children_errs = foldr add init_acc children_errs\\n where\\n init_acc :: IsSubordinateError\\n init_acc = IsSubordinateError gre [] [] []\\n\\n add :: LookupChildError -> IsSubordinateError -> IsSubordinateError\\n add children_err sub@IsSubordinateError{} =\\n case children_err of\\n LookupChildNonType{lce_nontype_item = g} ->\\n sub { subordinate_err_nontype = g : subordinate_err_nontype sub }\\n LookupChildNonData{lce_nondata_item = g} ->\\n sub { subordinate_err_nondata = g : subordinate_err_nondata sub }\\n LookupChildNotFound (L _ wname) ->\\n let fs = (occNameFS . rdrNameOcc . ieWrappedName) wname\\n in sub { subordinate_err_unavailable = fs : subordinate_err_unavailable sub }\\n add _ IsNotSubordinate = panic \\"mkSubordinateError: IsNotSubordinate\\"\\n\\ndata IELookupError\\n = QualImportError RdrName\\n | BadImport (IE GhcPs) IsSubordinateError\\n | IllegalImport\\n\\nfailLookupWith :: IELookupError -> IELookupM a\\nfailLookupWith err = Failed err\\n\\ncatchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a\\ncatchIELookup m h = case m of\\n Succeeded r -> return r\\n Failed err -> h err\\n\\ncatIELookupM :: [IELookupM a] -> [a]\\ncatIELookupM ms = [ a | Succeeded a <- ms ]\\n\\n-- | Information associated to an \'AvailInfo\' used in constructing\\n-- an \'OccEnv\' corresponding to imports.\\n--\\n-- See Note [Dealing with imports].\\ndata ImpOccItem\\n = ImpOccItem\\n { imp_item :: GlobalRdrElt\\n -- ^ The import item\\n , imp_bundled :: [GlobalRdrElt]\\n -- ^ Items bundled in the Avail this import item came from,\\n -- not including the import item itself if it is a parent.\\n , imp_is_parent :: Bool\\n -- ^ Is the import item a parent? See Note [Dealing with imports].\\n }\\n\\ninstance Outputable ImpOccItem where\\n ppr (ImpOccItem { imp_item = item, imp_bundled = bundled, imp_is_parent = is_par })\\n = braces $ hsep\\n [ text \\"ImpOccItem\\"\\n , if is_par then text \\"[is_par]\\" else empty\\n , ppr (greName item) <+> ppr (greParent item)\\n , braces $ text \\"bundled:\\" <+> ppr (map greName bundled) ]\\n\\n-- | Make an \'OccEnv\' of all the imports.\\n--\\n-- Complicated by the fact that associated data types and pattern synonyms\\n-- can appear twice. See Note [Dealing with imports].\\nmkImportOccEnv :: HscEnv -> ImpDeclSpec -> [IfaceExport] -> OccEnv (NameEnv ImpOccItem)\\nmkImportOccEnv hsc_env decl_spec all_avails =\\n mkOccEnv_C (plusNameEnv_C combine)\\n [ (occ, mkNameEnv [(nm, item)])\\n | avail <- all_avails\\n , let gres = gresFromAvail hsc_env (Just hiding_spec) avail\\n , gre <- gres\\n , let nm = greName gre\\n occ = greOccName gre\\n (is_parent, bundled) = case avail of\\n AvailTC c _\\n | c == nm -- (Recall the AvailTC invariant from GHC.Types.AvailInfo)\\n -> ( True, drop 1 gres ) -- \\"drop 1\\": don\'t include the parent itself.\\n | otherwise\\n -> ( False, gres )\\n _ -> ( False, [] )\\n item = ImpOccItem\\n { imp_item = gre\\n , imp_bundled = bundled\\n , imp_is_parent = is_parent }\\n ]\\n where\\n\\n hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\n -- See Note [Dealing with imports]\\n -- \'combine\' may be called for associated data types which appear\\n -- twice in the all_avails. In the example, we have two Avails for T,\\n -- namely T(T,T1,T2,T3) and C(C,T), and we combine them by dropping the\\n -- latter, in which T is not the parent.\\n combine :: ImpOccItem -> ImpOccItem -> ImpOccItem\\n combine item1@(ImpOccItem { imp_item = gre1, imp_is_parent = is_parent1 })\\n item2@(ImpOccItem { imp_item = gre2, imp_is_parent = is_parent2 })\\n | is_parent1 || is_parent2\\n , not (isRecFldGRE gre1 || isRecFldGRE gre2) -- NB: does not force GREInfo.\\n , let name1 = greName gre1\\n name2 = greName gre2\\n gre = gre1 `plusGRE` gre2\\n -- See Note [Preserve parent information when combining import OccEnvs]\\n = assertPpr (name1 == name2)\\n (ppr name1 <+> ppr name2) $\\n if is_parent1\\n then item1 { imp_item = gre }\\n else item2 { imp_item = gre }\\n -- Discard C(C,T) in favour of T(T, T1, T2, T3).\\n\\n -- \'combine\' may also be called for pattern synonyms which appear both\\n -- unassociated and associated (see Note [Importing PatternSynonyms]).\\n combine item1@(ImpOccItem { imp_item = c1, imp_bundled = kids1 })\\n item2@(ImpOccItem { imp_item = c2, imp_bundled = kids2 })\\n = assertPpr (greName c1 == greName c2\\n && (not (null kids1 && null kids2)))\\n (ppr c1 <+> ppr c2 <+> ppr kids1 <+> ppr kids2) $\\n if null kids1\\n then item2\\n else item1\\n -- Discard standalone pattern P in favour of T(P).\\n\\n-- | Essentially like @lookupGRE env (LookupOccName occ which_gres)@,\\n-- but working with \'ImpOccItem\'s instead of \'GlobalRdrElt\'s.\\nlookupImpOccEnv :: WhichGREs GREInfo\\n -> OccEnv (NameEnv ImpOccItem) -> OccName -> [NameEnv ImpOccItem]\\nlookupImpOccEnv which_gres env occ =\\n mapMaybe relevant_items $ lookupOccEnv_AllNameSpaces env occ\\n where\\n is_relevant :: ImpOccItem -> Bool\\n is_relevant (ImpOccItem { imp_item = gre }) =\\n greIsRelevant which_gres (occNameSpace occ) gre\\n relevant_items :: NameEnv ImpOccItem -> Maybe (NameEnv ImpOccItem)\\n relevant_items nms\\n | let nms\' = filterNameEnv is_relevant nms\\n = if isEmptyNameEnv nms\'\\n then Nothing\\n else Just nms\'\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{Import/Export Utils}\\n* *\\n************************************************************************\\n-}\\n\\n-- | Given an import\\\\/export spec, appropriately set the @gre_imp@ field\\n-- for the \'GlobalRdrElt\'s.\\ngresFromIE :: ImpDeclSpec -> (LIE GhcRn, [GlobalRdrElt]) -> [GlobalRdrElt]\\ngresFromIE decl_spec (L loc ie, gres)\\n = map set_gre_imp gres\\n where\\n is_explicit = case ie of\\n IEThingAll _ _ name _ -> \\\\n -> n == lieWrappedName name\\n IEWholeNamespace _ _ -> \\\\_ -> False\\n _ -> \\\\_ -> True\\n prov_fn name\\n = ImpSpec { is_decl = decl_spec, is_item = item_spec }\\n where\\n item_spec = ImpSome { is_explicit = is_explicit name\\n , is_iloc = locA loc }\\n set_gre_imp gre@( GRE { gre_name = nm } )\\n = gre { gre_imp = unitBag $ prov_fn nm }\\n\\nparentOfImplicitlyImportedGRE :: Outputable info => GlobalRdrEltX info -> Maybe Name\\nparentOfImplicitlyImportedGRE gre =\\n if any (explicit_import . is_item) $ gre_imp gre\\n then Nothing\\n else greParent_maybe gre\\n where\\n explicit_import :: ImpItemSpec -> Bool\\n explicit_import (ImpAll {}) =\\n pprPanic \\"parentOfImplicitlyImportedGRE: ImpAll\\" (ppr gre)\\n explicit_import (ImpSome { is_explicit }) = is_explicit\\n\\n{- Note [Children for duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider the module\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (F(foo, MkFInt, MkFBool)) where\\n data family F a\\n data instance F Int = MkFInt { foo :: Int }\\n data instance F Bool = MkFBool { foo :: Bool }\\n\\nThe `foo` in the export list refers to *both* selectors! For this\\nreason, lookupChildren builds an environment that maps the FastString\\nto a list of items, rather than a single item.\\n-}\\n\\nmkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]\\nmkChildEnv gres = foldr add emptyNameEnv gres\\n where\\n add gre env = case greParent gre of\\n ParentIs p -> extendNameEnv_Acc (:) Utils.singleton env p gre\\n NoParent -> env\\n\\nfindChildren :: NameEnv [a] -> Name -> [a]\\nfindChildren env n = lookupNameEnv env n `orElse` []\\n\\ndata LookupChildError\\n = LookupChildNotFound { lce_wrapped_name :: !(LIEWrappedName GhcPs) }\\n | LookupChildNonType { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nontype_item :: !GlobalRdrElt }\\n | LookupChildNonData { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nondata_item :: !GlobalRdrElt }\\n\\nlookupChildren :: [GlobalRdrElt]\\n -> [LIEWrappedName GhcPs]\\n -> ( [LookupChildError] -- The ones for which the lookup failed\\n , [LocatedA GlobalRdrElt] )\\n-- (lookupChildren all_kids rdr_items) maps each rdr_item to its\\n-- corresponding Name in all_kids, if the former exists\\n-- The matching is done by FastString, not OccName, so that\\n-- Cls( meth, AssocTy )\\n-- will correctly find AssocTy among the all_kids of Cls, even though\\n-- the RdrName for AssocTy may have a (bogus) DataName namespace\\n-- (Really the rdr_items should be FastStrings in the first place.)\\nlookupChildren all_kids rdr_items = (fails, successes)\\n where\\n mb_xs = map do_one rdr_items\\n fails = [ err | Failed err <- mb_xs ]\\n successes = [ ok | Succeeded oks <- mb_xs, ok <- NE.toList oks ]\\n\\n do_one :: LIEWrappedName GhcPs -> MaybeErr LookupChildError (NonEmpty (LocatedA GlobalRdrElt))\\n do_one item@(L l r) =\\n case r of\\n IEName{}\\n -- IEName (unadorned name) places no restriction on the namespace of\\n -- the imported entity, so we look in both `val_gres` and `typ_gres`.\\n -- In case of conflict (punning), the value namespace takes priority.\\n -- See Note [Prioritise the value namespace in subordinate import lists]\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEType{}\\n -- IEType (\'type\' namespace specifier) restricts the lookup to the\\n -- type namespace, i.e. to `typ_gres`. In case of failure, we check\\n -- `val_gres` to produce a more helpful error message.\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- val_gres -> Failed $ LookupChildNonType item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEData{}\\n -- IEData (\'data\' namespace specifier) restricts the lookup to the\\n -- data namespace, i.e. to `val_gres`. In case of failure, we check\\n -- `typ_gres` to produce a more helpful error message.\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- typ_gres -> Failed $ LookupChildNonData item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEPattern{} -> panic \\"lookupChildren: IEPattern\\" -- Never happens (invalid syntax)\\n IEDefault{} -> panic \\"lookupChildren: IEDefault\\" -- Never happens (invalid syntax)\\n where\\n fs = (occNameFS . rdrNameOcc . ieWrappedName) r\\n gres = fromMaybe [] (lookupFsEnv kid_env fs)\\n (val_gres, typ_gres) = partition (isValNameSpace . greNameSpace) gres\\n\\n -- See Note [Children for duplicate record fields]\\n kid_env :: FastStringEnv [GlobalRdrElt]\\n kid_env = extendFsEnvList_C (++) emptyFsEnv\\n [(occNameFS (occName x), [x]) | x <- all_kids]\\n\\n\\n{- Note [Prioritise the value namespace in subordinate import lists]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider this program that defines a class that has both an associated type\\nnamed (#) and a method named (#)\\n\\n module M_assoc where\\n class C a b where\\n type a # b\\n (#) :: a -> b -> ()\\n module N_assoc where\\n import M_assoc( C((#)) )\\n\\nIn the import declaration, when we see the unadorned name (#) in the subordinate\\nimport list of C, which children should we bring into scope? Our options are:\\n\\n a) only the method (#)\\n b) only the associated type (#)\\n c) both the method and the associated type\\n\\nTo follow the precedent established by top-level items, we go with option (a).\\nIndeed, consider a slightly different program\\n\\n module M_top where\\n type family a # b\\n a # b = ()\\n module N_top where\\n import M_top( (#) )\\n\\nHere the import brings only the function (#) into scope, and one has to say\\n`type (#)` to get the type family.\\n-}\\n\\n-------------------------------\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused names}\\n* *\\n*********************************************************\\n-}\\n\\nreportUnusedNames :: TcGblEnv -> HscSource -> RnM ()\\nreportUnusedNames gbl_env hsc_src\\n = do { keep <- readTcRef (tcg_keep gbl_env)\\n ; traceRn \\"RUN\\" (ppr (tcg_dus gbl_env))\\n ; warnUnusedImportDecls gbl_env hsc_src\\n ; warnUnusedTopBinds $ unused_locals keep\\n ; warnMissingSignatures gbl_env\\n ; warnMissingKindSignatures gbl_env }\\n where\\n used_names :: NameSet -> NameSet\\n used_names keep = findUses (tcg_dus gbl_env) emptyNameSet `unionNameSet` keep\\n -- NB: currently, if f x = g, we only treat \'g\' as used if \'f\' is used\\n -- Hence findUses\\n\\n -- Collect the defined names from the in-scope environment\\n defined_names :: [GlobalRdrElt]\\n defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)\\n\\n kids_env = mkChildEnv defined_names\\n -- This is done in mkExports too; duplicated work\\n\\n gre_is_used :: NameSet -> GlobalRdrElt -> Bool\\n gre_is_used used_names gre0\\n = name `elemNameSet` used_names\\n || any (\\\\ gre -> greName gre `elemNameSet` used_names) (findChildren kids_env name)\\n -- A use of C implies a use of T,\\n -- if C was brought into scope by T(..) or T(C)\\n where\\n name = greName gre0\\n\\n -- Filter out the ones that are\\n -- (a) defined in this module, and\\n -- (b) not defined by a \'deriving\' clause\\n -- The latter have an Internal Name, so we can filter them out easily\\n unused_locals :: NameSet -> [GlobalRdrElt]\\n unused_locals keep =\\n let -- Note that defined_and_used, defined_but_not_used\\n -- are both [GRE]; that\'s why we need defined_and_used\\n -- rather than just used_names\\n _defined_and_used, defined_but_not_used :: [GlobalRdrElt]\\n (_defined_and_used, defined_but_not_used)\\n = partition (gre_is_used (used_names keep)) defined_names\\n\\n in filter is_unused_local defined_but_not_used\\n is_unused_local :: GlobalRdrElt -> Bool\\n is_unused_local gre = isLocalGRE gre\\n && isExternalName (greName gre)\\n\\n{- *********************************************************************\\n* *\\n Missing signatures\\n* *\\n********************************************************************* -}\\n\\n{-\\nNote [Missing signatures]\\n~~~~~~~~~~~~~~~~~~~~~~~~~\\nThere are four warning flags in play:\\n\\n * -Wmissing-exported-signatures\\n Warn about any exported top-level function/value without a type signature.\\n Does not include pattern synonyms.\\n\\n * -Wmissing-signatures\\n Warn about any top-level function/value without a type signature. Does not\\n include pattern synonyms. Takes priority over -Wmissing-exported-signatures.\\n\\n * -Wmissing-exported-pattern-synonym-signatures\\n Warn about any exported pattern synonym without a type signature.\\n\\n * -Wmissing-pattern-synonym-signatures\\n Warn about any pattern synonym without a type signature. Takes priority over\\n -Wmissing-exported-pattern-synonym-signatures.\\n\\n-}\\n\\n-- | Warn the user about top level binders that lack type signatures.\\n-- Called /after/ type inference, so that we can report the\\n-- inferred type of the function\\nwarnMissingSignatures :: TcGblEnv -> RnM ()\\nwarnMissingSignatures gbl_env\\n = do { let exports = availsToNameSet (tcg_exports gbl_env)\\n sig_ns = tcg_sigs gbl_env\\n -- We use sig_ns to exclude top-level bindings that are generated by GHC\\n binds = collectHsBindsBinders CollNoDictBinders $ tcg_binds gbl_env\\n pat_syns = tcg_patsyns gbl_env\\n\\n not_ghc_generated :: Name -> Bool\\n not_ghc_generated name = name `elemNameSet` sig_ns\\n\\n add_binding_warn :: Id -> RnM ()\\n add_binding_warn id =\\n when (not_ghc_generated name) $\\n do { env <- liftZonkM $ tcInitTidyEnv -- Why not use emptyTidyEnv?\\n ; let ty = tidyOpenType env (idType id)\\n missing = MissingTopLevelBindingSig name ty\\n diag = TcRnMissingSignature missing exported\\n ; addDiagnosticAt (getSrcSpan name) diag }\\n where\\n name = idName id\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n add_patsyn_warn :: PatSyn -> RnM ()\\n add_patsyn_warn ps =\\n when (not_ghc_generated name) $\\n addDiagnosticAt (getSrcSpan name)\\n (TcRnMissingSignature missing exported)\\n where\\n name = patSynName ps\\n missing = MissingPatSynSig ps\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n -- Warn about missing signatures\\n -- Do this only when we have a type to offer\\n -- See Note [Missing signatures]\\n ; mapM_ add_binding_warn binds\\n ; mapM_ add_patsyn_warn pat_syns\\n }\\n\\n-- | Warn the user about tycons that lack kind signatures.\\n-- Called /after/ type (and kind) inference, so that we can report the\\n-- inferred kinds.\\nwarnMissingKindSignatures :: TcGblEnv -> RnM ()\\nwarnMissingKindSignatures gbl_env\\n = do { cusks_enabled <- xoptM LangExt.CUSKs\\n ; mapM_ (add_ty_warn cusks_enabled) tcs\\n }\\n where\\n tcs = tcg_tcs gbl_env\\n ksig_ns = tcg_ksigs gbl_env\\n exports = availsToNameSet (tcg_exports gbl_env)\\n\\n has_kind_signature :: Name -> Bool\\n has_kind_signature name = name `elemNameSet` ksig_ns\\n\\n add_ty_warn :: Bool -> TyCon -> RnM ()\\n add_ty_warn cusks_enabled tyCon =\\n when (has_kind_signature name) $\\n addDiagnosticAt (getSrcSpan name) diag\\n where\\n name = tyConName tyCon\\n diag = TcRnMissingSignature missing exported\\n missing = MissingTyConKindSig tyCon cusks_enabled\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused imports}\\n* *\\n*********************************************************\\n\\nThis code finds which import declarations are unused. The\\nspecification and implementation notes are here:\\n https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/unused-imports\\n\\nSee also Note [Choosing the best import declaration] in GHC.Types.Name.Reader\\n-}\\n\\ntype ImportDeclUsage\\n = ( LImportDecl GhcRn -- The import declaration\\n , [GlobalRdrElt] -- What *is* used (normalised)\\n , [Name] -- What is imported but *not* used\\n , [NamespaceSpecifier GhcRn] ) -- Unused wildcards\\n\\nwarnUnusedImportDecls :: TcGblEnv -> HscSource -> RnM ()\\nwarnUnusedImportDecls gbl_env hsc_src\\n = do { uses <- readMutVar (tcg_used_gres gbl_env)\\n ; let imports = tcg_rn_imports gbl_env\\n rdr_env = tcg_rdr_env gbl_env\\n\\n -- We should only warn for unnecessary *user* imports, but deciding\\n -- minimal imports should take generated imports into account\\n ; let usageUserImports = findImportUsage (excludeGenerated imports) uses\\n usageAllImports = findImportUsage imports uses\\n\\n ; traceRn \\"warnUnusedImportDecls\\" $\\n (vcat [ text \\"Uses:\\" <+> ppr uses\\n , text \\"Usage all user imports: \\" <+> ppr usageUserImports\\n , text \\"Usage all imports: \\" <+> ppr usageAllImports])\\n\\n ; mapM_ (warnUnusedImport rdr_env) usageUserImports\\n\\n ; whenGOptM Opt_D_dump_minimal_imports $\\n printMinimalImports hsc_src usageAllImports }\\n\\n-- | Exclude generated imports\\nexcludeGenerated :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\nexcludeGenerated = filterOut (isGeneratedImport . ideclOrigin . ideclExt . unLoc)\\n\\nfindImportUsage :: [LImportDecl GhcRn]\\n -> [GlobalRdrElt]\\n -> [ImportDeclUsage]\\n\\nfindImportUsage imports used_gres\\n = map unused_decl imports\\n where\\n import_usage :: ImportMap\\n import_usage = mkImportMap used_gres\\n\\n unused_decl :: LImportDecl GhcRn -> ImportDeclUsage\\n unused_decl decl@(L _ (ImportDecl { ideclImportList = imps }))\\n = -- pprTrace \\"unused_decl\\" (vcat [ ppr decl\\n -- , text \\"used\\" <+> ppr used_gres\\n -- , text \\"unused\\" <+> ppr unused_names ]) $\\n (decl, used_gres, unused_names, unused_wcs)\\n where\\n used_gres = lookupImportMap decl import_usage\\n\\n used_gre_env = mkGlobalRdrEnv used_gres\\n used_parents = mkNameSet (mapMaybe greParent_maybe used_gres)\\n\\n (unused_names, unused_wcs) -- Not trivial; see eg #7454\\n = case imps of\\n Just (Exactly, imp_ies) ->\\n let unused = foldr (add_unused . unLoc) emptyUnusedNames imp_ies\\n nms = nameSetElemsStable (collectUnusedNames unused)\\n wcs = collectUnusedWildcards unused\\n in (nms, wcs)\\n _other -> ([], []) -- No explicit import list => no unused-name list\\n\\n add_unused :: IE GhcRn -> UnusedNames -> UnusedNames\\n add_unused (IEVar _ n _) acc = add_unused_name (lieWrappedName n) True acc\\n add_unused (IEThingAbs _ n _) acc = add_unused_name (lieWrappedName n) False acc\\n add_unused (IEThingAll _ _ n _) acc = add_unused_all (lieWrappedName n) acc\\n add_unused (IEThingWith _ p wc ns _) acc = add_wc_all (add_unused_with pn xs acc)\\n where pn = lieWrappedName p\\n xs = map lieWrappedName ns\\n add_wc_all = case wc of\\n NoIEWildcard -> id\\n IEWildcard _ -> add_unused_all pn\\n add_unused (IEWholeNamespace x ns_spec) acc = add_unused_wildcard ns_spec (iewn_names x) acc\\n add_unused _ acc = acc\\n\\n add_unused_name :: Name -> Bool -> UnusedNames -> UnusedNames\\n add_unused_name n is_ie_var acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | is_ie_var\\n , isFieldName n\\n -- See Note [Reporting unused imported duplicate record fields]\\n = let\\n fs = getOccFS n\\n (flds, flds_used) = lookupFsEnv acc_fs fs `orElse` (emptyNameSet, Any False)\\n acc_fs\' = extendFsEnv acc_fs fs (extendNameSet flds n, Any used S.<> flds_used)\\n in UnusedNames acc_ns acc_wcs acc_fs\'\\n\\n | used\\n = acc\\n\\n | otherwise\\n = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n where\\n used = isJust $ lookupGRE_Name used_gre_env n\\n\\n add_unused_all :: Name -> UnusedNames -> UnusedNames\\n add_unused_all n acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | Just {} <- lookupGRE_Name used_gre_env n = acc\\n | n `elemNameSet` used_parents = acc\\n | otherwise = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n\\n add_unused_with :: Name -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_with p ns acc\\n | all (`elemNameSet` acc1_ns) ns = add_unused_name p False acc1\\n | otherwise = acc1\\n where\\n acc1@(UnusedNames acc1_ns _ _) = foldr (\\\\n acc\' -> add_unused_name n False acc\') acc ns\\n -- If you use \'signum\' from Num, then the user may well have\\n -- imported Num(signum). We don\'t want to complain that\\n -- Num is not itself mentioned. Hence the two cases in add_unused_with.\\n\\n add_unused_wildcard :: NamespaceSpecifier GhcRn -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_wildcard ns_spec names acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | any_used = acc\\n | otherwise = UnusedNames acc_ns (ns_spec : acc_wcs) acc_fs\\n where\\n -- A wildcard `type ..` or `data ..` is used if at least one of\\n -- the names it expands to is used\\n any_used = any (isJust . lookupGRE_Name used_gre_env) names\\n\\n\\n-- | An accumulator for unused names in an import list.\\n--\\n-- See Note [Reporting unused imported duplicate record fields].\\ndata UnusedNames =\\n UnusedNames\\n { unused_names :: NameSet\\n -- ^ Unused \'Name\'s in an import list, not including record fields\\n -- that are plain \'IEVar\' imports (tracked by \'rec_fld_uses\')\\n -- or wildcard imports (tracked by \'unused_wildcards\').\\n , unused_wildcards :: [NamespaceSpecifier GhcRn]\\n -- ^ Unused wildcards @type ..@ or @data ..@ in an import list.\\n , rec_fld_uses :: FastStringEnv (NameSet, Any)\\n -- ^ Record fields imported without a parent (i.e. an \'IEVar\' import).\\n --\\n -- The \'Any\' value records whether any of the record fields\\n -- sharing the same underlying \'FastString\' have been used.\\n }\\n\\nemptyUnusedNames :: UnusedNames\\nemptyUnusedNames = UnusedNames emptyNameSet [] emptyFsEnv\\n\\ninstance Outputable UnusedNames where\\n ppr (UnusedNames nms wcs flds) =\\n text \\"UnusedNames\\" <+>\\n braces (ppr nms <+> ppr wcs <+> ppr (fmap (second getAny) flds))\\n\\n-- | Collect all unused names from a \'UnusedNames\' value.\\ncollectUnusedNames :: UnusedNames -> NameSet\\ncollectUnusedNames (UnusedNames { unused_names = nms, rec_fld_uses = flds })\\n = nms S.<> unused_flds\\n where\\n unused_flds = nonDetFoldFsEnv collect_unused emptyNameSet flds\\n collect_unused :: (NameSet, Any) -> NameSet -> NameSet\\n collect_unused (nms, Any at_least_one_name_is_used) acc\\n | at_least_one_name_is_used = acc\\n | otherwise = unionNameSet nms acc\\n\\ncollectUnusedWildcards :: UnusedNames -> [NamespaceSpecifier GhcRn]\\ncollectUnusedWildcards = unused_wildcards\\n\\n{- Note [Reporting unused imported duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have (#24035):\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M1 (R1(..), R2(..)) where\\n data R1 = MkR1 { fld :: Int }\\n data R2 = MkR2 { fld :: Int }\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M2 where\\n import M1 (R1(MkR1), R2, fld)\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nIn the import of \'M1\' in \'M2\', the \'fld\' import resolves to two separate GREs,\\nnamely R1(fld) and R2(fld). From the perspective of the renamer, and in particular\\nthe \'findImportUsage\' function, it\'s as if the user had imported the two names\\nseparately (even though no source syntax allows that).\\n\\nThis means that we need to be careful when reporting unused imports: the R2(fld)\\nimport is indeed unused, but because R1(fld) is used, we should not report\\nfld as unused altogether.\\n\\nTo achieve this, we keep track of record field imports without a parent (i.e.\\nusing the IEVar constructor) separately from other import items, using the\\nUnusedNames datatype.\\nOnce we have accumulated usages, we emit warnings for unused record fields\\nwithout parents one whole group (of record fields sharing the same textual name)\\nat a time, and only if *all* of the record fields in the group are unused;\\nsee \'collectUnusedNames\'.\\n\\nNote that this only applies to record fields imported without a parent. If we\\nhad:\\n\\n import M1 (R1(MkR1, fld), R2(fld))\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nthen of course we should report the second \'fld\' as unused.\\n-}\\n\\n\\n{- Note [The ImportMap]\\n~~~~~~~~~~~~~~~~~~~~~~~\\nThe ImportMap is a short-lived intermediate data structure records, for\\neach import declaration, what stuff brought into scope by that\\ndeclaration is actually used in the module.\\n\\nThe [GlobalRdrElt] are the things imported from that decl.\\n-}\\n\\ndata ImportMap = ImportMap\\n { im_imports :: Map RealSrcSpan [GlobalRdrElt]\\n -- ^ See [The ImportMap]\\n -- If loc :-> gres, then\\n -- \'loc\' = the end loc of the bestImport of each GRE in \'gres\'\\n , im_generatedImports :: Map ModuleName [GlobalRdrElt]\\n }\\n\\nmkImportMap :: [GlobalRdrElt] -> ImportMap\\n-- For each of a list of used GREs, find all the import decls that brought\\n-- it into scope; choose one of them (bestImport), and record\\n-- the RdrName in that import decl\'s entry in the ImportMap\\nmkImportMap = foldr insertImportMap $ ImportMap Map.empty Map.empty\\n\\ninsertImportMap :: GlobalRdrElt -> ImportMap -> ImportMap\\ninsertImportMap gre@(GRE { gre_imp = imp_specs }) importMap\\n | RealSrcSpan importSpan _ <- is_dloc best_imp_spec =\\n importMap{im_imports = insertElem importSpan gre $ im_imports importMap}\\n | GeneratedSrcSpan{} <- is_dloc best_imp_spec =\\n importMap{im_generatedImports = insertElem (moduleName $ is_mod best_imp_spec) gre $ im_generatedImports importMap}\\n | otherwise = importMap\\n where\\n best_imp_spec =\\n case bagToList imp_specs of\\n [] -> pprPanic \\"mkImportMap: GRE with no ImportSpecs\\" (ppr gre)\\n is:iss -> is_decl $ bestImport (is NE.:| iss)\\n\\n -- https://github.com/haskell/containers/issues/784\\n insertElem :: Ord k => k -> v -> Map k [v] -> Map k [v]\\n insertElem k v = flip Map.alter k $ \\\\case\\n Just vs -> Just (v : vs)\\n Nothing -> Just [v]\\n\\nlookupImportMap :: LImportDecl GhcRn -> ImportMap -> [GlobalRdrElt]\\nlookupImportMap (L srcSpan ImportDecl{ideclName = L _ modName}) importMap =\\n fromMaybe [] $\\n -- should match logic in insertImportMap\\n case locA srcSpan of\\n RealSrcSpan realSrcSpan _ -> realSrcSpan `Map.lookup` im_imports importMap\\n GeneratedSrcSpan{} -> modName `Map.lookup` im_generatedImports importMap\\n _ -> Nothing\\n\\nlieNames :: LIE (GhcPass p) -> [Located (IdP (GhcPass p))]\\nlieNames = _\\n\\nwarnUnusedImport :: GlobalRdrEnv -> ImportDeclUsage -> RnM ()\\nwarnUnusedImport rdr_env (L loc decl, used, unused, unused_wcs)\\n\\n -- Do not warn for \'import M()\'\\n -- See (UI1) in Note [Unused imports]\\n | Just (Exactly, _) <- ideclImportList decl\\n , null unused && null unused_wcs\\n = return ()\\n\\n -- Note [Do not warn about Prelude hiding]\\n | Just (EverythingBut, hides) <- ideclImportList decl\\n , not (null hides)\\n , pRELUDE_NAME == unLoc (ideclName decl)\\n = return ()\\n\\n -- Do not warn about import X as Rebindable\\n -- See (UI2) in Note [Unused imports]\\n | Just (L _ mod) <- ideclAs decl\\n , mod == rEBINDABLE_MOD_NAME\\n = return ()\\n\\n -- Nothing used; drop entire declaration\\n | null used\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl UnusedImportNone)\\n\\n -- Everything imported is used; nop\\n | null unused && null unused_wcs\\n = return ()\\n\\n -- Some imports are unused: make the `SrcSpan` cover only the unused\\n -- items instead of the whole import statement\\n | Just (_, imports) <- ideclImportList decl\\n , let unused_locs = [ locA loc | L loc ie <- imports\\n , name <- ieNames ie\\n , name `elem` unused ]\\n , loc1 : locs <- unused_locs\\n , let span = foldr1 combineSrcSpans ( loc1 NE.:| locs )\\n = addDiagnosticAt span (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n -- Some imports are unused\\n | otherwise\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n where\\n -- In warning message, pretty-print identifiers unqualified unconditionally\\n -- to improve the consistent for ambiguous/unambiguous identifiers.\\n -- See #14881.\\n possible_field n =\\n case lookupGRE_Name rdr_env n of\\n Just (GRE { gre_par = par, gre_info = IAmRecField info }) ->\\n let fld_occ :: OccName\\n fld_occ = nameOccName $ flSelector $ recFieldLabel info\\n in UnusedImportNameRecField par fld_occ\\n _ -> UnusedImportNameRegular n\\n\\n -- Print unused names in a deterministic (lexicographic) order\\n sort_unused :: [UnusedImportName]\\n sort_unused =\\n [ UnusedImportWildcard wc | wc <- unused_wcs ] ++\\n [ possible_field nm | nm <- sortBy (comparing nameOccName) unused ]\\n\\ngetMinimalImports :: [ImportDeclUsage] -> RnM [LImportDecl GhcRn]\\ngetMinimalImports ie_decls\\n = do { rdr_env <- getGlobalRdrEnv\\n ; fmap combine $ mapM (mk_minimal rdr_env) ie_decls }\\n where\\n mk_minimal rdr_env (L l decl, used_gres, unused, unused_wcs)\\n | null unused && null unused_wcs\\n , Just (Exactly, _) <- ideclImportList decl\\n = return (L l decl)\\n | otherwise\\n = do { let ImportDecl { ideclName = L _ mod_name\\n , ideclSource = is_boot\\n , ideclPkgQual = pkg_qual\\n , ideclExt = XImportDeclPass { ideclOrigin = origin } } = decl\\n ; iface <- loadSrcInterface doc (importDeclLookupScope origin)\\n mod_name is_boot pkg_qual\\n ; let used_avails = gresToAvailInfo used_gres\\n ; lies <- map (L l) <$> concatMapM (to_ie rdr_env iface) used_avails\\n ; return (L l (decl { ideclImportList = Just (Exactly, lies) })) }\\n where\\n doc = text \\"Compute minimal imports for\\" <+> ppr decl\\n\\n to_ie :: GlobalRdrEnv -> ModIface -> AvailInfo -> RnM [IE GhcRn]\\n -- The main trick here is that if we\'re importing all the constructors\\n -- we want to say \\"T(..)\\", but if we\'re importing only a subset we want\\n -- to say \\"T(A,B,C)\\". So we have to find out what the module exports.\\n to_ie rdr_env _ (Avail c) -- Note [Overloaded field import]\\n = do { let\\n gre = expectJust $ lookupGRE_Name rdr_env c\\n ; return $ [IEVar Nothing (to_ie_post_rn $ noLocA $ greName gre) Nothing] }\\n to_ie _ _ avail@(AvailTC n [_]) -- Exporting the main decl and nothing else\\n | availExportsDecl avail\\n = return [IEThingAbs Nothing (to_ie_post_rn $ noLocA n) Nothing]\\n to_ie rdr_env iface (AvailTC n cs) =\\n case [ xs | avail@(AvailTC x xs) <- mi_exports iface\\n , x == n\\n , availExportsDecl avail -- Note [Partial export]\\n ] of\\n [xs]\\n | all_used xs\\n -> return [IEThingAll (IEThingAllExt Nothing noAnn noAnn noAnn)\\n (NoNamespaceSpecifier noExtField)\\n (to_ie_post_rn $ noLocA n)\\n Nothing]\\n | otherwise\\n -> do { let ns_gres = map (expectJust . lookupGRE_Name rdr_env) cs\\n ns = map greName ns_gres\\n ; return [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n -- Note [Overloaded field import]\\n _other\\n -> do { let infos = map (expectJust . lookupGRE_Name rdr_env) cs\\n (ns_gres,fs_gres) = classifyGREs infos\\n ns = map greName (ns_gres ++ fs_gres)\\n fs = map fieldGREInfo fs_gres\\n ; return $\\n if all_non_overloaded fs\\n then map (\\\\nm -> IEVar Nothing (to_ie_post_rn_var $ noLocA nm) Nothing) ns\\n else [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n where\\n\\n all_used avail_cs = all (`elem` cs) avail_cs\\n\\n all_non_overloaded = all (not . flIsOverloaded . recFieldLabel)\\n\\n combine :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\n combine = map merge . NE.groupAllWith getKey\\n\\n getKey :: LImportDecl GhcRn -> (Bool, Maybe ModuleName, ModuleName)\\n getKey decl =\\n ( isImportDeclQualified . ideclQualified $ idecl -- is this qualified? (important that this be first)\\n , unLoc <$> ideclAs idecl -- what is the qualifier (inside Maybe monad)\\n , unLoc . ideclName $ idecl -- Module Name\\n )\\n where\\n idecl :: ImportDecl GhcRn\\n idecl = unLoc decl\\n\\n merge :: NonEmpty (LImportDecl GhcRn) -> LImportDecl GhcRn\\n merge decls@((L l decl) :| _) = L l (decl { ideclImportList = Just (Exactly, lies) })\\n where lies = concatMap snd $ mapMaybe (ideclImportList . unLoc) $ NE.toList decls\\n\\nclassifyGREs :: [GlobalRdrElt] -> ([GlobalRdrElt], [FieldGlobalRdrElt])\\nclassifyGREs = partition (not . isRecFldGRE)\\n\\nprintMinimalImports :: HscSource -> [ImportDeclUsage] -> RnM ()\\n-- See Note [Printing minimal imports]\\nprintMinimalImports hsc_src imports_w_usage\\n = do { imports\' <- excludeGenerated <$> getMinimalImports imports_w_usage\\n ; this_mod <- getModule\\n ; dflags <- getDynFlags\\n ; liftIO $ withFile (mkFilename dflags this_mod) WriteMode $ \\\\h ->\\n printForUser dflags h neverQualify AllTheWay (vcat (map ppr imports\'))\\n -- The neverQualify is important. We are printing Names\\n -- but they are in the context of an \'import\' decl, and\\n -- we never qualify things inside there\\n -- E.g. import Blag( f, b )\\n -- not import Blag( Blag.f, Blag.g )!\\n }\\n where\\n mkFilename dflags this_mod\\n | Just d <- dumpDir dflags = d basefn\\n | otherwise = basefn\\n where\\n suffix = case hsc_src of\\n HsBootFile -> \\".imports-boot\\"\\n HsSrcFile -> \\".imports\\"\\n HsigFile -> \\".imports\\"\\n basefn = moduleNameString (moduleName this_mod) ++ suffix\\n\\n\\nto_ie_post_rn_var :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn_var (L l n)\\n | isDataOcc $ occName n = L l (IEPattern noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n\\n\\nto_ie_post_rn :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn (L l n)\\n | isTcOcc occ && isSymOcc occ = L l (IEType noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n where occ = occName n\\n\\n{- Note [Do not warn about Prelude hiding]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWe do not warn about\\n import Prelude hiding( x, y )\\nbecause even if nothing else from Prelude is used, it may be essential to hide\\nx,y to avoid name-shadowing warnings. Example (#9061)\\n import Prelude hiding( log )\\n f x = log where log = ()\\n\\nNote [Unused imports]\\n~~~~~~~~~~~~~~~~~~~~~\\nIn `warnUnusedImport`, if we see an import with an explicit list imports, thus\\n import M( a, b )\\nand neither `a` nor `b` is used, we report the entire import decl as unused. We\\ncheck this by looking at the names that it brings into scope scope; if there are\\nno ununused names, don\'t report.\\n\\n(UI1) We don\'t want to complain about `import M()`, because that is often used to bring\\n M\'s /instances/ into scope. That is neatly dealt with by the \\"no unused\\n names\\" (nor unused wildcard imports) criterion.\\n\\n(UI2) We don\'t report a decl as unused if it has an `as Rebindable` qualifier.\\n See (KN1) in Note [Overview of known entities] in GHC.Builtin\\n\\n\\nNote [Printing minimal imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nTo print the minimal imports we walk over all import decls (both user-supplied\\nand generated), trim their import lists, then filter out generated decls.\\n\\nNB that\\n\\n * We do *not* change the \'qualified\' or \'as\' parts!\\n\\n * We do not discard a decl altogether; we might need instances\\n from it. Instead we just trim to an empty import list\\n\\nNote [Partial export]\\n~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have\\n\\n module A( op ) where\\n class C a where\\n op :: a -> a\\n\\n module B where\\n import A\\n f = ..op...\\n\\nThen the minimal import for module B is\\n import A( op )\\nnot\\n import A( C( op ) )\\nwhich we would usually generate if C was exported from B. Hence\\nthe availExportsDecl test when deciding what to generate.\\n\\n\\nNote [Overloaded field import]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nOn the other hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n data T = MkT { foo :: Int }\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( T(foo) )\\nbecause when DuplicateRecordFields is enabled, field selectors are\\nnot in scope without their enclosing datatype.\\n\\nOn the third hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n pattern MkT { foo } = Just foo\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( foo )\\nbecause foo doesn\'t have a parent. This might actually be ambiguous if A\\nexports another field called foo, but there is no good answer to return and this\\nis a very obscure corner, so it seems to be the best we can do. See\\nDRFPatSynExport for a test of this.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Errors}\\n* *\\n************************************************************************\\n-}\\n\\nbadImportItemErr\\n :: ModIface -> ImpDeclSpec -> IE GhcPs\\n -> IsSubordinateError\\n -> [AvailInfo]\\n -> TcRn (NonEmpty ImportLookupReason)\\nbadImportItemErr iface decl_spec ie sub avails = do\\n exts <- importLookupExtensions\\n let import_lookup_bad :: BadImportKind -> ImportLookupReason\\n import_lookup_bad k = ImportLookupBad k iface decl_spec ie exts\\n dflags <- getDynFlags\\n hsc_env <- getTopEnv\\n let rdr_env = mkGlobalRdrEnv\\n $ gresFromAvails hsc_env (Just imp_spec) all_avails\\n pure $ fmap import_lookup_bad (importErrorKind dflags rdr_env)\\n where\\n importErrorKind :: DynFlags -> GlobalRdrEnv -> NonEmpty BadImportKind\\n importErrorKind dflags rdr_env\\n | any checkIfTyCon avails = case sub of\\n IsNotSubordinate -> NE.singleton BadImportAvailTyCon\\n IsSubordinateError { subordinate_err_parent = gre\\n , subordinate_err_unavailable = unavailable\\n , subordinate_err_nontype = nontype\\n , subordinate_err_nondata = nondata }\\n -> NE.fromList $ catMaybes $\\n [ fmap (BadImportNotExportedSubordinates gre) (NE.nonEmpty unavailable)\\n , fmap (BadImportNonTypeSubordinates gre) (NE.nonEmpty nontype)\\n , fmap (BadImportNonDataSubordinates gre) (NE.nonEmpty nondata) ]\\n | any checkIfVarName avails = NE.singleton BadImportAvailVar\\n | Just con <- find checkIfDataCon avails = NE.singleton (BadImportAvailDataCon (availOccName con))\\n | otherwise = NE.singleton (BadImportNotExported suggs)\\n where\\n suggs = similar_suggs ++ fieldSelectorSuggestions rdr_env rdr\\n what_look = case sub of\\n IsNotSubordinate -> WL_TyCon_or_TermVar\\n IsSubordinateError { subordinate_err_parent = gre } ->\\n case greInfo gre of\\n IAmTyCon ClassFlavour\\n -> WL_TyCon_or_TermVar\\n _ -> WL_Term\\n similar_names =\\n similarNameSuggestions (Unbound.LF what_look WL_Global)\\n dflags rdr_env emptyLocalRdrEnv rdr\\n similar_suggs =\\n case NE.nonEmpty $ mapMaybe imported_item $ similar_names of\\n Just similar -> [ SuggestSimilarNames rdr similar ]\\n Nothing -> [ ]\\n\\n -- Only keep imported items, and set the \\"HowInScope\\" to\\n -- \\"Nothing\\" to avoid printing \\"imported from...\\" in the suggestion\\n -- error message.\\n imported_item (SimilarRdrName rdr_name gre (Just (ImportedBy {})))\\n = Just (SimilarRdrName rdr_name gre Nothing)\\n imported_item _ = Nothing\\n\\n checkIfDataCon = checkIfAvailMatches isDataConName\\n checkIfTyCon = checkIfAvailMatches isTyConName\\n checkIfVarName =\\n \\\\case\\n AvailTC{} -> False\\n Avail n -> importedFS == occNameFS (occName n)\\n && (isVarOcc <||> isFieldOcc) (occName n)\\n checkIfAvailMatches namePred =\\n \\\\case\\n AvailTC _ ns ->\\n case find (\\\\n -> importedFS == occNameFS (occName n)) ns of\\n Just n -> namePred n\\n Nothing -> False\\n Avail{} -> False\\n availOccName = occName . availName\\n rdr = ieName ie\\n importedFS = occNameFS $ rdrNameOcc rdr\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n all_avails = mi_exports iface\\n\\nimportLookupExtensions :: TcRn ImportLookupExtensions\\nimportLookupExtensions = do\\n ile_pattern_synonyms <- xoptM LangExt.PatternSynonyms\\n ile_explicit_namespaces <- xoptM LangExt.ExplicitNamespaces\\n return ImportLookupExtensions{ile_pattern_synonyms, ile_explicit_namespaces}\\n\\naddDupDeclErr :: NonEmpty GlobalRdrElt -> TcRn ()\\naddDupDeclErr gres@(gre :| _)\\n -- Report the error at the later location\\n = addErrAt (getSrcSpan (NE.last sorted_names)) $ (TcRnDuplicateDecls (greOccName gre) sorted_names)\\n where\\n sorted_names =\\n NE.sortBy (SrcLoc.leftmost_smallest `on` nameSrcSpan)\\n (fmap greName gres)\\n\\n-- This data decl will parse OK\\n-- data T = a Int\\n-- treating \\"a\\" as the constructor.\\n-- It is really hard to make the parser spot this malformation.\\n-- So the renamer has to check that the constructor is legal\\n--\\n-- We can get an operator as the constructor, even in the prefix form:\\n-- data T = :% Int Int\\n-- from interface files, which always print in prefix form\\n--\\n-- We also allow type constructor names, which are defined by \\"type data\\"\\n-- declarations. See Note [Type data declarations] in GHC.Rename.Module.\\n\\ncheckConName :: RdrName -> TcRn ()\\ncheckConName name\\n = checkErr (isRdrDataCon name || isRdrTc name) (TcRnIllegalDataCon name)\\n", "filetypes": ["haskell"]}}}' 2026-10-16 14:47:31,221 - DEBUG - POST b'http://127.0.0.1:37093/receive_messages' {'content-type': 'application/json', 'x-ycm-hmac': b'Rga7Yd4l4fgfufwYw+0sxzurvznImlBO0MPmgAlS4EY='} b'{"filepath": "/home/enrico/ghc/compiler/GHC/Rename/Names.hs", "line_num": 1, "column_num": 1, "working_dir": "/home/enrico/ghc", "file_data": {"/home/enrico/ghc/compiler/GHC/Rename/Names.hs": {"contents": "{-\\n(c) The GRASP/AQUA Project, Glasgow University, 1992-1998\\n\\nExtracting imported and top-level names in scope\\n-}\\n\\n{-# LANGUAGE NondecreasingIndentation #-}\\n{-# LANGUAGE TypeFamilies #-}\\n\\nmodule GHC.Rename.Names (\\n rnImports, getLocalNonValBinders, newRecordFieldLabel,\\n importsFromIface,\\n ImportUserSpec(..),\\n extendGlobalRdrEnvRn,\\n gresFromAvails,\\n calculateAvails,\\n reportUnusedNames,\\n checkConName,\\n mkChildEnv,\\n findChildren,\\n mkBadExportSubordinate,\\n findImportUsage,\\n getMinimalImports,\\n printMinimalImports,\\n renamePkgQual, renameRawPkgQual,\\n classifyGREs,\\n ImportDeclUsage,\\n rnNamespaceSpecifier\\n ) where\\n\\nimport GHC.Prelude hiding ( head, init, last, tail )\\n\\nimport GHC.Driver.Env\\nimport GHC.Driver.Session\\nimport GHC.Driver.Ppr\\n\\nimport GHC.Rename.Env\\nimport GHC.Rename.Fixity\\nimport GHC.Rename.Utils ( warnUnusedTopBinds )\\nimport GHC.Rename.Unbound\\nimport qualified GHC.Rename.Unbound as Unbound\\n\\nimport GHC.Tc.Errors.Types\\nimport GHC.Tc.Utils.Env\\nimport GHC.Tc.Utils.Monad\\nimport GHC.Tc.Types.LclEnv\\nimport GHC.Tc.Zonk.TcType ( tcInitTidyEnv )\\n\\nimport GHC.Hs\\nimport GHC.Iface.Load ( loadSrcInterface, loadSrcInterface_maybe )\\nimport GHC.Iface.Errors.Types\\n ( IfaceMessage(..), MissingInterfaceError, InterfaceLookingFor(..)\\n , LoadEssentialsReason(..) )\\nimport GHC.Iface.Syntax ( fromIfaceWarnings )\\nimport GHC.Builtin.Modules( pRELUDE_NAME, rEBINDABLE_MOD_NAME )\\nimport GHC.Parser.PostProcess ( setRdrNameSpace )\\nimport GHC.Core.TyCo.Tidy\\nimport GHC.Core.PatSyn\\nimport GHC.Core.TyCon ( TyCon, tyConName )\\nimport qualified GHC.LanguageExtensions as LangExt\\n\\nimport GHC.Utils.Outputable as Outputable\\nimport GHC.Utils.Misc as Utils\\nimport GHC.Utils.Panic\\n\\nimport GHC.Types.Fixity.Env\\nimport GHC.Types.SafeHaskell\\nimport GHC.Types.Name\\nimport GHC.Types.Name.Env\\nimport GHC.Types.Name.Set\\nimport GHC.Types.Name.Reader\\nimport GHC.Types.Avail\\nimport GHC.Types.FieldLabel\\nimport GHC.Types.Hint\\nimport GHC.Types.SourceFile\\nimport GHC.Types.SrcLoc as SrcLoc\\nimport GHC.Types.Basic (TyConFlavour (..), convImportLevel, VisArity)\\nimport GHC.Types.UnresolvedImport\\nimport GHC.Types.Id\\nimport GHC.Types.PkgQual\\nimport GHC.Types.GREInfo (ConInfo(..), ConFieldInfo (..), ConLikeInfo (ConIsData))\\n\\nimport GHC.Unit\\nimport GHC.Unit.Module.Warnings\\nimport GHC.Unit.Module.ModIface\\nimport GHC.Unit.Module.Imported\\nimport GHC.Unit.Module.Deps\\nimport GHC.Unit.Env\\n\\nimport GHC.Data.Bag\\nimport GHC.Data.FastString\\nimport GHC.Data.FastString.Env\\nimport GHC.Data.Maybe\\nimport GHC.Data.List.SetOps ( removeDups )\\n\\nimport Control.Arrow ( second )\\nimport Control.Monad\\nimport Data.Foldable ( for_ )\\nimport Data.IntMap ( IntMap )\\nimport qualified Data.IntMap as IntMap\\nimport Data.Map ( Map )\\nimport qualified Data.Map as Map\\nimport Data.Ord ( comparing )\\nimport Data.Semigroup ( Any(..) )\\nimport qualified Data.Semigroup as S\\nimport Data.List ( partition, find, sortBy )\\nimport Data.List.NonEmpty (NonEmpty(..))\\nimport qualified Data.List.NonEmpty as NE\\nimport Data.Function ( on )\\nimport qualified Data.Set as S\\nimport System.FilePath (())\\nimport System.IO\\n\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{rnImports}\\n* *\\n************************************************************************\\n\\nNote [Tracking Trust Transitively]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen we import a package as well as checking that the direct imports are safe\\naccording to the rules outlined in the Note [Safe Haskell Trust Check] in GHC.Driver.Main\\nwe must also check that these rules hold transitively for all dependent modules\\nand packages. Doing this without caching any trust information would be very\\nslow as we would need to touch all packages and interface files a module depends\\non. To avoid this we make use of the property that if a modules Safe Haskell\\nmode changes, this triggers a recompilation from that module in the dependency\\ngraph. So we can just worry mostly about direct imports.\\n\\nThere is one trust property that can change for a package though without\\nrecompilation being triggered: package trust. So we must check that all\\npackages a module transitively depends on to be trusted are still trusted when\\nwe are compiling this module (as due to recompilation avoidance some modules\\nbelow may not be considered trusted any more without recompilation being\\ntriggered).\\n\\nWe handle this by augmenting the existing transitive list of packages a module M\\ndepends on with a bool for each package that says if it must be trusted when the\\nmodule M is being checked for trust. This list of trust required packages for a\\nsingle import is gathered in the rnImportDecl function and stored in an\\nImportAvails data structure. The union of these trust required packages for all\\nimports is done by the rnImports function using the combine function which calls\\nthe plusImportAvails function that is a union operation for the ImportAvails\\ntype. This gives us in an ImportAvails structure all packages required to be\\ntrusted for the module we are currently compiling. Checking that these packages\\nare still trusted (and that direct imports are trusted) is done in\\nGHC.Driver.Main.checkSafeImports.\\n\\nSee the note below, [Trust Own Package] for a corner case in this method and\\nhow its handled.\\n\\n\\nNote [Trust Own Package]\\n~~~~~~~~~~~~~~~~~~~~~~~~\\nThere is a corner case of package trust checking that the usual transitive check\\ndoesn\'t cover. (For how the usual check operates see the Note [Tracking Trust\\nTransitively] below). The case is when you import a -XSafe module M and M\\nimports a -XTrustworthy module N. If N resides in a different package than M,\\nthen the usual check works as M will record a package dependency on N\'s package\\nand mark it as required to be trusted. If N resides in the same package as M\\nthough, then importing M should require its own package be trusted due to N\\n(since M is -XSafe so doesn\'t create this requirement by itself). The usual\\ncheck fails as a module doesn\'t record a package dependency of its own package.\\nSo instead we now have a bool field in a modules interface file that simply\\nstates if the module requires its own package to be trusted. This field avoids\\nus having to load all interface files that the module depends on to see if one\\nis trustworthy.\\n\\n\\nNote [Trust Transitive Property]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSo there is an interesting design question in regards to transitive trust\\nchecking. Say I have a module B compiled with -XSafe. B is dependent on a bunch\\nof modules and packages, some packages it requires to be trusted as its using\\n-XTrustworthy modules from them. Now if I have a module A that doesn\'t use safe\\nhaskell at all and simply imports B, should A inherit all the trust\\nrequirements from B? Should A now also require that a package p is trusted since\\nB required it?\\n\\nWe currently say no but saying yes also makes sense. The difference is, if a\\nmodule M that doesn\'t use Safe Haskell imports a module N that does, should all\\nthe trusted package requirements be dropped since M didn\'t declare that it cares\\nabout Safe Haskell (so -XSafe is more strongly associated with the module doing\\nthe importing) or should it be done still since the author of the module N that\\nuses Safe Haskell said they cared (so -XSafe is more strongly associated with\\nthe module that was compiled that used it).\\n\\nGoing with yes is a simpler semantics we think and harder for the user to stuff\\nup but it does mean that Safe Haskell will affect users who don\'t care about\\nSafe Haskell as they might grab a package from Cabal which uses safe haskell (say\\nnetwork) and that packages imports -XTrustworthy modules from another package\\n(say bytestring), so requires that package is trusted. The user may now get\\ncompilation errors in code that doesn\'t do anything with Safe Haskell simply\\nbecause they are using the network package. They will have to call \'ghc-pkg\\ntrust network\' to get everything working. Due to this invasive nature of going\\nwith yes we have gone with no for now.\\n-}\\n\\n-- | Process Import Decls. See \'rnImportDecl\' for a description of what\\n-- the return types represent.\\n-- Note: Do the non SOURCE ones first, so that we get a helpful warning\\n-- for SOURCE ones that are unnecessary\\nrnImports :: [(LImportDecl GhcPs, SDoc)]\\n -> RnM ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\nrnImports imports = do\\n tcg_env <- getGblEnv\\n -- NB: want an identity module here, because it\'s OK for a signature\\n -- module to import from its implementor\\n let this_mod = tcg_mod tcg_env\\n let (source, ordinary) = partition (is_source_import . fst) imports\\n is_source_import (d::LImportDecl GhcPs) = ideclSource (unLoc d) == IsBoot\\n stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary\\n stuff2 <- mapAndReportM (rnImportDecl this_mod) source\\n -- Safe Haskell: See Note [Tracking Trust Transitively]\\n let (decls, imp_user_spec, rdr_env, imp_avails) = combine (stuff1 ++ stuff2)\\n -- Update imp_boot_mods if imp_direct_mods mentions any of them\\n let merged_import_avail = clobberSourceImports imp_avails\\n return (decls, imp_user_spec, rdr_env, merged_import_avail)\\n\\n where\\n clobberSourceImports imp_avails =\\n imp_avails { imp_boot_mods = imp_boot_mods\' }\\n where\\n imp_boot_mods\' = mergeInstalledModuleEnv combJ id (const emptyInstalledModuleEnv)\\n (imp_boot_mods imp_avails)\\n (imp_direct_dep_mods imp_avails)\\n\\n combJ (GWIB _ IsBoot) (_, x) = Just x\\n combJ r _ = Just r\\n -- See Note [Combining ImportAvails]\\n combine :: [(LImportDecl GhcRn, ImportUserSpec, GlobalRdrEnv, ImportAvails)]\\n -> ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\n combine ss =\\n let (decls, imp_user_spec, rdr_env, imp_avails, finsts) = foldr\\n plus\\n ([], [], emptyGlobalRdrEnv, emptyImportAvails, emptyModuleSet)\\n ss\\n in (decls, imp_user_spec, rdr_env, imp_avails { imp_finsts = moduleSetElts finsts })\\n\\n plus (decl, us, gbl_env1, imp_avails1)\\n (decls, uss, gbl_env2, imp_avails2, finsts_set)\\n = ( decl:decls,\\n us:uss,\\n gbl_env1 `plusGlobalRdrEnv` gbl_env2,\\n imp_avails1\' `plusImportAvails` imp_avails2,\\n extendModuleSetList finsts_set new_finsts )\\n where\\n imp_avails1\' = imp_avails1 { imp_finsts = [] }\\n new_finsts = imp_finsts imp_avails1\\n\\n{-\\nNote [Combining ImportAvails]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nimp_finsts in ImportAvails is a list of family instance modules\\ntransitively depended on by an import. imp_finsts for a currently\\ncompiled module is a union of all the imp_finsts of imports.\\nComputing the union of two lists of size N is O(N^2) and if we\\ndo it to M imports we end up with O(M*N^2). That can get very\\nexpensive for bigger module hierarchies.\\n\\nUnion can be optimized to O(N log N) if we use a Set.\\nimp_finsts is converted back and forth between dep_finsts, so\\nchanging a type of imp_finsts means either paying for the conversions\\nor changing the type of dep_finsts as well.\\n\\nI\'ve measured that the conversions would cost 20% of allocations on my\\ntest case, so that can be ruled out.\\n\\nChanging the type of dep_finsts forces checkFamInsts to\\nget the module lists in non-deterministic order. If we wanted to restore\\nthe deterministic order, we\'d have to sort there, which is an additional\\ncost. As far as I can tell, using a non-deterministic order is fine there,\\nbut that\'s a brittle nonlocal property which I\'d like to avoid.\\n\\nAdditionally, dep_finsts is read from an interface file, so its \\"natural\\"\\ntype is a list. Which makes it a natural type for imp_finsts.\\n\\nSince rnImports.combine is really the only place that would benefit from\\nit being a Set, it makes sense to optimize the hot loop in rnImports.combine\\nwithout changing the representation.\\n\\nSo here\'s what we do: instead of naively merging ImportAvails with\\nplusImportAvails in a loop, we make plusImportAvails merge empty imp_finsts\\nand compute the union on the side using Sets. When we\'re done, we can\\nconvert it back to a list. One nice side effect of this approach is that\\nif there\'s a lot of overlap in the imp_finsts of imports, the\\nSet doesn\'t really need to grow and we don\'t need to allocate.\\n\\nRunning generateModules from #14693 with DEPTH=16, WIDTH=30 finishes in\\n23s before, and 11s after.\\n-}\\n\\n-- | Given a located import declaration @decl@ from @this_mod@,\\n-- calculate the following pieces of information:\\n--\\n-- 1. An updated \'LImportDecl\', where all unresolved \'RdrName\' in\\n-- the entity lists have been resolved into \'Name\'s,\\n--\\n-- 2. A \'GlobalRdrEnv\' representing the new identifiers that were\\n-- brought into scope (taking into account module qualification\\n-- and hiding),\\n--\\n-- 3. \'ImportAvails\' summarizing the identifiers that were imported\\n-- by this declaration, and\\n--\\n-- 4. A boolean \'AnyHpcUsage\' which is true if the imported module\\n-- used HPC.\\nrnImportDecl :: Module -> (LImportDecl GhcPs, SDoc)\\n -> RnM (LImportDecl GhcRn, ImportUserSpec , GlobalRdrEnv, ImportAvails)\\nrnImportDecl this_mod\\n (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name\\n , ideclPkgQual = raw_pkg_qual\\n , ideclSource = want_boot\\n , ideclSafe = mod_safe\\n , ideclLevelSpec = import_level\\n , ideclQualified = qual_style\\n , ideclExt = XImportDeclPass { ideclOrigin = origin }\\n , ideclAs = as_mod, ideclImportList = imp_details }), import_reason)\\n = setSrcSpanA loc $ do\\n\\n case raw_pkg_qual of\\n NoRawPkgQual -> pure ()\\n RawPkgQual {} -> do\\n pkg_imports <- xoptM LangExt.PackageImports\\n when (not pkg_imports) $ addErr TcRnPackageImportsDisabled\\n\\n let qual_only = isImportDeclQualified qual_style\\n generated = isGeneratedImport origin\\n\\n lookup_scope = importDeclLookupScope origin\\n\\n -- If there\'s an error in loadInterface, (e.g. interface\\n -- file not found) we get lots of spurious errors from \'filterImports\'\\n let imp_mod_name = unLoc loc_imp_mod_name\\n doc = ppr imp_mod_name <+> import_reason\\n\\n hsc_env <- getTopEnv\\n unit_env <- hsc_unit_env <$> getTopEnv\\n let pkg_qual = renameRawPkgQual unit_env imp_mod_name raw_pkg_qual\\n\\n -- Check for self-import, which confuses the typechecker (#9032)\\n -- ghc --make rejects self-import cycles already, but batch-mode may not\\n -- at least not until GHC.IfaceToCore.tcHiBootIface, which is too late to avoid\\n -- typechecker crashes. (Indirect self imports are not caught until\\n -- GHC.IfaceToCore, see #10337 tracking how to make this error better.)\\n --\\n -- Originally, we also allowed \'import {-# SOURCE #-} M\', but this\\n -- caused bug #10182: in one-shot mode, we should never load an hs-boot\\n -- file for the module we are compiling into the EPS. In principle,\\n -- it should be possible to support this mode of use, but we would have to\\n -- extend Provenance to support a local definition in a qualified location.\\n -- For now, we don\'t support it, but see #10336\\n when (imp_mod_name == moduleName this_mod &&\\n (case pkg_qual of -- If we have import \\"\\" M, then we should\\n -- check that \\"\\" is \\"this\\" (which is magic)\\n -- or the name of this_mod\'s package. Yurgh!\\n -- c.f. GHC.findModule, and #9997\\n NoPkgQual -> True\\n ThisPkg uid -> uid == homeUnitId_ (hsc_dflags hsc_env)\\n OtherPkg _ -> False))\\n (addErr (TcRnSelfImport imp_mod_name))\\n\\n -- Check for a missing import list (Opt_WarnMissingImportList also\\n -- checks for T(..) items but that is done in checkDodgyImport below)\\n case imp_details of\\n Just (Exactly, _) -> return () -- Explicit import list\\n _ | generated -> return () -- Do not bleat for generated imports\\n | qual_only -> return ()\\n | otherwise -> addDiagnostic (TcRnNoExplicitImportList imp_mod_name)\\n\\n\\n mb_iface <- loadSrcInterface_maybe doc lookup_scope imp_mod_name want_boot pkg_qual\\n iface <- case mb_iface of\\n Succeeded iface -> return iface\\n Failed err -> failWithTc $\\n importDeclLoadFailure origin imp_mod_name want_boot err\\n\\n -- Compiler sanity check: if the import didn\'t say\\n -- {-# SOURCE #-} we should not get a hi-boot file\\n warnPprTrace ((want_boot == NotBoot) && (mi_boot iface == IsBoot)) \\"rnImportDecl\\" (ppr imp_mod_name) $ do\\n\\n -- Issue a user warning for a redundant {- SOURCE -} import\\n -- NB that we arrange to read all the ordinary imports before\\n -- any of the {- SOURCE -} imports.\\n --\\n -- in --make and GHCi, the compilation manager checks for this,\\n -- and indeed we shouldn\'t do it here because the existence of\\n -- the non-boot module depends on the compilation order, which\\n -- is not deterministic. The hs-boot test can show this up.\\n dflags <- getDynFlags\\n warnIf ((want_boot == IsBoot) && (mi_boot iface == NotBoot) && isOneShot (ghcMode dflags))\\n (TcRnRedundantSourceImport imp_mod_name)\\n when (mod_safe && not (safeImportsOn dflags)) $\\n addErr (TcRnSafeImportsDisabled imp_mod_name)\\n\\n let imp_mod = mi_module iface\\n qual_mod_name = fmap unLoc as_mod `orElse` imp_mod_name\\n imp_spec = ImpDeclSpec { is_mod = imp_mod, is_qual = qual_only,\\n is_dloc = locA loc, is_as = qual_mod_name,\\n is_pkg_qual = pkg_qual, is_isboot = want_boot,\\n is_level = convImportLevel import_level }\\n\\n let filter_imports = do\\n -- filter the imports according to the import declaration\\n (new_imp_details, imp_user_list, gbl_env)\\n <- filterImports hsc_env iface imp_spec imp_details\\n -- for certain error messages, we\\u2019d like to know what could be\\n -- imported here, if everything were imported\\n potential_gres <- (\\\\(_,_,x) -> x) <$> filterImports hsc_env iface imp_spec Nothing\\n return (new_imp_details, imp_user_list, gbl_env, potential_gres)\\n\\n (new_imp_details, imp_user_list, gbl_env, potential_gres) <-\\n case origin of\\n ImplicitEssentialsImport ->\\n -- The implicit GHC.Essentials import does not bring anything into scope.\\n -- See Note [Finding GHC.Essentials] in GHC.Builtin.\\n return (Nothing, ImpUserDependOnly, emptyGlobalRdrEnv, emptyGlobalRdrEnv)\\n UserWrittenImport -> filter_imports\\n ImplicitPreludeImport -> filter_imports\\n PluginImport -> filter_imports\\n\\n let is_hiding | Just (EverythingBut,_) <- imp_details = True\\n | otherwise = False\\n\\n -- should the import be safe?\\n mod_safe\' = mod_safe\\n || (not generated && safeDirectImpsReq dflags)\\n || (generated && safeImplicitImpsReq dflags)\\n\\n hsc_env <- getTopEnv\\n let home_unit = hsc_home_unit hsc_env\\n other_home_units = hsc_all_home_unit_ids hsc_env\\n\\n imported_by\\n | isDependOnlyImport imp_user_list\\n = ImportedBySystem\\n | otherwise\\n = ImportedByUser $ ImportedModsVal\\n { imv_name = is_as imp_spec\\n , imv_span = locA loc\\n , imv_is_safe = mod_safe\'\\n , imv_is_hiding = is_hiding\\n , imv_all_exports = potential_gres\\n , imv_qualified = qual_only\\n , imv_is_level = convImportLevel import_level\\n }\\n imports = calculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by\\n\\n -- Complain if we import a deprecated module\\n case fromIfaceWarnings (mi_warns iface) of\\n WarnAll txt -> addDiagnostic (TcRnDeprecatedModule imp_mod_name txt)\\n _ -> return ()\\n\\n let new_imp_decl = ImportDecl\\n { ideclExt = ideclExt decl\\n , ideclName = ideclName decl\\n , ideclPkgQual = pkg_qual\\n , ideclSource = ideclSource decl\\n , ideclSafe = mod_safe\'\\n , ideclQualified = ideclQualified decl\\n , ideclAs = ideclAs decl\\n , ideclImportList = new_imp_details\\n , ideclLevelSpec = ideclLevelSpec decl\\n }\\n\\n return (L loc new_imp_decl, ImpUserSpec imp_spec imp_user_list, gbl_env, imports)\\n\\n-- | The error message to emit when we failed to load an interface.\\nimportDeclLoadFailure :: ImportDeclOrigin -> ModuleName -> IsBootInterface\\n -> MissingInterfaceError -> TcRnMessage\\nimportDeclLoadFailure ImplicitEssentialsImport _ _ err\\n = TcRnInterfaceError $ CantFindEssentials err LookingForEssentialsModule\\nimportDeclLoadFailure _ mod_name want_boot err\\n = TcRnInterfaceError $ Can\'tFindInterface err $ LookingForModule mod_name want_boot\\n\\n-- | Rename raw package imports\\nrenameRawPkgQual :: UnitEnv -> ModuleName -> RawPkgQual -> PkgQual\\nrenameRawPkgQual unit_env mn = \\\\case\\n NoRawPkgQual -> NoPkgQual\\n RawPkgQual _ fs -> renamePkgQual unit_env mn $ Just fs\\n\\n-- | Rename raw package imports\\nrenamePkgQual :: UnitEnv -> ModuleName -> Maybe FastString -> PkgQual\\nrenamePkgQual unit_env mn mb_pkg = case mb_pkg of\\n Nothing -> NoPkgQual\\n Just pkg_fs\\n | Just uid <- homeUnitId <$> ue_homeUnit unit_env\\n , pkg_fs == fsLit \\"this\\"\\n -> ThisPkg uid\\n\\n | Just (uid, _) <- find (fromMaybe False . fmap (== pkg_fs) . snd) home_names\\n -> ThisPkg uid\\n\\n | Just uid <- resolvePackageImport unit_state mn (PackageName pkg_fs)\\n -> OtherPkg uid\\n\\n | otherwise\\n -> OtherPkg (UnitId pkg_fs)\\n -- not really correct as pkg_fs is unlikely to be a valid unit-id but\\n -- we will report the failure later...\\n where\\n home_names =\\n [ (uid, mkFastString <$> thisPackageName (homeUnitEnv_dflags (ue_findHomeUnitEnv uid unit_env)))\\n | uid <- S.toList hpt_deps\\n ]\\n\\n unit_state = ue_homeUnitState unit_env\\n\\n hpt_deps :: S.Set UnitId\\n hpt_deps = homeUnitDepends unit_state\\n\\n\\n-- | Calculate the \'ImportAvails\' induced by an import of a particular\\n-- interface, but without \'imp_mods\'.\\ncalculateAvails :: HomeUnit\\n -> S.Set UnitId\\n -> ModIface\\n -> IsSafeImport\\n -> IsBootInterface\\n -> ImportedBy\\n -> ImportAvails\\ncalculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by =\\n let imp_mod = mi_module iface\\n imp_sem_mod= mi_semantic_module iface\\n orph_iface = mi_orphan iface\\n has_finsts = mi_finsts iface\\n deps = mi_deps iface\\n trust = getSafeMode $ mi_trust iface\\n trust_pkg = mi_trust_pkg iface\\n is_sig = mi_hsc_src iface == HsigFile\\n\\n -- If the module exports anything defined in this module, just\\n -- ignore it. Reason: otherwise it looks as if there are two\\n -- local definition sites for the thing, and an error gets\\n -- reported. Easiest thing is just to filter them out up\\n -- front. This situation only arises if a module imports\\n -- itself, or another module that imported it. (Necessarily,\\n -- this involves a loop.)\\n --\\n -- We do this *after* filterImports, so that if you say\\n -- module A where\\n -- import B( AType )\\n -- type AType = ...\\n --\\n -- module B( AType ) where\\n -- import {-# SOURCE #-} A( AType )\\n --\\n -- then you won\'t get a \'B does not export AType\' message.\\n\\n\\n -- Compute new transitive dependencies\\n --\\n -- \'dep_orphs\' and \'dep_finsts\' do NOT include the imported module\\n -- itself, but we DO need to include this module in \'imp_orphs\' and\\n -- \'imp_finsts\' if it defines an orphan or instance family; thus the\\n -- orph_iface/has_iface tests.\\n\\n deporphs = dep_orphs deps\\n depfinsts = dep_finsts deps\\n\\n orphans | orph_iface = assertPpr (not (imp_sem_mod `elem` deporphs)) (ppr imp_sem_mod <+> ppr deporphs) $\\n imp_sem_mod : deporphs\\n | otherwise = deporphs\\n\\n finsts | has_finsts = assertPpr (not (imp_sem_mod `elem` depfinsts)) (ppr imp_sem_mod <+> ppr depfinsts) $\\n imp_sem_mod : depfinsts\\n | otherwise = depfinsts\\n\\n -- Trusted packages are a lot like orphans.\\n trusted_pkgs | mod_safe\' = dep_trusted_pkgs deps\\n | otherwise = S.empty\\n\\n\\n pkg = moduleUnit (mi_module iface)\\n ipkg = toUnitId pkg\\n\\n -- Does this import mean we now require our own pkg\\n -- to be trusted? See Note [Trust Own Package]\\n ptrust = trust == Sf_Trustworthy || trust_pkg\\n pkg_trust_req\\n | isHomeUnit home_unit pkg = ptrust\\n | otherwise = False\\n\\n dependent_pkgs = if toUnitId pkg `S.member` other_home_units\\n then S.empty\\n else S.singleton (lvl, ipkg)\\n\\n lvl = case imported_by of\\n ImportedByUser imv -> imv_is_level imv\\n ImportedBySystem -> NormalLevel\\n\\n\\n direct_mods = if toUnitId pkg `S.member` other_home_units\\n then mkPlusModDeps (moduleUnitId imp_mod) lvl (GWIB (moduleName imp_mod) want_boot)\\n else emptyInstalledModuleEnv\\n\\n dep_boot_mods_map = mkModDeps (dep_boot_mods deps)\\n\\n\\n boot_mods\\n -- If we are looking for a boot module, it must be HPT\\n | IsBoot <- want_boot = extendInstalledModuleEnv dep_boot_mods_map (toUnitId <$> imp_mod) (GWIB (moduleName imp_mod) IsBoot)\\n -- Now we are importing A properly, so don\'t go looking for\\n -- A.hs-boot\\n | isHomeUnit home_unit pkg = dep_boot_mods_map\\n -- There\'s no boot files to find in external imports\\n | otherwise = emptyInstalledModuleEnv\\n\\n sig_mods =\\n if is_sig\\n then moduleName imp_mod : dep_sig_mods deps\\n else dep_sig_mods deps\\n\\n\\n in ImportAvails {\\n imp_mods = Map.singleton (mi_module iface) [imported_by],\\n imp_orphs = orphans,\\n imp_finsts = finsts,\\n imp_sig_mods = sig_mods,\\n imp_direct_dep_mods = direct_mods,\\n imp_dep_direct_pkgs = dependent_pkgs,\\n imp_boot_mods = boot_mods,\\n\\n -- Add in the imported modules trusted package\\n -- requirements. ONLY do this though if we import the\\n -- module as a safe import.\\n -- See Note [Tracking Trust Transitively]\\n -- and Note [Trust Transitive Property]\\n imp_trust_pkgs = trusted_pkgs,\\n -- Do we require our own pkg to be trusted?\\n -- See Note [Trust Own Package]\\n imp_trust_own_pkg = pkg_trust_req\\n }\\n\\nmkPlusModDeps :: UnitId -> ImportLevel -> ModuleNameWithIsBoot\\n -> InstalledModuleEnv (S.Set ImportLevel, ModuleNameWithIsBoot)\\nmkPlusModDeps uid st elt = extendInstalledModuleEnv emptyInstalledModuleEnv (mkModule uid (gwib_mod elt)) (S.singleton st, elt)\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{importsFromLocalDecls}\\n* *\\n************************************************************************\\n\\nFrom the top-level declarations of this module produce\\n * the lexical environment\\n * the ImportAvails\\ncreated by its bindings.\\n\\nNote [Top-level Names in Template Haskell decl quotes]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSee also: Note [Interactively-bound Ids in GHCi] in GHC.Driver.Env\\n Note [Looking up Exact RdrNames] in GHC.Rename.Env\\n\\nConsider a Template Haskell declaration quotation like this:\\n module M where\\n f x = h [d| f = 3 |]\\nWhen renaming the declarations inside [d| ...|], we treat the\\ntop level binders specially in two ways\\n\\n1. We give them an Internal Name, not (as usual) an External one.\\n This is done by GHC.Rename.Env.newTopSrcBinder.\\n\\n2. We make them *shadow* the outer bindings.\\n See Note [GlobalRdrEnv shadowing]\\n\\n3. We find out whether we are inside a [d| ... |] by testing the TH\\n level. This is a slight hack, because the level field was really\\n meant for the type checker, and here we are not interested in the\\n fields of Brack, hence the error thunks in thRnBrack.\\n-}\\n\\nextendGlobalRdrEnvRn :: [GlobalRdrElt]\\n -> MiniFixityEnv\\n -> RnM (TcGblEnv, TcLclEnv)\\n-- Updates both the GlobalRdrEnv and the FixityEnv\\n-- We return a new TcLclEnv only because we might have to\\n-- delete some bindings from it;\\n-- see Note [Top-level Names in Template Haskell decl quotes]\\n\\nextendGlobalRdrEnvRn new_gres new_fixities\\n = checkNoErrs $ -- See Note [Fail fast on duplicate definitions]\\n do { (gbl_env, lcl_env) <- getEnvs\\n ; level <- getThLevel\\n ; isGHCi <- getIsGHCi\\n ; let rdr_env = tcg_rdr_env gbl_env\\n fix_env = tcg_fix_env gbl_env\\n th_bndrs = getLclEnvThBndrs lcl_env\\n th_lvl = thLevelIndex level\\n\\n -- Delete new_occs from global and local envs\\n -- If we are in a TemplateHaskell decl bracket,\\n -- we are going to shadow them\\n -- See Note [GlobalRdrEnv shadowing]\\n inBracket = isBrackLevel level\\n\\n lcl_env_TH = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_rdr = minusLocalRdrEnv (tcl_rdr lcl_env) new_gres_env }) lcl_env\\n -- See Note [GlobalRdrEnv shadowing]\\n\\n lcl_env2 | inBracket = lcl_env_TH\\n | otherwise = lcl_env\\n\\n -- Deal with shadowing: see Note [GlobalRdrEnv shadowing]\\n want_shadowing = isGHCi || inBracket\\n rdr_env1 | want_shadowing = shadowNames False rdr_env new_gres_env\\n | otherwise = rdr_env\\n\\n lcl_env3 = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_th_bndrs = extendNameEnvList th_bndrs\\n [ ( n, (TopLevel, th_lvl) )\\n | n <- new_names ] }) lcl_env2\\n\\n ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres\\n\\n ; let fix_env\' = foldl\' extend_fix_env fix_env new_gres\\n gbl_env\' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env\' }\\n\\n ; traceRn \\"extendGlobalRdrEnvRn 2\\" (pprGlobalRdrEnv True rdr_env2)\\n ; return (gbl_env\', lcl_env3) }\\n where\\n new_names = map greName new_gres\\n new_gres_env = mkGlobalRdrEnv new_gres\\n\\n -- If there is a fixity decl for the gre, add it to the fixity env\\n extend_fix_env fix_env gre\\n | Just (L _ fi) <- lookupMiniFixityEnv new_fixities name\\n = extendNameEnv fix_env name (FixItem occ fi)\\n | otherwise\\n = fix_env\\n where\\n name = greName gre\\n occ = greOccName gre\\n\\n add_gre :: GlobalRdrEnv -> GlobalRdrElt -> RnM GlobalRdrEnv\\n -- Extend the GlobalRdrEnv with a LocalDef GRE\\n -- If there is already a LocalDef GRE with the same OccName,\\n -- report an error and discard the new GRE\\n -- This establishes INVARIANT 1 of GlobalRdrEnvs\\n add_gre env gre\\n | not (null dups) -- Same OccName defined twice\\n = do { addDupDeclErr (gre :| dups); return env }\\n\\n | otherwise\\n = return (extendGlobalRdrEnv env gre)\\n where\\n -- See Note [Reporting duplicate local declarations]\\n dups = filter isBadDupGRE\\n $ lookupGRE env (LookupOccName (greOccName gre) (RelevantGREsFOS WantBoth))\\n isBadDupGRE old_gre = isLocalGRE old_gre && greClashesWith gre old_gre\\n\\n{- Note [Fail fast on duplicate definitions]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIf there are duplicate bindings for the same thing, we want to fail\\nfast. Having two bindings for the same thing can cause follow-on errors.\\nExample (test T9975a):\\n data Test = Test { x :: Int }\\n pattern Test wat = Test { x = wat }\\nThis defines \'Test\' twice. The second defn has no field-names; and then\\nwe get an error from Test { x=wat }, saying \\"Test has no field \'x\'\\".\\n\\nEasiest thing is to bale out fast on duplicate definitions, which\\nwe do via `checkNoErrs` on `extendGlobalRdrEnvRn`.\\n\\nNote [Reporting duplicate local declarations]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn general, a single module may not define the same OccName multiple times. This\\nis checked in extendGlobalRdrEnvRn: when adding a new locally-defined GRE to the\\nGlobalRdrEnv we report an error if there are already duplicates in the\\nenvironment. This establishes INVARIANT 1 (see comments on GlobalRdrEnv in\\nGHC.Types.Name.Reader), which says that for a given OccName, all the\\nGlobalRdrElts to which it maps must have distinct \'greName\'s.\\n\\nFor example, the following will be rejected:\\n\\n f x = x\\n g x = x\\n f x = x -- Duplicate!\\n\\nUsers are allowed to introduce new GREs with the same OccName as an imported GRE,\\nas disambiguation is possible through the module system, e.g.:\\n\\n module M where\\n import N (f)\\n f x = x\\n g x = M.f x + N.f x\\n\\nIf both GREs are local, the general rule is that two GREs clash if they have\\nthe same OccName, i.e. they share a textual name and live in the same namespace.\\nHowever, there are additional clashes due to record fields:\\n\\n - a new variable clashes with previously defined record fields\\n which define field selectors,\\n\\n - a new record field shadows:\\n\\n - previously defined variables, if it defines a field selector,\\n - previously defined record fields, unless it is a duplicate record field.\\n\\nThis logic is implemented in the function \'GHC.Types.Name.Reader.greClashesWith\'.\\n\\nSee also Note [Skipping ambiguity errors at use sites of local declarations] in\\nGHC.Rename.Utils.\\n-}\\n\\n\\n{- *********************************************************************\\n* *\\n getLocalDeclBindersd@ returns the names for an HsDecl\\n It\'s used for source code.\\n\\n *** See Note [The Naming story] in GHC.Hs.Decls ****\\n* *\\n********************************************************************* -}\\n\\ngetLocalNonValBinders :: MiniFixityEnv -> HsGroup GhcPs\\n -> RnM ((TcGblEnv, TcLclEnv), NameSet)\\n-- Get all the top-level binders bound the group *except*\\n-- for value bindings, which are treated separately\\n-- Specifically we return AvailInfo for\\n-- * type decls (incl constructors and record selectors)\\n-- * class decls (including class ops)\\n-- * associated types\\n-- * foreign imports\\n-- * value signatures (in hs-boot files only)\\n\\ngetLocalNonValBinders fixity_env\\n (HsGroup { hs_valds = binds,\\n hs_tyclds = tycl_decls,\\n hs_fords = foreign_decls })\\n = do { -- Process all type/class decls *except* family instances\\n ; let inst_decls = tycl_decls >>= group_instds\\n ; dup_fields_ok <- xopt_DuplicateRecordFields <$> getDynFlags\\n ; has_sel <- xopt_FieldSelectors <$> getDynFlags\\n ; tc_gres\\n <- concatMapM\\n (new_tc dup_fields_ok has_sel)\\n (tyClGroupTyClDecls tycl_decls)\\n ; traceRn \\"getLocalNonValBinders 1\\" (ppr tc_gres)\\n ; envs <- extendGlobalRdrEnvRn tc_gres fixity_env\\n ; restoreEnvs envs $ do {\\n -- Bring these things into scope first\\n -- See Note [Looking up family names in family instances]\\n\\n -- Process all family instances\\n -- to bring new data constructors into scope\\n ; nti_gress <- mapM (new_assoc dup_fields_ok has_sel) inst_decls\\n\\n -- Finish off with value binders:\\n -- foreign decls and pattern synonyms for an ordinary module\\n -- type sigs in case of a hs-boot file only\\n ; is_boot <- tcIsHsBootOrSig\\n ; let val_bndrs\\n | is_boot = case binds of\\n ValBinds _ val_binds ->\\n -- In a hs-boot file, the value binders come from the\\n -- *signatures*, and there should be no foreign binders\\n [ L (l2l decl_loc) (unLoc n)\\n | L decl_loc (TypeSig _ _ ns _) <- (val_sigs val_binds), n <- ns]\\n _ -> panic \\"Non-ValBinds in hs-boot group\\"\\n | otherwise = for_hs_bndrs\\n ; val_gres <- mapM new_simple val_bndrs\\n\\n ; let avails = concat nti_gress ++ val_gres\\n new_bndrs = gresToNameSet avails `unionNameSet`\\n gresToNameSet tc_gres\\n ; traceRn \\"getLocalNonValBinders 2\\" (ppr avails)\\n ; envs <- extendGlobalRdrEnvRn avails fixity_env\\n ; return (envs, new_bndrs) } }\\n where\\n for_hs_bndrs :: [LocatedN RdrName]\\n for_hs_bndrs = hsForeignDeclsBinders foreign_decls\\n\\n -- the SrcSpan attached to the input should be the span of the\\n -- declaration, not just the name\\n new_simple :: LocatedN RdrName -> RnM GlobalRdrElt\\n new_simple rdr_name = do { nm <- newTopSrcBinder rdr_name\\n ; return (mkLocalVanillaGRE NoParent nm) }\\n\\n new_tc :: DuplicateRecordFields -> FieldSelectors -> LTyClDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_tc dup_fields_ok has_sel tc_decl -- NOT for type/data instances\\n = do { let TyDeclBinders (main_bndr, tc_flav) at_bndrs sig_bndrs\\n (LConsWithFields cons_with_flds flds) = hsLTyClDeclBinders tc_decl\\n ; tycon_name <- newTopSrcBinder $ la2la main_bndr\\n ; at_names <- mapM (newTopSrcBinder . la2la . fst) at_bndrs\\n ; sig_names <- mapM (newTopSrcBinder . la2la) sig_bndrs\\n ; con_names_with_flds <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst con_names_with_flds) flds\\n ; mapM_ (add_dup_fld_errs flds\') con_names_with_flds\\n ; let tc_gre = mkLocalTyConGRE (fmap (const tycon_name) tc_flav) tycon_name\\n fld_env = mk_fld_env con_names_with_flds flds\'\\n at_gres = zipWith (\\\\ (_, at_flav) at_nm -> mkLocalTyConGRE (fmap (const tycon_name) at_flav) at_nm)\\n at_bndrs at_names\\n sig_gres = map (mkLocalVanillaGRE (ParentIs tycon_name)) sig_names\\n con_gres = map (mkLocalConLikeGRE (ParentIs tycon_name)) fld_env\\n fld_gres = mkLocalFieldGREs (ParentIs tycon_name) fld_env\\n sub_gres = at_gres ++ sig_gres ++ con_gres ++ fld_gres\\n ; traceRn \\"getLocalNonValBinders new_tc\\" $\\n vcat [ text \\"tycon:\\" <+> ppr tycon_name\\n , text \\"tc_gre:\\" <+> ppr tc_gre\\n , text \\"sub_gres:\\" <+> ppr sub_gres ]\\n ; return $ tc_gre : sub_gres }\\n\\n -- Calculate the record field information, which feeds into the GlobalRdrElts\\n -- for DataCons and their fields. It\'s convenient to do this here where\\n -- we are working with a single datatype definition.\\n --\\n -- The information we needed was all set up for us:\\n -- see Note [Collecting record fields in data declarations] in GHC.Hs.Utils.\\n mk_fld_env :: [(Name, Either VisArity [Located Int])] -> IntMap FieldLabel\\n -> [(ConLikeName, ConInfo)]\\n mk_fld_env names flds =\\n [ (DataConName con, ConInfo (ConIsData (map fst names)) fld_info)\\n | (con, con_fl_indxs) <- names\\n , let fld_info = case fmap (map ((flds IntMap.!) . unLoc)) con_fl_indxs of\\n Left 0 -> ConIsNullary\\n Left arity -> ConHasPositionalArgs arity\\n Right [] -> ConIsNullary\\n Right (fld:flds) -> ConHasRecordFields $ fld NE.:| flds ]\\n\\n new_assoc :: DuplicateRecordFields -> FieldSelectors -> LInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_assoc _ _ (L _ (TyFamInstD {})) = return []\\n -- type instances don\'t bind new names\\n\\n new_assoc dup_fields_ok has_sel (L _ (DataFamInstD _ d))\\n = new_di dup_fields_ok has_sel Nothing d\\n new_assoc dup_fields_ok has_sel\\n (L _ (ClsInstD _ (ClsInstDecl { cid_poly_ty = inst_ty\\n , cid_decls = decls })))\\n = do -- First, attempt to grab the name of the class from the instance.\\n -- This step could fail if the instance is not headed by a class,\\n -- such as in the following examples:\\n --\\n -- (1) The class is headed by a bang pattern, such as in\\n -- `instance !Show Int` (#3811c)\\n -- (2) The class is headed by a type variable, such as in\\n -- `instance c` (#16385)\\n --\\n -- If looking up the class name fails, then mb_cls_gre will\\n -- be Nothing.\\n mb_cls_gre <- runMaybeT $ do\\n -- See (1) above\\n L loc cls_rdr <- MaybeT $ pure $ getLHsInstDeclClass_maybe inst_ty\\n -- See (2) above\\n MaybeT $ setSrcSpan (locA loc) $ lookupGlobalOccRn_maybe SameNameSpace cls_rdr\\n -- Assuming the previous step succeeded, process any associated data\\n -- family instances. If the previous step failed, bail out.\\n case mb_cls_gre of\\n Nothing\\n -> pure []\\n Just cls_gre\\n -> let cls_nm = greName cls_gre\\n in concatMapM (new_di dup_fields_ok has_sel (Just cls_nm) . unLoc) (data_fam_insts decls)\\n\\n data_fam_insts decls = concatMap get decls\\n where\\n get (L l (InstD _ (DataFamInstD { dfid_inst = d}))) = [L l d]\\n get _ = []\\n\\n new_di :: DuplicateRecordFields -> FieldSelectors\\n -> Maybe Name -- class name\\n -> DataFamInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_di dup_fields_ok has_sel mb_cls dfid@(DataFamInstDecl { dfid_eqn = ti_decl })\\n = do { main_name <- unLoc <$> lookupFamInstName mb_cls (feqn_tycon ti_decl)\\n ; let LConsWithFields cons_with_flds flds = hsDataFamInstBinders dfid\\n ; sub_names <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst sub_names) flds\\n ; mapM_ (add_dup_fld_errs flds\') sub_names\\n ; let fld_env = mk_fld_env sub_names flds\'\\n con_gres = map (mkLocalConLikeGRE (ParentIs main_name)) fld_env\\n field_gres = mkLocalFieldGREs (ParentIs main_name) fld_env\\n -- NB: the data family name is not bound here,\\n -- so we don\'t return a GlobalRdrElt for it here!\\n ; return $ con_gres ++ field_gres }\\n\\n -- Add errors if a constructor has a duplicate record field.\\n add_dup_fld_errs :: IntMap FieldLabel\\n -> (Name, Either VisArity [Located Int])\\n -> IOEnv (Env TcGblEnv TcLclEnv) ()\\n add_dup_fld_errs all_flds (con, con_flds_or_arity)\\n | Right con_flds <- con_flds_or_arity\\n , let (_, dups) = removeDups (comparing unLoc) con_flds\\n = for_ dups $ \\\\ dup_flds ->\\n -- Report the error at the location of the second occurrence\\n -- of the duplicate field.\\n let loc =\\n case dup_flds of\\n _ :| ( L loc _ : _) -> loc\\n L loc _ :| _ -> loc\\n dup_rdrs = fmap (nameRdrName . flSelector . (all_flds IntMap.!) . unLoc) dup_flds\\n in addErrAt loc $ TcRnDuplicateFieldName (RecordFieldDecl con) dup_rdrs\\n | otherwise\\n = return ()\\n\\nnewRecordFieldLabel :: DuplicateRecordFields -> FieldSelectors -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel\\nnewRecordFieldLabel _ _ [] _ = error \\"newRecordFieldLabel: datatype has no constructors!\\"\\nnewRecordFieldLabel dup_fields_ok has_sel (dc:_) (L loc (FieldOcc _ (L _ fld)))\\n = do { selName <- newTopSrcBinder $ L (l2l loc) $ field\\n ; return $ FieldLabel { flHasDuplicateRecordFields = dup_fields_ok\\n , flHasFieldSelector = has_sel\\n , flSelector = selName } }\\n where\\n fld_occ = rdrNameOcc fld\\n dc_fs = occNameFS $ nameOccName dc\\n field\\n -- Use an Exact RdrName as-is, to preserve the bindings\\n -- of an already renamer-resolved field and its use\\n -- sites. This is needed to correctly support record\\n -- selectors in Template Haskell. See Note [Binders in\\n -- Template Haskell] in \\"GHC.ThToHs\\" and Note [Looking up\\n -- Exact RdrNames] in \\"GHC.Rename.Env\\".\\n | isExact fld\\n = assertPpr (fieldOcc_maybe fld_occ == Just dc_fs)\\n (vcat [ text \\"newRecordFieldLabel: incorrect namespace for exact Name\\" <+> quotes (ppr fld)\\n , text \\"expected namespace:\\" <+> pprNameSpace (fieldName dc_fs)\\n , text \\" actual namespace:\\" <+> pprNameSpace (occNameSpace fld_occ) ])\\n fld\\n\\n -- Field names produced by the parser are namespaced with VarName.\\n -- Here we namespace them according to the first constructor.\\n -- See Note [Record field namespacing] in GHC.Types.Name.Occurrence.\\n | otherwise\\n = mkRdrUnqual $ varToRecFieldOcc dc_fs fld_occ\\n\\n{-\\nNote [Looking up family names in family instances]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider\\n\\n module M where\\n type family T a :: *\\n type instance M.T Int = Bool\\n\\nWe might think that we can simply use \'lookupOccRn\' when processing the type\\ninstance to look up \'M.T\'. Alas, we can\'t! The type family declaration is in\\nthe *same* HsGroup as the type instance declaration. Hence, as we are\\ncurrently collecting the binders declared in that HsGroup, these binders will\\nnot have been added to the global environment yet.\\n\\nSolution is simple: process the type family declarations first, extend\\nthe environment, and then process the type instances.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Filtering imports}\\n* *\\n************************************************************************\\n\\n@filterImports@ takes the @ExportEnv@ telling what the imported module makes\\navailable, and filters it through the import spec (if any).\\n\\nNote [Dealing with imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nFor import M( ies ), we take each AvailInfo from the mi_exports of M, and make\\n\\n imp_occ_env :: OccEnv (NameEnv ImpOccItem)\\n\\nThis map contains one entry for each OccName that M exports, mapping each OccName\\nto the following information:\\n\\n 1. the GlobalRdrElt corresponding to the OccName,\\n 2. whether this GlobalRdrElt was the parent in the AvailInfo we found\\n the OccName in.\\n 3. the GlobalRdrElts that were bundled together in the AvailInfo we found\\n this OccName in (not including the parent),\\n\\nWe need (2) and (3) during the construction of the OccEnv because of associated\\ntypes and bundled pattern synonyms, respectively.\\n(3) is explained in Note [Importing PatternSynonyms].\\n\\nTo explain (2), consider for example:\\n\\n module M where\\n class C a where { data T a }\\n instance C Int where { data T Int = T1 | T2 }\\n instance C Bool where { data T Int = T3 }\\n\\nHere, M\'s exports avails are (recalling the AvailTC invariant from GHC.Types.Avail)\\n\\n C(C,T), T(T,T1,T2,T3)\\n\\nNotice that T appears *twice*, once as a child and once as a parent. From\\nthese two exports, respectively, during construction of the imp_occ_env, we begin\\nby associating the following two elements with the key T:\\n\\n T -> ImpOccItem { imp_item = gre1, imp_bundled = [C,T] , imp_is_parent = False }\\n T -> ImpOccItem { imp_item = gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nwhere `gre1`, `gre2` are two GlobalRdrElts with greName T.\\nWe combine these (in function \'combine\' in \'mkImportOccEnv\') by discarding the\\nnon-parent item, thusly:\\n\\n T -> IE_ITem { imp_item = gre1 `plusGRE` gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nNote the `plusGRE`: this ensures we don\'t drop parent information;\\nsee Note [Preserve parent information when combining import OccEnvs].\\n\\nSo the overall imp_occ_env is:\\n\\n C -> ImpOccItem { imp_item = C, imp_bundled = [T ], imp_is_parent = True }\\n T -> ImpOccItem { imp_item = T , imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n T1 -> ImpOccItem { imp_item = T1, imp_bundled = [T1,T2,T3], imp_is_parent = False }\\n -- similarly for T2, T3\\n\\nNote that the imp_occ_env will have entries for data constructors too,\\nalthough we never look up data constructors.\\n\\nNote [Importing PatternSynonyms]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nAs described in Note [Dealing with imports], associated types can lead to the\\nsame Name appearing twice, both as a child and once as a parent, when\\nconstructing the imp_occ_env. The same thing can happen with pattern synonyms\\nif they are exported bundled with a type.\\n\\nA simplified example, based on #11959:\\n\\n {-# LANGUAGE PatternSynonyms #-}\\n module M (T(P), pattern P) where -- Duplicate export warning, but allowed\\n data T = MkT\\n pattern P = MkT\\n\\nHere we have T(P) and P in export_avails, and respectively construct both\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n P -> ImpOccItem { imp_item = P, imp_bundled = [] , imp_is_parent = False }\\n\\nWe combine these by dropping the one with no siblings, leaving us with:\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n\\nThat is, we simply discard the non-bundled Avail.\\n\\nNote [Importing DuplicateRecordFields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn filterImports, another complicating factor is DuplicateRecordFields.\\nSuppose we have:\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (S(foo), T(foo)) where\\n data S = MkS { foo :: Int }\\n data T = MkT { foo :: Int }\\n\\n module N where\\n import M (foo) -- this is allowed (A)\\n import M (S(foo)) -- this is allowed (B)\\n\\nHere M exports \'foo\' at two different OccNames, with different namespaces for\\nthe two construtors MkS and MkT. Then, when we look up \'foo\' in lookup_names\\nfor case (A), we have a variable foo but must look in all the record field\\nnamespaces to find the two fields (and hence two different Avails).\\nWhereas in case (B) we reach the lookup_ie case for IEThingWith,\\nwhich looks up \'S\' and then finds the unique \'foo\' amongst its children.\\n\\nSee T16745 for a test of this.\\n\\nNote [Preserve parent information when combining import OccEnvs]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen discarding one ImpOccItem in favour of another, as described in\\nNote [Dealing with imports], we must make sure to combine the GREs so that\\nwe don\'t lose information.\\n\\nConsider for example #24084:\\n\\n module M1 where { class C a where { type T a } }\\n module M2 ( module M1 ) where { import M1 }\\n module M3 where { import M2 ( C, T ); instance C () where T () = () }\\n\\nWhen processing the import list of `M3`, we will have two `Avail`s attached\\nto `T`, namely `C(C, T)` and `T(T)`. We combine them in the `combine` function\\nof `mkImportOccEnv`; as described in Note [Dealing with imports] we discard\\n`C(C, T)` in favour of `T(T)`. However, in doing so, we **must not**\\ndiscard the information want that `C` is the parent of `T`. Indeed,\\nlosing track of this information can cause errors when importing,\\nas we could get an error of the form\\n\\n \\u2018T\\u2019 is not a (visible) associated type of class \\u2018C\\u2019\\n\\nThis explains why we use `plusGRE` when combining the two ImpOccItems, even\\nthough we are discarding one in favour of the other.\\n-}\\n\\n-- | All the \'GlobalRdrElt\'s associated with an \'AvailInfo\'.\\ngresFromAvail :: HasDebugCallStack\\n => HscEnv -> Maybe ImportSpec -> AvailInfo -> [GlobalRdrElt]\\ngresFromAvail hsc_env prov avail =\\n [ mk_gre nm info\\n | nm <- availNames avail\\n , let info = lookupGREInfo hsc_env nm ]\\n where\\n\\n mk_gre n info\\n = case prov of\\n -- Nothing => bound locally\\n -- Just is => imported from \'is\'\\n Nothing -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = True, gre_imp = emptyBag\\n , gre_info = info }\\n Just is -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = False, gre_imp = unitBag is\\n , gre_info = info }\\n\\n-- | All the \'GlobalRdrElt\'s associated with a collection of \'AvailInfo\'s.\\ngresFromAvails :: HscEnv -> Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]\\ngresFromAvails hsc_env prov = concatMap (gresFromAvail hsc_env prov)\\n\\nimportsFromIface :: HscEnv -> ModIface -> ImpDeclSpec -> Maybe NameSet -> GlobalRdrEnv\\nimportsFromIface hsc_env iface decl_spec hidden = mkGlobalRdrEnv $ case hidden of\\n Nothing -> all_gres\\n Just hidden_names -> filter (not . (`elemNameSet` hidden_names) . greName) all_gres\\n where\\n all_gres = gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\nrnNamespaceSpecifier :: NamespaceSpecifier GhcPs -> NamespaceSpecifier GhcRn\\nrnNamespaceSpecifier (NoNamespaceSpecifier _) = NoNamespaceSpecifier noExtField\\nrnNamespaceSpecifier (TypeNamespaceSpecifier x) = TypeNamespaceSpecifier x\\nrnNamespaceSpecifier (DataNamespaceSpecifier x) = DataNamespaceSpecifier x\\n\\nfilterImports\\n :: HasDebugCallStack\\n => HscEnv\\n -> ModIface\\n -> ImpDeclSpec\\n -- ^ Import spec\\n -> Maybe (ImportListInterpretation, [LIE GhcPs])\\n -- ^ Whether this is a \\"hiding\\" import list\\n -> RnM (Maybe (ImportListInterpretation, [LIE GhcRn]), -- Import spec w/ Names\\n ImpUserList, -- same, but designed for storage in interfaces\\n GlobalRdrEnv) -- Same again, but in GRE form\\nfilterImports hsc_env iface decl_spec Nothing\\n = return (Nothing, ImpUserAll, importsFromIface hsc_env iface decl_spec Nothing)\\nfilterImports hsc_env iface decl_spec (Just (want_hiding, import_items))\\n = do -- check for errors, convert RdrNames to Names\\n items1 <- mapM lookup_lie import_items\\n\\n let items2 :: [(LIE GhcRn, [GlobalRdrElt])]\\n items2 = concat items1\\n -- NB we may have duplicates, and several items\\n -- for the same parent; e.g N(x) and N(y)\\n\\n (gres, imp_user_list) = case want_hiding of\\n Exactly ->\\n let gres = concatMap (gresFromIE decl_spec) items2\\n gre_env = mkGlobalRdrEnv gres\\n implicit_parents = mkNameSet $ mapMaybe parentOfImplicitlyImportedGRE gres\\n in (gre_env, ImpUserExplicit (gresToAvailInfo $ globalRdrEnvElts $ gre_env) implicit_parents)\\n EverythingBut ->\\n let hidden_names = mkNameSet $ concatMap (map greName . snd) items2\\n in (importsFromIface hsc_env iface decl_spec (Just hidden_names), ImpUserEverythingBut hidden_names)\\n\\n return (Just (want_hiding, map fst items2), imp_user_list, gres)\\n where\\n import_mod = mi_module iface\\n all_avails = mi_exports iface\\n imp_occ_env = mkImportOccEnv hsc_env decl_spec all_avails\\n\\n -- Look up a parent (type constructor, class or data constructor)\\n -- in an import.\\n lookup_parent :: IE GhcPs -> RdrName -> IELookupM ImpOccItem\\n lookup_parent ie rdr =\\n assertPpr (not $ isVarNameSpace ns)\\n (vcat [ text \\"filterImports lookup_parent: unexpected variable\\"\\n , text \\"rdr:\\" <+> ppr rdr\\n , text \\"namespace:\\" <+> pprNameSpace ns ]) $\\n do { xs <- lookup_names ie rdr\\n ; case xs of\\n cax :| [] -> return cax\\n _ -> pprPanic \\"filter_imports lookup_parent ambiguous\\" $\\n vcat [ text \\"rdr:\\" <+> ppr rdr\\n , text \\"lookups:\\" <+> ppr (fmap imp_item xs) ] }\\n -- Looking up non-variables is always unambiguous,\\n -- as there can be at most one corresponding item\\n -- in the imp_occ_env.\\n -- See item (1) of Note [Exporting duplicate declarations]\\n -- in GHC.Tc.Gen.Export.\\n where\\n occ = rdrNameOcc rdr\\n ns = occNameSpace occ\\n\\n -- Look up a RdrName used in an import, returning multiple values if there\\n -- are several fields with the same name exposed by the module\\n lookup_names :: IE GhcPs -> RdrName -> IELookupM (NonEmpty ImpOccItem)\\n lookup_names ie rdr\\n | isQual rdr\\n = failLookupWith (QualImportError rdr)\\n | otherwise\\n = case lookups of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n item:items -> return $ item :| items\\n where\\n lookups = concatMap nonDetNameEnvElts\\n $ lookupImpOccEnv (RelevantGREsFOS WantNormal) imp_occ_env (rdrNameOcc rdr)\\n\\n lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, [GlobalRdrElt])]\\n lookup_lie (L loc ieRdr)\\n = setSrcSpanA loc $\\n do (stuff, warns) <- run_lookup ([],[]) (lookup_ie ieRdr)\\n mapM_ (addTcRnDiagnostic <=< warning_msg) warns\\n return [ (L loc ie, gres) | (ie,gres) <- stuff ]\\n where\\n\\n -- Warn when importing T(..) and no children are brought in scope\\n warning_msg (DodgyImport reason) =\\n pure (TcRnDodgyImports reason)\\n warning_msg MissingImportList =\\n pure (TcRnMissingImportList ieRdr)\\n warning_msg (BadImportW ie sub) = do\\n -- \'BadImportW\' is only constructed below in \'bad_import_w\', in\\n -- the \'EverythingBut\' case, so here we assume a \'hiding\' clause.\\n (reason :| _) <- badImportItemErr iface decl_spec ie sub all_avails\\n pure (TcRnDodgyImports (DodgyImportsHiding reason))\\n warning_msg (DeprecatedExport n w) =\\n pure $ TcRnPragmaWarning\\n PragmaWarningExport\\n { pwarn_occname = occName n\\n , pwarn_impmod = moduleName import_mod }\\n w\\n\\n run_lookup :: a -> IELookupM a -> TcRn a\\n run_lookup def m = case m of\\n Failed err -> do\\n msgs <- lookup_err_msgs err\\n forM_ msgs $ \\\\msg -> addErr (TcRnImportLookup msg)\\n return def\\n Succeeded a -> return a\\n\\n lookup_err_msgs err = case err of\\n BadImport ie sub -> badImportItemErr iface decl_spec ie sub all_avails\\n IllegalImport -> pure $ NE.singleton ImportLookupIllegal\\n QualImportError rdr -> pure $ NE.singleton (ImportLookupQualified rdr)\\n\\n -- For each import item, we convert its RdrNames to Names,\\n -- and at the same time compute all the GlobalRdrElt corresponding\\n -- to what is actually imported by this item.\\n -- Returns Nothing on error.\\n --\\n -- Returns a list because, with DuplicateRecordFields, a naked\\n -- import/export of a record field can correspond to multiple\\n -- different GlobalRdrElts. See Note [Importing DuplicateRecordFields].\\n lookup_ie :: IE GhcPs\\n -> IELookupM ([(IE GhcRn, [GlobalRdrElt])], [IELookupWarning])\\n lookup_ie ie = handle_bad_import $\\n case ie of\\n IEVar _ (L l n) _ -> do\\n -- See Note [Importing DuplicateRecordFields]\\n xs <- lookup_names ie (ieWrappedName n)\\n let gres = map imp_item $ NE.toList xs\\n export_depr_warns\\n | want_hiding == Exactly\\n = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ( [ (IEVar Nothing (L l (replaceWrappedName n name)) noDocstring, [gre])\\n | gre <- gres\\n , let name = greName gre ]\\n , export_depr_warns )\\n\\n IEThingAll x ns_spec (L l tc) _ -> do\\n ImpOccItem { imp_item = gre\\n , imp_bundled = bundled_gres\\n , imp_is_parent = is_par\\n }\\n <- lookup_parent ie $ ieWrappedName tc\\n let name = greName gre\\n\\n child_gres :: [GlobalRdrElt]\\n child_gres\\n | is_par = filterByNamespaceSpecifierGREs ns_spec bundled_gres\\n | otherwise = []\\n\\n imp_list_warn\\n\\n | null child_gres\\n -- e.g. f(..) or T(..) where T is a type synonym\\n = [DodgyImport (DodgyImportsEmptyParent ie ns_spec gre)]\\n\\n -- e.g. import M( T(..) )\\n | not (is_qual decl_spec)\\n = [MissingImportList]\\n\\n | otherwise\\n = []\\n\\n renamed_ie = IEThingAll (x { ieta_warning = Nothing })\\n (rnNamespaceSpecifier ns_spec)\\n (L l (replaceWrappedName tc name))\\n noDocstring\\n export_depr_warn\\n | want_hiding == Exactly\\n = maybeToList $ mk_depr_export_warning gre\\n -- We don\'t want to warn about the children as they\\n -- are not explicitly mentioned; the warning will\\n -- be emitted later on if they are used\\n | otherwise = []\\n\\n return ( [(renamed_ie, gre:child_gres)]\\n , imp_list_warn ++ export_depr_warn)\\n\\n\\n IEThingAbs _ (L l tc\') _\\n | want_hiding == EverythingBut -- hiding ( C )\\n -- Here the \'C\' can be a data constructor\\n -- *or* a type/class, or even both\\n -> let tc = ieWrappedName tc\'\\n tc_name = lookup_parent ie tc\\n dc_name = lookup_parent ie (setRdrNameSpace tc srcDataName)\\n in\\n case catIELookupM [ tc_name, dc_name ] of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n names -> return ( [mkIEThingAbs tc\' l (imp_item name) | name <- names], [])\\n | otherwise\\n -> do ImpOccItem { imp_item = gre } <- lookup_parent ie (ieWrappedName tc\')\\n return ( [mkIEThingAbs tc\' l gre]\\n , maybeToList $ mk_depr_export_warning gre)\\n\\n IEThingWith (deprecation, ann) ltc@(L l rdr_tc) wc rdr_ns _ -> do\\n ImpOccItem { imp_item = gre, imp_bundled = subnames }\\n <- lookup_parent (IEThingAbs Nothing ltc noDocstring) (ieWrappedName rdr_tc)\\n let name = greName gre\\n\\n -- Look up the children in the sub-names of the parent\\n -- See Note [Importing DuplicateRecordFields]\\n let (children_errs, childnames) = lookupChildren subnames rdr_ns\\n\\n bad_import_warns <-\\n if null children_errs then return [] else\\n let items = map lce_wrapped_name children_errs\\n ie = IEThingWith (deprecation, ann) ltc wc items noDocstring\\n -- We are trying to import T( a,b,c,d ), and failed\\n -- to find \'b\' and \'d\'. So we make up an import item\\n -- to report as failing, namely T( b, d ).\\n -- c.f. #15413\\n subordinate_err = mkSubordinateError gre children_errs\\n in bad_import_w ie subordinate_err\\n\\n let name\' = replaceWrappedName rdr_tc name\\n childnames\' = map (to_ie_post_rn . fmap greName) childnames\\n gres = gre : map unLoc childnames\\n export_depr_warns\\n | want_hiding == Exactly = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ([ (IEThingWith (Nothing, ann) (L l name\') wc childnames\' noDocstring\\n ,gres)]\\n , bad_import_warns ++ export_depr_warns)\\n\\n IEWholeNamespace x ns_spec -> do\\n let mod_name = moduleName import_mod\\n names = map greName gres\\n renamed_ie = IEWholeNamespace x { iewn_warning = Nothing\\n , iewn_names = names }\\n (rnNamespaceSpecifier ns_spec)\\n gres = filterByNamespaceSpecifierGREs ns_spec $\\n gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n dodgy_warn\\n | null gres = [DodgyImport (DodgyImportsWildcard mod_name ns_spec)]\\n | otherwise = []\\n return ([(renamed_ie, gres)],\\n dodgy_warn)\\n\\n _other -> failLookupWith IllegalImport\\n -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed...\\n -- all of those constitute errors.\\n\\n where\\n mkIEThingAbs tc l gre\\n = (IEThingAbs Nothing (L l (replaceWrappedName tc n)) noDocstring, [gre])\\n where n = greName gre\\n\\n -- N.B. imports never have docstrings\\n noDocstring = Nothing\\n\\n handle_bad_import m = catchIELookup m $ \\\\case\\n BadImport ie sub -> do\\n ws <- bad_import_w ie sub\\n return ([], ws)\\n err -> failLookupWith err\\n\\n bad_import_w :: IE GhcPs -> IsSubordinateError -> IELookupM [IELookupWarning]\\n bad_import_w ie sub\\n | want_hiding == EverythingBut = return [BadImportW ie sub]\\n | otherwise = failLookupWith (BadImport ie sub)\\n\\n mk_depr_export_warning gre\\n = DeprecatedExport name <$> mi_export_warn_fn iface name\\n where\\n name = greName gre\\n\\n-- | Assuming a subordinate item could not be found, do another lookup for a\\n-- more specific error message.\\nmkBadExportSubordinate :: [GlobalRdrElt] -> LIEWrappedName GhcPs -> BadExportSubordinate\\nmkBadExportSubordinate child_gres n =\\n case lookupChildren child_gres [n] of\\n (LookupChildNonType {lce_nontype_item = g} : _, _) -> BadExportSubordinateNonType g\\n (LookupChildNonData {lce_nondata_item = g} : _, _) -> BadExportSubordinateNonData g\\n _ -> BadExportSubordinateNotFound n\\n\\ntype IELookupM = MaybeErr IELookupError\\n\\ndata IELookupWarning\\n = BadImportW (IE GhcPs) IsSubordinateError\\n | MissingImportList\\n | DodgyImport DodgyImportsReason\\n | DeprecatedExport Name (WarningTxt GhcRn)\\n\\n-- | Is this import/export item a subordinate or not?\\ndata IsSubordinateError\\n = IsSubordinateError { subordinate_err_parent :: !GlobalRdrElt\\n , subordinate_err_unavailable :: [FastString]\\n , subordinate_err_nontype :: [GlobalRdrElt]\\n , subordinate_err_nondata :: [GlobalRdrElt] }\\n | IsNotSubordinate\\n\\nmkSubordinateError :: GlobalRdrElt -> [LookupChildError] -> IsSubordinateError\\nmkSubordinateError gre children_errs = foldr add init_acc children_errs\\n where\\n init_acc :: IsSubordinateError\\n init_acc = IsSubordinateError gre [] [] []\\n\\n add :: LookupChildError -> IsSubordinateError -> IsSubordinateError\\n add children_err sub@IsSubordinateError{} =\\n case children_err of\\n LookupChildNonType{lce_nontype_item = g} ->\\n sub { subordinate_err_nontype = g : subordinate_err_nontype sub }\\n LookupChildNonData{lce_nondata_item = g} ->\\n sub { subordinate_err_nondata = g : subordinate_err_nondata sub }\\n LookupChildNotFound (L _ wname) ->\\n let fs = (occNameFS . rdrNameOcc . ieWrappedName) wname\\n in sub { subordinate_err_unavailable = fs : subordinate_err_unavailable sub }\\n add _ IsNotSubordinate = panic \\"mkSubordinateError: IsNotSubordinate\\"\\n\\ndata IELookupError\\n = QualImportError RdrName\\n | BadImport (IE GhcPs) IsSubordinateError\\n | IllegalImport\\n\\nfailLookupWith :: IELookupError -> IELookupM a\\nfailLookupWith err = Failed err\\n\\ncatchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a\\ncatchIELookup m h = case m of\\n Succeeded r -> return r\\n Failed err -> h err\\n\\ncatIELookupM :: [IELookupM a] -> [a]\\ncatIELookupM ms = [ a | Succeeded a <- ms ]\\n\\n-- | Information associated to an \'AvailInfo\' used in constructing\\n-- an \'OccEnv\' corresponding to imports.\\n--\\n-- See Note [Dealing with imports].\\ndata ImpOccItem\\n = ImpOccItem\\n { imp_item :: GlobalRdrElt\\n -- ^ The import item\\n , imp_bundled :: [GlobalRdrElt]\\n -- ^ Items bundled in the Avail this import item came from,\\n -- not including the import item itself if it is a parent.\\n , imp_is_parent :: Bool\\n -- ^ Is the import item a parent? See Note [Dealing with imports].\\n }\\n\\ninstance Outputable ImpOccItem where\\n ppr (ImpOccItem { imp_item = item, imp_bundled = bundled, imp_is_parent = is_par })\\n = braces $ hsep\\n [ text \\"ImpOccItem\\"\\n , if is_par then text \\"[is_par]\\" else empty\\n , ppr (greName item) <+> ppr (greParent item)\\n , braces $ text \\"bundled:\\" <+> ppr (map greName bundled) ]\\n\\n-- | Make an \'OccEnv\' of all the imports.\\n--\\n-- Complicated by the fact that associated data types and pattern synonyms\\n-- can appear twice. See Note [Dealing with imports].\\nmkImportOccEnv :: HscEnv -> ImpDeclSpec -> [IfaceExport] -> OccEnv (NameEnv ImpOccItem)\\nmkImportOccEnv hsc_env decl_spec all_avails =\\n mkOccEnv_C (plusNameEnv_C combine)\\n [ (occ, mkNameEnv [(nm, item)])\\n | avail <- all_avails\\n , let gres = gresFromAvail hsc_env (Just hiding_spec) avail\\n , gre <- gres\\n , let nm = greName gre\\n occ = greOccName gre\\n (is_parent, bundled) = case avail of\\n AvailTC c _\\n | c == nm -- (Recall the AvailTC invariant from GHC.Types.AvailInfo)\\n -> ( True, drop 1 gres ) -- \\"drop 1\\": don\'t include the parent itself.\\n | otherwise\\n -> ( False, gres )\\n _ -> ( False, [] )\\n item = ImpOccItem\\n { imp_item = gre\\n , imp_bundled = bundled\\n , imp_is_parent = is_parent }\\n ]\\n where\\n\\n hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\n -- See Note [Dealing with imports]\\n -- \'combine\' may be called for associated data types which appear\\n -- twice in the all_avails. In the example, we have two Avails for T,\\n -- namely T(T,T1,T2,T3) and C(C,T), and we combine them by dropping the\\n -- latter, in which T is not the parent.\\n combine :: ImpOccItem -> ImpOccItem -> ImpOccItem\\n combine item1@(ImpOccItem { imp_item = gre1, imp_is_parent = is_parent1 })\\n item2@(ImpOccItem { imp_item = gre2, imp_is_parent = is_parent2 })\\n | is_parent1 || is_parent2\\n , not (isRecFldGRE gre1 || isRecFldGRE gre2) -- NB: does not force GREInfo.\\n , let name1 = greName gre1\\n name2 = greName gre2\\n gre = gre1 `plusGRE` gre2\\n -- See Note [Preserve parent information when combining import OccEnvs]\\n = assertPpr (name1 == name2)\\n (ppr name1 <+> ppr name2) $\\n if is_parent1\\n then item1 { imp_item = gre }\\n else item2 { imp_item = gre }\\n -- Discard C(C,T) in favour of T(T, T1, T2, T3).\\n\\n -- \'combine\' may also be called for pattern synonyms which appear both\\n -- unassociated and associated (see Note [Importing PatternSynonyms]).\\n combine item1@(ImpOccItem { imp_item = c1, imp_bundled = kids1 })\\n item2@(ImpOccItem { imp_item = c2, imp_bundled = kids2 })\\n = assertPpr (greName c1 == greName c2\\n && (not (null kids1 && null kids2)))\\n (ppr c1 <+> ppr c2 <+> ppr kids1 <+> ppr kids2) $\\n if null kids1\\n then item2\\n else item1\\n -- Discard standalone pattern P in favour of T(P).\\n\\n-- | Essentially like @lookupGRE env (LookupOccName occ which_gres)@,\\n-- but working with \'ImpOccItem\'s instead of \'GlobalRdrElt\'s.\\nlookupImpOccEnv :: WhichGREs GREInfo\\n -> OccEnv (NameEnv ImpOccItem) -> OccName -> [NameEnv ImpOccItem]\\nlookupImpOccEnv which_gres env occ =\\n mapMaybe relevant_items $ lookupOccEnv_AllNameSpaces env occ\\n where\\n is_relevant :: ImpOccItem -> Bool\\n is_relevant (ImpOccItem { imp_item = gre }) =\\n greIsRelevant which_gres (occNameSpace occ) gre\\n relevant_items :: NameEnv ImpOccItem -> Maybe (NameEnv ImpOccItem)\\n relevant_items nms\\n | let nms\' = filterNameEnv is_relevant nms\\n = if isEmptyNameEnv nms\'\\n then Nothing\\n else Just nms\'\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{Import/Export Utils}\\n* *\\n************************************************************************\\n-}\\n\\n-- | Given an import\\\\/export spec, appropriately set the @gre_imp@ field\\n-- for the \'GlobalRdrElt\'s.\\ngresFromIE :: ImpDeclSpec -> (LIE GhcRn, [GlobalRdrElt]) -> [GlobalRdrElt]\\ngresFromIE decl_spec (L loc ie, gres)\\n = map set_gre_imp gres\\n where\\n is_explicit = case ie of\\n IEThingAll _ _ name _ -> \\\\n -> n == lieWrappedName name\\n IEWholeNamespace _ _ -> \\\\_ -> False\\n _ -> \\\\_ -> True\\n prov_fn name\\n = ImpSpec { is_decl = decl_spec, is_item = item_spec }\\n where\\n item_spec = ImpSome { is_explicit = is_explicit name\\n , is_iloc = locA loc }\\n set_gre_imp gre@( GRE { gre_name = nm } )\\n = gre { gre_imp = unitBag $ prov_fn nm }\\n\\nparentOfImplicitlyImportedGRE :: Outputable info => GlobalRdrEltX info -> Maybe Name\\nparentOfImplicitlyImportedGRE gre =\\n if any (explicit_import . is_item) $ gre_imp gre\\n then Nothing\\n else greParent_maybe gre\\n where\\n explicit_import :: ImpItemSpec -> Bool\\n explicit_import (ImpAll {}) =\\n pprPanic \\"parentOfImplicitlyImportedGRE: ImpAll\\" (ppr gre)\\n explicit_import (ImpSome { is_explicit }) = is_explicit\\n\\n{- Note [Children for duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider the module\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (F(foo, MkFInt, MkFBool)) where\\n data family F a\\n data instance F Int = MkFInt { foo :: Int }\\n data instance F Bool = MkFBool { foo :: Bool }\\n\\nThe `foo` in the export list refers to *both* selectors! For this\\nreason, lookupChildren builds an environment that maps the FastString\\nto a list of items, rather than a single item.\\n-}\\n\\nmkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]\\nmkChildEnv gres = foldr add emptyNameEnv gres\\n where\\n add gre env = case greParent gre of\\n ParentIs p -> extendNameEnv_Acc (:) Utils.singleton env p gre\\n NoParent -> env\\n\\nfindChildren :: NameEnv [a] -> Name -> [a]\\nfindChildren env n = lookupNameEnv env n `orElse` []\\n\\ndata LookupChildError\\n = LookupChildNotFound { lce_wrapped_name :: !(LIEWrappedName GhcPs) }\\n | LookupChildNonType { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nontype_item :: !GlobalRdrElt }\\n | LookupChildNonData { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nondata_item :: !GlobalRdrElt }\\n\\nlookupChildren :: [GlobalRdrElt]\\n -> [LIEWrappedName GhcPs]\\n -> ( [LookupChildError] -- The ones for which the lookup failed\\n , [LocatedA GlobalRdrElt] )\\n-- (lookupChildren all_kids rdr_items) maps each rdr_item to its\\n-- corresponding Name in all_kids, if the former exists\\n-- The matching is done by FastString, not OccName, so that\\n-- Cls( meth, AssocTy )\\n-- will correctly find AssocTy among the all_kids of Cls, even though\\n-- the RdrName for AssocTy may have a (bogus) DataName namespace\\n-- (Really the rdr_items should be FastStrings in the first place.)\\nlookupChildren all_kids rdr_items = (fails, successes)\\n where\\n mb_xs = map do_one rdr_items\\n fails = [ err | Failed err <- mb_xs ]\\n successes = [ ok | Succeeded oks <- mb_xs, ok <- NE.toList oks ]\\n\\n do_one :: LIEWrappedName GhcPs -> MaybeErr LookupChildError (NonEmpty (LocatedA GlobalRdrElt))\\n do_one item@(L l r) =\\n case r of\\n IEName{}\\n -- IEName (unadorned name) places no restriction on the namespace of\\n -- the imported entity, so we look in both `val_gres` and `typ_gres`.\\n -- In case of conflict (punning), the value namespace takes priority.\\n -- See Note [Prioritise the value namespace in subordinate import lists]\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEType{}\\n -- IEType (\'type\' namespace specifier) restricts the lookup to the\\n -- type namespace, i.e. to `typ_gres`. In case of failure, we check\\n -- `val_gres` to produce a more helpful error message.\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- val_gres -> Failed $ LookupChildNonType item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEData{}\\n -- IEData (\'data\' namespace specifier) restricts the lookup to the\\n -- data namespace, i.e. to `val_gres`. In case of failure, we check\\n -- `typ_gres` to produce a more helpful error message.\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- typ_gres -> Failed $ LookupChildNonData item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEPattern{} -> panic \\"lookupChildren: IEPattern\\" -- Never happens (invalid syntax)\\n IEDefault{} -> panic \\"lookupChildren: IEDefault\\" -- Never happens (invalid syntax)\\n where\\n fs = (occNameFS . rdrNameOcc . ieWrappedName) r\\n gres = fromMaybe [] (lookupFsEnv kid_env fs)\\n (val_gres, typ_gres) = partition (isValNameSpace . greNameSpace) gres\\n\\n -- See Note [Children for duplicate record fields]\\n kid_env :: FastStringEnv [GlobalRdrElt]\\n kid_env = extendFsEnvList_C (++) emptyFsEnv\\n [(occNameFS (occName x), [x]) | x <- all_kids]\\n\\n\\n{- Note [Prioritise the value namespace in subordinate import lists]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider this program that defines a class that has both an associated type\\nnamed (#) and a method named (#)\\n\\n module M_assoc where\\n class C a b where\\n type a # b\\n (#) :: a -> b -> ()\\n module N_assoc where\\n import M_assoc( C((#)) )\\n\\nIn the import declaration, when we see the unadorned name (#) in the subordinate\\nimport list of C, which children should we bring into scope? Our options are:\\n\\n a) only the method (#)\\n b) only the associated type (#)\\n c) both the method and the associated type\\n\\nTo follow the precedent established by top-level items, we go with option (a).\\nIndeed, consider a slightly different program\\n\\n module M_top where\\n type family a # b\\n a # b = ()\\n module N_top where\\n import M_top( (#) )\\n\\nHere the import brings only the function (#) into scope, and one has to say\\n`type (#)` to get the type family.\\n-}\\n\\n-------------------------------\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused names}\\n* *\\n*********************************************************\\n-}\\n\\nreportUnusedNames :: TcGblEnv -> HscSource -> RnM ()\\nreportUnusedNames gbl_env hsc_src\\n = do { keep <- readTcRef (tcg_keep gbl_env)\\n ; traceRn \\"RUN\\" (ppr (tcg_dus gbl_env))\\n ; warnUnusedImportDecls gbl_env hsc_src\\n ; warnUnusedTopBinds $ unused_locals keep\\n ; warnMissingSignatures gbl_env\\n ; warnMissingKindSignatures gbl_env }\\n where\\n used_names :: NameSet -> NameSet\\n used_names keep = findUses (tcg_dus gbl_env) emptyNameSet `unionNameSet` keep\\n -- NB: currently, if f x = g, we only treat \'g\' as used if \'f\' is used\\n -- Hence findUses\\n\\n -- Collect the defined names from the in-scope environment\\n defined_names :: [GlobalRdrElt]\\n defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)\\n\\n kids_env = mkChildEnv defined_names\\n -- This is done in mkExports too; duplicated work\\n\\n gre_is_used :: NameSet -> GlobalRdrElt -> Bool\\n gre_is_used used_names gre0\\n = name `elemNameSet` used_names\\n || any (\\\\ gre -> greName gre `elemNameSet` used_names) (findChildren kids_env name)\\n -- A use of C implies a use of T,\\n -- if C was brought into scope by T(..) or T(C)\\n where\\n name = greName gre0\\n\\n -- Filter out the ones that are\\n -- (a) defined in this module, and\\n -- (b) not defined by a \'deriving\' clause\\n -- The latter have an Internal Name, so we can filter them out easily\\n unused_locals :: NameSet -> [GlobalRdrElt]\\n unused_locals keep =\\n let -- Note that defined_and_used, defined_but_not_used\\n -- are both [GRE]; that\'s why we need defined_and_used\\n -- rather than just used_names\\n _defined_and_used, defined_but_not_used :: [GlobalRdrElt]\\n (_defined_and_used, defined_but_not_used)\\n = partition (gre_is_used (used_names keep)) defined_names\\n\\n in filter is_unused_local defined_but_not_used\\n is_unused_local :: GlobalRdrElt -> Bool\\n is_unused_local gre = isLocalGRE gre\\n && isExternalName (greName gre)\\n\\n{- *********************************************************************\\n* *\\n Missing signatures\\n* *\\n********************************************************************* -}\\n\\n{-\\nNote [Missing signatures]\\n~~~~~~~~~~~~~~~~~~~~~~~~~\\nThere are four warning flags in play:\\n\\n * -Wmissing-exported-signatures\\n Warn about any exported top-level function/value without a type signature.\\n Does not include pattern synonyms.\\n\\n * -Wmissing-signatures\\n Warn about any top-level function/value without a type signature. Does not\\n include pattern synonyms. Takes priority over -Wmissing-exported-signatures.\\n\\n * -Wmissing-exported-pattern-synonym-signatures\\n Warn about any exported pattern synonym without a type signature.\\n\\n * -Wmissing-pattern-synonym-signatures\\n Warn about any pattern synonym without a type signature. Takes priority over\\n -Wmissing-exported-pattern-synonym-signatures.\\n\\n-}\\n\\n-- | Warn the user about top level binders that lack type signatures.\\n-- Called /after/ type inference, so that we can report the\\n-- inferred type of the function\\nwarnMissingSignatures :: TcGblEnv -> RnM ()\\nwarnMissingSignatures gbl_env\\n = do { let exports = availsToNameSet (tcg_exports gbl_env)\\n sig_ns = tcg_sigs gbl_env\\n -- We use sig_ns to exclude top-level bindings that are generated by GHC\\n binds = collectHsBindsBinders CollNoDictBinders $ tcg_binds gbl_env\\n pat_syns = tcg_patsyns gbl_env\\n\\n not_ghc_generated :: Name -> Bool\\n not_ghc_generated name = name `elemNameSet` sig_ns\\n\\n add_binding_warn :: Id -> RnM ()\\n add_binding_warn id =\\n when (not_ghc_generated name) $\\n do { env <- liftZonkM $ tcInitTidyEnv -- Why not use emptyTidyEnv?\\n ; let ty = tidyOpenType env (idType id)\\n missing = MissingTopLevelBindingSig name ty\\n diag = TcRnMissingSignature missing exported\\n ; addDiagnosticAt (getSrcSpan name) diag }\\n where\\n name = idName id\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n add_patsyn_warn :: PatSyn -> RnM ()\\n add_patsyn_warn ps =\\n when (not_ghc_generated name) $\\n addDiagnosticAt (getSrcSpan name)\\n (TcRnMissingSignature missing exported)\\n where\\n name = patSynName ps\\n missing = MissingPatSynSig ps\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n -- Warn about missing signatures\\n -- Do this only when we have a type to offer\\n -- See Note [Missing signatures]\\n ; mapM_ add_binding_warn binds\\n ; mapM_ add_patsyn_warn pat_syns\\n }\\n\\n-- | Warn the user about tycons that lack kind signatures.\\n-- Called /after/ type (and kind) inference, so that we can report the\\n-- inferred kinds.\\nwarnMissingKindSignatures :: TcGblEnv -> RnM ()\\nwarnMissingKindSignatures gbl_env\\n = do { cusks_enabled <- xoptM LangExt.CUSKs\\n ; mapM_ (add_ty_warn cusks_enabled) tcs\\n }\\n where\\n tcs = tcg_tcs gbl_env\\n ksig_ns = tcg_ksigs gbl_env\\n exports = availsToNameSet (tcg_exports gbl_env)\\n\\n has_kind_signature :: Name -> Bool\\n has_kind_signature name = name `elemNameSet` ksig_ns\\n\\n add_ty_warn :: Bool -> TyCon -> RnM ()\\n add_ty_warn cusks_enabled tyCon =\\n when (has_kind_signature name) $\\n addDiagnosticAt (getSrcSpan name) diag\\n where\\n name = tyConName tyCon\\n diag = TcRnMissingSignature missing exported\\n missing = MissingTyConKindSig tyCon cusks_enabled\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused imports}\\n* *\\n*********************************************************\\n\\nThis code finds which import declarations are unused. The\\nspecification and implementation notes are here:\\n https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/unused-imports\\n\\nSee also Note [Choosing the best import declaration] in GHC.Types.Name.Reader\\n-}\\n\\ntype ImportDeclUsage\\n = ( LImportDecl GhcRn -- The import declaration\\n , [GlobalRdrElt] -- What *is* used (normalised)\\n , [Name] -- What is imported but *not* used\\n , [NamespaceSpecifier GhcRn] ) -- Unused wildcards\\n\\nwarnUnusedImportDecls :: TcGblEnv -> HscSource -> RnM ()\\nwarnUnusedImportDecls gbl_env hsc_src\\n = do { uses <- readMutVar (tcg_used_gres gbl_env)\\n ; let imports = tcg_rn_imports gbl_env\\n rdr_env = tcg_rdr_env gbl_env\\n\\n -- We should only warn for unnecessary *user* imports, but deciding\\n -- minimal imports should take generated imports into account\\n ; let usageUserImports = findImportUsage (excludeGenerated imports) uses\\n usageAllImports = findImportUsage imports uses\\n\\n ; traceRn \\"warnUnusedImportDecls\\" $\\n (vcat [ text \\"Uses:\\" <+> ppr uses\\n , text \\"Usage all user imports: \\" <+> ppr usageUserImports\\n , text \\"Usage all imports: \\" <+> ppr usageAllImports])\\n\\n ; mapM_ (warnUnusedImport rdr_env) usageUserImports\\n\\n ; whenGOptM Opt_D_dump_minimal_imports $\\n printMinimalImports hsc_src usageAllImports }\\n\\n-- | Exclude generated imports\\nexcludeGenerated :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\nexcludeGenerated = filterOut (isGeneratedImport . ideclOrigin . ideclExt . unLoc)\\n\\nfindImportUsage :: [LImportDecl GhcRn]\\n -> [GlobalRdrElt]\\n -> [ImportDeclUsage]\\n\\nfindImportUsage imports used_gres\\n = map unused_decl imports\\n where\\n import_usage :: ImportMap\\n import_usage = mkImportMap used_gres\\n\\n unused_decl :: LImportDecl GhcRn -> ImportDeclUsage\\n unused_decl decl@(L _ (ImportDecl { ideclImportList = imps }))\\n = -- pprTrace \\"unused_decl\\" (vcat [ ppr decl\\n -- , text \\"used\\" <+> ppr used_gres\\n -- , text \\"unused\\" <+> ppr unused_names ]) $\\n (decl, used_gres, unused_names, unused_wcs)\\n where\\n used_gres = lookupImportMap decl import_usage\\n\\n used_gre_env = mkGlobalRdrEnv used_gres\\n used_parents = mkNameSet (mapMaybe greParent_maybe used_gres)\\n\\n (unused_names, unused_wcs) -- Not trivial; see eg #7454\\n = case imps of\\n Just (Exactly, imp_ies) ->\\n let unused = foldr (add_unused . unLoc) emptyUnusedNames imp_ies\\n nms = nameSetElemsStable (collectUnusedNames unused)\\n wcs = collectUnusedWildcards unused\\n in (nms, wcs)\\n _other -> ([], []) -- No explicit import list => no unused-name list\\n\\n add_unused :: IE GhcRn -> UnusedNames -> UnusedNames\\n add_unused (IEVar _ n _) acc = add_unused_name (lieWrappedName n) True acc\\n add_unused (IEThingAbs _ n _) acc = add_unused_name (lieWrappedName n) False acc\\n add_unused (IEThingAll _ _ n _) acc = add_unused_all (lieWrappedName n) acc\\n add_unused (IEThingWith _ p wc ns _) acc = add_wc_all (add_unused_with pn xs acc)\\n where pn = lieWrappedName p\\n xs = map lieWrappedName ns\\n add_wc_all = case wc of\\n NoIEWildcard -> id\\n IEWildcard _ -> add_unused_all pn\\n add_unused (IEWholeNamespace x ns_spec) acc = add_unused_wildcard ns_spec (iewn_names x) acc\\n add_unused _ acc = acc\\n\\n add_unused_name :: Name -> Bool -> UnusedNames -> UnusedNames\\n add_unused_name n is_ie_var acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | is_ie_var\\n , isFieldName n\\n -- See Note [Reporting unused imported duplicate record fields]\\n = let\\n fs = getOccFS n\\n (flds, flds_used) = lookupFsEnv acc_fs fs `orElse` (emptyNameSet, Any False)\\n acc_fs\' = extendFsEnv acc_fs fs (extendNameSet flds n, Any used S.<> flds_used)\\n in UnusedNames acc_ns acc_wcs acc_fs\'\\n\\n | used\\n = acc\\n\\n | otherwise\\n = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n where\\n used = isJust $ lookupGRE_Name used_gre_env n\\n\\n add_unused_all :: Name -> UnusedNames -> UnusedNames\\n add_unused_all n acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | Just {} <- lookupGRE_Name used_gre_env n = acc\\n | n `elemNameSet` used_parents = acc\\n | otherwise = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n\\n add_unused_with :: Name -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_with p ns acc\\n | all (`elemNameSet` acc1_ns) ns = add_unused_name p False acc1\\n | otherwise = acc1\\n where\\n acc1@(UnusedNames acc1_ns _ _) = foldr (\\\\n acc\' -> add_unused_name n False acc\') acc ns\\n -- If you use \'signum\' from Num, then the user may well have\\n -- imported Num(signum). We don\'t want to complain that\\n -- Num is not itself mentioned. Hence the two cases in add_unused_with.\\n\\n add_unused_wildcard :: NamespaceSpecifier GhcRn -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_wildcard ns_spec names acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | any_used = acc\\n | otherwise = UnusedNames acc_ns (ns_spec : acc_wcs) acc_fs\\n where\\n -- A wildcard `type ..` or `data ..` is used if at least one of\\n -- the names it expands to is used\\n any_used = any (isJust . lookupGRE_Name used_gre_env) names\\n\\n\\n-- | An accumulator for unused names in an import list.\\n--\\n-- See Note [Reporting unused imported duplicate record fields].\\ndata UnusedNames =\\n UnusedNames\\n { unused_names :: NameSet\\n -- ^ Unused \'Name\'s in an import list, not including record fields\\n -- that are plain \'IEVar\' imports (tracked by \'rec_fld_uses\')\\n -- or wildcard imports (tracked by \'unused_wildcards\').\\n , unused_wildcards :: [NamespaceSpecifier GhcRn]\\n -- ^ Unused wildcards @type ..@ or @data ..@ in an import list.\\n , rec_fld_uses :: FastStringEnv (NameSet, Any)\\n -- ^ Record fields imported without a parent (i.e. an \'IEVar\' import).\\n --\\n -- The \'Any\' value records whether any of the record fields\\n -- sharing the same underlying \'FastString\' have been used.\\n }\\n\\nemptyUnusedNames :: UnusedNames\\nemptyUnusedNames = UnusedNames emptyNameSet [] emptyFsEnv\\n\\ninstance Outputable UnusedNames where\\n ppr (UnusedNames nms wcs flds) =\\n text \\"UnusedNames\\" <+>\\n braces (ppr nms <+> ppr wcs <+> ppr (fmap (second getAny) flds))\\n\\n-- | Collect all unused names from a \'UnusedNames\' value.\\ncollectUnusedNames :: UnusedNames -> NameSet\\ncollectUnusedNames (UnusedNames { unused_names = nms, rec_fld_uses = flds })\\n = nms S.<> unused_flds\\n where\\n unused_flds = nonDetFoldFsEnv collect_unused emptyNameSet flds\\n collect_unused :: (NameSet, Any) -> NameSet -> NameSet\\n collect_unused (nms, Any at_least_one_name_is_used) acc\\n | at_least_one_name_is_used = acc\\n | otherwise = unionNameSet nms acc\\n\\ncollectUnusedWildcards :: UnusedNames -> [NamespaceSpecifier GhcRn]\\ncollectUnusedWildcards = unused_wildcards\\n\\n{- Note [Reporting unused imported duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have (#24035):\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M1 (R1(..), R2(..)) where\\n data R1 = MkR1 { fld :: Int }\\n data R2 = MkR2 { fld :: Int }\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M2 where\\n import M1 (R1(MkR1), R2, fld)\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nIn the import of \'M1\' in \'M2\', the \'fld\' import resolves to two separate GREs,\\nnamely R1(fld) and R2(fld). From the perspective of the renamer, and in particular\\nthe \'findImportUsage\' function, it\'s as if the user had imported the two names\\nseparately (even though no source syntax allows that).\\n\\nThis means that we need to be careful when reporting unused imports: the R2(fld)\\nimport is indeed unused, but because R1(fld) is used, we should not report\\nfld as unused altogether.\\n\\nTo achieve this, we keep track of record field imports without a parent (i.e.\\nusing the IEVar constructor) separately from other import items, using the\\nUnusedNames datatype.\\nOnce we have accumulated usages, we emit warnings for unused record fields\\nwithout parents one whole group (of record fields sharing the same textual name)\\nat a time, and only if *all* of the record fields in the group are unused;\\nsee \'collectUnusedNames\'.\\n\\nNote that this only applies to record fields imported without a parent. If we\\nhad:\\n\\n import M1 (R1(MkR1, fld), R2(fld))\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nthen of course we should report the second \'fld\' as unused.\\n-}\\n\\n\\n{- Note [The ImportMap]\\n~~~~~~~~~~~~~~~~~~~~~~~\\nThe ImportMap is a short-lived intermediate data structure records, for\\neach import declaration, what stuff brought into scope by that\\ndeclaration is actually used in the module.\\n\\nThe [GlobalRdrElt] are the things imported from that decl.\\n-}\\n\\ndata ImportMap = ImportMap\\n { im_imports :: Map RealSrcSpan [GlobalRdrElt]\\n -- ^ See [The ImportMap]\\n -- If loc :-> gres, then\\n -- \'loc\' = the end loc of the bestImport of each GRE in \'gres\'\\n , im_generatedImports :: Map ModuleName [GlobalRdrElt]\\n }\\n\\nmkImportMap :: [GlobalRdrElt] -> ImportMap\\n-- For each of a list of used GREs, find all the import decls that brought\\n-- it into scope; choose one of them (bestImport), and record\\n-- the RdrName in that import decl\'s entry in the ImportMap\\nmkImportMap = foldr insertImportMap $ ImportMap Map.empty Map.empty\\n\\ninsertImportMap :: GlobalRdrElt -> ImportMap -> ImportMap\\ninsertImportMap gre@(GRE { gre_imp = imp_specs }) importMap\\n | RealSrcSpan importSpan _ <- is_dloc best_imp_spec =\\n importMap{im_imports = insertElem importSpan gre $ im_imports importMap}\\n | GeneratedSrcSpan{} <- is_dloc best_imp_spec =\\n importMap{im_generatedImports = insertElem (moduleName $ is_mod best_imp_spec) gre $ im_generatedImports importMap}\\n | otherwise = importMap\\n where\\n best_imp_spec =\\n case bagToList imp_specs of\\n [] -> pprPanic \\"mkImportMap: GRE with no ImportSpecs\\" (ppr gre)\\n is:iss -> is_decl $ bestImport (is NE.:| iss)\\n\\n -- https://github.com/haskell/containers/issues/784\\n insertElem :: Ord k => k -> v -> Map k [v] -> Map k [v]\\n insertElem k v = flip Map.alter k $ \\\\case\\n Just vs -> Just (v : vs)\\n Nothing -> Just [v]\\n\\nlookupImportMap :: LImportDecl GhcRn -> ImportMap -> [GlobalRdrElt]\\nlookupImportMap (L srcSpan ImportDecl{ideclName = L _ modName}) importMap =\\n fromMaybe [] $\\n -- should match logic in insertImportMap\\n case locA srcSpan of\\n RealSrcSpan realSrcSpan _ -> realSrcSpan `Map.lookup` im_imports importMap\\n GeneratedSrcSpan{} -> modName `Map.lookup` im_generatedImports importMap\\n _ -> Nothing\\n\\nlieNames :: LIE (GhcPass p) -> [Located (IdP (GhcPass p))]\\nlieNames = _\\n\\nwarnUnusedImport :: GlobalRdrEnv -> ImportDeclUsage -> RnM ()\\nwarnUnusedImport rdr_env (L loc decl, used, unused, unused_wcs)\\n\\n -- Do not warn for \'import M()\'\\n -- See (UI1) in Note [Unused imports]\\n | Just (Exactly, _) <- ideclImportList decl\\n , null unused && null unused_wcs\\n = return ()\\n\\n -- Note [Do not warn about Prelude hiding]\\n | Just (EverythingBut, hides) <- ideclImportList decl\\n , not (null hides)\\n , pRELUDE_NAME == unLoc (ideclName decl)\\n = return ()\\n\\n -- Do not warn about import X as Rebindable\\n -- See (UI2) in Note [Unused imports]\\n | Just (L _ mod) <- ideclAs decl\\n , mod == rEBINDABLE_MOD_NAME\\n = return ()\\n\\n -- Nothing used; drop entire declaration\\n | null used\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl UnusedImportNone)\\n\\n -- Everything imported is used; nop\\n | null unused && null unused_wcs\\n = return ()\\n\\n -- Some imports are unused: make the `SrcSpan` cover only the unused\\n -- items instead of the whole import statement\\n | Just (_, imports) <- ideclImportList decl\\n , let unused_locs = [ locA loc | L loc ie <- imports\\n , name <- ieNames ie\\n , name `elem` unused ]\\n , loc1 : locs <- unused_locs\\n , let span = foldr1 combineSrcSpans ( loc1 NE.:| locs )\\n = addDiagnosticAt span (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n -- Some imports are unused\\n | otherwise\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n where\\n -- In warning message, pretty-print identifiers unqualified unconditionally\\n -- to improve the consistent for ambiguous/unambiguous identifiers.\\n -- See #14881.\\n possible_field n =\\n case lookupGRE_Name rdr_env n of\\n Just (GRE { gre_par = par, gre_info = IAmRecField info }) ->\\n let fld_occ :: OccName\\n fld_occ = nameOccName $ flSelector $ recFieldLabel info\\n in UnusedImportNameRecField par fld_occ\\n _ -> UnusedImportNameRegular n\\n\\n -- Print unused names in a deterministic (lexicographic) order\\n sort_unused :: [UnusedImportName]\\n sort_unused =\\n [ UnusedImportWildcard wc | wc <- unused_wcs ] ++\\n [ possible_field nm | nm <- sortBy (comparing nameOccName) unused ]\\n\\ngetMinimalImports :: [ImportDeclUsage] -> RnM [LImportDecl GhcRn]\\ngetMinimalImports ie_decls\\n = do { rdr_env <- getGlobalRdrEnv\\n ; fmap combine $ mapM (mk_minimal rdr_env) ie_decls }\\n where\\n mk_minimal rdr_env (L l decl, used_gres, unused, unused_wcs)\\n | null unused && null unused_wcs\\n , Just (Exactly, _) <- ideclImportList decl\\n = return (L l decl)\\n | otherwise\\n = do { let ImportDecl { ideclName = L _ mod_name\\n , ideclSource = is_boot\\n , ideclPkgQual = pkg_qual\\n , ideclExt = XImportDeclPass { ideclOrigin = origin } } = decl\\n ; iface <- loadSrcInterface doc (importDeclLookupScope origin)\\n mod_name is_boot pkg_qual\\n ; let used_avails = gresToAvailInfo used_gres\\n ; lies <- map (L l) <$> concatMapM (to_ie rdr_env iface) used_avails\\n ; return (L l (decl { ideclImportList = Just (Exactly, lies) })) }\\n where\\n doc = text \\"Compute minimal imports for\\" <+> ppr decl\\n\\n to_ie :: GlobalRdrEnv -> ModIface -> AvailInfo -> RnM [IE GhcRn]\\n -- The main trick here is that if we\'re importing all the constructors\\n -- we want to say \\"T(..)\\", but if we\'re importing only a subset we want\\n -- to say \\"T(A,B,C)\\". So we have to find out what the module exports.\\n to_ie rdr_env _ (Avail c) -- Note [Overloaded field import]\\n = do { let\\n gre = expectJust $ lookupGRE_Name rdr_env c\\n ; return $ [IEVar Nothing (to_ie_post_rn $ noLocA $ greName gre) Nothing] }\\n to_ie _ _ avail@(AvailTC n [_]) -- Exporting the main decl and nothing else\\n | availExportsDecl avail\\n = return [IEThingAbs Nothing (to_ie_post_rn $ noLocA n) Nothing]\\n to_ie rdr_env iface (AvailTC n cs) =\\n case [ xs | avail@(AvailTC x xs) <- mi_exports iface\\n , x == n\\n , availExportsDecl avail -- Note [Partial export]\\n ] of\\n [xs]\\n | all_used xs\\n -> return [IEThingAll (IEThingAllExt Nothing noAnn noAnn noAnn)\\n (NoNamespaceSpecifier noExtField)\\n (to_ie_post_rn $ noLocA n)\\n Nothing]\\n | otherwise\\n -> do { let ns_gres = map (expectJust . lookupGRE_Name rdr_env) cs\\n ns = map greName ns_gres\\n ; return [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n -- Note [Overloaded field import]\\n _other\\n -> do { let infos = map (expectJust . lookupGRE_Name rdr_env) cs\\n (ns_gres,fs_gres) = classifyGREs infos\\n ns = map greName (ns_gres ++ fs_gres)\\n fs = map fieldGREInfo fs_gres\\n ; return $\\n if all_non_overloaded fs\\n then map (\\\\nm -> IEVar Nothing (to_ie_post_rn_var $ noLocA nm) Nothing) ns\\n else [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n where\\n\\n all_used avail_cs = all (`elem` cs) avail_cs\\n\\n all_non_overloaded = all (not . flIsOverloaded . recFieldLabel)\\n\\n combine :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\n combine = map merge . NE.groupAllWith getKey\\n\\n getKey :: LImportDecl GhcRn -> (Bool, Maybe ModuleName, ModuleName)\\n getKey decl =\\n ( isImportDeclQualified . ideclQualified $ idecl -- is this qualified? (important that this be first)\\n , unLoc <$> ideclAs idecl -- what is the qualifier (inside Maybe monad)\\n , unLoc . ideclName $ idecl -- Module Name\\n )\\n where\\n idecl :: ImportDecl GhcRn\\n idecl = unLoc decl\\n\\n merge :: NonEmpty (LImportDecl GhcRn) -> LImportDecl GhcRn\\n merge decls@((L l decl) :| _) = L l (decl { ideclImportList = Just (Exactly, lies) })\\n where lies = concatMap snd $ mapMaybe (ideclImportList . unLoc) $ NE.toList decls\\n\\nclassifyGREs :: [GlobalRdrElt] -> ([GlobalRdrElt], [FieldGlobalRdrElt])\\nclassifyGREs = partition (not . isRecFldGRE)\\n\\nprintMinimalImports :: HscSource -> [ImportDeclUsage] -> RnM ()\\n-- See Note [Printing minimal imports]\\nprintMinimalImports hsc_src imports_w_usage\\n = do { imports\' <- excludeGenerated <$> getMinimalImports imports_w_usage\\n ; this_mod <- getModule\\n ; dflags <- getDynFlags\\n ; liftIO $ withFile (mkFilename dflags this_mod) WriteMode $ \\\\h ->\\n printForUser dflags h neverQualify AllTheWay (vcat (map ppr imports\'))\\n -- The neverQualify is important. We are printing Names\\n -- but they are in the context of an \'import\' decl, and\\n -- we never qualify things inside there\\n -- E.g. import Blag( f, b )\\n -- not import Blag( Blag.f, Blag.g )!\\n }\\n where\\n mkFilename dflags this_mod\\n | Just d <- dumpDir dflags = d basefn\\n | otherwise = basefn\\n where\\n suffix = case hsc_src of\\n HsBootFile -> \\".imports-boot\\"\\n HsSrcFile -> \\".imports\\"\\n HsigFile -> \\".imports\\"\\n basefn = moduleNameString (moduleName this_mod) ++ suffix\\n\\n\\nto_ie_post_rn_var :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn_var (L l n)\\n | isDataOcc $ occName n = L l (IEPattern noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n\\n\\nto_ie_post_rn :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn (L l n)\\n | isTcOcc occ && isSymOcc occ = L l (IEType noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n where occ = occName n\\n\\n{- Note [Do not warn about Prelude hiding]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWe do not warn about\\n import Prelude hiding( x, y )\\nbecause even if nothing else from Prelude is used, it may be essential to hide\\nx,y to avoid name-shadowing warnings. Example (#9061)\\n import Prelude hiding( log )\\n f x = log where log = ()\\n\\nNote [Unused imports]\\n~~~~~~~~~~~~~~~~~~~~~\\nIn `warnUnusedImport`, if we see an import with an explicit list imports, thus\\n import M( a, b )\\nand neither `a` nor `b` is used, we report the entire import decl as unused. We\\ncheck this by looking at the names that it brings into scope scope; if there are\\nno ununused names, don\'t report.\\n\\n(UI1) We don\'t want to complain about `import M()`, because that is often used to bring\\n M\'s /instances/ into scope. That is neatly dealt with by the \\"no unused\\n names\\" (nor unused wildcard imports) criterion.\\n\\n(UI2) We don\'t report a decl as unused if it has an `as Rebindable` qualifier.\\n See (KN1) in Note [Overview of known entities] in GHC.Builtin\\n\\n\\nNote [Printing minimal imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nTo print the minimal imports we walk over all import decls (both user-supplied\\nand generated), trim their import lists, then filter out generated decls.\\n\\nNB that\\n\\n * We do *not* change the \'qualified\' or \'as\' parts!\\n\\n * We do not discard a decl altogether; we might need instances\\n from it. Instead we just trim to an empty import list\\n\\nNote [Partial export]\\n~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have\\n\\n module A( op ) where\\n class C a where\\n op :: a -> a\\n\\n module B where\\n import A\\n f = ..op...\\n\\nThen the minimal import for module B is\\n import A( op )\\nnot\\n import A( C( op ) )\\nwhich we would usually generate if C was exported from B. Hence\\nthe availExportsDecl test when deciding what to generate.\\n\\n\\nNote [Overloaded field import]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nOn the other hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n data T = MkT { foo :: Int }\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( T(foo) )\\nbecause when DuplicateRecordFields is enabled, field selectors are\\nnot in scope without their enclosing datatype.\\n\\nOn the third hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n pattern MkT { foo } = Just foo\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( foo )\\nbecause foo doesn\'t have a parent. This might actually be ambiguous if A\\nexports another field called foo, but there is no good answer to return and this\\nis a very obscure corner, so it seems to be the best we can do. See\\nDRFPatSynExport for a test of this.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Errors}\\n* *\\n************************************************************************\\n-}\\n\\nbadImportItemErr\\n :: ModIface -> ImpDeclSpec -> IE GhcPs\\n -> IsSubordinateError\\n -> [AvailInfo]\\n -> TcRn (NonEmpty ImportLookupReason)\\nbadImportItemErr iface decl_spec ie sub avails = do\\n exts <- importLookupExtensions\\n let import_lookup_bad :: BadImportKind -> ImportLookupReason\\n import_lookup_bad k = ImportLookupBad k iface decl_spec ie exts\\n dflags <- getDynFlags\\n hsc_env <- getTopEnv\\n let rdr_env = mkGlobalRdrEnv\\n $ gresFromAvails hsc_env (Just imp_spec) all_avails\\n pure $ fmap import_lookup_bad (importErrorKind dflags rdr_env)\\n where\\n importErrorKind :: DynFlags -> GlobalRdrEnv -> NonEmpty BadImportKind\\n importErrorKind dflags rdr_env\\n | any checkIfTyCon avails = case sub of\\n IsNotSubordinate -> NE.singleton BadImportAvailTyCon\\n IsSubordinateError { subordinate_err_parent = gre\\n , subordinate_err_unavailable = unavailable\\n , subordinate_err_nontype = nontype\\n , subordinate_err_nondata = nondata }\\n -> NE.fromList $ catMaybes $\\n [ fmap (BadImportNotExportedSubordinates gre) (NE.nonEmpty unavailable)\\n , fmap (BadImportNonTypeSubordinates gre) (NE.nonEmpty nontype)\\n , fmap (BadImportNonDataSubordinates gre) (NE.nonEmpty nondata) ]\\n | any checkIfVarName avails = NE.singleton BadImportAvailVar\\n | Just con <- find checkIfDataCon avails = NE.singleton (BadImportAvailDataCon (availOccName con))\\n | otherwise = NE.singleton (BadImportNotExported suggs)\\n where\\n suggs = similar_suggs ++ fieldSelectorSuggestions rdr_env rdr\\n what_look = case sub of\\n IsNotSubordinate -> WL_TyCon_or_TermVar\\n IsSubordinateError { subordinate_err_parent = gre } ->\\n case greInfo gre of\\n IAmTyCon ClassFlavour\\n -> WL_TyCon_or_TermVar\\n _ -> WL_Term\\n similar_names =\\n similarNameSuggestions (Unbound.LF what_look WL_Global)\\n dflags rdr_env emptyLocalRdrEnv rdr\\n similar_suggs =\\n case NE.nonEmpty $ mapMaybe imported_item $ similar_names of\\n Just similar -> [ SuggestSimilarNames rdr similar ]\\n Nothing -> [ ]\\n\\n -- Only keep imported items, and set the \\"HowInScope\\" to\\n -- \\"Nothing\\" to avoid printing \\"imported from...\\" in the suggestion\\n -- error message.\\n imported_item (SimilarRdrName rdr_name gre (Just (ImportedBy {})))\\n = Just (SimilarRdrName rdr_name gre Nothing)\\n imported_item _ = Nothing\\n\\n checkIfDataCon = checkIfAvailMatches isDataConName\\n checkIfTyCon = checkIfAvailMatches isTyConName\\n checkIfVarName =\\n \\\\case\\n AvailTC{} -> False\\n Avail n -> importedFS == occNameFS (occName n)\\n && (isVarOcc <||> isFieldOcc) (occName n)\\n checkIfAvailMatches namePred =\\n \\\\case\\n AvailTC _ ns ->\\n case find (\\\\n -> importedFS == occNameFS (occName n)) ns of\\n Just n -> namePred n\\n Nothing -> False\\n Avail{} -> False\\n availOccName = occName . availName\\n rdr = ieName ie\\n importedFS = occNameFS $ rdrNameOcc rdr\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n all_avails = mi_exports iface\\n\\nimportLookupExtensions :: TcRn ImportLookupExtensions\\nimportLookupExtensions = do\\n ile_pattern_synonyms <- xoptM LangExt.PatternSynonyms\\n ile_explicit_namespaces <- xoptM LangExt.ExplicitNamespaces\\n return ImportLookupExtensions{ile_pattern_synonyms, ile_explicit_namespaces}\\n\\naddDupDeclErr :: NonEmpty GlobalRdrElt -> TcRn ()\\naddDupDeclErr gres@(gre :| _)\\n -- Report the error at the later location\\n = addErrAt (getSrcSpan (NE.last sorted_names)) $ (TcRnDuplicateDecls (greOccName gre) sorted_names)\\n where\\n sorted_names =\\n NE.sortBy (SrcLoc.leftmost_smallest `on` nameSrcSpan)\\n (fmap greName gres)\\n\\n-- This data decl will parse OK\\n-- data T = a Int\\n-- treating \\"a\\" as the constructor.\\n-- It is really hard to make the parser spot this malformation.\\n-- So the renamer has to check that the constructor is legal\\n--\\n-- We can get an operator as the constructor, even in the prefix form:\\n-- data T = :% Int Int\\n-- from interface files, which always print in prefix form\\n--\\n-- We also allow type constructor names, which are defined by \\"type data\\"\\n-- declarations. See Note [Type data declarations] in GHC.Rename.Module.\\n\\ncheckConName :: RdrName -> TcRn ()\\ncheckConName name\\n = checkErr (isRdrDataCon name || isRdrTc name) (TcRnIllegalDataCon name)\\n", "filetypes": ["haskell"]}}}' 2026-10-16 14:47:41,288 - DEBUG - POST b'http://127.0.0.1:37093/receive_messages' {'content-type': 'application/json', 'x-ycm-hmac': b'Rga7Yd4l4fgfufwYw+0sxzurvznImlBO0MPmgAlS4EY='} b'{"filepath": "/home/enrico/ghc/compiler/GHC/Rename/Names.hs", "line_num": 1, "column_num": 1, "working_dir": "/home/enrico/ghc", "file_data": {"/home/enrico/ghc/compiler/GHC/Rename/Names.hs": {"contents": "{-\\n(c) The GRASP/AQUA Project, Glasgow University, 1992-1998\\n\\nExtracting imported and top-level names in scope\\n-}\\n\\n{-# LANGUAGE NondecreasingIndentation #-}\\n{-# LANGUAGE TypeFamilies #-}\\n\\nmodule GHC.Rename.Names (\\n rnImports, getLocalNonValBinders, newRecordFieldLabel,\\n importsFromIface,\\n ImportUserSpec(..),\\n extendGlobalRdrEnvRn,\\n gresFromAvails,\\n calculateAvails,\\n reportUnusedNames,\\n checkConName,\\n mkChildEnv,\\n findChildren,\\n mkBadExportSubordinate,\\n findImportUsage,\\n getMinimalImports,\\n printMinimalImports,\\n renamePkgQual, renameRawPkgQual,\\n classifyGREs,\\n ImportDeclUsage,\\n rnNamespaceSpecifier\\n ) where\\n\\nimport GHC.Prelude hiding ( head, init, last, tail )\\n\\nimport GHC.Driver.Env\\nimport GHC.Driver.Session\\nimport GHC.Driver.Ppr\\n\\nimport GHC.Rename.Env\\nimport GHC.Rename.Fixity\\nimport GHC.Rename.Utils ( warnUnusedTopBinds )\\nimport GHC.Rename.Unbound\\nimport qualified GHC.Rename.Unbound as Unbound\\n\\nimport GHC.Tc.Errors.Types\\nimport GHC.Tc.Utils.Env\\nimport GHC.Tc.Utils.Monad\\nimport GHC.Tc.Types.LclEnv\\nimport GHC.Tc.Zonk.TcType ( tcInitTidyEnv )\\n\\nimport GHC.Hs\\nimport GHC.Iface.Load ( loadSrcInterface, loadSrcInterface_maybe )\\nimport GHC.Iface.Errors.Types\\n ( IfaceMessage(..), MissingInterfaceError, InterfaceLookingFor(..)\\n , LoadEssentialsReason(..) )\\nimport GHC.Iface.Syntax ( fromIfaceWarnings )\\nimport GHC.Builtin.Modules( pRELUDE_NAME, rEBINDABLE_MOD_NAME )\\nimport GHC.Parser.PostProcess ( setRdrNameSpace )\\nimport GHC.Core.TyCo.Tidy\\nimport GHC.Core.PatSyn\\nimport GHC.Core.TyCon ( TyCon, tyConName )\\nimport qualified GHC.LanguageExtensions as LangExt\\n\\nimport GHC.Utils.Outputable as Outputable\\nimport GHC.Utils.Misc as Utils\\nimport GHC.Utils.Panic\\n\\nimport GHC.Types.Fixity.Env\\nimport GHC.Types.SafeHaskell\\nimport GHC.Types.Name\\nimport GHC.Types.Name.Env\\nimport GHC.Types.Name.Set\\nimport GHC.Types.Name.Reader\\nimport GHC.Types.Avail\\nimport GHC.Types.FieldLabel\\nimport GHC.Types.Hint\\nimport GHC.Types.SourceFile\\nimport GHC.Types.SrcLoc as SrcLoc\\nimport GHC.Types.Basic (TyConFlavour (..), convImportLevel, VisArity)\\nimport GHC.Types.UnresolvedImport\\nimport GHC.Types.Id\\nimport GHC.Types.PkgQual\\nimport GHC.Types.GREInfo (ConInfo(..), ConFieldInfo (..), ConLikeInfo (ConIsData))\\n\\nimport GHC.Unit\\nimport GHC.Unit.Module.Warnings\\nimport GHC.Unit.Module.ModIface\\nimport GHC.Unit.Module.Imported\\nimport GHC.Unit.Module.Deps\\nimport GHC.Unit.Env\\n\\nimport GHC.Data.Bag\\nimport GHC.Data.FastString\\nimport GHC.Data.FastString.Env\\nimport GHC.Data.Maybe\\nimport GHC.Data.List.SetOps ( removeDups )\\n\\nimport Control.Arrow ( second )\\nimport Control.Monad\\nimport Data.Foldable ( for_ )\\nimport Data.IntMap ( IntMap )\\nimport qualified Data.IntMap as IntMap\\nimport Data.Map ( Map )\\nimport qualified Data.Map as Map\\nimport Data.Ord ( comparing )\\nimport Data.Semigroup ( Any(..) )\\nimport qualified Data.Semigroup as S\\nimport Data.List ( partition, find, sortBy )\\nimport Data.List.NonEmpty (NonEmpty(..))\\nimport qualified Data.List.NonEmpty as NE\\nimport Data.Function ( on )\\nimport qualified Data.Set as S\\nimport System.FilePath (())\\nimport System.IO\\n\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{rnImports}\\n* *\\n************************************************************************\\n\\nNote [Tracking Trust Transitively]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen we import a package as well as checking that the direct imports are safe\\naccording to the rules outlined in the Note [Safe Haskell Trust Check] in GHC.Driver.Main\\nwe must also check that these rules hold transitively for all dependent modules\\nand packages. Doing this without caching any trust information would be very\\nslow as we would need to touch all packages and interface files a module depends\\non. To avoid this we make use of the property that if a modules Safe Haskell\\nmode changes, this triggers a recompilation from that module in the dependency\\ngraph. So we can just worry mostly about direct imports.\\n\\nThere is one trust property that can change for a package though without\\nrecompilation being triggered: package trust. So we must check that all\\npackages a module transitively depends on to be trusted are still trusted when\\nwe are compiling this module (as due to recompilation avoidance some modules\\nbelow may not be considered trusted any more without recompilation being\\ntriggered).\\n\\nWe handle this by augmenting the existing transitive list of packages a module M\\ndepends on with a bool for each package that says if it must be trusted when the\\nmodule M is being checked for trust. This list of trust required packages for a\\nsingle import is gathered in the rnImportDecl function and stored in an\\nImportAvails data structure. The union of these trust required packages for all\\nimports is done by the rnImports function using the combine function which calls\\nthe plusImportAvails function that is a union operation for the ImportAvails\\ntype. This gives us in an ImportAvails structure all packages required to be\\ntrusted for the module we are currently compiling. Checking that these packages\\nare still trusted (and that direct imports are trusted) is done in\\nGHC.Driver.Main.checkSafeImports.\\n\\nSee the note below, [Trust Own Package] for a corner case in this method and\\nhow its handled.\\n\\n\\nNote [Trust Own Package]\\n~~~~~~~~~~~~~~~~~~~~~~~~\\nThere is a corner case of package trust checking that the usual transitive check\\ndoesn\'t cover. (For how the usual check operates see the Note [Tracking Trust\\nTransitively] below). The case is when you import a -XSafe module M and M\\nimports a -XTrustworthy module N. If N resides in a different package than M,\\nthen the usual check works as M will record a package dependency on N\'s package\\nand mark it as required to be trusted. If N resides in the same package as M\\nthough, then importing M should require its own package be trusted due to N\\n(since M is -XSafe so doesn\'t create this requirement by itself). The usual\\ncheck fails as a module doesn\'t record a package dependency of its own package.\\nSo instead we now have a bool field in a modules interface file that simply\\nstates if the module requires its own package to be trusted. This field avoids\\nus having to load all interface files that the module depends on to see if one\\nis trustworthy.\\n\\n\\nNote [Trust Transitive Property]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSo there is an interesting design question in regards to transitive trust\\nchecking. Say I have a module B compiled with -XSafe. B is dependent on a bunch\\nof modules and packages, some packages it requires to be trusted as its using\\n-XTrustworthy modules from them. Now if I have a module A that doesn\'t use safe\\nhaskell at all and simply imports B, should A inherit all the trust\\nrequirements from B? Should A now also require that a package p is trusted since\\nB required it?\\n\\nWe currently say no but saying yes also makes sense. The difference is, if a\\nmodule M that doesn\'t use Safe Haskell imports a module N that does, should all\\nthe trusted package requirements be dropped since M didn\'t declare that it cares\\nabout Safe Haskell (so -XSafe is more strongly associated with the module doing\\nthe importing) or should it be done still since the author of the module N that\\nuses Safe Haskell said they cared (so -XSafe is more strongly associated with\\nthe module that was compiled that used it).\\n\\nGoing with yes is a simpler semantics we think and harder for the user to stuff\\nup but it does mean that Safe Haskell will affect users who don\'t care about\\nSafe Haskell as they might grab a package from Cabal which uses safe haskell (say\\nnetwork) and that packages imports -XTrustworthy modules from another package\\n(say bytestring), so requires that package is trusted. The user may now get\\ncompilation errors in code that doesn\'t do anything with Safe Haskell simply\\nbecause they are using the network package. They will have to call \'ghc-pkg\\ntrust network\' to get everything working. Due to this invasive nature of going\\nwith yes we have gone with no for now.\\n-}\\n\\n-- | Process Import Decls. See \'rnImportDecl\' for a description of what\\n-- the return types represent.\\n-- Note: Do the non SOURCE ones first, so that we get a helpful warning\\n-- for SOURCE ones that are unnecessary\\nrnImports :: [(LImportDecl GhcPs, SDoc)]\\n -> RnM ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\nrnImports imports = do\\n tcg_env <- getGblEnv\\n -- NB: want an identity module here, because it\'s OK for a signature\\n -- module to import from its implementor\\n let this_mod = tcg_mod tcg_env\\n let (source, ordinary) = partition (is_source_import . fst) imports\\n is_source_import (d::LImportDecl GhcPs) = ideclSource (unLoc d) == IsBoot\\n stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary\\n stuff2 <- mapAndReportM (rnImportDecl this_mod) source\\n -- Safe Haskell: See Note [Tracking Trust Transitively]\\n let (decls, imp_user_spec, rdr_env, imp_avails) = combine (stuff1 ++ stuff2)\\n -- Update imp_boot_mods if imp_direct_mods mentions any of them\\n let merged_import_avail = clobberSourceImports imp_avails\\n return (decls, imp_user_spec, rdr_env, merged_import_avail)\\n\\n where\\n clobberSourceImports imp_avails =\\n imp_avails { imp_boot_mods = imp_boot_mods\' }\\n where\\n imp_boot_mods\' = mergeInstalledModuleEnv combJ id (const emptyInstalledModuleEnv)\\n (imp_boot_mods imp_avails)\\n (imp_direct_dep_mods imp_avails)\\n\\n combJ (GWIB _ IsBoot) (_, x) = Just x\\n combJ r _ = Just r\\n -- See Note [Combining ImportAvails]\\n combine :: [(LImportDecl GhcRn, ImportUserSpec, GlobalRdrEnv, ImportAvails)]\\n -> ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\n combine ss =\\n let (decls, imp_user_spec, rdr_env, imp_avails, finsts) = foldr\\n plus\\n ([], [], emptyGlobalRdrEnv, emptyImportAvails, emptyModuleSet)\\n ss\\n in (decls, imp_user_spec, rdr_env, imp_avails { imp_finsts = moduleSetElts finsts })\\n\\n plus (decl, us, gbl_env1, imp_avails1)\\n (decls, uss, gbl_env2, imp_avails2, finsts_set)\\n = ( decl:decls,\\n us:uss,\\n gbl_env1 `plusGlobalRdrEnv` gbl_env2,\\n imp_avails1\' `plusImportAvails` imp_avails2,\\n extendModuleSetList finsts_set new_finsts )\\n where\\n imp_avails1\' = imp_avails1 { imp_finsts = [] }\\n new_finsts = imp_finsts imp_avails1\\n\\n{-\\nNote [Combining ImportAvails]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nimp_finsts in ImportAvails is a list of family instance modules\\ntransitively depended on by an import. imp_finsts for a currently\\ncompiled module is a union of all the imp_finsts of imports.\\nComputing the union of two lists of size N is O(N^2) and if we\\ndo it to M imports we end up with O(M*N^2). That can get very\\nexpensive for bigger module hierarchies.\\n\\nUnion can be optimized to O(N log N) if we use a Set.\\nimp_finsts is converted back and forth between dep_finsts, so\\nchanging a type of imp_finsts means either paying for the conversions\\nor changing the type of dep_finsts as well.\\n\\nI\'ve measured that the conversions would cost 20% of allocations on my\\ntest case, so that can be ruled out.\\n\\nChanging the type of dep_finsts forces checkFamInsts to\\nget the module lists in non-deterministic order. If we wanted to restore\\nthe deterministic order, we\'d have to sort there, which is an additional\\ncost. As far as I can tell, using a non-deterministic order is fine there,\\nbut that\'s a brittle nonlocal property which I\'d like to avoid.\\n\\nAdditionally, dep_finsts is read from an interface file, so its \\"natural\\"\\ntype is a list. Which makes it a natural type for imp_finsts.\\n\\nSince rnImports.combine is really the only place that would benefit from\\nit being a Set, it makes sense to optimize the hot loop in rnImports.combine\\nwithout changing the representation.\\n\\nSo here\'s what we do: instead of naively merging ImportAvails with\\nplusImportAvails in a loop, we make plusImportAvails merge empty imp_finsts\\nand compute the union on the side using Sets. When we\'re done, we can\\nconvert it back to a list. One nice side effect of this approach is that\\nif there\'s a lot of overlap in the imp_finsts of imports, the\\nSet doesn\'t really need to grow and we don\'t need to allocate.\\n\\nRunning generateModules from #14693 with DEPTH=16, WIDTH=30 finishes in\\n23s before, and 11s after.\\n-}\\n\\n-- | Given a located import declaration @decl@ from @this_mod@,\\n-- calculate the following pieces of information:\\n--\\n-- 1. An updated \'LImportDecl\', where all unresolved \'RdrName\' in\\n-- the entity lists have been resolved into \'Name\'s,\\n--\\n-- 2. A \'GlobalRdrEnv\' representing the new identifiers that were\\n-- brought into scope (taking into account module qualification\\n-- and hiding),\\n--\\n-- 3. \'ImportAvails\' summarizing the identifiers that were imported\\n-- by this declaration, and\\n--\\n-- 4. A boolean \'AnyHpcUsage\' which is true if the imported module\\n-- used HPC.\\nrnImportDecl :: Module -> (LImportDecl GhcPs, SDoc)\\n -> RnM (LImportDecl GhcRn, ImportUserSpec , GlobalRdrEnv, ImportAvails)\\nrnImportDecl this_mod\\n (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name\\n , ideclPkgQual = raw_pkg_qual\\n , ideclSource = want_boot\\n , ideclSafe = mod_safe\\n , ideclLevelSpec = import_level\\n , ideclQualified = qual_style\\n , ideclExt = XImportDeclPass { ideclOrigin = origin }\\n , ideclAs = as_mod, ideclImportList = imp_details }), import_reason)\\n = setSrcSpanA loc $ do\\n\\n case raw_pkg_qual of\\n NoRawPkgQual -> pure ()\\n RawPkgQual {} -> do\\n pkg_imports <- xoptM LangExt.PackageImports\\n when (not pkg_imports) $ addErr TcRnPackageImportsDisabled\\n\\n let qual_only = isImportDeclQualified qual_style\\n generated = isGeneratedImport origin\\n\\n lookup_scope = importDeclLookupScope origin\\n\\n -- If there\'s an error in loadInterface, (e.g. interface\\n -- file not found) we get lots of spurious errors from \'filterImports\'\\n let imp_mod_name = unLoc loc_imp_mod_name\\n doc = ppr imp_mod_name <+> import_reason\\n\\n hsc_env <- getTopEnv\\n unit_env <- hsc_unit_env <$> getTopEnv\\n let pkg_qual = renameRawPkgQual unit_env imp_mod_name raw_pkg_qual\\n\\n -- Check for self-import, which confuses the typechecker (#9032)\\n -- ghc --make rejects self-import cycles already, but batch-mode may not\\n -- at least not until GHC.IfaceToCore.tcHiBootIface, which is too late to avoid\\n -- typechecker crashes. (Indirect self imports are not caught until\\n -- GHC.IfaceToCore, see #10337 tracking how to make this error better.)\\n --\\n -- Originally, we also allowed \'import {-# SOURCE #-} M\', but this\\n -- caused bug #10182: in one-shot mode, we should never load an hs-boot\\n -- file for the module we are compiling into the EPS. In principle,\\n -- it should be possible to support this mode of use, but we would have to\\n -- extend Provenance to support a local definition in a qualified location.\\n -- For now, we don\'t support it, but see #10336\\n when (imp_mod_name == moduleName this_mod &&\\n (case pkg_qual of -- If we have import \\"\\" M, then we should\\n -- check that \\"\\" is \\"this\\" (which is magic)\\n -- or the name of this_mod\'s package. Yurgh!\\n -- c.f. GHC.findModule, and #9997\\n NoPkgQual -> True\\n ThisPkg uid -> uid == homeUnitId_ (hsc_dflags hsc_env)\\n OtherPkg _ -> False))\\n (addErr (TcRnSelfImport imp_mod_name))\\n\\n -- Check for a missing import list (Opt_WarnMissingImportList also\\n -- checks for T(..) items but that is done in checkDodgyImport below)\\n case imp_details of\\n Just (Exactly, _) -> return () -- Explicit import list\\n _ | generated -> return () -- Do not bleat for generated imports\\n | qual_only -> return ()\\n | otherwise -> addDiagnostic (TcRnNoExplicitImportList imp_mod_name)\\n\\n\\n mb_iface <- loadSrcInterface_maybe doc lookup_scope imp_mod_name want_boot pkg_qual\\n iface <- case mb_iface of\\n Succeeded iface -> return iface\\n Failed err -> failWithTc $\\n importDeclLoadFailure origin imp_mod_name want_boot err\\n\\n -- Compiler sanity check: if the import didn\'t say\\n -- {-# SOURCE #-} we should not get a hi-boot file\\n warnPprTrace ((want_boot == NotBoot) && (mi_boot iface == IsBoot)) \\"rnImportDecl\\" (ppr imp_mod_name) $ do\\n\\n -- Issue a user warning for a redundant {- SOURCE -} import\\n -- NB that we arrange to read all the ordinary imports before\\n -- any of the {- SOURCE -} imports.\\n --\\n -- in --make and GHCi, the compilation manager checks for this,\\n -- and indeed we shouldn\'t do it here because the existence of\\n -- the non-boot module depends on the compilation order, which\\n -- is not deterministic. The hs-boot test can show this up.\\n dflags <- getDynFlags\\n warnIf ((want_boot == IsBoot) && (mi_boot iface == NotBoot) && isOneShot (ghcMode dflags))\\n (TcRnRedundantSourceImport imp_mod_name)\\n when (mod_safe && not (safeImportsOn dflags)) $\\n addErr (TcRnSafeImportsDisabled imp_mod_name)\\n\\n let imp_mod = mi_module iface\\n qual_mod_name = fmap unLoc as_mod `orElse` imp_mod_name\\n imp_spec = ImpDeclSpec { is_mod = imp_mod, is_qual = qual_only,\\n is_dloc = locA loc, is_as = qual_mod_name,\\n is_pkg_qual = pkg_qual, is_isboot = want_boot,\\n is_level = convImportLevel import_level }\\n\\n let filter_imports = do\\n -- filter the imports according to the import declaration\\n (new_imp_details, imp_user_list, gbl_env)\\n <- filterImports hsc_env iface imp_spec imp_details\\n -- for certain error messages, we\\u2019d like to know what could be\\n -- imported here, if everything were imported\\n potential_gres <- (\\\\(_,_,x) -> x) <$> filterImports hsc_env iface imp_spec Nothing\\n return (new_imp_details, imp_user_list, gbl_env, potential_gres)\\n\\n (new_imp_details, imp_user_list, gbl_env, potential_gres) <-\\n case origin of\\n ImplicitEssentialsImport ->\\n -- The implicit GHC.Essentials import does not bring anything into scope.\\n -- See Note [Finding GHC.Essentials] in GHC.Builtin.\\n return (Nothing, ImpUserDependOnly, emptyGlobalRdrEnv, emptyGlobalRdrEnv)\\n UserWrittenImport -> filter_imports\\n ImplicitPreludeImport -> filter_imports\\n PluginImport -> filter_imports\\n\\n let is_hiding | Just (EverythingBut,_) <- imp_details = True\\n | otherwise = False\\n\\n -- should the import be safe?\\n mod_safe\' = mod_safe\\n || (not generated && safeDirectImpsReq dflags)\\n || (generated && safeImplicitImpsReq dflags)\\n\\n hsc_env <- getTopEnv\\n let home_unit = hsc_home_unit hsc_env\\n other_home_units = hsc_all_home_unit_ids hsc_env\\n\\n imported_by\\n | isDependOnlyImport imp_user_list\\n = ImportedBySystem\\n | otherwise\\n = ImportedByUser $ ImportedModsVal\\n { imv_name = is_as imp_spec\\n , imv_span = locA loc\\n , imv_is_safe = mod_safe\'\\n , imv_is_hiding = is_hiding\\n , imv_all_exports = potential_gres\\n , imv_qualified = qual_only\\n , imv_is_level = convImportLevel import_level\\n }\\n imports = calculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by\\n\\n -- Complain if we import a deprecated module\\n case fromIfaceWarnings (mi_warns iface) of\\n WarnAll txt -> addDiagnostic (TcRnDeprecatedModule imp_mod_name txt)\\n _ -> return ()\\n\\n let new_imp_decl = ImportDecl\\n { ideclExt = ideclExt decl\\n , ideclName = ideclName decl\\n , ideclPkgQual = pkg_qual\\n , ideclSource = ideclSource decl\\n , ideclSafe = mod_safe\'\\n , ideclQualified = ideclQualified decl\\n , ideclAs = ideclAs decl\\n , ideclImportList = new_imp_details\\n , ideclLevelSpec = ideclLevelSpec decl\\n }\\n\\n return (L loc new_imp_decl, ImpUserSpec imp_spec imp_user_list, gbl_env, imports)\\n\\n-- | The error message to emit when we failed to load an interface.\\nimportDeclLoadFailure :: ImportDeclOrigin -> ModuleName -> IsBootInterface\\n -> MissingInterfaceError -> TcRnMessage\\nimportDeclLoadFailure ImplicitEssentialsImport _ _ err\\n = TcRnInterfaceError $ CantFindEssentials err LookingForEssentialsModule\\nimportDeclLoadFailure _ mod_name want_boot err\\n = TcRnInterfaceError $ Can\'tFindInterface err $ LookingForModule mod_name want_boot\\n\\n-- | Rename raw package imports\\nrenameRawPkgQual :: UnitEnv -> ModuleName -> RawPkgQual -> PkgQual\\nrenameRawPkgQual unit_env mn = \\\\case\\n NoRawPkgQual -> NoPkgQual\\n RawPkgQual _ fs -> renamePkgQual unit_env mn $ Just fs\\n\\n-- | Rename raw package imports\\nrenamePkgQual :: UnitEnv -> ModuleName -> Maybe FastString -> PkgQual\\nrenamePkgQual unit_env mn mb_pkg = case mb_pkg of\\n Nothing -> NoPkgQual\\n Just pkg_fs\\n | Just uid <- homeUnitId <$> ue_homeUnit unit_env\\n , pkg_fs == fsLit \\"this\\"\\n -> ThisPkg uid\\n\\n | Just (uid, _) <- find (fromMaybe False . fmap (== pkg_fs) . snd) home_names\\n -> ThisPkg uid\\n\\n | Just uid <- resolvePackageImport unit_state mn (PackageName pkg_fs)\\n -> OtherPkg uid\\n\\n | otherwise\\n -> OtherPkg (UnitId pkg_fs)\\n -- not really correct as pkg_fs is unlikely to be a valid unit-id but\\n -- we will report the failure later...\\n where\\n home_names =\\n [ (uid, mkFastString <$> thisPackageName (homeUnitEnv_dflags (ue_findHomeUnitEnv uid unit_env)))\\n | uid <- S.toList hpt_deps\\n ]\\n\\n unit_state = ue_homeUnitState unit_env\\n\\n hpt_deps :: S.Set UnitId\\n hpt_deps = homeUnitDepends unit_state\\n\\n\\n-- | Calculate the \'ImportAvails\' induced by an import of a particular\\n-- interface, but without \'imp_mods\'.\\ncalculateAvails :: HomeUnit\\n -> S.Set UnitId\\n -> ModIface\\n -> IsSafeImport\\n -> IsBootInterface\\n -> ImportedBy\\n -> ImportAvails\\ncalculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by =\\n let imp_mod = mi_module iface\\n imp_sem_mod= mi_semantic_module iface\\n orph_iface = mi_orphan iface\\n has_finsts = mi_finsts iface\\n deps = mi_deps iface\\n trust = getSafeMode $ mi_trust iface\\n trust_pkg = mi_trust_pkg iface\\n is_sig = mi_hsc_src iface == HsigFile\\n\\n -- If the module exports anything defined in this module, just\\n -- ignore it. Reason: otherwise it looks as if there are two\\n -- local definition sites for the thing, and an error gets\\n -- reported. Easiest thing is just to filter them out up\\n -- front. This situation only arises if a module imports\\n -- itself, or another module that imported it. (Necessarily,\\n -- this involves a loop.)\\n --\\n -- We do this *after* filterImports, so that if you say\\n -- module A where\\n -- import B( AType )\\n -- type AType = ...\\n --\\n -- module B( AType ) where\\n -- import {-# SOURCE #-} A( AType )\\n --\\n -- then you won\'t get a \'B does not export AType\' message.\\n\\n\\n -- Compute new transitive dependencies\\n --\\n -- \'dep_orphs\' and \'dep_finsts\' do NOT include the imported module\\n -- itself, but we DO need to include this module in \'imp_orphs\' and\\n -- \'imp_finsts\' if it defines an orphan or instance family; thus the\\n -- orph_iface/has_iface tests.\\n\\n deporphs = dep_orphs deps\\n depfinsts = dep_finsts deps\\n\\n orphans | orph_iface = assertPpr (not (imp_sem_mod `elem` deporphs)) (ppr imp_sem_mod <+> ppr deporphs) $\\n imp_sem_mod : deporphs\\n | otherwise = deporphs\\n\\n finsts | has_finsts = assertPpr (not (imp_sem_mod `elem` depfinsts)) (ppr imp_sem_mod <+> ppr depfinsts) $\\n imp_sem_mod : depfinsts\\n | otherwise = depfinsts\\n\\n -- Trusted packages are a lot like orphans.\\n trusted_pkgs | mod_safe\' = dep_trusted_pkgs deps\\n | otherwise = S.empty\\n\\n\\n pkg = moduleUnit (mi_module iface)\\n ipkg = toUnitId pkg\\n\\n -- Does this import mean we now require our own pkg\\n -- to be trusted? See Note [Trust Own Package]\\n ptrust = trust == Sf_Trustworthy || trust_pkg\\n pkg_trust_req\\n | isHomeUnit home_unit pkg = ptrust\\n | otherwise = False\\n\\n dependent_pkgs = if toUnitId pkg `S.member` other_home_units\\n then S.empty\\n else S.singleton (lvl, ipkg)\\n\\n lvl = case imported_by of\\n ImportedByUser imv -> imv_is_level imv\\n ImportedBySystem -> NormalLevel\\n\\n\\n direct_mods = if toUnitId pkg `S.member` other_home_units\\n then mkPlusModDeps (moduleUnitId imp_mod) lvl (GWIB (moduleName imp_mod) want_boot)\\n else emptyInstalledModuleEnv\\n\\n dep_boot_mods_map = mkModDeps (dep_boot_mods deps)\\n\\n\\n boot_mods\\n -- If we are looking for a boot module, it must be HPT\\n | IsBoot <- want_boot = extendInstalledModuleEnv dep_boot_mods_map (toUnitId <$> imp_mod) (GWIB (moduleName imp_mod) IsBoot)\\n -- Now we are importing A properly, so don\'t go looking for\\n -- A.hs-boot\\n | isHomeUnit home_unit pkg = dep_boot_mods_map\\n -- There\'s no boot files to find in external imports\\n | otherwise = emptyInstalledModuleEnv\\n\\n sig_mods =\\n if is_sig\\n then moduleName imp_mod : dep_sig_mods deps\\n else dep_sig_mods deps\\n\\n\\n in ImportAvails {\\n imp_mods = Map.singleton (mi_module iface) [imported_by],\\n imp_orphs = orphans,\\n imp_finsts = finsts,\\n imp_sig_mods = sig_mods,\\n imp_direct_dep_mods = direct_mods,\\n imp_dep_direct_pkgs = dependent_pkgs,\\n imp_boot_mods = boot_mods,\\n\\n -- Add in the imported modules trusted package\\n -- requirements. ONLY do this though if we import the\\n -- module as a safe import.\\n -- See Note [Tracking Trust Transitively]\\n -- and Note [Trust Transitive Property]\\n imp_trust_pkgs = trusted_pkgs,\\n -- Do we require our own pkg to be trusted?\\n -- See Note [Trust Own Package]\\n imp_trust_own_pkg = pkg_trust_req\\n }\\n\\nmkPlusModDeps :: UnitId -> ImportLevel -> ModuleNameWithIsBoot\\n -> InstalledModuleEnv (S.Set ImportLevel, ModuleNameWithIsBoot)\\nmkPlusModDeps uid st elt = extendInstalledModuleEnv emptyInstalledModuleEnv (mkModule uid (gwib_mod elt)) (S.singleton st, elt)\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{importsFromLocalDecls}\\n* *\\n************************************************************************\\n\\nFrom the top-level declarations of this module produce\\n * the lexical environment\\n * the ImportAvails\\ncreated by its bindings.\\n\\nNote [Top-level Names in Template Haskell decl quotes]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSee also: Note [Interactively-bound Ids in GHCi] in GHC.Driver.Env\\n Note [Looking up Exact RdrNames] in GHC.Rename.Env\\n\\nConsider a Template Haskell declaration quotation like this:\\n module M where\\n f x = h [d| f = 3 |]\\nWhen renaming the declarations inside [d| ...|], we treat the\\ntop level binders specially in two ways\\n\\n1. We give them an Internal Name, not (as usual) an External one.\\n This is done by GHC.Rename.Env.newTopSrcBinder.\\n\\n2. We make them *shadow* the outer bindings.\\n See Note [GlobalRdrEnv shadowing]\\n\\n3. We find out whether we are inside a [d| ... |] by testing the TH\\n level. This is a slight hack, because the level field was really\\n meant for the type checker, and here we are not interested in the\\n fields of Brack, hence the error thunks in thRnBrack.\\n-}\\n\\nextendGlobalRdrEnvRn :: [GlobalRdrElt]\\n -> MiniFixityEnv\\n -> RnM (TcGblEnv, TcLclEnv)\\n-- Updates both the GlobalRdrEnv and the FixityEnv\\n-- We return a new TcLclEnv only because we might have to\\n-- delete some bindings from it;\\n-- see Note [Top-level Names in Template Haskell decl quotes]\\n\\nextendGlobalRdrEnvRn new_gres new_fixities\\n = checkNoErrs $ -- See Note [Fail fast on duplicate definitions]\\n do { (gbl_env, lcl_env) <- getEnvs\\n ; level <- getThLevel\\n ; isGHCi <- getIsGHCi\\n ; let rdr_env = tcg_rdr_env gbl_env\\n fix_env = tcg_fix_env gbl_env\\n th_bndrs = getLclEnvThBndrs lcl_env\\n th_lvl = thLevelIndex level\\n\\n -- Delete new_occs from global and local envs\\n -- If we are in a TemplateHaskell decl bracket,\\n -- we are going to shadow them\\n -- See Note [GlobalRdrEnv shadowing]\\n inBracket = isBrackLevel level\\n\\n lcl_env_TH = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_rdr = minusLocalRdrEnv (tcl_rdr lcl_env) new_gres_env }) lcl_env\\n -- See Note [GlobalRdrEnv shadowing]\\n\\n lcl_env2 | inBracket = lcl_env_TH\\n | otherwise = lcl_env\\n\\n -- Deal with shadowing: see Note [GlobalRdrEnv shadowing]\\n want_shadowing = isGHCi || inBracket\\n rdr_env1 | want_shadowing = shadowNames False rdr_env new_gres_env\\n | otherwise = rdr_env\\n\\n lcl_env3 = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_th_bndrs = extendNameEnvList th_bndrs\\n [ ( n, (TopLevel, th_lvl) )\\n | n <- new_names ] }) lcl_env2\\n\\n ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres\\n\\n ; let fix_env\' = foldl\' extend_fix_env fix_env new_gres\\n gbl_env\' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env\' }\\n\\n ; traceRn \\"extendGlobalRdrEnvRn 2\\" (pprGlobalRdrEnv True rdr_env2)\\n ; return (gbl_env\', lcl_env3) }\\n where\\n new_names = map greName new_gres\\n new_gres_env = mkGlobalRdrEnv new_gres\\n\\n -- If there is a fixity decl for the gre, add it to the fixity env\\n extend_fix_env fix_env gre\\n | Just (L _ fi) <- lookupMiniFixityEnv new_fixities name\\n = extendNameEnv fix_env name (FixItem occ fi)\\n | otherwise\\n = fix_env\\n where\\n name = greName gre\\n occ = greOccName gre\\n\\n add_gre :: GlobalRdrEnv -> GlobalRdrElt -> RnM GlobalRdrEnv\\n -- Extend the GlobalRdrEnv with a LocalDef GRE\\n -- If there is already a LocalDef GRE with the same OccName,\\n -- report an error and discard the new GRE\\n -- This establishes INVARIANT 1 of GlobalRdrEnvs\\n add_gre env gre\\n | not (null dups) -- Same OccName defined twice\\n = do { addDupDeclErr (gre :| dups); return env }\\n\\n | otherwise\\n = return (extendGlobalRdrEnv env gre)\\n where\\n -- See Note [Reporting duplicate local declarations]\\n dups = filter isBadDupGRE\\n $ lookupGRE env (LookupOccName (greOccName gre) (RelevantGREsFOS WantBoth))\\n isBadDupGRE old_gre = isLocalGRE old_gre && greClashesWith gre old_gre\\n\\n{- Note [Fail fast on duplicate definitions]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIf there are duplicate bindings for the same thing, we want to fail\\nfast. Having two bindings for the same thing can cause follow-on errors.\\nExample (test T9975a):\\n data Test = Test { x :: Int }\\n pattern Test wat = Test { x = wat }\\nThis defines \'Test\' twice. The second defn has no field-names; and then\\nwe get an error from Test { x=wat }, saying \\"Test has no field \'x\'\\".\\n\\nEasiest thing is to bale out fast on duplicate definitions, which\\nwe do via `checkNoErrs` on `extendGlobalRdrEnvRn`.\\n\\nNote [Reporting duplicate local declarations]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn general, a single module may not define the same OccName multiple times. This\\nis checked in extendGlobalRdrEnvRn: when adding a new locally-defined GRE to the\\nGlobalRdrEnv we report an error if there are already duplicates in the\\nenvironment. This establishes INVARIANT 1 (see comments on GlobalRdrEnv in\\nGHC.Types.Name.Reader), which says that for a given OccName, all the\\nGlobalRdrElts to which it maps must have distinct \'greName\'s.\\n\\nFor example, the following will be rejected:\\n\\n f x = x\\n g x = x\\n f x = x -- Duplicate!\\n\\nUsers are allowed to introduce new GREs with the same OccName as an imported GRE,\\nas disambiguation is possible through the module system, e.g.:\\n\\n module M where\\n import N (f)\\n f x = x\\n g x = M.f x + N.f x\\n\\nIf both GREs are local, the general rule is that two GREs clash if they have\\nthe same OccName, i.e. they share a textual name and live in the same namespace.\\nHowever, there are additional clashes due to record fields:\\n\\n - a new variable clashes with previously defined record fields\\n which define field selectors,\\n\\n - a new record field shadows:\\n\\n - previously defined variables, if it defines a field selector,\\n - previously defined record fields, unless it is a duplicate record field.\\n\\nThis logic is implemented in the function \'GHC.Types.Name.Reader.greClashesWith\'.\\n\\nSee also Note [Skipping ambiguity errors at use sites of local declarations] in\\nGHC.Rename.Utils.\\n-}\\n\\n\\n{- *********************************************************************\\n* *\\n getLocalDeclBindersd@ returns the names for an HsDecl\\n It\'s used for source code.\\n\\n *** See Note [The Naming story] in GHC.Hs.Decls ****\\n* *\\n********************************************************************* -}\\n\\ngetLocalNonValBinders :: MiniFixityEnv -> HsGroup GhcPs\\n -> RnM ((TcGblEnv, TcLclEnv), NameSet)\\n-- Get all the top-level binders bound the group *except*\\n-- for value bindings, which are treated separately\\n-- Specifically we return AvailInfo for\\n-- * type decls (incl constructors and record selectors)\\n-- * class decls (including class ops)\\n-- * associated types\\n-- * foreign imports\\n-- * value signatures (in hs-boot files only)\\n\\ngetLocalNonValBinders fixity_env\\n (HsGroup { hs_valds = binds,\\n hs_tyclds = tycl_decls,\\n hs_fords = foreign_decls })\\n = do { -- Process all type/class decls *except* family instances\\n ; let inst_decls = tycl_decls >>= group_instds\\n ; dup_fields_ok <- xopt_DuplicateRecordFields <$> getDynFlags\\n ; has_sel <- xopt_FieldSelectors <$> getDynFlags\\n ; tc_gres\\n <- concatMapM\\n (new_tc dup_fields_ok has_sel)\\n (tyClGroupTyClDecls tycl_decls)\\n ; traceRn \\"getLocalNonValBinders 1\\" (ppr tc_gres)\\n ; envs <- extendGlobalRdrEnvRn tc_gres fixity_env\\n ; restoreEnvs envs $ do {\\n -- Bring these things into scope first\\n -- See Note [Looking up family names in family instances]\\n\\n -- Process all family instances\\n -- to bring new data constructors into scope\\n ; nti_gress <- mapM (new_assoc dup_fields_ok has_sel) inst_decls\\n\\n -- Finish off with value binders:\\n -- foreign decls and pattern synonyms for an ordinary module\\n -- type sigs in case of a hs-boot file only\\n ; is_boot <- tcIsHsBootOrSig\\n ; let val_bndrs\\n | is_boot = case binds of\\n ValBinds _ val_binds ->\\n -- In a hs-boot file, the value binders come from the\\n -- *signatures*, and there should be no foreign binders\\n [ L (l2l decl_loc) (unLoc n)\\n | L decl_loc (TypeSig _ _ ns _) <- (val_sigs val_binds), n <- ns]\\n _ -> panic \\"Non-ValBinds in hs-boot group\\"\\n | otherwise = for_hs_bndrs\\n ; val_gres <- mapM new_simple val_bndrs\\n\\n ; let avails = concat nti_gress ++ val_gres\\n new_bndrs = gresToNameSet avails `unionNameSet`\\n gresToNameSet tc_gres\\n ; traceRn \\"getLocalNonValBinders 2\\" (ppr avails)\\n ; envs <- extendGlobalRdrEnvRn avails fixity_env\\n ; return (envs, new_bndrs) } }\\n where\\n for_hs_bndrs :: [LocatedN RdrName]\\n for_hs_bndrs = hsForeignDeclsBinders foreign_decls\\n\\n -- the SrcSpan attached to the input should be the span of the\\n -- declaration, not just the name\\n new_simple :: LocatedN RdrName -> RnM GlobalRdrElt\\n new_simple rdr_name = do { nm <- newTopSrcBinder rdr_name\\n ; return (mkLocalVanillaGRE NoParent nm) }\\n\\n new_tc :: DuplicateRecordFields -> FieldSelectors -> LTyClDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_tc dup_fields_ok has_sel tc_decl -- NOT for type/data instances\\n = do { let TyDeclBinders (main_bndr, tc_flav) at_bndrs sig_bndrs\\n (LConsWithFields cons_with_flds flds) = hsLTyClDeclBinders tc_decl\\n ; tycon_name <- newTopSrcBinder $ la2la main_bndr\\n ; at_names <- mapM (newTopSrcBinder . la2la . fst) at_bndrs\\n ; sig_names <- mapM (newTopSrcBinder . la2la) sig_bndrs\\n ; con_names_with_flds <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst con_names_with_flds) flds\\n ; mapM_ (add_dup_fld_errs flds\') con_names_with_flds\\n ; let tc_gre = mkLocalTyConGRE (fmap (const tycon_name) tc_flav) tycon_name\\n fld_env = mk_fld_env con_names_with_flds flds\'\\n at_gres = zipWith (\\\\ (_, at_flav) at_nm -> mkLocalTyConGRE (fmap (const tycon_name) at_flav) at_nm)\\n at_bndrs at_names\\n sig_gres = map (mkLocalVanillaGRE (ParentIs tycon_name)) sig_names\\n con_gres = map (mkLocalConLikeGRE (ParentIs tycon_name)) fld_env\\n fld_gres = mkLocalFieldGREs (ParentIs tycon_name) fld_env\\n sub_gres = at_gres ++ sig_gres ++ con_gres ++ fld_gres\\n ; traceRn \\"getLocalNonValBinders new_tc\\" $\\n vcat [ text \\"tycon:\\" <+> ppr tycon_name\\n , text \\"tc_gre:\\" <+> ppr tc_gre\\n , text \\"sub_gres:\\" <+> ppr sub_gres ]\\n ; return $ tc_gre : sub_gres }\\n\\n -- Calculate the record field information, which feeds into the GlobalRdrElts\\n -- for DataCons and their fields. It\'s convenient to do this here where\\n -- we are working with a single datatype definition.\\n --\\n -- The information we needed was all set up for us:\\n -- see Note [Collecting record fields in data declarations] in GHC.Hs.Utils.\\n mk_fld_env :: [(Name, Either VisArity [Located Int])] -> IntMap FieldLabel\\n -> [(ConLikeName, ConInfo)]\\n mk_fld_env names flds =\\n [ (DataConName con, ConInfo (ConIsData (map fst names)) fld_info)\\n | (con, con_fl_indxs) <- names\\n , let fld_info = case fmap (map ((flds IntMap.!) . unLoc)) con_fl_indxs of\\n Left 0 -> ConIsNullary\\n Left arity -> ConHasPositionalArgs arity\\n Right [] -> ConIsNullary\\n Right (fld:flds) -> ConHasRecordFields $ fld NE.:| flds ]\\n\\n new_assoc :: DuplicateRecordFields -> FieldSelectors -> LInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_assoc _ _ (L _ (TyFamInstD {})) = return []\\n -- type instances don\'t bind new names\\n\\n new_assoc dup_fields_ok has_sel (L _ (DataFamInstD _ d))\\n = new_di dup_fields_ok has_sel Nothing d\\n new_assoc dup_fields_ok has_sel\\n (L _ (ClsInstD _ (ClsInstDecl { cid_poly_ty = inst_ty\\n , cid_decls = decls })))\\n = do -- First, attempt to grab the name of the class from the instance.\\n -- This step could fail if the instance is not headed by a class,\\n -- such as in the following examples:\\n --\\n -- (1) The class is headed by a bang pattern, such as in\\n -- `instance !Show Int` (#3811c)\\n -- (2) The class is headed by a type variable, such as in\\n -- `instance c` (#16385)\\n --\\n -- If looking up the class name fails, then mb_cls_gre will\\n -- be Nothing.\\n mb_cls_gre <- runMaybeT $ do\\n -- See (1) above\\n L loc cls_rdr <- MaybeT $ pure $ getLHsInstDeclClass_maybe inst_ty\\n -- See (2) above\\n MaybeT $ setSrcSpan (locA loc) $ lookupGlobalOccRn_maybe SameNameSpace cls_rdr\\n -- Assuming the previous step succeeded, process any associated data\\n -- family instances. If the previous step failed, bail out.\\n case mb_cls_gre of\\n Nothing\\n -> pure []\\n Just cls_gre\\n -> let cls_nm = greName cls_gre\\n in concatMapM (new_di dup_fields_ok has_sel (Just cls_nm) . unLoc) (data_fam_insts decls)\\n\\n data_fam_insts decls = concatMap get decls\\n where\\n get (L l (InstD _ (DataFamInstD { dfid_inst = d}))) = [L l d]\\n get _ = []\\n\\n new_di :: DuplicateRecordFields -> FieldSelectors\\n -> Maybe Name -- class name\\n -> DataFamInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_di dup_fields_ok has_sel mb_cls dfid@(DataFamInstDecl { dfid_eqn = ti_decl })\\n = do { main_name <- unLoc <$> lookupFamInstName mb_cls (feqn_tycon ti_decl)\\n ; let LConsWithFields cons_with_flds flds = hsDataFamInstBinders dfid\\n ; sub_names <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst sub_names) flds\\n ; mapM_ (add_dup_fld_errs flds\') sub_names\\n ; let fld_env = mk_fld_env sub_names flds\'\\n con_gres = map (mkLocalConLikeGRE (ParentIs main_name)) fld_env\\n field_gres = mkLocalFieldGREs (ParentIs main_name) fld_env\\n -- NB: the data family name is not bound here,\\n -- so we don\'t return a GlobalRdrElt for it here!\\n ; return $ con_gres ++ field_gres }\\n\\n -- Add errors if a constructor has a duplicate record field.\\n add_dup_fld_errs :: IntMap FieldLabel\\n -> (Name, Either VisArity [Located Int])\\n -> IOEnv (Env TcGblEnv TcLclEnv) ()\\n add_dup_fld_errs all_flds (con, con_flds_or_arity)\\n | Right con_flds <- con_flds_or_arity\\n , let (_, dups) = removeDups (comparing unLoc) con_flds\\n = for_ dups $ \\\\ dup_flds ->\\n -- Report the error at the location of the second occurrence\\n -- of the duplicate field.\\n let loc =\\n case dup_flds of\\n _ :| ( L loc _ : _) -> loc\\n L loc _ :| _ -> loc\\n dup_rdrs = fmap (nameRdrName . flSelector . (all_flds IntMap.!) . unLoc) dup_flds\\n in addErrAt loc $ TcRnDuplicateFieldName (RecordFieldDecl con) dup_rdrs\\n | otherwise\\n = return ()\\n\\nnewRecordFieldLabel :: DuplicateRecordFields -> FieldSelectors -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel\\nnewRecordFieldLabel _ _ [] _ = error \\"newRecordFieldLabel: datatype has no constructors!\\"\\nnewRecordFieldLabel dup_fields_ok has_sel (dc:_) (L loc (FieldOcc _ (L _ fld)))\\n = do { selName <- newTopSrcBinder $ L (l2l loc) $ field\\n ; return $ FieldLabel { flHasDuplicateRecordFields = dup_fields_ok\\n , flHasFieldSelector = has_sel\\n , flSelector = selName } }\\n where\\n fld_occ = rdrNameOcc fld\\n dc_fs = occNameFS $ nameOccName dc\\n field\\n -- Use an Exact RdrName as-is, to preserve the bindings\\n -- of an already renamer-resolved field and its use\\n -- sites. This is needed to correctly support record\\n -- selectors in Template Haskell. See Note [Binders in\\n -- Template Haskell] in \\"GHC.ThToHs\\" and Note [Looking up\\n -- Exact RdrNames] in \\"GHC.Rename.Env\\".\\n | isExact fld\\n = assertPpr (fieldOcc_maybe fld_occ == Just dc_fs)\\n (vcat [ text \\"newRecordFieldLabel: incorrect namespace for exact Name\\" <+> quotes (ppr fld)\\n , text \\"expected namespace:\\" <+> pprNameSpace (fieldName dc_fs)\\n , text \\" actual namespace:\\" <+> pprNameSpace (occNameSpace fld_occ) ])\\n fld\\n\\n -- Field names produced by the parser are namespaced with VarName.\\n -- Here we namespace them according to the first constructor.\\n -- See Note [Record field namespacing] in GHC.Types.Name.Occurrence.\\n | otherwise\\n = mkRdrUnqual $ varToRecFieldOcc dc_fs fld_occ\\n\\n{-\\nNote [Looking up family names in family instances]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider\\n\\n module M where\\n type family T a :: *\\n type instance M.T Int = Bool\\n\\nWe might think that we can simply use \'lookupOccRn\' when processing the type\\ninstance to look up \'M.T\'. Alas, we can\'t! The type family declaration is in\\nthe *same* HsGroup as the type instance declaration. Hence, as we are\\ncurrently collecting the binders declared in that HsGroup, these binders will\\nnot have been added to the global environment yet.\\n\\nSolution is simple: process the type family declarations first, extend\\nthe environment, and then process the type instances.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Filtering imports}\\n* *\\n************************************************************************\\n\\n@filterImports@ takes the @ExportEnv@ telling what the imported module makes\\navailable, and filters it through the import spec (if any).\\n\\nNote [Dealing with imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nFor import M( ies ), we take each AvailInfo from the mi_exports of M, and make\\n\\n imp_occ_env :: OccEnv (NameEnv ImpOccItem)\\n\\nThis map contains one entry for each OccName that M exports, mapping each OccName\\nto the following information:\\n\\n 1. the GlobalRdrElt corresponding to the OccName,\\n 2. whether this GlobalRdrElt was the parent in the AvailInfo we found\\n the OccName in.\\n 3. the GlobalRdrElts that were bundled together in the AvailInfo we found\\n this OccName in (not including the parent),\\n\\nWe need (2) and (3) during the construction of the OccEnv because of associated\\ntypes and bundled pattern synonyms, respectively.\\n(3) is explained in Note [Importing PatternSynonyms].\\n\\nTo explain (2), consider for example:\\n\\n module M where\\n class C a where { data T a }\\n instance C Int where { data T Int = T1 | T2 }\\n instance C Bool where { data T Int = T3 }\\n\\nHere, M\'s exports avails are (recalling the AvailTC invariant from GHC.Types.Avail)\\n\\n C(C,T), T(T,T1,T2,T3)\\n\\nNotice that T appears *twice*, once as a child and once as a parent. From\\nthese two exports, respectively, during construction of the imp_occ_env, we begin\\nby associating the following two elements with the key T:\\n\\n T -> ImpOccItem { imp_item = gre1, imp_bundled = [C,T] , imp_is_parent = False }\\n T -> ImpOccItem { imp_item = gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nwhere `gre1`, `gre2` are two GlobalRdrElts with greName T.\\nWe combine these (in function \'combine\' in \'mkImportOccEnv\') by discarding the\\nnon-parent item, thusly:\\n\\n T -> IE_ITem { imp_item = gre1 `plusGRE` gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nNote the `plusGRE`: this ensures we don\'t drop parent information;\\nsee Note [Preserve parent information when combining import OccEnvs].\\n\\nSo the overall imp_occ_env is:\\n\\n C -> ImpOccItem { imp_item = C, imp_bundled = [T ], imp_is_parent = True }\\n T -> ImpOccItem { imp_item = T , imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n T1 -> ImpOccItem { imp_item = T1, imp_bundled = [T1,T2,T3], imp_is_parent = False }\\n -- similarly for T2, T3\\n\\nNote that the imp_occ_env will have entries for data constructors too,\\nalthough we never look up data constructors.\\n\\nNote [Importing PatternSynonyms]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nAs described in Note [Dealing with imports], associated types can lead to the\\nsame Name appearing twice, both as a child and once as a parent, when\\nconstructing the imp_occ_env. The same thing can happen with pattern synonyms\\nif they are exported bundled with a type.\\n\\nA simplified example, based on #11959:\\n\\n {-# LANGUAGE PatternSynonyms #-}\\n module M (T(P), pattern P) where -- Duplicate export warning, but allowed\\n data T = MkT\\n pattern P = MkT\\n\\nHere we have T(P) and P in export_avails, and respectively construct both\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n P -> ImpOccItem { imp_item = P, imp_bundled = [] , imp_is_parent = False }\\n\\nWe combine these by dropping the one with no siblings, leaving us with:\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n\\nThat is, we simply discard the non-bundled Avail.\\n\\nNote [Importing DuplicateRecordFields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn filterImports, another complicating factor is DuplicateRecordFields.\\nSuppose we have:\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (S(foo), T(foo)) where\\n data S = MkS { foo :: Int }\\n data T = MkT { foo :: Int }\\n\\n module N where\\n import M (foo) -- this is allowed (A)\\n import M (S(foo)) -- this is allowed (B)\\n\\nHere M exports \'foo\' at two different OccNames, with different namespaces for\\nthe two construtors MkS and MkT. Then, when we look up \'foo\' in lookup_names\\nfor case (A), we have a variable foo but must look in all the record field\\nnamespaces to find the two fields (and hence two different Avails).\\nWhereas in case (B) we reach the lookup_ie case for IEThingWith,\\nwhich looks up \'S\' and then finds the unique \'foo\' amongst its children.\\n\\nSee T16745 for a test of this.\\n\\nNote [Preserve parent information when combining import OccEnvs]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen discarding one ImpOccItem in favour of another, as described in\\nNote [Dealing with imports], we must make sure to combine the GREs so that\\nwe don\'t lose information.\\n\\nConsider for example #24084:\\n\\n module M1 where { class C a where { type T a } }\\n module M2 ( module M1 ) where { import M1 }\\n module M3 where { import M2 ( C, T ); instance C () where T () = () }\\n\\nWhen processing the import list of `M3`, we will have two `Avail`s attached\\nto `T`, namely `C(C, T)` and `T(T)`. We combine them in the `combine` function\\nof `mkImportOccEnv`; as described in Note [Dealing with imports] we discard\\n`C(C, T)` in favour of `T(T)`. However, in doing so, we **must not**\\ndiscard the information want that `C` is the parent of `T`. Indeed,\\nlosing track of this information can cause errors when importing,\\nas we could get an error of the form\\n\\n \\u2018T\\u2019 is not a (visible) associated type of class \\u2018C\\u2019\\n\\nThis explains why we use `plusGRE` when combining the two ImpOccItems, even\\nthough we are discarding one in favour of the other.\\n-}\\n\\n-- | All the \'GlobalRdrElt\'s associated with an \'AvailInfo\'.\\ngresFromAvail :: HasDebugCallStack\\n => HscEnv -> Maybe ImportSpec -> AvailInfo -> [GlobalRdrElt]\\ngresFromAvail hsc_env prov avail =\\n [ mk_gre nm info\\n | nm <- availNames avail\\n , let info = lookupGREInfo hsc_env nm ]\\n where\\n\\n mk_gre n info\\n = case prov of\\n -- Nothing => bound locally\\n -- Just is => imported from \'is\'\\n Nothing -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = True, gre_imp = emptyBag\\n , gre_info = info }\\n Just is -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = False, gre_imp = unitBag is\\n , gre_info = info }\\n\\n-- | All the \'GlobalRdrElt\'s associated with a collection of \'AvailInfo\'s.\\ngresFromAvails :: HscEnv -> Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]\\ngresFromAvails hsc_env prov = concatMap (gresFromAvail hsc_env prov)\\n\\nimportsFromIface :: HscEnv -> ModIface -> ImpDeclSpec -> Maybe NameSet -> GlobalRdrEnv\\nimportsFromIface hsc_env iface decl_spec hidden = mkGlobalRdrEnv $ case hidden of\\n Nothing -> all_gres\\n Just hidden_names -> filter (not . (`elemNameSet` hidden_names) . greName) all_gres\\n where\\n all_gres = gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\nrnNamespaceSpecifier :: NamespaceSpecifier GhcPs -> NamespaceSpecifier GhcRn\\nrnNamespaceSpecifier (NoNamespaceSpecifier _) = NoNamespaceSpecifier noExtField\\nrnNamespaceSpecifier (TypeNamespaceSpecifier x) = TypeNamespaceSpecifier x\\nrnNamespaceSpecifier (DataNamespaceSpecifier x) = DataNamespaceSpecifier x\\n\\nfilterImports\\n :: HasDebugCallStack\\n => HscEnv\\n -> ModIface\\n -> ImpDeclSpec\\n -- ^ Import spec\\n -> Maybe (ImportListInterpretation, [LIE GhcPs])\\n -- ^ Whether this is a \\"hiding\\" import list\\n -> RnM (Maybe (ImportListInterpretation, [LIE GhcRn]), -- Import spec w/ Names\\n ImpUserList, -- same, but designed for storage in interfaces\\n GlobalRdrEnv) -- Same again, but in GRE form\\nfilterImports hsc_env iface decl_spec Nothing\\n = return (Nothing, ImpUserAll, importsFromIface hsc_env iface decl_spec Nothing)\\nfilterImports hsc_env iface decl_spec (Just (want_hiding, import_items))\\n = do -- check for errors, convert RdrNames to Names\\n items1 <- mapM lookup_lie import_items\\n\\n let items2 :: [(LIE GhcRn, [GlobalRdrElt])]\\n items2 = concat items1\\n -- NB we may have duplicates, and several items\\n -- for the same parent; e.g N(x) and N(y)\\n\\n (gres, imp_user_list) = case want_hiding of\\n Exactly ->\\n let gres = concatMap (gresFromIE decl_spec) items2\\n gre_env = mkGlobalRdrEnv gres\\n implicit_parents = mkNameSet $ mapMaybe parentOfImplicitlyImportedGRE gres\\n in (gre_env, ImpUserExplicit (gresToAvailInfo $ globalRdrEnvElts $ gre_env) implicit_parents)\\n EverythingBut ->\\n let hidden_names = mkNameSet $ concatMap (map greName . snd) items2\\n in (importsFromIface hsc_env iface decl_spec (Just hidden_names), ImpUserEverythingBut hidden_names)\\n\\n return (Just (want_hiding, map fst items2), imp_user_list, gres)\\n where\\n import_mod = mi_module iface\\n all_avails = mi_exports iface\\n imp_occ_env = mkImportOccEnv hsc_env decl_spec all_avails\\n\\n -- Look up a parent (type constructor, class or data constructor)\\n -- in an import.\\n lookup_parent :: IE GhcPs -> RdrName -> IELookupM ImpOccItem\\n lookup_parent ie rdr =\\n assertPpr (not $ isVarNameSpace ns)\\n (vcat [ text \\"filterImports lookup_parent: unexpected variable\\"\\n , text \\"rdr:\\" <+> ppr rdr\\n , text \\"namespace:\\" <+> pprNameSpace ns ]) $\\n do { xs <- lookup_names ie rdr\\n ; case xs of\\n cax :| [] -> return cax\\n _ -> pprPanic \\"filter_imports lookup_parent ambiguous\\" $\\n vcat [ text \\"rdr:\\" <+> ppr rdr\\n , text \\"lookups:\\" <+> ppr (fmap imp_item xs) ] }\\n -- Looking up non-variables is always unambiguous,\\n -- as there can be at most one corresponding item\\n -- in the imp_occ_env.\\n -- See item (1) of Note [Exporting duplicate declarations]\\n -- in GHC.Tc.Gen.Export.\\n where\\n occ = rdrNameOcc rdr\\n ns = occNameSpace occ\\n\\n -- Look up a RdrName used in an import, returning multiple values if there\\n -- are several fields with the same name exposed by the module\\n lookup_names :: IE GhcPs -> RdrName -> IELookupM (NonEmpty ImpOccItem)\\n lookup_names ie rdr\\n | isQual rdr\\n = failLookupWith (QualImportError rdr)\\n | otherwise\\n = case lookups of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n item:items -> return $ item :| items\\n where\\n lookups = concatMap nonDetNameEnvElts\\n $ lookupImpOccEnv (RelevantGREsFOS WantNormal) imp_occ_env (rdrNameOcc rdr)\\n\\n lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, [GlobalRdrElt])]\\n lookup_lie (L loc ieRdr)\\n = setSrcSpanA loc $\\n do (stuff, warns) <- run_lookup ([],[]) (lookup_ie ieRdr)\\n mapM_ (addTcRnDiagnostic <=< warning_msg) warns\\n return [ (L loc ie, gres) | (ie,gres) <- stuff ]\\n where\\n\\n -- Warn when importing T(..) and no children are brought in scope\\n warning_msg (DodgyImport reason) =\\n pure (TcRnDodgyImports reason)\\n warning_msg MissingImportList =\\n pure (TcRnMissingImportList ieRdr)\\n warning_msg (BadImportW ie sub) = do\\n -- \'BadImportW\' is only constructed below in \'bad_import_w\', in\\n -- the \'EverythingBut\' case, so here we assume a \'hiding\' clause.\\n (reason :| _) <- badImportItemErr iface decl_spec ie sub all_avails\\n pure (TcRnDodgyImports (DodgyImportsHiding reason))\\n warning_msg (DeprecatedExport n w) =\\n pure $ TcRnPragmaWarning\\n PragmaWarningExport\\n { pwarn_occname = occName n\\n , pwarn_impmod = moduleName import_mod }\\n w\\n\\n run_lookup :: a -> IELookupM a -> TcRn a\\n run_lookup def m = case m of\\n Failed err -> do\\n msgs <- lookup_err_msgs err\\n forM_ msgs $ \\\\msg -> addErr (TcRnImportLookup msg)\\n return def\\n Succeeded a -> return a\\n\\n lookup_err_msgs err = case err of\\n BadImport ie sub -> badImportItemErr iface decl_spec ie sub all_avails\\n IllegalImport -> pure $ NE.singleton ImportLookupIllegal\\n QualImportError rdr -> pure $ NE.singleton (ImportLookupQualified rdr)\\n\\n -- For each import item, we convert its RdrNames to Names,\\n -- and at the same time compute all the GlobalRdrElt corresponding\\n -- to what is actually imported by this item.\\n -- Returns Nothing on error.\\n --\\n -- Returns a list because, with DuplicateRecordFields, a naked\\n -- import/export of a record field can correspond to multiple\\n -- different GlobalRdrElts. See Note [Importing DuplicateRecordFields].\\n lookup_ie :: IE GhcPs\\n -> IELookupM ([(IE GhcRn, [GlobalRdrElt])], [IELookupWarning])\\n lookup_ie ie = handle_bad_import $\\n case ie of\\n IEVar _ (L l n) _ -> do\\n -- See Note [Importing DuplicateRecordFields]\\n xs <- lookup_names ie (ieWrappedName n)\\n let gres = map imp_item $ NE.toList xs\\n export_depr_warns\\n | want_hiding == Exactly\\n = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ( [ (IEVar Nothing (L l (replaceWrappedName n name)) noDocstring, [gre])\\n | gre <- gres\\n , let name = greName gre ]\\n , export_depr_warns )\\n\\n IEThingAll x ns_spec (L l tc) _ -> do\\n ImpOccItem { imp_item = gre\\n , imp_bundled = bundled_gres\\n , imp_is_parent = is_par\\n }\\n <- lookup_parent ie $ ieWrappedName tc\\n let name = greName gre\\n\\n child_gres :: [GlobalRdrElt]\\n child_gres\\n | is_par = filterByNamespaceSpecifierGREs ns_spec bundled_gres\\n | otherwise = []\\n\\n imp_list_warn\\n\\n | null child_gres\\n -- e.g. f(..) or T(..) where T is a type synonym\\n = [DodgyImport (DodgyImportsEmptyParent ie ns_spec gre)]\\n\\n -- e.g. import M( T(..) )\\n | not (is_qual decl_spec)\\n = [MissingImportList]\\n\\n | otherwise\\n = []\\n\\n renamed_ie = IEThingAll (x { ieta_warning = Nothing })\\n (rnNamespaceSpecifier ns_spec)\\n (L l (replaceWrappedName tc name))\\n noDocstring\\n export_depr_warn\\n | want_hiding == Exactly\\n = maybeToList $ mk_depr_export_warning gre\\n -- We don\'t want to warn about the children as they\\n -- are not explicitly mentioned; the warning will\\n -- be emitted later on if they are used\\n | otherwise = []\\n\\n return ( [(renamed_ie, gre:child_gres)]\\n , imp_list_warn ++ export_depr_warn)\\n\\n\\n IEThingAbs _ (L l tc\') _\\n | want_hiding == EverythingBut -- hiding ( C )\\n -- Here the \'C\' can be a data constructor\\n -- *or* a type/class, or even both\\n -> let tc = ieWrappedName tc\'\\n tc_name = lookup_parent ie tc\\n dc_name = lookup_parent ie (setRdrNameSpace tc srcDataName)\\n in\\n case catIELookupM [ tc_name, dc_name ] of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n names -> return ( [mkIEThingAbs tc\' l (imp_item name) | name <- names], [])\\n | otherwise\\n -> do ImpOccItem { imp_item = gre } <- lookup_parent ie (ieWrappedName tc\')\\n return ( [mkIEThingAbs tc\' l gre]\\n , maybeToList $ mk_depr_export_warning gre)\\n\\n IEThingWith (deprecation, ann) ltc@(L l rdr_tc) wc rdr_ns _ -> do\\n ImpOccItem { imp_item = gre, imp_bundled = subnames }\\n <- lookup_parent (IEThingAbs Nothing ltc noDocstring) (ieWrappedName rdr_tc)\\n let name = greName gre\\n\\n -- Look up the children in the sub-names of the parent\\n -- See Note [Importing DuplicateRecordFields]\\n let (children_errs, childnames) = lookupChildren subnames rdr_ns\\n\\n bad_import_warns <-\\n if null children_errs then return [] else\\n let items = map lce_wrapped_name children_errs\\n ie = IEThingWith (deprecation, ann) ltc wc items noDocstring\\n -- We are trying to import T( a,b,c,d ), and failed\\n -- to find \'b\' and \'d\'. So we make up an import item\\n -- to report as failing, namely T( b, d ).\\n -- c.f. #15413\\n subordinate_err = mkSubordinateError gre children_errs\\n in bad_import_w ie subordinate_err\\n\\n let name\' = replaceWrappedName rdr_tc name\\n childnames\' = map (to_ie_post_rn . fmap greName) childnames\\n gres = gre : map unLoc childnames\\n export_depr_warns\\n | want_hiding == Exactly = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ([ (IEThingWith (Nothing, ann) (L l name\') wc childnames\' noDocstring\\n ,gres)]\\n , bad_import_warns ++ export_depr_warns)\\n\\n IEWholeNamespace x ns_spec -> do\\n let mod_name = moduleName import_mod\\n names = map greName gres\\n renamed_ie = IEWholeNamespace x { iewn_warning = Nothing\\n , iewn_names = names }\\n (rnNamespaceSpecifier ns_spec)\\n gres = filterByNamespaceSpecifierGREs ns_spec $\\n gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n dodgy_warn\\n | null gres = [DodgyImport (DodgyImportsWildcard mod_name ns_spec)]\\n | otherwise = []\\n return ([(renamed_ie, gres)],\\n dodgy_warn)\\n\\n _other -> failLookupWith IllegalImport\\n -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed...\\n -- all of those constitute errors.\\n\\n where\\n mkIEThingAbs tc l gre\\n = (IEThingAbs Nothing (L l (replaceWrappedName tc n)) noDocstring, [gre])\\n where n = greName gre\\n\\n -- N.B. imports never have docstrings\\n noDocstring = Nothing\\n\\n handle_bad_import m = catchIELookup m $ \\\\case\\n BadImport ie sub -> do\\n ws <- bad_import_w ie sub\\n return ([], ws)\\n err -> failLookupWith err\\n\\n bad_import_w :: IE GhcPs -> IsSubordinateError -> IELookupM [IELookupWarning]\\n bad_import_w ie sub\\n | want_hiding == EverythingBut = return [BadImportW ie sub]\\n | otherwise = failLookupWith (BadImport ie sub)\\n\\n mk_depr_export_warning gre\\n = DeprecatedExport name <$> mi_export_warn_fn iface name\\n where\\n name = greName gre\\n\\n-- | Assuming a subordinate item could not be found, do another lookup for a\\n-- more specific error message.\\nmkBadExportSubordinate :: [GlobalRdrElt] -> LIEWrappedName GhcPs -> BadExportSubordinate\\nmkBadExportSubordinate child_gres n =\\n case lookupChildren child_gres [n] of\\n (LookupChildNonType {lce_nontype_item = g} : _, _) -> BadExportSubordinateNonType g\\n (LookupChildNonData {lce_nondata_item = g} : _, _) -> BadExportSubordinateNonData g\\n _ -> BadExportSubordinateNotFound n\\n\\ntype IELookupM = MaybeErr IELookupError\\n\\ndata IELookupWarning\\n = BadImportW (IE GhcPs) IsSubordinateError\\n | MissingImportList\\n | DodgyImport DodgyImportsReason\\n | DeprecatedExport Name (WarningTxt GhcRn)\\n\\n-- | Is this import/export item a subordinate or not?\\ndata IsSubordinateError\\n = IsSubordinateError { subordinate_err_parent :: !GlobalRdrElt\\n , subordinate_err_unavailable :: [FastString]\\n , subordinate_err_nontype :: [GlobalRdrElt]\\n , subordinate_err_nondata :: [GlobalRdrElt] }\\n | IsNotSubordinate\\n\\nmkSubordinateError :: GlobalRdrElt -> [LookupChildError] -> IsSubordinateError\\nmkSubordinateError gre children_errs = foldr add init_acc children_errs\\n where\\n init_acc :: IsSubordinateError\\n init_acc = IsSubordinateError gre [] [] []\\n\\n add :: LookupChildError -> IsSubordinateError -> IsSubordinateError\\n add children_err sub@IsSubordinateError{} =\\n case children_err of\\n LookupChildNonType{lce_nontype_item = g} ->\\n sub { subordinate_err_nontype = g : subordinate_err_nontype sub }\\n LookupChildNonData{lce_nondata_item = g} ->\\n sub { subordinate_err_nondata = g : subordinate_err_nondata sub }\\n LookupChildNotFound (L _ wname) ->\\n let fs = (occNameFS . rdrNameOcc . ieWrappedName) wname\\n in sub { subordinate_err_unavailable = fs : subordinate_err_unavailable sub }\\n add _ IsNotSubordinate = panic \\"mkSubordinateError: IsNotSubordinate\\"\\n\\ndata IELookupError\\n = QualImportError RdrName\\n | BadImport (IE GhcPs) IsSubordinateError\\n | IllegalImport\\n\\nfailLookupWith :: IELookupError -> IELookupM a\\nfailLookupWith err = Failed err\\n\\ncatchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a\\ncatchIELookup m h = case m of\\n Succeeded r -> return r\\n Failed err -> h err\\n\\ncatIELookupM :: [IELookupM a] -> [a]\\ncatIELookupM ms = [ a | Succeeded a <- ms ]\\n\\n-- | Information associated to an \'AvailInfo\' used in constructing\\n-- an \'OccEnv\' corresponding to imports.\\n--\\n-- See Note [Dealing with imports].\\ndata ImpOccItem\\n = ImpOccItem\\n { imp_item :: GlobalRdrElt\\n -- ^ The import item\\n , imp_bundled :: [GlobalRdrElt]\\n -- ^ Items bundled in the Avail this import item came from,\\n -- not including the import item itself if it is a parent.\\n , imp_is_parent :: Bool\\n -- ^ Is the import item a parent? See Note [Dealing with imports].\\n }\\n\\ninstance Outputable ImpOccItem where\\n ppr (ImpOccItem { imp_item = item, imp_bundled = bundled, imp_is_parent = is_par })\\n = braces $ hsep\\n [ text \\"ImpOccItem\\"\\n , if is_par then text \\"[is_par]\\" else empty\\n , ppr (greName item) <+> ppr (greParent item)\\n , braces $ text \\"bundled:\\" <+> ppr (map greName bundled) ]\\n\\n-- | Make an \'OccEnv\' of all the imports.\\n--\\n-- Complicated by the fact that associated data types and pattern synonyms\\n-- can appear twice. See Note [Dealing with imports].\\nmkImportOccEnv :: HscEnv -> ImpDeclSpec -> [IfaceExport] -> OccEnv (NameEnv ImpOccItem)\\nmkImportOccEnv hsc_env decl_spec all_avails =\\n mkOccEnv_C (plusNameEnv_C combine)\\n [ (occ, mkNameEnv [(nm, item)])\\n | avail <- all_avails\\n , let gres = gresFromAvail hsc_env (Just hiding_spec) avail\\n , gre <- gres\\n , let nm = greName gre\\n occ = greOccName gre\\n (is_parent, bundled) = case avail of\\n AvailTC c _\\n | c == nm -- (Recall the AvailTC invariant from GHC.Types.AvailInfo)\\n -> ( True, drop 1 gres ) -- \\"drop 1\\": don\'t include the parent itself.\\n | otherwise\\n -> ( False, gres )\\n _ -> ( False, [] )\\n item = ImpOccItem\\n { imp_item = gre\\n , imp_bundled = bundled\\n , imp_is_parent = is_parent }\\n ]\\n where\\n\\n hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\n -- See Note [Dealing with imports]\\n -- \'combine\' may be called for associated data types which appear\\n -- twice in the all_avails. In the example, we have two Avails for T,\\n -- namely T(T,T1,T2,T3) and C(C,T), and we combine them by dropping the\\n -- latter, in which T is not the parent.\\n combine :: ImpOccItem -> ImpOccItem -> ImpOccItem\\n combine item1@(ImpOccItem { imp_item = gre1, imp_is_parent = is_parent1 })\\n item2@(ImpOccItem { imp_item = gre2, imp_is_parent = is_parent2 })\\n | is_parent1 || is_parent2\\n , not (isRecFldGRE gre1 || isRecFldGRE gre2) -- NB: does not force GREInfo.\\n , let name1 = greName gre1\\n name2 = greName gre2\\n gre = gre1 `plusGRE` gre2\\n -- See Note [Preserve parent information when combining import OccEnvs]\\n = assertPpr (name1 == name2)\\n (ppr name1 <+> ppr name2) $\\n if is_parent1\\n then item1 { imp_item = gre }\\n else item2 { imp_item = gre }\\n -- Discard C(C,T) in favour of T(T, T1, T2, T3).\\n\\n -- \'combine\' may also be called for pattern synonyms which appear both\\n -- unassociated and associated (see Note [Importing PatternSynonyms]).\\n combine item1@(ImpOccItem { imp_item = c1, imp_bundled = kids1 })\\n item2@(ImpOccItem { imp_item = c2, imp_bundled = kids2 })\\n = assertPpr (greName c1 == greName c2\\n && (not (null kids1 && null kids2)))\\n (ppr c1 <+> ppr c2 <+> ppr kids1 <+> ppr kids2) $\\n if null kids1\\n then item2\\n else item1\\n -- Discard standalone pattern P in favour of T(P).\\n\\n-- | Essentially like @lookupGRE env (LookupOccName occ which_gres)@,\\n-- but working with \'ImpOccItem\'s instead of \'GlobalRdrElt\'s.\\nlookupImpOccEnv :: WhichGREs GREInfo\\n -> OccEnv (NameEnv ImpOccItem) -> OccName -> [NameEnv ImpOccItem]\\nlookupImpOccEnv which_gres env occ =\\n mapMaybe relevant_items $ lookupOccEnv_AllNameSpaces env occ\\n where\\n is_relevant :: ImpOccItem -> Bool\\n is_relevant (ImpOccItem { imp_item = gre }) =\\n greIsRelevant which_gres (occNameSpace occ) gre\\n relevant_items :: NameEnv ImpOccItem -> Maybe (NameEnv ImpOccItem)\\n relevant_items nms\\n | let nms\' = filterNameEnv is_relevant nms\\n = if isEmptyNameEnv nms\'\\n then Nothing\\n else Just nms\'\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{Import/Export Utils}\\n* *\\n************************************************************************\\n-}\\n\\n-- | Given an import\\\\/export spec, appropriately set the @gre_imp@ field\\n-- for the \'GlobalRdrElt\'s.\\ngresFromIE :: ImpDeclSpec -> (LIE GhcRn, [GlobalRdrElt]) -> [GlobalRdrElt]\\ngresFromIE decl_spec (L loc ie, gres)\\n = map set_gre_imp gres\\n where\\n is_explicit = case ie of\\n IEThingAll _ _ name _ -> \\\\n -> n == lieWrappedName name\\n IEWholeNamespace _ _ -> \\\\_ -> False\\n _ -> \\\\_ -> True\\n prov_fn name\\n = ImpSpec { is_decl = decl_spec, is_item = item_spec }\\n where\\n item_spec = ImpSome { is_explicit = is_explicit name\\n , is_iloc = locA loc }\\n set_gre_imp gre@( GRE { gre_name = nm } )\\n = gre { gre_imp = unitBag $ prov_fn nm }\\n\\nparentOfImplicitlyImportedGRE :: Outputable info => GlobalRdrEltX info -> Maybe Name\\nparentOfImplicitlyImportedGRE gre =\\n if any (explicit_import . is_item) $ gre_imp gre\\n then Nothing\\n else greParent_maybe gre\\n where\\n explicit_import :: ImpItemSpec -> Bool\\n explicit_import (ImpAll {}) =\\n pprPanic \\"parentOfImplicitlyImportedGRE: ImpAll\\" (ppr gre)\\n explicit_import (ImpSome { is_explicit }) = is_explicit\\n\\n{- Note [Children for duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider the module\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (F(foo, MkFInt, MkFBool)) where\\n data family F a\\n data instance F Int = MkFInt { foo :: Int }\\n data instance F Bool = MkFBool { foo :: Bool }\\n\\nThe `foo` in the export list refers to *both* selectors! For this\\nreason, lookupChildren builds an environment that maps the FastString\\nto a list of items, rather than a single item.\\n-}\\n\\nmkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]\\nmkChildEnv gres = foldr add emptyNameEnv gres\\n where\\n add gre env = case greParent gre of\\n ParentIs p -> extendNameEnv_Acc (:) Utils.singleton env p gre\\n NoParent -> env\\n\\nfindChildren :: NameEnv [a] -> Name -> [a]\\nfindChildren env n = lookupNameEnv env n `orElse` []\\n\\ndata LookupChildError\\n = LookupChildNotFound { lce_wrapped_name :: !(LIEWrappedName GhcPs) }\\n | LookupChildNonType { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nontype_item :: !GlobalRdrElt }\\n | LookupChildNonData { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nondata_item :: !GlobalRdrElt }\\n\\nlookupChildren :: [GlobalRdrElt]\\n -> [LIEWrappedName GhcPs]\\n -> ( [LookupChildError] -- The ones for which the lookup failed\\n , [LocatedA GlobalRdrElt] )\\n-- (lookupChildren all_kids rdr_items) maps each rdr_item to its\\n-- corresponding Name in all_kids, if the former exists\\n-- The matching is done by FastString, not OccName, so that\\n-- Cls( meth, AssocTy )\\n-- will correctly find AssocTy among the all_kids of Cls, even though\\n-- the RdrName for AssocTy may have a (bogus) DataName namespace\\n-- (Really the rdr_items should be FastStrings in the first place.)\\nlookupChildren all_kids rdr_items = (fails, successes)\\n where\\n mb_xs = map do_one rdr_items\\n fails = [ err | Failed err <- mb_xs ]\\n successes = [ ok | Succeeded oks <- mb_xs, ok <- NE.toList oks ]\\n\\n do_one :: LIEWrappedName GhcPs -> MaybeErr LookupChildError (NonEmpty (LocatedA GlobalRdrElt))\\n do_one item@(L l r) =\\n case r of\\n IEName{}\\n -- IEName (unadorned name) places no restriction on the namespace of\\n -- the imported entity, so we look in both `val_gres` and `typ_gres`.\\n -- In case of conflict (punning), the value namespace takes priority.\\n -- See Note [Prioritise the value namespace in subordinate import lists]\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEType{}\\n -- IEType (\'type\' namespace specifier) restricts the lookup to the\\n -- type namespace, i.e. to `typ_gres`. In case of failure, we check\\n -- `val_gres` to produce a more helpful error message.\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- val_gres -> Failed $ LookupChildNonType item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEData{}\\n -- IEData (\'data\' namespace specifier) restricts the lookup to the\\n -- data namespace, i.e. to `val_gres`. In case of failure, we check\\n -- `typ_gres` to produce a more helpful error message.\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- typ_gres -> Failed $ LookupChildNonData item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEPattern{} -> panic \\"lookupChildren: IEPattern\\" -- Never happens (invalid syntax)\\n IEDefault{} -> panic \\"lookupChildren: IEDefault\\" -- Never happens (invalid syntax)\\n where\\n fs = (occNameFS . rdrNameOcc . ieWrappedName) r\\n gres = fromMaybe [] (lookupFsEnv kid_env fs)\\n (val_gres, typ_gres) = partition (isValNameSpace . greNameSpace) gres\\n\\n -- See Note [Children for duplicate record fields]\\n kid_env :: FastStringEnv [GlobalRdrElt]\\n kid_env = extendFsEnvList_C (++) emptyFsEnv\\n [(occNameFS (occName x), [x]) | x <- all_kids]\\n\\n\\n{- Note [Prioritise the value namespace in subordinate import lists]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider this program that defines a class that has both an associated type\\nnamed (#) and a method named (#)\\n\\n module M_assoc where\\n class C a b where\\n type a # b\\n (#) :: a -> b -> ()\\n module N_assoc where\\n import M_assoc( C((#)) )\\n\\nIn the import declaration, when we see the unadorned name (#) in the subordinate\\nimport list of C, which children should we bring into scope? Our options are:\\n\\n a) only the method (#)\\n b) only the associated type (#)\\n c) both the method and the associated type\\n\\nTo follow the precedent established by top-level items, we go with option (a).\\nIndeed, consider a slightly different program\\n\\n module M_top where\\n type family a # b\\n a # b = ()\\n module N_top where\\n import M_top( (#) )\\n\\nHere the import brings only the function (#) into scope, and one has to say\\n`type (#)` to get the type family.\\n-}\\n\\n-------------------------------\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused names}\\n* *\\n*********************************************************\\n-}\\n\\nreportUnusedNames :: TcGblEnv -> HscSource -> RnM ()\\nreportUnusedNames gbl_env hsc_src\\n = do { keep <- readTcRef (tcg_keep gbl_env)\\n ; traceRn \\"RUN\\" (ppr (tcg_dus gbl_env))\\n ; warnUnusedImportDecls gbl_env hsc_src\\n ; warnUnusedTopBinds $ unused_locals keep\\n ; warnMissingSignatures gbl_env\\n ; warnMissingKindSignatures gbl_env }\\n where\\n used_names :: NameSet -> NameSet\\n used_names keep = findUses (tcg_dus gbl_env) emptyNameSet `unionNameSet` keep\\n -- NB: currently, if f x = g, we only treat \'g\' as used if \'f\' is used\\n -- Hence findUses\\n\\n -- Collect the defined names from the in-scope environment\\n defined_names :: [GlobalRdrElt]\\n defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)\\n\\n kids_env = mkChildEnv defined_names\\n -- This is done in mkExports too; duplicated work\\n\\n gre_is_used :: NameSet -> GlobalRdrElt -> Bool\\n gre_is_used used_names gre0\\n = name `elemNameSet` used_names\\n || any (\\\\ gre -> greName gre `elemNameSet` used_names) (findChildren kids_env name)\\n -- A use of C implies a use of T,\\n -- if C was brought into scope by T(..) or T(C)\\n where\\n name = greName gre0\\n\\n -- Filter out the ones that are\\n -- (a) defined in this module, and\\n -- (b) not defined by a \'deriving\' clause\\n -- The latter have an Internal Name, so we can filter them out easily\\n unused_locals :: NameSet -> [GlobalRdrElt]\\n unused_locals keep =\\n let -- Note that defined_and_used, defined_but_not_used\\n -- are both [GRE]; that\'s why we need defined_and_used\\n -- rather than just used_names\\n _defined_and_used, defined_but_not_used :: [GlobalRdrElt]\\n (_defined_and_used, defined_but_not_used)\\n = partition (gre_is_used (used_names keep)) defined_names\\n\\n in filter is_unused_local defined_but_not_used\\n is_unused_local :: GlobalRdrElt -> Bool\\n is_unused_local gre = isLocalGRE gre\\n && isExternalName (greName gre)\\n\\n{- *********************************************************************\\n* *\\n Missing signatures\\n* *\\n********************************************************************* -}\\n\\n{-\\nNote [Missing signatures]\\n~~~~~~~~~~~~~~~~~~~~~~~~~\\nThere are four warning flags in play:\\n\\n * -Wmissing-exported-signatures\\n Warn about any exported top-level function/value without a type signature.\\n Does not include pattern synonyms.\\n\\n * -Wmissing-signatures\\n Warn about any top-level function/value without a type signature. Does not\\n include pattern synonyms. Takes priority over -Wmissing-exported-signatures.\\n\\n * -Wmissing-exported-pattern-synonym-signatures\\n Warn about any exported pattern synonym without a type signature.\\n\\n * -Wmissing-pattern-synonym-signatures\\n Warn about any pattern synonym without a type signature. Takes priority over\\n -Wmissing-exported-pattern-synonym-signatures.\\n\\n-}\\n\\n-- | Warn the user about top level binders that lack type signatures.\\n-- Called /after/ type inference, so that we can report the\\n-- inferred type of the function\\nwarnMissingSignatures :: TcGblEnv -> RnM ()\\nwarnMissingSignatures gbl_env\\n = do { let exports = availsToNameSet (tcg_exports gbl_env)\\n sig_ns = tcg_sigs gbl_env\\n -- We use sig_ns to exclude top-level bindings that are generated by GHC\\n binds = collectHsBindsBinders CollNoDictBinders $ tcg_binds gbl_env\\n pat_syns = tcg_patsyns gbl_env\\n\\n not_ghc_generated :: Name -> Bool\\n not_ghc_generated name = name `elemNameSet` sig_ns\\n\\n add_binding_warn :: Id -> RnM ()\\n add_binding_warn id =\\n when (not_ghc_generated name) $\\n do { env <- liftZonkM $ tcInitTidyEnv -- Why not use emptyTidyEnv?\\n ; let ty = tidyOpenType env (idType id)\\n missing = MissingTopLevelBindingSig name ty\\n diag = TcRnMissingSignature missing exported\\n ; addDiagnosticAt (getSrcSpan name) diag }\\n where\\n name = idName id\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n add_patsyn_warn :: PatSyn -> RnM ()\\n add_patsyn_warn ps =\\n when (not_ghc_generated name) $\\n addDiagnosticAt (getSrcSpan name)\\n (TcRnMissingSignature missing exported)\\n where\\n name = patSynName ps\\n missing = MissingPatSynSig ps\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n -- Warn about missing signatures\\n -- Do this only when we have a type to offer\\n -- See Note [Missing signatures]\\n ; mapM_ add_binding_warn binds\\n ; mapM_ add_patsyn_warn pat_syns\\n }\\n\\n-- | Warn the user about tycons that lack kind signatures.\\n-- Called /after/ type (and kind) inference, so that we can report the\\n-- inferred kinds.\\nwarnMissingKindSignatures :: TcGblEnv -> RnM ()\\nwarnMissingKindSignatures gbl_env\\n = do { cusks_enabled <- xoptM LangExt.CUSKs\\n ; mapM_ (add_ty_warn cusks_enabled) tcs\\n }\\n where\\n tcs = tcg_tcs gbl_env\\n ksig_ns = tcg_ksigs gbl_env\\n exports = availsToNameSet (tcg_exports gbl_env)\\n\\n has_kind_signature :: Name -> Bool\\n has_kind_signature name = name `elemNameSet` ksig_ns\\n\\n add_ty_warn :: Bool -> TyCon -> RnM ()\\n add_ty_warn cusks_enabled tyCon =\\n when (has_kind_signature name) $\\n addDiagnosticAt (getSrcSpan name) diag\\n where\\n name = tyConName tyCon\\n diag = TcRnMissingSignature missing exported\\n missing = MissingTyConKindSig tyCon cusks_enabled\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused imports}\\n* *\\n*********************************************************\\n\\nThis code finds which import declarations are unused. The\\nspecification and implementation notes are here:\\n https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/unused-imports\\n\\nSee also Note [Choosing the best import declaration] in GHC.Types.Name.Reader\\n-}\\n\\ntype ImportDeclUsage\\n = ( LImportDecl GhcRn -- The import declaration\\n , [GlobalRdrElt] -- What *is* used (normalised)\\n , [Name] -- What is imported but *not* used\\n , [NamespaceSpecifier GhcRn] ) -- Unused wildcards\\n\\nwarnUnusedImportDecls :: TcGblEnv -> HscSource -> RnM ()\\nwarnUnusedImportDecls gbl_env hsc_src\\n = do { uses <- readMutVar (tcg_used_gres gbl_env)\\n ; let imports = tcg_rn_imports gbl_env\\n rdr_env = tcg_rdr_env gbl_env\\n\\n -- We should only warn for unnecessary *user* imports, but deciding\\n -- minimal imports should take generated imports into account\\n ; let usageUserImports = findImportUsage (excludeGenerated imports) uses\\n usageAllImports = findImportUsage imports uses\\n\\n ; traceRn \\"warnUnusedImportDecls\\" $\\n (vcat [ text \\"Uses:\\" <+> ppr uses\\n , text \\"Usage all user imports: \\" <+> ppr usageUserImports\\n , text \\"Usage all imports: \\" <+> ppr usageAllImports])\\n\\n ; mapM_ (warnUnusedImport rdr_env) usageUserImports\\n\\n ; whenGOptM Opt_D_dump_minimal_imports $\\n printMinimalImports hsc_src usageAllImports }\\n\\n-- | Exclude generated imports\\nexcludeGenerated :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\nexcludeGenerated = filterOut (isGeneratedImport . ideclOrigin . ideclExt . unLoc)\\n\\nfindImportUsage :: [LImportDecl GhcRn]\\n -> [GlobalRdrElt]\\n -> [ImportDeclUsage]\\n\\nfindImportUsage imports used_gres\\n = map unused_decl imports\\n where\\n import_usage :: ImportMap\\n import_usage = mkImportMap used_gres\\n\\n unused_decl :: LImportDecl GhcRn -> ImportDeclUsage\\n unused_decl decl@(L _ (ImportDecl { ideclImportList = imps }))\\n = -- pprTrace \\"unused_decl\\" (vcat [ ppr decl\\n -- , text \\"used\\" <+> ppr used_gres\\n -- , text \\"unused\\" <+> ppr unused_names ]) $\\n (decl, used_gres, unused_names, unused_wcs)\\n where\\n used_gres = lookupImportMap decl import_usage\\n\\n used_gre_env = mkGlobalRdrEnv used_gres\\n used_parents = mkNameSet (mapMaybe greParent_maybe used_gres)\\n\\n (unused_names, unused_wcs) -- Not trivial; see eg #7454\\n = case imps of\\n Just (Exactly, imp_ies) ->\\n let unused = foldr (add_unused . unLoc) emptyUnusedNames imp_ies\\n nms = nameSetElemsStable (collectUnusedNames unused)\\n wcs = collectUnusedWildcards unused\\n in (nms, wcs)\\n _other -> ([], []) -- No explicit import list => no unused-name list\\n\\n add_unused :: IE GhcRn -> UnusedNames -> UnusedNames\\n add_unused (IEVar _ n _) acc = add_unused_name (lieWrappedName n) True acc\\n add_unused (IEThingAbs _ n _) acc = add_unused_name (lieWrappedName n) False acc\\n add_unused (IEThingAll _ _ n _) acc = add_unused_all (lieWrappedName n) acc\\n add_unused (IEThingWith _ p wc ns _) acc = add_wc_all (add_unused_with pn xs acc)\\n where pn = lieWrappedName p\\n xs = map lieWrappedName ns\\n add_wc_all = case wc of\\n NoIEWildcard -> id\\n IEWildcard _ -> add_unused_all pn\\n add_unused (IEWholeNamespace x ns_spec) acc = add_unused_wildcard ns_spec (iewn_names x) acc\\n add_unused _ acc = acc\\n\\n add_unused_name :: Name -> Bool -> UnusedNames -> UnusedNames\\n add_unused_name n is_ie_var acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | is_ie_var\\n , isFieldName n\\n -- See Note [Reporting unused imported duplicate record fields]\\n = let\\n fs = getOccFS n\\n (flds, flds_used) = lookupFsEnv acc_fs fs `orElse` (emptyNameSet, Any False)\\n acc_fs\' = extendFsEnv acc_fs fs (extendNameSet flds n, Any used S.<> flds_used)\\n in UnusedNames acc_ns acc_wcs acc_fs\'\\n\\n | used\\n = acc\\n\\n | otherwise\\n = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n where\\n used = isJust $ lookupGRE_Name used_gre_env n\\n\\n add_unused_all :: Name -> UnusedNames -> UnusedNames\\n add_unused_all n acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | Just {} <- lookupGRE_Name used_gre_env n = acc\\n | n `elemNameSet` used_parents = acc\\n | otherwise = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n\\n add_unused_with :: Name -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_with p ns acc\\n | all (`elemNameSet` acc1_ns) ns = add_unused_name p False acc1\\n | otherwise = acc1\\n where\\n acc1@(UnusedNames acc1_ns _ _) = foldr (\\\\n acc\' -> add_unused_name n False acc\') acc ns\\n -- If you use \'signum\' from Num, then the user may well have\\n -- imported Num(signum). We don\'t want to complain that\\n -- Num is not itself mentioned. Hence the two cases in add_unused_with.\\n\\n add_unused_wildcard :: NamespaceSpecifier GhcRn -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_wildcard ns_spec names acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | any_used = acc\\n | otherwise = UnusedNames acc_ns (ns_spec : acc_wcs) acc_fs\\n where\\n -- A wildcard `type ..` or `data ..` is used if at least one of\\n -- the names it expands to is used\\n any_used = any (isJust . lookupGRE_Name used_gre_env) names\\n\\n\\n-- | An accumulator for unused names in an import list.\\n--\\n-- See Note [Reporting unused imported duplicate record fields].\\ndata UnusedNames =\\n UnusedNames\\n { unused_names :: NameSet\\n -- ^ Unused \'Name\'s in an import list, not including record fields\\n -- that are plain \'IEVar\' imports (tracked by \'rec_fld_uses\')\\n -- or wildcard imports (tracked by \'unused_wildcards\').\\n , unused_wildcards :: [NamespaceSpecifier GhcRn]\\n -- ^ Unused wildcards @type ..@ or @data ..@ in an import list.\\n , rec_fld_uses :: FastStringEnv (NameSet, Any)\\n -- ^ Record fields imported without a parent (i.e. an \'IEVar\' import).\\n --\\n -- The \'Any\' value records whether any of the record fields\\n -- sharing the same underlying \'FastString\' have been used.\\n }\\n\\nemptyUnusedNames :: UnusedNames\\nemptyUnusedNames = UnusedNames emptyNameSet [] emptyFsEnv\\n\\ninstance Outputable UnusedNames where\\n ppr (UnusedNames nms wcs flds) =\\n text \\"UnusedNames\\" <+>\\n braces (ppr nms <+> ppr wcs <+> ppr (fmap (second getAny) flds))\\n\\n-- | Collect all unused names from a \'UnusedNames\' value.\\ncollectUnusedNames :: UnusedNames -> NameSet\\ncollectUnusedNames (UnusedNames { unused_names = nms, rec_fld_uses = flds })\\n = nms S.<> unused_flds\\n where\\n unused_flds = nonDetFoldFsEnv collect_unused emptyNameSet flds\\n collect_unused :: (NameSet, Any) -> NameSet -> NameSet\\n collect_unused (nms, Any at_least_one_name_is_used) acc\\n | at_least_one_name_is_used = acc\\n | otherwise = unionNameSet nms acc\\n\\ncollectUnusedWildcards :: UnusedNames -> [NamespaceSpecifier GhcRn]\\ncollectUnusedWildcards = unused_wildcards\\n\\n{- Note [Reporting unused imported duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have (#24035):\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M1 (R1(..), R2(..)) where\\n data R1 = MkR1 { fld :: Int }\\n data R2 = MkR2 { fld :: Int }\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M2 where\\n import M1 (R1(MkR1), R2, fld)\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nIn the import of \'M1\' in \'M2\', the \'fld\' import resolves to two separate GREs,\\nnamely R1(fld) and R2(fld). From the perspective of the renamer, and in particular\\nthe \'findImportUsage\' function, it\'s as if the user had imported the two names\\nseparately (even though no source syntax allows that).\\n\\nThis means that we need to be careful when reporting unused imports: the R2(fld)\\nimport is indeed unused, but because R1(fld) is used, we should not report\\nfld as unused altogether.\\n\\nTo achieve this, we keep track of record field imports without a parent (i.e.\\nusing the IEVar constructor) separately from other import items, using the\\nUnusedNames datatype.\\nOnce we have accumulated usages, we emit warnings for unused record fields\\nwithout parents one whole group (of record fields sharing the same textual name)\\nat a time, and only if *all* of the record fields in the group are unused;\\nsee \'collectUnusedNames\'.\\n\\nNote that this only applies to record fields imported without a parent. If we\\nhad:\\n\\n import M1 (R1(MkR1, fld), R2(fld))\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nthen of course we should report the second \'fld\' as unused.\\n-}\\n\\n\\n{- Note [The ImportMap]\\n~~~~~~~~~~~~~~~~~~~~~~~\\nThe ImportMap is a short-lived intermediate data structure records, for\\neach import declaration, what stuff brought into scope by that\\ndeclaration is actually used in the module.\\n\\nThe [GlobalRdrElt] are the things imported from that decl.\\n-}\\n\\ndata ImportMap = ImportMap\\n { im_imports :: Map RealSrcSpan [GlobalRdrElt]\\n -- ^ See [The ImportMap]\\n -- If loc :-> gres, then\\n -- \'loc\' = the end loc of the bestImport of each GRE in \'gres\'\\n , im_generatedImports :: Map ModuleName [GlobalRdrElt]\\n }\\n\\nmkImportMap :: [GlobalRdrElt] -> ImportMap\\n-- For each of a list of used GREs, find all the import decls that brought\\n-- it into scope; choose one of them (bestImport), and record\\n-- the RdrName in that import decl\'s entry in the ImportMap\\nmkImportMap = foldr insertImportMap $ ImportMap Map.empty Map.empty\\n\\ninsertImportMap :: GlobalRdrElt -> ImportMap -> ImportMap\\ninsertImportMap gre@(GRE { gre_imp = imp_specs }) importMap\\n | RealSrcSpan importSpan _ <- is_dloc best_imp_spec =\\n importMap{im_imports = insertElem importSpan gre $ im_imports importMap}\\n | GeneratedSrcSpan{} <- is_dloc best_imp_spec =\\n importMap{im_generatedImports = insertElem (moduleName $ is_mod best_imp_spec) gre $ im_generatedImports importMap}\\n | otherwise = importMap\\n where\\n best_imp_spec =\\n case bagToList imp_specs of\\n [] -> pprPanic \\"mkImportMap: GRE with no ImportSpecs\\" (ppr gre)\\n is:iss -> is_decl $ bestImport (is NE.:| iss)\\n\\n -- https://github.com/haskell/containers/issues/784\\n insertElem :: Ord k => k -> v -> Map k [v] -> Map k [v]\\n insertElem k v = flip Map.alter k $ \\\\case\\n Just vs -> Just (v : vs)\\n Nothing -> Just [v]\\n\\nlookupImportMap :: LImportDecl GhcRn -> ImportMap -> [GlobalRdrElt]\\nlookupImportMap (L srcSpan ImportDecl{ideclName = L _ modName}) importMap =\\n fromMaybe [] $\\n -- should match logic in insertImportMap\\n case locA srcSpan of\\n RealSrcSpan realSrcSpan _ -> realSrcSpan `Map.lookup` im_imports importMap\\n GeneratedSrcSpan{} -> modName `Map.lookup` im_generatedImports importMap\\n _ -> Nothing\\n\\nlieNames :: LIE (GhcPass p) -> [Located (IdP (GhcPass p))]\\nlieNames = _\\n\\nwarnUnusedImport :: GlobalRdrEnv -> ImportDeclUsage -> RnM ()\\nwarnUnusedImport rdr_env (L loc decl, used, unused, unused_wcs)\\n\\n -- Do not warn for \'import M()\'\\n -- See (UI1) in Note [Unused imports]\\n | Just (Exactly, _) <- ideclImportList decl\\n , null unused && null unused_wcs\\n = return ()\\n\\n -- Note [Do not warn about Prelude hiding]\\n | Just (EverythingBut, hides) <- ideclImportList decl\\n , not (null hides)\\n , pRELUDE_NAME == unLoc (ideclName decl)\\n = return ()\\n\\n -- Do not warn about import X as Rebindable\\n -- See (UI2) in Note [Unused imports]\\n | Just (L _ mod) <- ideclAs decl\\n , mod == rEBINDABLE_MOD_NAME\\n = return ()\\n\\n -- Nothing used; drop entire declaration\\n | null used\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl UnusedImportNone)\\n\\n -- Everything imported is used; nop\\n | null unused && null unused_wcs\\n = return ()\\n\\n -- Some imports are unused: make the `SrcSpan` cover only the unused\\n -- items instead of the whole import statement\\n | Just (_, imports) <- ideclImportList decl\\n , let unused_locs = [ locA loc | L loc ie <- imports\\n , name <- ieNames ie\\n , name `elem` unused ]\\n , loc1 : locs <- unused_locs\\n , let span = foldr1 combineSrcSpans ( loc1 NE.:| locs )\\n = addDiagnosticAt span (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n -- Some imports are unused\\n | otherwise\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n where\\n -- In warning message, pretty-print identifiers unqualified unconditionally\\n -- to improve the consistent for ambiguous/unambiguous identifiers.\\n -- See #14881.\\n possible_field n =\\n case lookupGRE_Name rdr_env n of\\n Just (GRE { gre_par = par, gre_info = IAmRecField info }) ->\\n let fld_occ :: OccName\\n fld_occ = nameOccName $ flSelector $ recFieldLabel info\\n in UnusedImportNameRecField par fld_occ\\n _ -> UnusedImportNameRegular n\\n\\n -- Print unused names in a deterministic (lexicographic) order\\n sort_unused :: [UnusedImportName]\\n sort_unused =\\n [ UnusedImportWildcard wc | wc <- unused_wcs ] ++\\n [ possible_field nm | nm <- sortBy (comparing nameOccName) unused ]\\n\\ngetMinimalImports :: [ImportDeclUsage] -> RnM [LImportDecl GhcRn]\\ngetMinimalImports ie_decls\\n = do { rdr_env <- getGlobalRdrEnv\\n ; fmap combine $ mapM (mk_minimal rdr_env) ie_decls }\\n where\\n mk_minimal rdr_env (L l decl, used_gres, unused, unused_wcs)\\n | null unused && null unused_wcs\\n , Just (Exactly, _) <- ideclImportList decl\\n = return (L l decl)\\n | otherwise\\n = do { let ImportDecl { ideclName = L _ mod_name\\n , ideclSource = is_boot\\n , ideclPkgQual = pkg_qual\\n , ideclExt = XImportDeclPass { ideclOrigin = origin } } = decl\\n ; iface <- loadSrcInterface doc (importDeclLookupScope origin)\\n mod_name is_boot pkg_qual\\n ; let used_avails = gresToAvailInfo used_gres\\n ; lies <- map (L l) <$> concatMapM (to_ie rdr_env iface) used_avails\\n ; return (L l (decl { ideclImportList = Just (Exactly, lies) })) }\\n where\\n doc = text \\"Compute minimal imports for\\" <+> ppr decl\\n\\n to_ie :: GlobalRdrEnv -> ModIface -> AvailInfo -> RnM [IE GhcRn]\\n -- The main trick here is that if we\'re importing all the constructors\\n -- we want to say \\"T(..)\\", but if we\'re importing only a subset we want\\n -- to say \\"T(A,B,C)\\". So we have to find out what the module exports.\\n to_ie rdr_env _ (Avail c) -- Note [Overloaded field import]\\n = do { let\\n gre = expectJust $ lookupGRE_Name rdr_env c\\n ; return $ [IEVar Nothing (to_ie_post_rn $ noLocA $ greName gre) Nothing] }\\n to_ie _ _ avail@(AvailTC n [_]) -- Exporting the main decl and nothing else\\n | availExportsDecl avail\\n = return [IEThingAbs Nothing (to_ie_post_rn $ noLocA n) Nothing]\\n to_ie rdr_env iface (AvailTC n cs) =\\n case [ xs | avail@(AvailTC x xs) <- mi_exports iface\\n , x == n\\n , availExportsDecl avail -- Note [Partial export]\\n ] of\\n [xs]\\n | all_used xs\\n -> return [IEThingAll (IEThingAllExt Nothing noAnn noAnn noAnn)\\n (NoNamespaceSpecifier noExtField)\\n (to_ie_post_rn $ noLocA n)\\n Nothing]\\n | otherwise\\n -> do { let ns_gres = map (expectJust . lookupGRE_Name rdr_env) cs\\n ns = map greName ns_gres\\n ; return [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n -- Note [Overloaded field import]\\n _other\\n -> do { let infos = map (expectJust . lookupGRE_Name rdr_env) cs\\n (ns_gres,fs_gres) = classifyGREs infos\\n ns = map greName (ns_gres ++ fs_gres)\\n fs = map fieldGREInfo fs_gres\\n ; return $\\n if all_non_overloaded fs\\n then map (\\\\nm -> IEVar Nothing (to_ie_post_rn_var $ noLocA nm) Nothing) ns\\n else [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n where\\n\\n all_used avail_cs = all (`elem` cs) avail_cs\\n\\n all_non_overloaded = all (not . flIsOverloaded . recFieldLabel)\\n\\n combine :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\n combine = map merge . NE.groupAllWith getKey\\n\\n getKey :: LImportDecl GhcRn -> (Bool, Maybe ModuleName, ModuleName)\\n getKey decl =\\n ( isImportDeclQualified . ideclQualified $ idecl -- is this qualified? (important that this be first)\\n , unLoc <$> ideclAs idecl -- what is the qualifier (inside Maybe monad)\\n , unLoc . ideclName $ idecl -- Module Name\\n )\\n where\\n idecl :: ImportDecl GhcRn\\n idecl = unLoc decl\\n\\n merge :: NonEmpty (LImportDecl GhcRn) -> LImportDecl GhcRn\\n merge decls@((L l decl) :| _) = L l (decl { ideclImportList = Just (Exactly, lies) })\\n where lies = concatMap snd $ mapMaybe (ideclImportList . unLoc) $ NE.toList decls\\n\\nclassifyGREs :: [GlobalRdrElt] -> ([GlobalRdrElt], [FieldGlobalRdrElt])\\nclassifyGREs = partition (not . isRecFldGRE)\\n\\nprintMinimalImports :: HscSource -> [ImportDeclUsage] -> RnM ()\\n-- See Note [Printing minimal imports]\\nprintMinimalImports hsc_src imports_w_usage\\n = do { imports\' <- excludeGenerated <$> getMinimalImports imports_w_usage\\n ; this_mod <- getModule\\n ; dflags <- getDynFlags\\n ; liftIO $ withFile (mkFilename dflags this_mod) WriteMode $ \\\\h ->\\n printForUser dflags h neverQualify AllTheWay (vcat (map ppr imports\'))\\n -- The neverQualify is important. We are printing Names\\n -- but they are in the context of an \'import\' decl, and\\n -- we never qualify things inside there\\n -- E.g. import Blag( f, b )\\n -- not import Blag( Blag.f, Blag.g )!\\n }\\n where\\n mkFilename dflags this_mod\\n | Just d <- dumpDir dflags = d basefn\\n | otherwise = basefn\\n where\\n suffix = case hsc_src of\\n HsBootFile -> \\".imports-boot\\"\\n HsSrcFile -> \\".imports\\"\\n HsigFile -> \\".imports\\"\\n basefn = moduleNameString (moduleName this_mod) ++ suffix\\n\\n\\nto_ie_post_rn_var :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn_var (L l n)\\n | isDataOcc $ occName n = L l (IEPattern noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n\\n\\nto_ie_post_rn :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn (L l n)\\n | isTcOcc occ && isSymOcc occ = L l (IEType noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n where occ = occName n\\n\\n{- Note [Do not warn about Prelude hiding]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWe do not warn about\\n import Prelude hiding( x, y )\\nbecause even if nothing else from Prelude is used, it may be essential to hide\\nx,y to avoid name-shadowing warnings. Example (#9061)\\n import Prelude hiding( log )\\n f x = log where log = ()\\n\\nNote [Unused imports]\\n~~~~~~~~~~~~~~~~~~~~~\\nIn `warnUnusedImport`, if we see an import with an explicit list imports, thus\\n import M( a, b )\\nand neither `a` nor `b` is used, we report the entire import decl as unused. We\\ncheck this by looking at the names that it brings into scope scope; if there are\\nno ununused names, don\'t report.\\n\\n(UI1) We don\'t want to complain about `import M()`, because that is often used to bring\\n M\'s /instances/ into scope. That is neatly dealt with by the \\"no unused\\n names\\" (nor unused wildcard imports) criterion.\\n\\n(UI2) We don\'t report a decl as unused if it has an `as Rebindable` qualifier.\\n See (KN1) in Note [Overview of known entities] in GHC.Builtin\\n\\n\\nNote [Printing minimal imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nTo print the minimal imports we walk over all import decls (both user-supplied\\nand generated), trim their import lists, then filter out generated decls.\\n\\nNB that\\n\\n * We do *not* change the \'qualified\' or \'as\' parts!\\n\\n * We do not discard a decl altogether; we might need instances\\n from it. Instead we just trim to an empty import list\\n\\nNote [Partial export]\\n~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have\\n\\n module A( op ) where\\n class C a where\\n op :: a -> a\\n\\n module B where\\n import A\\n f = ..op...\\n\\nThen the minimal import for module B is\\n import A( op )\\nnot\\n import A( C( op ) )\\nwhich we would usually generate if C was exported from B. Hence\\nthe availExportsDecl test when deciding what to generate.\\n\\n\\nNote [Overloaded field import]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nOn the other hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n data T = MkT { foo :: Int }\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( T(foo) )\\nbecause when DuplicateRecordFields is enabled, field selectors are\\nnot in scope without their enclosing datatype.\\n\\nOn the third hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n pattern MkT { foo } = Just foo\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( foo )\\nbecause foo doesn\'t have a parent. This might actually be ambiguous if A\\nexports another field called foo, but there is no good answer to return and this\\nis a very obscure corner, so it seems to be the best we can do. See\\nDRFPatSynExport for a test of this.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Errors}\\n* *\\n************************************************************************\\n-}\\n\\nbadImportItemErr\\n :: ModIface -> ImpDeclSpec -> IE GhcPs\\n -> IsSubordinateError\\n -> [AvailInfo]\\n -> TcRn (NonEmpty ImportLookupReason)\\nbadImportItemErr iface decl_spec ie sub avails = do\\n exts <- importLookupExtensions\\n let import_lookup_bad :: BadImportKind -> ImportLookupReason\\n import_lookup_bad k = ImportLookupBad k iface decl_spec ie exts\\n dflags <- getDynFlags\\n hsc_env <- getTopEnv\\n let rdr_env = mkGlobalRdrEnv\\n $ gresFromAvails hsc_env (Just imp_spec) all_avails\\n pure $ fmap import_lookup_bad (importErrorKind dflags rdr_env)\\n where\\n importErrorKind :: DynFlags -> GlobalRdrEnv -> NonEmpty BadImportKind\\n importErrorKind dflags rdr_env\\n | any checkIfTyCon avails = case sub of\\n IsNotSubordinate -> NE.singleton BadImportAvailTyCon\\n IsSubordinateError { subordinate_err_parent = gre\\n , subordinate_err_unavailable = unavailable\\n , subordinate_err_nontype = nontype\\n , subordinate_err_nondata = nondata }\\n -> NE.fromList $ catMaybes $\\n [ fmap (BadImportNotExportedSubordinates gre) (NE.nonEmpty unavailable)\\n , fmap (BadImportNonTypeSubordinates gre) (NE.nonEmpty nontype)\\n , fmap (BadImportNonDataSubordinates gre) (NE.nonEmpty nondata) ]\\n | any checkIfVarName avails = NE.singleton BadImportAvailVar\\n | Just con <- find checkIfDataCon avails = NE.singleton (BadImportAvailDataCon (availOccName con))\\n | otherwise = NE.singleton (BadImportNotExported suggs)\\n where\\n suggs = similar_suggs ++ fieldSelectorSuggestions rdr_env rdr\\n what_look = case sub of\\n IsNotSubordinate -> WL_TyCon_or_TermVar\\n IsSubordinateError { subordinate_err_parent = gre } ->\\n case greInfo gre of\\n IAmTyCon ClassFlavour\\n -> WL_TyCon_or_TermVar\\n _ -> WL_Term\\n similar_names =\\n similarNameSuggestions (Unbound.LF what_look WL_Global)\\n dflags rdr_env emptyLocalRdrEnv rdr\\n similar_suggs =\\n case NE.nonEmpty $ mapMaybe imported_item $ similar_names of\\n Just similar -> [ SuggestSimilarNames rdr similar ]\\n Nothing -> [ ]\\n\\n -- Only keep imported items, and set the \\"HowInScope\\" to\\n -- \\"Nothing\\" to avoid printing \\"imported from...\\" in the suggestion\\n -- error message.\\n imported_item (SimilarRdrName rdr_name gre (Just (ImportedBy {})))\\n = Just (SimilarRdrName rdr_name gre Nothing)\\n imported_item _ = Nothing\\n\\n checkIfDataCon = checkIfAvailMatches isDataConName\\n checkIfTyCon = checkIfAvailMatches isTyConName\\n checkIfVarName =\\n \\\\case\\n AvailTC{} -> False\\n Avail n -> importedFS == occNameFS (occName n)\\n && (isVarOcc <||> isFieldOcc) (occName n)\\n checkIfAvailMatches namePred =\\n \\\\case\\n AvailTC _ ns ->\\n case find (\\\\n -> importedFS == occNameFS (occName n)) ns of\\n Just n -> namePred n\\n Nothing -> False\\n Avail{} -> False\\n availOccName = occName . availName\\n rdr = ieName ie\\n importedFS = occNameFS $ rdrNameOcc rdr\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n all_avails = mi_exports iface\\n\\nimportLookupExtensions :: TcRn ImportLookupExtensions\\nimportLookupExtensions = do\\n ile_pattern_synonyms <- xoptM LangExt.PatternSynonyms\\n ile_explicit_namespaces <- xoptM LangExt.ExplicitNamespaces\\n return ImportLookupExtensions{ile_pattern_synonyms, ile_explicit_namespaces}\\n\\naddDupDeclErr :: NonEmpty GlobalRdrElt -> TcRn ()\\naddDupDeclErr gres@(gre :| _)\\n -- Report the error at the later location\\n = addErrAt (getSrcSpan (NE.last sorted_names)) $ (TcRnDuplicateDecls (greOccName gre) sorted_names)\\n where\\n sorted_names =\\n NE.sortBy (SrcLoc.leftmost_smallest `on` nameSrcSpan)\\n (fmap greName gres)\\n\\n-- This data decl will parse OK\\n-- data T = a Int\\n-- treating \\"a\\" as the constructor.\\n-- It is really hard to make the parser spot this malformation.\\n-- So the renamer has to check that the constructor is legal\\n--\\n-- We can get an operator as the constructor, even in the prefix form:\\n-- data T = :% Int Int\\n-- from interface files, which always print in prefix form\\n--\\n-- We also allow type constructor names, which are defined by \\"type data\\"\\n-- declarations. See Note [Type data declarations] in GHC.Rename.Module.\\n\\ncheckConName :: RdrName -> TcRn ()\\ncheckConName name\\n = checkErr (isRdrDataCon name || isRdrTc name) (TcRnIllegalDataCon name)\\n", "filetypes": ["haskell"]}}}' 2026-10-16 14:47:51,360 - DEBUG - POST b'http://127.0.0.1:37093/receive_messages' {'content-type': 'application/json', 'x-ycm-hmac': b'Rga7Yd4l4fgfufwYw+0sxzurvznImlBO0MPmgAlS4EY='} b'{"filepath": "/home/enrico/ghc/compiler/GHC/Rename/Names.hs", "line_num": 1, "column_num": 1, "working_dir": "/home/enrico/ghc", "file_data": {"/home/enrico/ghc/compiler/GHC/Rename/Names.hs": {"contents": "{-\\n(c) The GRASP/AQUA Project, Glasgow University, 1992-1998\\n\\nExtracting imported and top-level names in scope\\n-}\\n\\n{-# LANGUAGE NondecreasingIndentation #-}\\n{-# LANGUAGE TypeFamilies #-}\\n\\nmodule GHC.Rename.Names (\\n rnImports, getLocalNonValBinders, newRecordFieldLabel,\\n importsFromIface,\\n ImportUserSpec(..),\\n extendGlobalRdrEnvRn,\\n gresFromAvails,\\n calculateAvails,\\n reportUnusedNames,\\n checkConName,\\n mkChildEnv,\\n findChildren,\\n mkBadExportSubordinate,\\n findImportUsage,\\n getMinimalImports,\\n printMinimalImports,\\n renamePkgQual, renameRawPkgQual,\\n classifyGREs,\\n ImportDeclUsage,\\n rnNamespaceSpecifier\\n ) where\\n\\nimport GHC.Prelude hiding ( head, init, last, tail )\\n\\nimport GHC.Driver.Env\\nimport GHC.Driver.Session\\nimport GHC.Driver.Ppr\\n\\nimport GHC.Rename.Env\\nimport GHC.Rename.Fixity\\nimport GHC.Rename.Utils ( warnUnusedTopBinds )\\nimport GHC.Rename.Unbound\\nimport qualified GHC.Rename.Unbound as Unbound\\n\\nimport GHC.Tc.Errors.Types\\nimport GHC.Tc.Utils.Env\\nimport GHC.Tc.Utils.Monad\\nimport GHC.Tc.Types.LclEnv\\nimport GHC.Tc.Zonk.TcType ( tcInitTidyEnv )\\n\\nimport GHC.Hs\\nimport GHC.Iface.Load ( loadSrcInterface, loadSrcInterface_maybe )\\nimport GHC.Iface.Errors.Types\\n ( IfaceMessage(..), MissingInterfaceError, InterfaceLookingFor(..)\\n , LoadEssentialsReason(..) )\\nimport GHC.Iface.Syntax ( fromIfaceWarnings )\\nimport GHC.Builtin.Modules( pRELUDE_NAME, rEBINDABLE_MOD_NAME )\\nimport GHC.Parser.PostProcess ( setRdrNameSpace )\\nimport GHC.Core.TyCo.Tidy\\nimport GHC.Core.PatSyn\\nimport GHC.Core.TyCon ( TyCon, tyConName )\\nimport qualified GHC.LanguageExtensions as LangExt\\n\\nimport GHC.Utils.Outputable as Outputable\\nimport GHC.Utils.Misc as Utils\\nimport GHC.Utils.Panic\\n\\nimport GHC.Types.Fixity.Env\\nimport GHC.Types.SafeHaskell\\nimport GHC.Types.Name\\nimport GHC.Types.Name.Env\\nimport GHC.Types.Name.Set\\nimport GHC.Types.Name.Reader\\nimport GHC.Types.Avail\\nimport GHC.Types.FieldLabel\\nimport GHC.Types.Hint\\nimport GHC.Types.SourceFile\\nimport GHC.Types.SrcLoc as SrcLoc\\nimport GHC.Types.Basic (TyConFlavour (..), convImportLevel, VisArity)\\nimport GHC.Types.UnresolvedImport\\nimport GHC.Types.Id\\nimport GHC.Types.PkgQual\\nimport GHC.Types.GREInfo (ConInfo(..), ConFieldInfo (..), ConLikeInfo (ConIsData))\\n\\nimport GHC.Unit\\nimport GHC.Unit.Module.Warnings\\nimport GHC.Unit.Module.ModIface\\nimport GHC.Unit.Module.Imported\\nimport GHC.Unit.Module.Deps\\nimport GHC.Unit.Env\\n\\nimport GHC.Data.Bag\\nimport GHC.Data.FastString\\nimport GHC.Data.FastString.Env\\nimport GHC.Data.Maybe\\nimport GHC.Data.List.SetOps ( removeDups )\\n\\nimport Control.Arrow ( second )\\nimport Control.Monad\\nimport Data.Foldable ( for_ )\\nimport Data.IntMap ( IntMap )\\nimport qualified Data.IntMap as IntMap\\nimport Data.Map ( Map )\\nimport qualified Data.Map as Map\\nimport Data.Ord ( comparing )\\nimport Data.Semigroup ( Any(..) )\\nimport qualified Data.Semigroup as S\\nimport Data.List ( partition, find, sortBy )\\nimport Data.List.NonEmpty (NonEmpty(..))\\nimport qualified Data.List.NonEmpty as NE\\nimport Data.Function ( on )\\nimport qualified Data.Set as S\\nimport System.FilePath (())\\nimport System.IO\\n\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{rnImports}\\n* *\\n************************************************************************\\n\\nNote [Tracking Trust Transitively]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen we import a package as well as checking that the direct imports are safe\\naccording to the rules outlined in the Note [Safe Haskell Trust Check] in GHC.Driver.Main\\nwe must also check that these rules hold transitively for all dependent modules\\nand packages. Doing this without caching any trust information would be very\\nslow as we would need to touch all packages and interface files a module depends\\non. To avoid this we make use of the property that if a modules Safe Haskell\\nmode changes, this triggers a recompilation from that module in the dependency\\ngraph. So we can just worry mostly about direct imports.\\n\\nThere is one trust property that can change for a package though without\\nrecompilation being triggered: package trust. So we must check that all\\npackages a module transitively depends on to be trusted are still trusted when\\nwe are compiling this module (as due to recompilation avoidance some modules\\nbelow may not be considered trusted any more without recompilation being\\ntriggered).\\n\\nWe handle this by augmenting the existing transitive list of packages a module M\\ndepends on with a bool for each package that says if it must be trusted when the\\nmodule M is being checked for trust. This list of trust required packages for a\\nsingle import is gathered in the rnImportDecl function and stored in an\\nImportAvails data structure. The union of these trust required packages for all\\nimports is done by the rnImports function using the combine function which calls\\nthe plusImportAvails function that is a union operation for the ImportAvails\\ntype. This gives us in an ImportAvails structure all packages required to be\\ntrusted for the module we are currently compiling. Checking that these packages\\nare still trusted (and that direct imports are trusted) is done in\\nGHC.Driver.Main.checkSafeImports.\\n\\nSee the note below, [Trust Own Package] for a corner case in this method and\\nhow its handled.\\n\\n\\nNote [Trust Own Package]\\n~~~~~~~~~~~~~~~~~~~~~~~~\\nThere is a corner case of package trust checking that the usual transitive check\\ndoesn\'t cover. (For how the usual check operates see the Note [Tracking Trust\\nTransitively] below). The case is when you import a -XSafe module M and M\\nimports a -XTrustworthy module N. If N resides in a different package than M,\\nthen the usual check works as M will record a package dependency on N\'s package\\nand mark it as required to be trusted. If N resides in the same package as M\\nthough, then importing M should require its own package be trusted due to N\\n(since M is -XSafe so doesn\'t create this requirement by itself). The usual\\ncheck fails as a module doesn\'t record a package dependency of its own package.\\nSo instead we now have a bool field in a modules interface file that simply\\nstates if the module requires its own package to be trusted. This field avoids\\nus having to load all interface files that the module depends on to see if one\\nis trustworthy.\\n\\n\\nNote [Trust Transitive Property]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSo there is an interesting design question in regards to transitive trust\\nchecking. Say I have a module B compiled with -XSafe. B is dependent on a bunch\\nof modules and packages, some packages it requires to be trusted as its using\\n-XTrustworthy modules from them. Now if I have a module A that doesn\'t use safe\\nhaskell at all and simply imports B, should A inherit all the trust\\nrequirements from B? Should A now also require that a package p is trusted since\\nB required it?\\n\\nWe currently say no but saying yes also makes sense. The difference is, if a\\nmodule M that doesn\'t use Safe Haskell imports a module N that does, should all\\nthe trusted package requirements be dropped since M didn\'t declare that it cares\\nabout Safe Haskell (so -XSafe is more strongly associated with the module doing\\nthe importing) or should it be done still since the author of the module N that\\nuses Safe Haskell said they cared (so -XSafe is more strongly associated with\\nthe module that was compiled that used it).\\n\\nGoing with yes is a simpler semantics we think and harder for the user to stuff\\nup but it does mean that Safe Haskell will affect users who don\'t care about\\nSafe Haskell as they might grab a package from Cabal which uses safe haskell (say\\nnetwork) and that packages imports -XTrustworthy modules from another package\\n(say bytestring), so requires that package is trusted. The user may now get\\ncompilation errors in code that doesn\'t do anything with Safe Haskell simply\\nbecause they are using the network package. They will have to call \'ghc-pkg\\ntrust network\' to get everything working. Due to this invasive nature of going\\nwith yes we have gone with no for now.\\n-}\\n\\n-- | Process Import Decls. See \'rnImportDecl\' for a description of what\\n-- the return types represent.\\n-- Note: Do the non SOURCE ones first, so that we get a helpful warning\\n-- for SOURCE ones that are unnecessary\\nrnImports :: [(LImportDecl GhcPs, SDoc)]\\n -> RnM ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\nrnImports imports = do\\n tcg_env <- getGblEnv\\n -- NB: want an identity module here, because it\'s OK for a signature\\n -- module to import from its implementor\\n let this_mod = tcg_mod tcg_env\\n let (source, ordinary) = partition (is_source_import . fst) imports\\n is_source_import (d::LImportDecl GhcPs) = ideclSource (unLoc d) == IsBoot\\n stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary\\n stuff2 <- mapAndReportM (rnImportDecl this_mod) source\\n -- Safe Haskell: See Note [Tracking Trust Transitively]\\n let (decls, imp_user_spec, rdr_env, imp_avails) = combine (stuff1 ++ stuff2)\\n -- Update imp_boot_mods if imp_direct_mods mentions any of them\\n let merged_import_avail = clobberSourceImports imp_avails\\n return (decls, imp_user_spec, rdr_env, merged_import_avail)\\n\\n where\\n clobberSourceImports imp_avails =\\n imp_avails { imp_boot_mods = imp_boot_mods\' }\\n where\\n imp_boot_mods\' = mergeInstalledModuleEnv combJ id (const emptyInstalledModuleEnv)\\n (imp_boot_mods imp_avails)\\n (imp_direct_dep_mods imp_avails)\\n\\n combJ (GWIB _ IsBoot) (_, x) = Just x\\n combJ r _ = Just r\\n -- See Note [Combining ImportAvails]\\n combine :: [(LImportDecl GhcRn, ImportUserSpec, GlobalRdrEnv, ImportAvails)]\\n -> ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\n combine ss =\\n let (decls, imp_user_spec, rdr_env, imp_avails, finsts) = foldr\\n plus\\n ([], [], emptyGlobalRdrEnv, emptyImportAvails, emptyModuleSet)\\n ss\\n in (decls, imp_user_spec, rdr_env, imp_avails { imp_finsts = moduleSetElts finsts })\\n\\n plus (decl, us, gbl_env1, imp_avails1)\\n (decls, uss, gbl_env2, imp_avails2, finsts_set)\\n = ( decl:decls,\\n us:uss,\\n gbl_env1 `plusGlobalRdrEnv` gbl_env2,\\n imp_avails1\' `plusImportAvails` imp_avails2,\\n extendModuleSetList finsts_set new_finsts )\\n where\\n imp_avails1\' = imp_avails1 { imp_finsts = [] }\\n new_finsts = imp_finsts imp_avails1\\n\\n{-\\nNote [Combining ImportAvails]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nimp_finsts in ImportAvails is a list of family instance modules\\ntransitively depended on by an import. imp_finsts for a currently\\ncompiled module is a union of all the imp_finsts of imports.\\nComputing the union of two lists of size N is O(N^2) and if we\\ndo it to M imports we end up with O(M*N^2). That can get very\\nexpensive for bigger module hierarchies.\\n\\nUnion can be optimized to O(N log N) if we use a Set.\\nimp_finsts is converted back and forth between dep_finsts, so\\nchanging a type of imp_finsts means either paying for the conversions\\nor changing the type of dep_finsts as well.\\n\\nI\'ve measured that the conversions would cost 20% of allocations on my\\ntest case, so that can be ruled out.\\n\\nChanging the type of dep_finsts forces checkFamInsts to\\nget the module lists in non-deterministic order. If we wanted to restore\\nthe deterministic order, we\'d have to sort there, which is an additional\\ncost. As far as I can tell, using a non-deterministic order is fine there,\\nbut that\'s a brittle nonlocal property which I\'d like to avoid.\\n\\nAdditionally, dep_finsts is read from an interface file, so its \\"natural\\"\\ntype is a list. Which makes it a natural type for imp_finsts.\\n\\nSince rnImports.combine is really the only place that would benefit from\\nit being a Set, it makes sense to optimize the hot loop in rnImports.combine\\nwithout changing the representation.\\n\\nSo here\'s what we do: instead of naively merging ImportAvails with\\nplusImportAvails in a loop, we make plusImportAvails merge empty imp_finsts\\nand compute the union on the side using Sets. When we\'re done, we can\\nconvert it back to a list. One nice side effect of this approach is that\\nif there\'s a lot of overlap in the imp_finsts of imports, the\\nSet doesn\'t really need to grow and we don\'t need to allocate.\\n\\nRunning generateModules from #14693 with DEPTH=16, WIDTH=30 finishes in\\n23s before, and 11s after.\\n-}\\n\\n-- | Given a located import declaration @decl@ from @this_mod@,\\n-- calculate the following pieces of information:\\n--\\n-- 1. An updated \'LImportDecl\', where all unresolved \'RdrName\' in\\n-- the entity lists have been resolved into \'Name\'s,\\n--\\n-- 2. A \'GlobalRdrEnv\' representing the new identifiers that were\\n-- brought into scope (taking into account module qualification\\n-- and hiding),\\n--\\n-- 3. \'ImportAvails\' summarizing the identifiers that were imported\\n-- by this declaration, and\\n--\\n-- 4. A boolean \'AnyHpcUsage\' which is true if the imported module\\n-- used HPC.\\nrnImportDecl :: Module -> (LImportDecl GhcPs, SDoc)\\n -> RnM (LImportDecl GhcRn, ImportUserSpec , GlobalRdrEnv, ImportAvails)\\nrnImportDecl this_mod\\n (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name\\n , ideclPkgQual = raw_pkg_qual\\n , ideclSource = want_boot\\n , ideclSafe = mod_safe\\n , ideclLevelSpec = import_level\\n , ideclQualified = qual_style\\n , ideclExt = XImportDeclPass { ideclOrigin = origin }\\n , ideclAs = as_mod, ideclImportList = imp_details }), import_reason)\\n = setSrcSpanA loc $ do\\n\\n case raw_pkg_qual of\\n NoRawPkgQual -> pure ()\\n RawPkgQual {} -> do\\n pkg_imports <- xoptM LangExt.PackageImports\\n when (not pkg_imports) $ addErr TcRnPackageImportsDisabled\\n\\n let qual_only = isImportDeclQualified qual_style\\n generated = isGeneratedImport origin\\n\\n lookup_scope = importDeclLookupScope origin\\n\\n -- If there\'s an error in loadInterface, (e.g. interface\\n -- file not found) we get lots of spurious errors from \'filterImports\'\\n let imp_mod_name = unLoc loc_imp_mod_name\\n doc = ppr imp_mod_name <+> import_reason\\n\\n hsc_env <- getTopEnv\\n unit_env <- hsc_unit_env <$> getTopEnv\\n let pkg_qual = renameRawPkgQual unit_env imp_mod_name raw_pkg_qual\\n\\n -- Check for self-import, which confuses the typechecker (#9032)\\n -- ghc --make rejects self-import cycles already, but batch-mode may not\\n -- at least not until GHC.IfaceToCore.tcHiBootIface, which is too late to avoid\\n -- typechecker crashes. (Indirect self imports are not caught until\\n -- GHC.IfaceToCore, see #10337 tracking how to make this error better.)\\n --\\n -- Originally, we also allowed \'import {-# SOURCE #-} M\', but this\\n -- caused bug #10182: in one-shot mode, we should never load an hs-boot\\n -- file for the module we are compiling into the EPS. In principle,\\n -- it should be possible to support this mode of use, but we would have to\\n -- extend Provenance to support a local definition in a qualified location.\\n -- For now, we don\'t support it, but see #10336\\n when (imp_mod_name == moduleName this_mod &&\\n (case pkg_qual of -- If we have import \\"\\" M, then we should\\n -- check that \\"\\" is \\"this\\" (which is magic)\\n -- or the name of this_mod\'s package. Yurgh!\\n -- c.f. GHC.findModule, and #9997\\n NoPkgQual -> True\\n ThisPkg uid -> uid == homeUnitId_ (hsc_dflags hsc_env)\\n OtherPkg _ -> False))\\n (addErr (TcRnSelfImport imp_mod_name))\\n\\n -- Check for a missing import list (Opt_WarnMissingImportList also\\n -- checks for T(..) items but that is done in checkDodgyImport below)\\n case imp_details of\\n Just (Exactly, _) -> return () -- Explicit import list\\n _ | generated -> return () -- Do not bleat for generated imports\\n | qual_only -> return ()\\n | otherwise -> addDiagnostic (TcRnNoExplicitImportList imp_mod_name)\\n\\n\\n mb_iface <- loadSrcInterface_maybe doc lookup_scope imp_mod_name want_boot pkg_qual\\n iface <- case mb_iface of\\n Succeeded iface -> return iface\\n Failed err -> failWithTc $\\n importDeclLoadFailure origin imp_mod_name want_boot err\\n\\n -- Compiler sanity check: if the import didn\'t say\\n -- {-# SOURCE #-} we should not get a hi-boot file\\n warnPprTrace ((want_boot == NotBoot) && (mi_boot iface == IsBoot)) \\"rnImportDecl\\" (ppr imp_mod_name) $ do\\n\\n -- Issue a user warning for a redundant {- SOURCE -} import\\n -- NB that we arrange to read all the ordinary imports before\\n -- any of the {- SOURCE -} imports.\\n --\\n -- in --make and GHCi, the compilation manager checks for this,\\n -- and indeed we shouldn\'t do it here because the existence of\\n -- the non-boot module depends on the compilation order, which\\n -- is not deterministic. The hs-boot test can show this up.\\n dflags <- getDynFlags\\n warnIf ((want_boot == IsBoot) && (mi_boot iface == NotBoot) && isOneShot (ghcMode dflags))\\n (TcRnRedundantSourceImport imp_mod_name)\\n when (mod_safe && not (safeImportsOn dflags)) $\\n addErr (TcRnSafeImportsDisabled imp_mod_name)\\n\\n let imp_mod = mi_module iface\\n qual_mod_name = fmap unLoc as_mod `orElse` imp_mod_name\\n imp_spec = ImpDeclSpec { is_mod = imp_mod, is_qual = qual_only,\\n is_dloc = locA loc, is_as = qual_mod_name,\\n is_pkg_qual = pkg_qual, is_isboot = want_boot,\\n is_level = convImportLevel import_level }\\n\\n let filter_imports = do\\n -- filter the imports according to the import declaration\\n (new_imp_details, imp_user_list, gbl_env)\\n <- filterImports hsc_env iface imp_spec imp_details\\n -- for certain error messages, we\\u2019d like to know what could be\\n -- imported here, if everything were imported\\n potential_gres <- (\\\\(_,_,x) -> x) <$> filterImports hsc_env iface imp_spec Nothing\\n return (new_imp_details, imp_user_list, gbl_env, potential_gres)\\n\\n (new_imp_details, imp_user_list, gbl_env, potential_gres) <-\\n case origin of\\n ImplicitEssentialsImport ->\\n -- The implicit GHC.Essentials import does not bring anything into scope.\\n -- See Note [Finding GHC.Essentials] in GHC.Builtin.\\n return (Nothing, ImpUserDependOnly, emptyGlobalRdrEnv, emptyGlobalRdrEnv)\\n UserWrittenImport -> filter_imports\\n ImplicitPreludeImport -> filter_imports\\n PluginImport -> filter_imports\\n\\n let is_hiding | Just (EverythingBut,_) <- imp_details = True\\n | otherwise = False\\n\\n -- should the import be safe?\\n mod_safe\' = mod_safe\\n || (not generated && safeDirectImpsReq dflags)\\n || (generated && safeImplicitImpsReq dflags)\\n\\n hsc_env <- getTopEnv\\n let home_unit = hsc_home_unit hsc_env\\n other_home_units = hsc_all_home_unit_ids hsc_env\\n\\n imported_by\\n | isDependOnlyImport imp_user_list\\n = ImportedBySystem\\n | otherwise\\n = ImportedByUser $ ImportedModsVal\\n { imv_name = is_as imp_spec\\n , imv_span = locA loc\\n , imv_is_safe = mod_safe\'\\n , imv_is_hiding = is_hiding\\n , imv_all_exports = potential_gres\\n , imv_qualified = qual_only\\n , imv_is_level = convImportLevel import_level\\n }\\n imports = calculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by\\n\\n -- Complain if we import a deprecated module\\n case fromIfaceWarnings (mi_warns iface) of\\n WarnAll txt -> addDiagnostic (TcRnDeprecatedModule imp_mod_name txt)\\n _ -> return ()\\n\\n let new_imp_decl = ImportDecl\\n { ideclExt = ideclExt decl\\n , ideclName = ideclName decl\\n , ideclPkgQual = pkg_qual\\n , ideclSource = ideclSource decl\\n , ideclSafe = mod_safe\'\\n , ideclQualified = ideclQualified decl\\n , ideclAs = ideclAs decl\\n , ideclImportList = new_imp_details\\n , ideclLevelSpec = ideclLevelSpec decl\\n }\\n\\n return (L loc new_imp_decl, ImpUserSpec imp_spec imp_user_list, gbl_env, imports)\\n\\n-- | The error message to emit when we failed to load an interface.\\nimportDeclLoadFailure :: ImportDeclOrigin -> ModuleName -> IsBootInterface\\n -> MissingInterfaceError -> TcRnMessage\\nimportDeclLoadFailure ImplicitEssentialsImport _ _ err\\n = TcRnInterfaceError $ CantFindEssentials err LookingForEssentialsModule\\nimportDeclLoadFailure _ mod_name want_boot err\\n = TcRnInterfaceError $ Can\'tFindInterface err $ LookingForModule mod_name want_boot\\n\\n-- | Rename raw package imports\\nrenameRawPkgQual :: UnitEnv -> ModuleName -> RawPkgQual -> PkgQual\\nrenameRawPkgQual unit_env mn = \\\\case\\n NoRawPkgQual -> NoPkgQual\\n RawPkgQual _ fs -> renamePkgQual unit_env mn $ Just fs\\n\\n-- | Rename raw package imports\\nrenamePkgQual :: UnitEnv -> ModuleName -> Maybe FastString -> PkgQual\\nrenamePkgQual unit_env mn mb_pkg = case mb_pkg of\\n Nothing -> NoPkgQual\\n Just pkg_fs\\n | Just uid <- homeUnitId <$> ue_homeUnit unit_env\\n , pkg_fs == fsLit \\"this\\"\\n -> ThisPkg uid\\n\\n | Just (uid, _) <- find (fromMaybe False . fmap (== pkg_fs) . snd) home_names\\n -> ThisPkg uid\\n\\n | Just uid <- resolvePackageImport unit_state mn (PackageName pkg_fs)\\n -> OtherPkg uid\\n\\n | otherwise\\n -> OtherPkg (UnitId pkg_fs)\\n -- not really correct as pkg_fs is unlikely to be a valid unit-id but\\n -- we will report the failure later...\\n where\\n home_names =\\n [ (uid, mkFastString <$> thisPackageName (homeUnitEnv_dflags (ue_findHomeUnitEnv uid unit_env)))\\n | uid <- S.toList hpt_deps\\n ]\\n\\n unit_state = ue_homeUnitState unit_env\\n\\n hpt_deps :: S.Set UnitId\\n hpt_deps = homeUnitDepends unit_state\\n\\n\\n-- | Calculate the \'ImportAvails\' induced by an import of a particular\\n-- interface, but without \'imp_mods\'.\\ncalculateAvails :: HomeUnit\\n -> S.Set UnitId\\n -> ModIface\\n -> IsSafeImport\\n -> IsBootInterface\\n -> ImportedBy\\n -> ImportAvails\\ncalculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by =\\n let imp_mod = mi_module iface\\n imp_sem_mod= mi_semantic_module iface\\n orph_iface = mi_orphan iface\\n has_finsts = mi_finsts iface\\n deps = mi_deps iface\\n trust = getSafeMode $ mi_trust iface\\n trust_pkg = mi_trust_pkg iface\\n is_sig = mi_hsc_src iface == HsigFile\\n\\n -- If the module exports anything defined in this module, just\\n -- ignore it. Reason: otherwise it looks as if there are two\\n -- local definition sites for the thing, and an error gets\\n -- reported. Easiest thing is just to filter them out up\\n -- front. This situation only arises if a module imports\\n -- itself, or another module that imported it. (Necessarily,\\n -- this involves a loop.)\\n --\\n -- We do this *after* filterImports, so that if you say\\n -- module A where\\n -- import B( AType )\\n -- type AType = ...\\n --\\n -- module B( AType ) where\\n -- import {-# SOURCE #-} A( AType )\\n --\\n -- then you won\'t get a \'B does not export AType\' message.\\n\\n\\n -- Compute new transitive dependencies\\n --\\n -- \'dep_orphs\' and \'dep_finsts\' do NOT include the imported module\\n -- itself, but we DO need to include this module in \'imp_orphs\' and\\n -- \'imp_finsts\' if it defines an orphan or instance family; thus the\\n -- orph_iface/has_iface tests.\\n\\n deporphs = dep_orphs deps\\n depfinsts = dep_finsts deps\\n\\n orphans | orph_iface = assertPpr (not (imp_sem_mod `elem` deporphs)) (ppr imp_sem_mod <+> ppr deporphs) $\\n imp_sem_mod : deporphs\\n | otherwise = deporphs\\n\\n finsts | has_finsts = assertPpr (not (imp_sem_mod `elem` depfinsts)) (ppr imp_sem_mod <+> ppr depfinsts) $\\n imp_sem_mod : depfinsts\\n | otherwise = depfinsts\\n\\n -- Trusted packages are a lot like orphans.\\n trusted_pkgs | mod_safe\' = dep_trusted_pkgs deps\\n | otherwise = S.empty\\n\\n\\n pkg = moduleUnit (mi_module iface)\\n ipkg = toUnitId pkg\\n\\n -- Does this import mean we now require our own pkg\\n -- to be trusted? See Note [Trust Own Package]\\n ptrust = trust == Sf_Trustworthy || trust_pkg\\n pkg_trust_req\\n | isHomeUnit home_unit pkg = ptrust\\n | otherwise = False\\n\\n dependent_pkgs = if toUnitId pkg `S.member` other_home_units\\n then S.empty\\n else S.singleton (lvl, ipkg)\\n\\n lvl = case imported_by of\\n ImportedByUser imv -> imv_is_level imv\\n ImportedBySystem -> NormalLevel\\n\\n\\n direct_mods = if toUnitId pkg `S.member` other_home_units\\n then mkPlusModDeps (moduleUnitId imp_mod) lvl (GWIB (moduleName imp_mod) want_boot)\\n else emptyInstalledModuleEnv\\n\\n dep_boot_mods_map = mkModDeps (dep_boot_mods deps)\\n\\n\\n boot_mods\\n -- If we are looking for a boot module, it must be HPT\\n | IsBoot <- want_boot = extendInstalledModuleEnv dep_boot_mods_map (toUnitId <$> imp_mod) (GWIB (moduleName imp_mod) IsBoot)\\n -- Now we are importing A properly, so don\'t go looking for\\n -- A.hs-boot\\n | isHomeUnit home_unit pkg = dep_boot_mods_map\\n -- There\'s no boot files to find in external imports\\n | otherwise = emptyInstalledModuleEnv\\n\\n sig_mods =\\n if is_sig\\n then moduleName imp_mod : dep_sig_mods deps\\n else dep_sig_mods deps\\n\\n\\n in ImportAvails {\\n imp_mods = Map.singleton (mi_module iface) [imported_by],\\n imp_orphs = orphans,\\n imp_finsts = finsts,\\n imp_sig_mods = sig_mods,\\n imp_direct_dep_mods = direct_mods,\\n imp_dep_direct_pkgs = dependent_pkgs,\\n imp_boot_mods = boot_mods,\\n\\n -- Add in the imported modules trusted package\\n -- requirements. ONLY do this though if we import the\\n -- module as a safe import.\\n -- See Note [Tracking Trust Transitively]\\n -- and Note [Trust Transitive Property]\\n imp_trust_pkgs = trusted_pkgs,\\n -- Do we require our own pkg to be trusted?\\n -- See Note [Trust Own Package]\\n imp_trust_own_pkg = pkg_trust_req\\n }\\n\\nmkPlusModDeps :: UnitId -> ImportLevel -> ModuleNameWithIsBoot\\n -> InstalledModuleEnv (S.Set ImportLevel, ModuleNameWithIsBoot)\\nmkPlusModDeps uid st elt = extendInstalledModuleEnv emptyInstalledModuleEnv (mkModule uid (gwib_mod elt)) (S.singleton st, elt)\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{importsFromLocalDecls}\\n* *\\n************************************************************************\\n\\nFrom the top-level declarations of this module produce\\n * the lexical environment\\n * the ImportAvails\\ncreated by its bindings.\\n\\nNote [Top-level Names in Template Haskell decl quotes]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSee also: Note [Interactively-bound Ids in GHCi] in GHC.Driver.Env\\n Note [Looking up Exact RdrNames] in GHC.Rename.Env\\n\\nConsider a Template Haskell declaration quotation like this:\\n module M where\\n f x = h [d| f = 3 |]\\nWhen renaming the declarations inside [d| ...|], we treat the\\ntop level binders specially in two ways\\n\\n1. We give them an Internal Name, not (as usual) an External one.\\n This is done by GHC.Rename.Env.newTopSrcBinder.\\n\\n2. We make them *shadow* the outer bindings.\\n See Note [GlobalRdrEnv shadowing]\\n\\n3. We find out whether we are inside a [d| ... |] by testing the TH\\n level. This is a slight hack, because the level field was really\\n meant for the type checker, and here we are not interested in the\\n fields of Brack, hence the error thunks in thRnBrack.\\n-}\\n\\nextendGlobalRdrEnvRn :: [GlobalRdrElt]\\n -> MiniFixityEnv\\n -> RnM (TcGblEnv, TcLclEnv)\\n-- Updates both the GlobalRdrEnv and the FixityEnv\\n-- We return a new TcLclEnv only because we might have to\\n-- delete some bindings from it;\\n-- see Note [Top-level Names in Template Haskell decl quotes]\\n\\nextendGlobalRdrEnvRn new_gres new_fixities\\n = checkNoErrs $ -- See Note [Fail fast on duplicate definitions]\\n do { (gbl_env, lcl_env) <- getEnvs\\n ; level <- getThLevel\\n ; isGHCi <- getIsGHCi\\n ; let rdr_env = tcg_rdr_env gbl_env\\n fix_env = tcg_fix_env gbl_env\\n th_bndrs = getLclEnvThBndrs lcl_env\\n th_lvl = thLevelIndex level\\n\\n -- Delete new_occs from global and local envs\\n -- If we are in a TemplateHaskell decl bracket,\\n -- we are going to shadow them\\n -- See Note [GlobalRdrEnv shadowing]\\n inBracket = isBrackLevel level\\n\\n lcl_env_TH = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_rdr = minusLocalRdrEnv (tcl_rdr lcl_env) new_gres_env }) lcl_env\\n -- See Note [GlobalRdrEnv shadowing]\\n\\n lcl_env2 | inBracket = lcl_env_TH\\n | otherwise = lcl_env\\n\\n -- Deal with shadowing: see Note [GlobalRdrEnv shadowing]\\n want_shadowing = isGHCi || inBracket\\n rdr_env1 | want_shadowing = shadowNames False rdr_env new_gres_env\\n | otherwise = rdr_env\\n\\n lcl_env3 = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_th_bndrs = extendNameEnvList th_bndrs\\n [ ( n, (TopLevel, th_lvl) )\\n | n <- new_names ] }) lcl_env2\\n\\n ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres\\n\\n ; let fix_env\' = foldl\' extend_fix_env fix_env new_gres\\n gbl_env\' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env\' }\\n\\n ; traceRn \\"extendGlobalRdrEnvRn 2\\" (pprGlobalRdrEnv True rdr_env2)\\n ; return (gbl_env\', lcl_env3) }\\n where\\n new_names = map greName new_gres\\n new_gres_env = mkGlobalRdrEnv new_gres\\n\\n -- If there is a fixity decl for the gre, add it to the fixity env\\n extend_fix_env fix_env gre\\n | Just (L _ fi) <- lookupMiniFixityEnv new_fixities name\\n = extendNameEnv fix_env name (FixItem occ fi)\\n | otherwise\\n = fix_env\\n where\\n name = greName gre\\n occ = greOccName gre\\n\\n add_gre :: GlobalRdrEnv -> GlobalRdrElt -> RnM GlobalRdrEnv\\n -- Extend the GlobalRdrEnv with a LocalDef GRE\\n -- If there is already a LocalDef GRE with the same OccName,\\n -- report an error and discard the new GRE\\n -- This establishes INVARIANT 1 of GlobalRdrEnvs\\n add_gre env gre\\n | not (null dups) -- Same OccName defined twice\\n = do { addDupDeclErr (gre :| dups); return env }\\n\\n | otherwise\\n = return (extendGlobalRdrEnv env gre)\\n where\\n -- See Note [Reporting duplicate local declarations]\\n dups = filter isBadDupGRE\\n $ lookupGRE env (LookupOccName (greOccName gre) (RelevantGREsFOS WantBoth))\\n isBadDupGRE old_gre = isLocalGRE old_gre && greClashesWith gre old_gre\\n\\n{- Note [Fail fast on duplicate definitions]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIf there are duplicate bindings for the same thing, we want to fail\\nfast. Having two bindings for the same thing can cause follow-on errors.\\nExample (test T9975a):\\n data Test = Test { x :: Int }\\n pattern Test wat = Test { x = wat }\\nThis defines \'Test\' twice. The second defn has no field-names; and then\\nwe get an error from Test { x=wat }, saying \\"Test has no field \'x\'\\".\\n\\nEasiest thing is to bale out fast on duplicate definitions, which\\nwe do via `checkNoErrs` on `extendGlobalRdrEnvRn`.\\n\\nNote [Reporting duplicate local declarations]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn general, a single module may not define the same OccName multiple times. This\\nis checked in extendGlobalRdrEnvRn: when adding a new locally-defined GRE to the\\nGlobalRdrEnv we report an error if there are already duplicates in the\\nenvironment. This establishes INVARIANT 1 (see comments on GlobalRdrEnv in\\nGHC.Types.Name.Reader), which says that for a given OccName, all the\\nGlobalRdrElts to which it maps must have distinct \'greName\'s.\\n\\nFor example, the following will be rejected:\\n\\n f x = x\\n g x = x\\n f x = x -- Duplicate!\\n\\nUsers are allowed to introduce new GREs with the same OccName as an imported GRE,\\nas disambiguation is possible through the module system, e.g.:\\n\\n module M where\\n import N (f)\\n f x = x\\n g x = M.f x + N.f x\\n\\nIf both GREs are local, the general rule is that two GREs clash if they have\\nthe same OccName, i.e. they share a textual name and live in the same namespace.\\nHowever, there are additional clashes due to record fields:\\n\\n - a new variable clashes with previously defined record fields\\n which define field selectors,\\n\\n - a new record field shadows:\\n\\n - previously defined variables, if it defines a field selector,\\n - previously defined record fields, unless it is a duplicate record field.\\n\\nThis logic is implemented in the function \'GHC.Types.Name.Reader.greClashesWith\'.\\n\\nSee also Note [Skipping ambiguity errors at use sites of local declarations] in\\nGHC.Rename.Utils.\\n-}\\n\\n\\n{- *********************************************************************\\n* *\\n getLocalDeclBindersd@ returns the names for an HsDecl\\n It\'s used for source code.\\n\\n *** See Note [The Naming story] in GHC.Hs.Decls ****\\n* *\\n********************************************************************* -}\\n\\ngetLocalNonValBinders :: MiniFixityEnv -> HsGroup GhcPs\\n -> RnM ((TcGblEnv, TcLclEnv), NameSet)\\n-- Get all the top-level binders bound the group *except*\\n-- for value bindings, which are treated separately\\n-- Specifically we return AvailInfo for\\n-- * type decls (incl constructors and record selectors)\\n-- * class decls (including class ops)\\n-- * associated types\\n-- * foreign imports\\n-- * value signatures (in hs-boot files only)\\n\\ngetLocalNonValBinders fixity_env\\n (HsGroup { hs_valds = binds,\\n hs_tyclds = tycl_decls,\\n hs_fords = foreign_decls })\\n = do { -- Process all type/class decls *except* family instances\\n ; let inst_decls = tycl_decls >>= group_instds\\n ; dup_fields_ok <- xopt_DuplicateRecordFields <$> getDynFlags\\n ; has_sel <- xopt_FieldSelectors <$> getDynFlags\\n ; tc_gres\\n <- concatMapM\\n (new_tc dup_fields_ok has_sel)\\n (tyClGroupTyClDecls tycl_decls)\\n ; traceRn \\"getLocalNonValBinders 1\\" (ppr tc_gres)\\n ; envs <- extendGlobalRdrEnvRn tc_gres fixity_env\\n ; restoreEnvs envs $ do {\\n -- Bring these things into scope first\\n -- See Note [Looking up family names in family instances]\\n\\n -- Process all family instances\\n -- to bring new data constructors into scope\\n ; nti_gress <- mapM (new_assoc dup_fields_ok has_sel) inst_decls\\n\\n -- Finish off with value binders:\\n -- foreign decls and pattern synonyms for an ordinary module\\n -- type sigs in case of a hs-boot file only\\n ; is_boot <- tcIsHsBootOrSig\\n ; let val_bndrs\\n | is_boot = case binds of\\n ValBinds _ val_binds ->\\n -- In a hs-boot file, the value binders come from the\\n -- *signatures*, and there should be no foreign binders\\n [ L (l2l decl_loc) (unLoc n)\\n | L decl_loc (TypeSig _ _ ns _) <- (val_sigs val_binds), n <- ns]\\n _ -> panic \\"Non-ValBinds in hs-boot group\\"\\n | otherwise = for_hs_bndrs\\n ; val_gres <- mapM new_simple val_bndrs\\n\\n ; let avails = concat nti_gress ++ val_gres\\n new_bndrs = gresToNameSet avails `unionNameSet`\\n gresToNameSet tc_gres\\n ; traceRn \\"getLocalNonValBinders 2\\" (ppr avails)\\n ; envs <- extendGlobalRdrEnvRn avails fixity_env\\n ; return (envs, new_bndrs) } }\\n where\\n for_hs_bndrs :: [LocatedN RdrName]\\n for_hs_bndrs = hsForeignDeclsBinders foreign_decls\\n\\n -- the SrcSpan attached to the input should be the span of the\\n -- declaration, not just the name\\n new_simple :: LocatedN RdrName -> RnM GlobalRdrElt\\n new_simple rdr_name = do { nm <- newTopSrcBinder rdr_name\\n ; return (mkLocalVanillaGRE NoParent nm) }\\n\\n new_tc :: DuplicateRecordFields -> FieldSelectors -> LTyClDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_tc dup_fields_ok has_sel tc_decl -- NOT for type/data instances\\n = do { let TyDeclBinders (main_bndr, tc_flav) at_bndrs sig_bndrs\\n (LConsWithFields cons_with_flds flds) = hsLTyClDeclBinders tc_decl\\n ; tycon_name <- newTopSrcBinder $ la2la main_bndr\\n ; at_names <- mapM (newTopSrcBinder . la2la . fst) at_bndrs\\n ; sig_names <- mapM (newTopSrcBinder . la2la) sig_bndrs\\n ; con_names_with_flds <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst con_names_with_flds) flds\\n ; mapM_ (add_dup_fld_errs flds\') con_names_with_flds\\n ; let tc_gre = mkLocalTyConGRE (fmap (const tycon_name) tc_flav) tycon_name\\n fld_env = mk_fld_env con_names_with_flds flds\'\\n at_gres = zipWith (\\\\ (_, at_flav) at_nm -> mkLocalTyConGRE (fmap (const tycon_name) at_flav) at_nm)\\n at_bndrs at_names\\n sig_gres = map (mkLocalVanillaGRE (ParentIs tycon_name)) sig_names\\n con_gres = map (mkLocalConLikeGRE (ParentIs tycon_name)) fld_env\\n fld_gres = mkLocalFieldGREs (ParentIs tycon_name) fld_env\\n sub_gres = at_gres ++ sig_gres ++ con_gres ++ fld_gres\\n ; traceRn \\"getLocalNonValBinders new_tc\\" $\\n vcat [ text \\"tycon:\\" <+> ppr tycon_name\\n , text \\"tc_gre:\\" <+> ppr tc_gre\\n , text \\"sub_gres:\\" <+> ppr sub_gres ]\\n ; return $ tc_gre : sub_gres }\\n\\n -- Calculate the record field information, which feeds into the GlobalRdrElts\\n -- for DataCons and their fields. It\'s convenient to do this here where\\n -- we are working with a single datatype definition.\\n --\\n -- The information we needed was all set up for us:\\n -- see Note [Collecting record fields in data declarations] in GHC.Hs.Utils.\\n mk_fld_env :: [(Name, Either VisArity [Located Int])] -> IntMap FieldLabel\\n -> [(ConLikeName, ConInfo)]\\n mk_fld_env names flds =\\n [ (DataConName con, ConInfo (ConIsData (map fst names)) fld_info)\\n | (con, con_fl_indxs) <- names\\n , let fld_info = case fmap (map ((flds IntMap.!) . unLoc)) con_fl_indxs of\\n Left 0 -> ConIsNullary\\n Left arity -> ConHasPositionalArgs arity\\n Right [] -> ConIsNullary\\n Right (fld:flds) -> ConHasRecordFields $ fld NE.:| flds ]\\n\\n new_assoc :: DuplicateRecordFields -> FieldSelectors -> LInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_assoc _ _ (L _ (TyFamInstD {})) = return []\\n -- type instances don\'t bind new names\\n\\n new_assoc dup_fields_ok has_sel (L _ (DataFamInstD _ d))\\n = new_di dup_fields_ok has_sel Nothing d\\n new_assoc dup_fields_ok has_sel\\n (L _ (ClsInstD _ (ClsInstDecl { cid_poly_ty = inst_ty\\n , cid_decls = decls })))\\n = do -- First, attempt to grab the name of the class from the instance.\\n -- This step could fail if the instance is not headed by a class,\\n -- such as in the following examples:\\n --\\n -- (1) The class is headed by a bang pattern, such as in\\n -- `instance !Show Int` (#3811c)\\n -- (2) The class is headed by a type variable, such as in\\n -- `instance c` (#16385)\\n --\\n -- If looking up the class name fails, then mb_cls_gre will\\n -- be Nothing.\\n mb_cls_gre <- runMaybeT $ do\\n -- See (1) above\\n L loc cls_rdr <- MaybeT $ pure $ getLHsInstDeclClass_maybe inst_ty\\n -- See (2) above\\n MaybeT $ setSrcSpan (locA loc) $ lookupGlobalOccRn_maybe SameNameSpace cls_rdr\\n -- Assuming the previous step succeeded, process any associated data\\n -- family instances. If the previous step failed, bail out.\\n case mb_cls_gre of\\n Nothing\\n -> pure []\\n Just cls_gre\\n -> let cls_nm = greName cls_gre\\n in concatMapM (new_di dup_fields_ok has_sel (Just cls_nm) . unLoc) (data_fam_insts decls)\\n\\n data_fam_insts decls = concatMap get decls\\n where\\n get (L l (InstD _ (DataFamInstD { dfid_inst = d}))) = [L l d]\\n get _ = []\\n\\n new_di :: DuplicateRecordFields -> FieldSelectors\\n -> Maybe Name -- class name\\n -> DataFamInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_di dup_fields_ok has_sel mb_cls dfid@(DataFamInstDecl { dfid_eqn = ti_decl })\\n = do { main_name <- unLoc <$> lookupFamInstName mb_cls (feqn_tycon ti_decl)\\n ; let LConsWithFields cons_with_flds flds = hsDataFamInstBinders dfid\\n ; sub_names <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst sub_names) flds\\n ; mapM_ (add_dup_fld_errs flds\') sub_names\\n ; let fld_env = mk_fld_env sub_names flds\'\\n con_gres = map (mkLocalConLikeGRE (ParentIs main_name)) fld_env\\n field_gres = mkLocalFieldGREs (ParentIs main_name) fld_env\\n -- NB: the data family name is not bound here,\\n -- so we don\'t return a GlobalRdrElt for it here!\\n ; return $ con_gres ++ field_gres }\\n\\n -- Add errors if a constructor has a duplicate record field.\\n add_dup_fld_errs :: IntMap FieldLabel\\n -> (Name, Either VisArity [Located Int])\\n -> IOEnv (Env TcGblEnv TcLclEnv) ()\\n add_dup_fld_errs all_flds (con, con_flds_or_arity)\\n | Right con_flds <- con_flds_or_arity\\n , let (_, dups) = removeDups (comparing unLoc) con_flds\\n = for_ dups $ \\\\ dup_flds ->\\n -- Report the error at the location of the second occurrence\\n -- of the duplicate field.\\n let loc =\\n case dup_flds of\\n _ :| ( L loc _ : _) -> loc\\n L loc _ :| _ -> loc\\n dup_rdrs = fmap (nameRdrName . flSelector . (all_flds IntMap.!) . unLoc) dup_flds\\n in addErrAt loc $ TcRnDuplicateFieldName (RecordFieldDecl con) dup_rdrs\\n | otherwise\\n = return ()\\n\\nnewRecordFieldLabel :: DuplicateRecordFields -> FieldSelectors -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel\\nnewRecordFieldLabel _ _ [] _ = error \\"newRecordFieldLabel: datatype has no constructors!\\"\\nnewRecordFieldLabel dup_fields_ok has_sel (dc:_) (L loc (FieldOcc _ (L _ fld)))\\n = do { selName <- newTopSrcBinder $ L (l2l loc) $ field\\n ; return $ FieldLabel { flHasDuplicateRecordFields = dup_fields_ok\\n , flHasFieldSelector = has_sel\\n , flSelector = selName } }\\n where\\n fld_occ = rdrNameOcc fld\\n dc_fs = occNameFS $ nameOccName dc\\n field\\n -- Use an Exact RdrName as-is, to preserve the bindings\\n -- of an already renamer-resolved field and its use\\n -- sites. This is needed to correctly support record\\n -- selectors in Template Haskell. See Note [Binders in\\n -- Template Haskell] in \\"GHC.ThToHs\\" and Note [Looking up\\n -- Exact RdrNames] in \\"GHC.Rename.Env\\".\\n | isExact fld\\n = assertPpr (fieldOcc_maybe fld_occ == Just dc_fs)\\n (vcat [ text \\"newRecordFieldLabel: incorrect namespace for exact Name\\" <+> quotes (ppr fld)\\n , text \\"expected namespace:\\" <+> pprNameSpace (fieldName dc_fs)\\n , text \\" actual namespace:\\" <+> pprNameSpace (occNameSpace fld_occ) ])\\n fld\\n\\n -- Field names produced by the parser are namespaced with VarName.\\n -- Here we namespace them according to the first constructor.\\n -- See Note [Record field namespacing] in GHC.Types.Name.Occurrence.\\n | otherwise\\n = mkRdrUnqual $ varToRecFieldOcc dc_fs fld_occ\\n\\n{-\\nNote [Looking up family names in family instances]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider\\n\\n module M where\\n type family T a :: *\\n type instance M.T Int = Bool\\n\\nWe might think that we can simply use \'lookupOccRn\' when processing the type\\ninstance to look up \'M.T\'. Alas, we can\'t! The type family declaration is in\\nthe *same* HsGroup as the type instance declaration. Hence, as we are\\ncurrently collecting the binders declared in that HsGroup, these binders will\\nnot have been added to the global environment yet.\\n\\nSolution is simple: process the type family declarations first, extend\\nthe environment, and then process the type instances.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Filtering imports}\\n* *\\n************************************************************************\\n\\n@filterImports@ takes the @ExportEnv@ telling what the imported module makes\\navailable, and filters it through the import spec (if any).\\n\\nNote [Dealing with imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nFor import M( ies ), we take each AvailInfo from the mi_exports of M, and make\\n\\n imp_occ_env :: OccEnv (NameEnv ImpOccItem)\\n\\nThis map contains one entry for each OccName that M exports, mapping each OccName\\nto the following information:\\n\\n 1. the GlobalRdrElt corresponding to the OccName,\\n 2. whether this GlobalRdrElt was the parent in the AvailInfo we found\\n the OccName in.\\n 3. the GlobalRdrElts that were bundled together in the AvailInfo we found\\n this OccName in (not including the parent),\\n\\nWe need (2) and (3) during the construction of the OccEnv because of associated\\ntypes and bundled pattern synonyms, respectively.\\n(3) is explained in Note [Importing PatternSynonyms].\\n\\nTo explain (2), consider for example:\\n\\n module M where\\n class C a where { data T a }\\n instance C Int where { data T Int = T1 | T2 }\\n instance C Bool where { data T Int = T3 }\\n\\nHere, M\'s exports avails are (recalling the AvailTC invariant from GHC.Types.Avail)\\n\\n C(C,T), T(T,T1,T2,T3)\\n\\nNotice that T appears *twice*, once as a child and once as a parent. From\\nthese two exports, respectively, during construction of the imp_occ_env, we begin\\nby associating the following two elements with the key T:\\n\\n T -> ImpOccItem { imp_item = gre1, imp_bundled = [C,T] , imp_is_parent = False }\\n T -> ImpOccItem { imp_item = gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nwhere `gre1`, `gre2` are two GlobalRdrElts with greName T.\\nWe combine these (in function \'combine\' in \'mkImportOccEnv\') by discarding the\\nnon-parent item, thusly:\\n\\n T -> IE_ITem { imp_item = gre1 `plusGRE` gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nNote the `plusGRE`: this ensures we don\'t drop parent information;\\nsee Note [Preserve parent information when combining import OccEnvs].\\n\\nSo the overall imp_occ_env is:\\n\\n C -> ImpOccItem { imp_item = C, imp_bundled = [T ], imp_is_parent = True }\\n T -> ImpOccItem { imp_item = T , imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n T1 -> ImpOccItem { imp_item = T1, imp_bundled = [T1,T2,T3], imp_is_parent = False }\\n -- similarly for T2, T3\\n\\nNote that the imp_occ_env will have entries for data constructors too,\\nalthough we never look up data constructors.\\n\\nNote [Importing PatternSynonyms]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nAs described in Note [Dealing with imports], associated types can lead to the\\nsame Name appearing twice, both as a child and once as a parent, when\\nconstructing the imp_occ_env. The same thing can happen with pattern synonyms\\nif they are exported bundled with a type.\\n\\nA simplified example, based on #11959:\\n\\n {-# LANGUAGE PatternSynonyms #-}\\n module M (T(P), pattern P) where -- Duplicate export warning, but allowed\\n data T = MkT\\n pattern P = MkT\\n\\nHere we have T(P) and P in export_avails, and respectively construct both\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n P -> ImpOccItem { imp_item = P, imp_bundled = [] , imp_is_parent = False }\\n\\nWe combine these by dropping the one with no siblings, leaving us with:\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n\\nThat is, we simply discard the non-bundled Avail.\\n\\nNote [Importing DuplicateRecordFields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn filterImports, another complicating factor is DuplicateRecordFields.\\nSuppose we have:\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (S(foo), T(foo)) where\\n data S = MkS { foo :: Int }\\n data T = MkT { foo :: Int }\\n\\n module N where\\n import M (foo) -- this is allowed (A)\\n import M (S(foo)) -- this is allowed (B)\\n\\nHere M exports \'foo\' at two different OccNames, with different namespaces for\\nthe two construtors MkS and MkT. Then, when we look up \'foo\' in lookup_names\\nfor case (A), we have a variable foo but must look in all the record field\\nnamespaces to find the two fields (and hence two different Avails).\\nWhereas in case (B) we reach the lookup_ie case for IEThingWith,\\nwhich looks up \'S\' and then finds the unique \'foo\' amongst its children.\\n\\nSee T16745 for a test of this.\\n\\nNote [Preserve parent information when combining import OccEnvs]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen discarding one ImpOccItem in favour of another, as described in\\nNote [Dealing with imports], we must make sure to combine the GREs so that\\nwe don\'t lose information.\\n\\nConsider for example #24084:\\n\\n module M1 where { class C a where { type T a } }\\n module M2 ( module M1 ) where { import M1 }\\n module M3 where { import M2 ( C, T ); instance C () where T () = () }\\n\\nWhen processing the import list of `M3`, we will have two `Avail`s attached\\nto `T`, namely `C(C, T)` and `T(T)`. We combine them in the `combine` function\\nof `mkImportOccEnv`; as described in Note [Dealing with imports] we discard\\n`C(C, T)` in favour of `T(T)`. However, in doing so, we **must not**\\ndiscard the information want that `C` is the parent of `T`. Indeed,\\nlosing track of this information can cause errors when importing,\\nas we could get an error of the form\\n\\n \\u2018T\\u2019 is not a (visible) associated type of class \\u2018C\\u2019\\n\\nThis explains why we use `plusGRE` when combining the two ImpOccItems, even\\nthough we are discarding one in favour of the other.\\n-}\\n\\n-- | All the \'GlobalRdrElt\'s associated with an \'AvailInfo\'.\\ngresFromAvail :: HasDebugCallStack\\n => HscEnv -> Maybe ImportSpec -> AvailInfo -> [GlobalRdrElt]\\ngresFromAvail hsc_env prov avail =\\n [ mk_gre nm info\\n | nm <- availNames avail\\n , let info = lookupGREInfo hsc_env nm ]\\n where\\n\\n mk_gre n info\\n = case prov of\\n -- Nothing => bound locally\\n -- Just is => imported from \'is\'\\n Nothing -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = True, gre_imp = emptyBag\\n , gre_info = info }\\n Just is -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = False, gre_imp = unitBag is\\n , gre_info = info }\\n\\n-- | All the \'GlobalRdrElt\'s associated with a collection of \'AvailInfo\'s.\\ngresFromAvails :: HscEnv -> Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]\\ngresFromAvails hsc_env prov = concatMap (gresFromAvail hsc_env prov)\\n\\nimportsFromIface :: HscEnv -> ModIface -> ImpDeclSpec -> Maybe NameSet -> GlobalRdrEnv\\nimportsFromIface hsc_env iface decl_spec hidden = mkGlobalRdrEnv $ case hidden of\\n Nothing -> all_gres\\n Just hidden_names -> filter (not . (`elemNameSet` hidden_names) . greName) all_gres\\n where\\n all_gres = gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\nrnNamespaceSpecifier :: NamespaceSpecifier GhcPs -> NamespaceSpecifier GhcRn\\nrnNamespaceSpecifier (NoNamespaceSpecifier _) = NoNamespaceSpecifier noExtField\\nrnNamespaceSpecifier (TypeNamespaceSpecifier x) = TypeNamespaceSpecifier x\\nrnNamespaceSpecifier (DataNamespaceSpecifier x) = DataNamespaceSpecifier x\\n\\nfilterImports\\n :: HasDebugCallStack\\n => HscEnv\\n -> ModIface\\n -> ImpDeclSpec\\n -- ^ Import spec\\n -> Maybe (ImportListInterpretation, [LIE GhcPs])\\n -- ^ Whether this is a \\"hiding\\" import list\\n -> RnM (Maybe (ImportListInterpretation, [LIE GhcRn]), -- Import spec w/ Names\\n ImpUserList, -- same, but designed for storage in interfaces\\n GlobalRdrEnv) -- Same again, but in GRE form\\nfilterImports hsc_env iface decl_spec Nothing\\n = return (Nothing, ImpUserAll, importsFromIface hsc_env iface decl_spec Nothing)\\nfilterImports hsc_env iface decl_spec (Just (want_hiding, import_items))\\n = do -- check for errors, convert RdrNames to Names\\n items1 <- mapM lookup_lie import_items\\n\\n let items2 :: [(LIE GhcRn, [GlobalRdrElt])]\\n items2 = concat items1\\n -- NB we may have duplicates, and several items\\n -- for the same parent; e.g N(x) and N(y)\\n\\n (gres, imp_user_list) = case want_hiding of\\n Exactly ->\\n let gres = concatMap (gresFromIE decl_spec) items2\\n gre_env = mkGlobalRdrEnv gres\\n implicit_parents = mkNameSet $ mapMaybe parentOfImplicitlyImportedGRE gres\\n in (gre_env, ImpUserExplicit (gresToAvailInfo $ globalRdrEnvElts $ gre_env) implicit_parents)\\n EverythingBut ->\\n let hidden_names = mkNameSet $ concatMap (map greName . snd) items2\\n in (importsFromIface hsc_env iface decl_spec (Just hidden_names), ImpUserEverythingBut hidden_names)\\n\\n return (Just (want_hiding, map fst items2), imp_user_list, gres)\\n where\\n import_mod = mi_module iface\\n all_avails = mi_exports iface\\n imp_occ_env = mkImportOccEnv hsc_env decl_spec all_avails\\n\\n -- Look up a parent (type constructor, class or data constructor)\\n -- in an import.\\n lookup_parent :: IE GhcPs -> RdrName -> IELookupM ImpOccItem\\n lookup_parent ie rdr =\\n assertPpr (not $ isVarNameSpace ns)\\n (vcat [ text \\"filterImports lookup_parent: unexpected variable\\"\\n , text \\"rdr:\\" <+> ppr rdr\\n , text \\"namespace:\\" <+> pprNameSpace ns ]) $\\n do { xs <- lookup_names ie rdr\\n ; case xs of\\n cax :| [] -> return cax\\n _ -> pprPanic \\"filter_imports lookup_parent ambiguous\\" $\\n vcat [ text \\"rdr:\\" <+> ppr rdr\\n , text \\"lookups:\\" <+> ppr (fmap imp_item xs) ] }\\n -- Looking up non-variables is always unambiguous,\\n -- as there can be at most one corresponding item\\n -- in the imp_occ_env.\\n -- See item (1) of Note [Exporting duplicate declarations]\\n -- in GHC.Tc.Gen.Export.\\n where\\n occ = rdrNameOcc rdr\\n ns = occNameSpace occ\\n\\n -- Look up a RdrName used in an import, returning multiple values if there\\n -- are several fields with the same name exposed by the module\\n lookup_names :: IE GhcPs -> RdrName -> IELookupM (NonEmpty ImpOccItem)\\n lookup_names ie rdr\\n | isQual rdr\\n = failLookupWith (QualImportError rdr)\\n | otherwise\\n = case lookups of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n item:items -> return $ item :| items\\n where\\n lookups = concatMap nonDetNameEnvElts\\n $ lookupImpOccEnv (RelevantGREsFOS WantNormal) imp_occ_env (rdrNameOcc rdr)\\n\\n lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, [GlobalRdrElt])]\\n lookup_lie (L loc ieRdr)\\n = setSrcSpanA loc $\\n do (stuff, warns) <- run_lookup ([],[]) (lookup_ie ieRdr)\\n mapM_ (addTcRnDiagnostic <=< warning_msg) warns\\n return [ (L loc ie, gres) | (ie,gres) <- stuff ]\\n where\\n\\n -- Warn when importing T(..) and no children are brought in scope\\n warning_msg (DodgyImport reason) =\\n pure (TcRnDodgyImports reason)\\n warning_msg MissingImportList =\\n pure (TcRnMissingImportList ieRdr)\\n warning_msg (BadImportW ie sub) = do\\n -- \'BadImportW\' is only constructed below in \'bad_import_w\', in\\n -- the \'EverythingBut\' case, so here we assume a \'hiding\' clause.\\n (reason :| _) <- badImportItemErr iface decl_spec ie sub all_avails\\n pure (TcRnDodgyImports (DodgyImportsHiding reason))\\n warning_msg (DeprecatedExport n w) =\\n pure $ TcRnPragmaWarning\\n PragmaWarningExport\\n { pwarn_occname = occName n\\n , pwarn_impmod = moduleName import_mod }\\n w\\n\\n run_lookup :: a -> IELookupM a -> TcRn a\\n run_lookup def m = case m of\\n Failed err -> do\\n msgs <- lookup_err_msgs err\\n forM_ msgs $ \\\\msg -> addErr (TcRnImportLookup msg)\\n return def\\n Succeeded a -> return a\\n\\n lookup_err_msgs err = case err of\\n BadImport ie sub -> badImportItemErr iface decl_spec ie sub all_avails\\n IllegalImport -> pure $ NE.singleton ImportLookupIllegal\\n QualImportError rdr -> pure $ NE.singleton (ImportLookupQualified rdr)\\n\\n -- For each import item, we convert its RdrNames to Names,\\n -- and at the same time compute all the GlobalRdrElt corresponding\\n -- to what is actually imported by this item.\\n -- Returns Nothing on error.\\n --\\n -- Returns a list because, with DuplicateRecordFields, a naked\\n -- import/export of a record field can correspond to multiple\\n -- different GlobalRdrElts. See Note [Importing DuplicateRecordFields].\\n lookup_ie :: IE GhcPs\\n -> IELookupM ([(IE GhcRn, [GlobalRdrElt])], [IELookupWarning])\\n lookup_ie ie = handle_bad_import $\\n case ie of\\n IEVar _ (L l n) _ -> do\\n -- See Note [Importing DuplicateRecordFields]\\n xs <- lookup_names ie (ieWrappedName n)\\n let gres = map imp_item $ NE.toList xs\\n export_depr_warns\\n | want_hiding == Exactly\\n = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ( [ (IEVar Nothing (L l (replaceWrappedName n name)) noDocstring, [gre])\\n | gre <- gres\\n , let name = greName gre ]\\n , export_depr_warns )\\n\\n IEThingAll x ns_spec (L l tc) _ -> do\\n ImpOccItem { imp_item = gre\\n , imp_bundled = bundled_gres\\n , imp_is_parent = is_par\\n }\\n <- lookup_parent ie $ ieWrappedName tc\\n let name = greName gre\\n\\n child_gres :: [GlobalRdrElt]\\n child_gres\\n | is_par = filterByNamespaceSpecifierGREs ns_spec bundled_gres\\n | otherwise = []\\n\\n imp_list_warn\\n\\n | null child_gres\\n -- e.g. f(..) or T(..) where T is a type synonym\\n = [DodgyImport (DodgyImportsEmptyParent ie ns_spec gre)]\\n\\n -- e.g. import M( T(..) )\\n | not (is_qual decl_spec)\\n = [MissingImportList]\\n\\n | otherwise\\n = []\\n\\n renamed_ie = IEThingAll (x { ieta_warning = Nothing })\\n (rnNamespaceSpecifier ns_spec)\\n (L l (replaceWrappedName tc name))\\n noDocstring\\n export_depr_warn\\n | want_hiding == Exactly\\n = maybeToList $ mk_depr_export_warning gre\\n -- We don\'t want to warn about the children as they\\n -- are not explicitly mentioned; the warning will\\n -- be emitted later on if they are used\\n | otherwise = []\\n\\n return ( [(renamed_ie, gre:child_gres)]\\n , imp_list_warn ++ export_depr_warn)\\n\\n\\n IEThingAbs _ (L l tc\') _\\n | want_hiding == EverythingBut -- hiding ( C )\\n -- Here the \'C\' can be a data constructor\\n -- *or* a type/class, or even both\\n -> let tc = ieWrappedName tc\'\\n tc_name = lookup_parent ie tc\\n dc_name = lookup_parent ie (setRdrNameSpace tc srcDataName)\\n in\\n case catIELookupM [ tc_name, dc_name ] of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n names -> return ( [mkIEThingAbs tc\' l (imp_item name) | name <- names], [])\\n | otherwise\\n -> do ImpOccItem { imp_item = gre } <- lookup_parent ie (ieWrappedName tc\')\\n return ( [mkIEThingAbs tc\' l gre]\\n , maybeToList $ mk_depr_export_warning gre)\\n\\n IEThingWith (deprecation, ann) ltc@(L l rdr_tc) wc rdr_ns _ -> do\\n ImpOccItem { imp_item = gre, imp_bundled = subnames }\\n <- lookup_parent (IEThingAbs Nothing ltc noDocstring) (ieWrappedName rdr_tc)\\n let name = greName gre\\n\\n -- Look up the children in the sub-names of the parent\\n -- See Note [Importing DuplicateRecordFields]\\n let (children_errs, childnames) = lookupChildren subnames rdr_ns\\n\\n bad_import_warns <-\\n if null children_errs then return [] else\\n let items = map lce_wrapped_name children_errs\\n ie = IEThingWith (deprecation, ann) ltc wc items noDocstring\\n -- We are trying to import T( a,b,c,d ), and failed\\n -- to find \'b\' and \'d\'. So we make up an import item\\n -- to report as failing, namely T( b, d ).\\n -- c.f. #15413\\n subordinate_err = mkSubordinateError gre children_errs\\n in bad_import_w ie subordinate_err\\n\\n let name\' = replaceWrappedName rdr_tc name\\n childnames\' = map (to_ie_post_rn . fmap greName) childnames\\n gres = gre : map unLoc childnames\\n export_depr_warns\\n | want_hiding == Exactly = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ([ (IEThingWith (Nothing, ann) (L l name\') wc childnames\' noDocstring\\n ,gres)]\\n , bad_import_warns ++ export_depr_warns)\\n\\n IEWholeNamespace x ns_spec -> do\\n let mod_name = moduleName import_mod\\n names = map greName gres\\n renamed_ie = IEWholeNamespace x { iewn_warning = Nothing\\n , iewn_names = names }\\n (rnNamespaceSpecifier ns_spec)\\n gres = filterByNamespaceSpecifierGREs ns_spec $\\n gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n dodgy_warn\\n | null gres = [DodgyImport (DodgyImportsWildcard mod_name ns_spec)]\\n | otherwise = []\\n return ([(renamed_ie, gres)],\\n dodgy_warn)\\n\\n _other -> failLookupWith IllegalImport\\n -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed...\\n -- all of those constitute errors.\\n\\n where\\n mkIEThingAbs tc l gre\\n = (IEThingAbs Nothing (L l (replaceWrappedName tc n)) noDocstring, [gre])\\n where n = greName gre\\n\\n -- N.B. imports never have docstrings\\n noDocstring = Nothing\\n\\n handle_bad_import m = catchIELookup m $ \\\\case\\n BadImport ie sub -> do\\n ws <- bad_import_w ie sub\\n return ([], ws)\\n err -> failLookupWith err\\n\\n bad_import_w :: IE GhcPs -> IsSubordinateError -> IELookupM [IELookupWarning]\\n bad_import_w ie sub\\n | want_hiding == EverythingBut = return [BadImportW ie sub]\\n | otherwise = failLookupWith (BadImport ie sub)\\n\\n mk_depr_export_warning gre\\n = DeprecatedExport name <$> mi_export_warn_fn iface name\\n where\\n name = greName gre\\n\\n-- | Assuming a subordinate item could not be found, do another lookup for a\\n-- more specific error message.\\nmkBadExportSubordinate :: [GlobalRdrElt] -> LIEWrappedName GhcPs -> BadExportSubordinate\\nmkBadExportSubordinate child_gres n =\\n case lookupChildren child_gres [n] of\\n (LookupChildNonType {lce_nontype_item = g} : _, _) -> BadExportSubordinateNonType g\\n (LookupChildNonData {lce_nondata_item = g} : _, _) -> BadExportSubordinateNonData g\\n _ -> BadExportSubordinateNotFound n\\n\\ntype IELookupM = MaybeErr IELookupError\\n\\ndata IELookupWarning\\n = BadImportW (IE GhcPs) IsSubordinateError\\n | MissingImportList\\n | DodgyImport DodgyImportsReason\\n | DeprecatedExport Name (WarningTxt GhcRn)\\n\\n-- | Is this import/export item a subordinate or not?\\ndata IsSubordinateError\\n = IsSubordinateError { subordinate_err_parent :: !GlobalRdrElt\\n , subordinate_err_unavailable :: [FastString]\\n , subordinate_err_nontype :: [GlobalRdrElt]\\n , subordinate_err_nondata :: [GlobalRdrElt] }\\n | IsNotSubordinate\\n\\nmkSubordinateError :: GlobalRdrElt -> [LookupChildError] -> IsSubordinateError\\nmkSubordinateError gre children_errs = foldr add init_acc children_errs\\n where\\n init_acc :: IsSubordinateError\\n init_acc = IsSubordinateError gre [] [] []\\n\\n add :: LookupChildError -> IsSubordinateError -> IsSubordinateError\\n add children_err sub@IsSubordinateError{} =\\n case children_err of\\n LookupChildNonType{lce_nontype_item = g} ->\\n sub { subordinate_err_nontype = g : subordinate_err_nontype sub }\\n LookupChildNonData{lce_nondata_item = g} ->\\n sub { subordinate_err_nondata = g : subordinate_err_nondata sub }\\n LookupChildNotFound (L _ wname) ->\\n let fs = (occNameFS . rdrNameOcc . ieWrappedName) wname\\n in sub { subordinate_err_unavailable = fs : subordinate_err_unavailable sub }\\n add _ IsNotSubordinate = panic \\"mkSubordinateError: IsNotSubordinate\\"\\n\\ndata IELookupError\\n = QualImportError RdrName\\n | BadImport (IE GhcPs) IsSubordinateError\\n | IllegalImport\\n\\nfailLookupWith :: IELookupError -> IELookupM a\\nfailLookupWith err = Failed err\\n\\ncatchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a\\ncatchIELookup m h = case m of\\n Succeeded r -> return r\\n Failed err -> h err\\n\\ncatIELookupM :: [IELookupM a] -> [a]\\ncatIELookupM ms = [ a | Succeeded a <- ms ]\\n\\n-- | Information associated to an \'AvailInfo\' used in constructing\\n-- an \'OccEnv\' corresponding to imports.\\n--\\n-- See Note [Dealing with imports].\\ndata ImpOccItem\\n = ImpOccItem\\n { imp_item :: GlobalRdrElt\\n -- ^ The import item\\n , imp_bundled :: [GlobalRdrElt]\\n -- ^ Items bundled in the Avail this import item came from,\\n -- not including the import item itself if it is a parent.\\n , imp_is_parent :: Bool\\n -- ^ Is the import item a parent? See Note [Dealing with imports].\\n }\\n\\ninstance Outputable ImpOccItem where\\n ppr (ImpOccItem { imp_item = item, imp_bundled = bundled, imp_is_parent = is_par })\\n = braces $ hsep\\n [ text \\"ImpOccItem\\"\\n , if is_par then text \\"[is_par]\\" else empty\\n , ppr (greName item) <+> ppr (greParent item)\\n , braces $ text \\"bundled:\\" <+> ppr (map greName bundled) ]\\n\\n-- | Make an \'OccEnv\' of all the imports.\\n--\\n-- Complicated by the fact that associated data types and pattern synonyms\\n-- can appear twice. See Note [Dealing with imports].\\nmkImportOccEnv :: HscEnv -> ImpDeclSpec -> [IfaceExport] -> OccEnv (NameEnv ImpOccItem)\\nmkImportOccEnv hsc_env decl_spec all_avails =\\n mkOccEnv_C (plusNameEnv_C combine)\\n [ (occ, mkNameEnv [(nm, item)])\\n | avail <- all_avails\\n , let gres = gresFromAvail hsc_env (Just hiding_spec) avail\\n , gre <- gres\\n , let nm = greName gre\\n occ = greOccName gre\\n (is_parent, bundled) = case avail of\\n AvailTC c _\\n | c == nm -- (Recall the AvailTC invariant from GHC.Types.AvailInfo)\\n -> ( True, drop 1 gres ) -- \\"drop 1\\": don\'t include the parent itself.\\n | otherwise\\n -> ( False, gres )\\n _ -> ( False, [] )\\n item = ImpOccItem\\n { imp_item = gre\\n , imp_bundled = bundled\\n , imp_is_parent = is_parent }\\n ]\\n where\\n\\n hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\n -- See Note [Dealing with imports]\\n -- \'combine\' may be called for associated data types which appear\\n -- twice in the all_avails. In the example, we have two Avails for T,\\n -- namely T(T,T1,T2,T3) and C(C,T), and we combine them by dropping the\\n -- latter, in which T is not the parent.\\n combine :: ImpOccItem -> ImpOccItem -> ImpOccItem\\n combine item1@(ImpOccItem { imp_item = gre1, imp_is_parent = is_parent1 })\\n item2@(ImpOccItem { imp_item = gre2, imp_is_parent = is_parent2 })\\n | is_parent1 || is_parent2\\n , not (isRecFldGRE gre1 || isRecFldGRE gre2) -- NB: does not force GREInfo.\\n , let name1 = greName gre1\\n name2 = greName gre2\\n gre = gre1 `plusGRE` gre2\\n -- See Note [Preserve parent information when combining import OccEnvs]\\n = assertPpr (name1 == name2)\\n (ppr name1 <+> ppr name2) $\\n if is_parent1\\n then item1 { imp_item = gre }\\n else item2 { imp_item = gre }\\n -- Discard C(C,T) in favour of T(T, T1, T2, T3).\\n\\n -- \'combine\' may also be called for pattern synonyms which appear both\\n -- unassociated and associated (see Note [Importing PatternSynonyms]).\\n combine item1@(ImpOccItem { imp_item = c1, imp_bundled = kids1 })\\n item2@(ImpOccItem { imp_item = c2, imp_bundled = kids2 })\\n = assertPpr (greName c1 == greName c2\\n && (not (null kids1 && null kids2)))\\n (ppr c1 <+> ppr c2 <+> ppr kids1 <+> ppr kids2) $\\n if null kids1\\n then item2\\n else item1\\n -- Discard standalone pattern P in favour of T(P).\\n\\n-- | Essentially like @lookupGRE env (LookupOccName occ which_gres)@,\\n-- but working with \'ImpOccItem\'s instead of \'GlobalRdrElt\'s.\\nlookupImpOccEnv :: WhichGREs GREInfo\\n -> OccEnv (NameEnv ImpOccItem) -> OccName -> [NameEnv ImpOccItem]\\nlookupImpOccEnv which_gres env occ =\\n mapMaybe relevant_items $ lookupOccEnv_AllNameSpaces env occ\\n where\\n is_relevant :: ImpOccItem -> Bool\\n is_relevant (ImpOccItem { imp_item = gre }) =\\n greIsRelevant which_gres (occNameSpace occ) gre\\n relevant_items :: NameEnv ImpOccItem -> Maybe (NameEnv ImpOccItem)\\n relevant_items nms\\n | let nms\' = filterNameEnv is_relevant nms\\n = if isEmptyNameEnv nms\'\\n then Nothing\\n else Just nms\'\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{Import/Export Utils}\\n* *\\n************************************************************************\\n-}\\n\\n-- | Given an import\\\\/export spec, appropriately set the @gre_imp@ field\\n-- for the \'GlobalRdrElt\'s.\\ngresFromIE :: ImpDeclSpec -> (LIE GhcRn, [GlobalRdrElt]) -> [GlobalRdrElt]\\ngresFromIE decl_spec (L loc ie, gres)\\n = map set_gre_imp gres\\n where\\n is_explicit = case ie of\\n IEThingAll _ _ name _ -> \\\\n -> n == lieWrappedName name\\n IEWholeNamespace _ _ -> \\\\_ -> False\\n _ -> \\\\_ -> True\\n prov_fn name\\n = ImpSpec { is_decl = decl_spec, is_item = item_spec }\\n where\\n item_spec = ImpSome { is_explicit = is_explicit name\\n , is_iloc = locA loc }\\n set_gre_imp gre@( GRE { gre_name = nm } )\\n = gre { gre_imp = unitBag $ prov_fn nm }\\n\\nparentOfImplicitlyImportedGRE :: Outputable info => GlobalRdrEltX info -> Maybe Name\\nparentOfImplicitlyImportedGRE gre =\\n if any (explicit_import . is_item) $ gre_imp gre\\n then Nothing\\n else greParent_maybe gre\\n where\\n explicit_import :: ImpItemSpec -> Bool\\n explicit_import (ImpAll {}) =\\n pprPanic \\"parentOfImplicitlyImportedGRE: ImpAll\\" (ppr gre)\\n explicit_import (ImpSome { is_explicit }) = is_explicit\\n\\n{- Note [Children for duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider the module\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (F(foo, MkFInt, MkFBool)) where\\n data family F a\\n data instance F Int = MkFInt { foo :: Int }\\n data instance F Bool = MkFBool { foo :: Bool }\\n\\nThe `foo` in the export list refers to *both* selectors! For this\\nreason, lookupChildren builds an environment that maps the FastString\\nto a list of items, rather than a single item.\\n-}\\n\\nmkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]\\nmkChildEnv gres = foldr add emptyNameEnv gres\\n where\\n add gre env = case greParent gre of\\n ParentIs p -> extendNameEnv_Acc (:) Utils.singleton env p gre\\n NoParent -> env\\n\\nfindChildren :: NameEnv [a] -> Name -> [a]\\nfindChildren env n = lookupNameEnv env n `orElse` []\\n\\ndata LookupChildError\\n = LookupChildNotFound { lce_wrapped_name :: !(LIEWrappedName GhcPs) }\\n | LookupChildNonType { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nontype_item :: !GlobalRdrElt }\\n | LookupChildNonData { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nondata_item :: !GlobalRdrElt }\\n\\nlookupChildren :: [GlobalRdrElt]\\n -> [LIEWrappedName GhcPs]\\n -> ( [LookupChildError] -- The ones for which the lookup failed\\n , [LocatedA GlobalRdrElt] )\\n-- (lookupChildren all_kids rdr_items) maps each rdr_item to its\\n-- corresponding Name in all_kids, if the former exists\\n-- The matching is done by FastString, not OccName, so that\\n-- Cls( meth, AssocTy )\\n-- will correctly find AssocTy among the all_kids of Cls, even though\\n-- the RdrName for AssocTy may have a (bogus) DataName namespace\\n-- (Really the rdr_items should be FastStrings in the first place.)\\nlookupChildren all_kids rdr_items = (fails, successes)\\n where\\n mb_xs = map do_one rdr_items\\n fails = [ err | Failed err <- mb_xs ]\\n successes = [ ok | Succeeded oks <- mb_xs, ok <- NE.toList oks ]\\n\\n do_one :: LIEWrappedName GhcPs -> MaybeErr LookupChildError (NonEmpty (LocatedA GlobalRdrElt))\\n do_one item@(L l r) =\\n case r of\\n IEName{}\\n -- IEName (unadorned name) places no restriction on the namespace of\\n -- the imported entity, so we look in both `val_gres` and `typ_gres`.\\n -- In case of conflict (punning), the value namespace takes priority.\\n -- See Note [Prioritise the value namespace in subordinate import lists]\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEType{}\\n -- IEType (\'type\' namespace specifier) restricts the lookup to the\\n -- type namespace, i.e. to `typ_gres`. In case of failure, we check\\n -- `val_gres` to produce a more helpful error message.\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- val_gres -> Failed $ LookupChildNonType item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEData{}\\n -- IEData (\'data\' namespace specifier) restricts the lookup to the\\n -- data namespace, i.e. to `val_gres`. In case of failure, we check\\n -- `typ_gres` to produce a more helpful error message.\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- typ_gres -> Failed $ LookupChildNonData item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEPattern{} -> panic \\"lookupChildren: IEPattern\\" -- Never happens (invalid syntax)\\n IEDefault{} -> panic \\"lookupChildren: IEDefault\\" -- Never happens (invalid syntax)\\n where\\n fs = (occNameFS . rdrNameOcc . ieWrappedName) r\\n gres = fromMaybe [] (lookupFsEnv kid_env fs)\\n (val_gres, typ_gres) = partition (isValNameSpace . greNameSpace) gres\\n\\n -- See Note [Children for duplicate record fields]\\n kid_env :: FastStringEnv [GlobalRdrElt]\\n kid_env = extendFsEnvList_C (++) emptyFsEnv\\n [(occNameFS (occName x), [x]) | x <- all_kids]\\n\\n\\n{- Note [Prioritise the value namespace in subordinate import lists]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider this program that defines a class that has both an associated type\\nnamed (#) and a method named (#)\\n\\n module M_assoc where\\n class C a b where\\n type a # b\\n (#) :: a -> b -> ()\\n module N_assoc where\\n import M_assoc( C((#)) )\\n\\nIn the import declaration, when we see the unadorned name (#) in the subordinate\\nimport list of C, which children should we bring into scope? Our options are:\\n\\n a) only the method (#)\\n b) only the associated type (#)\\n c) both the method and the associated type\\n\\nTo follow the precedent established by top-level items, we go with option (a).\\nIndeed, consider a slightly different program\\n\\n module M_top where\\n type family a # b\\n a # b = ()\\n module N_top where\\n import M_top( (#) )\\n\\nHere the import brings only the function (#) into scope, and one has to say\\n`type (#)` to get the type family.\\n-}\\n\\n-------------------------------\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused names}\\n* *\\n*********************************************************\\n-}\\n\\nreportUnusedNames :: TcGblEnv -> HscSource -> RnM ()\\nreportUnusedNames gbl_env hsc_src\\n = do { keep <- readTcRef (tcg_keep gbl_env)\\n ; traceRn \\"RUN\\" (ppr (tcg_dus gbl_env))\\n ; warnUnusedImportDecls gbl_env hsc_src\\n ; warnUnusedTopBinds $ unused_locals keep\\n ; warnMissingSignatures gbl_env\\n ; warnMissingKindSignatures gbl_env }\\n where\\n used_names :: NameSet -> NameSet\\n used_names keep = findUses (tcg_dus gbl_env) emptyNameSet `unionNameSet` keep\\n -- NB: currently, if f x = g, we only treat \'g\' as used if \'f\' is used\\n -- Hence findUses\\n\\n -- Collect the defined names from the in-scope environment\\n defined_names :: [GlobalRdrElt]\\n defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)\\n\\n kids_env = mkChildEnv defined_names\\n -- This is done in mkExports too; duplicated work\\n\\n gre_is_used :: NameSet -> GlobalRdrElt -> Bool\\n gre_is_used used_names gre0\\n = name `elemNameSet` used_names\\n || any (\\\\ gre -> greName gre `elemNameSet` used_names) (findChildren kids_env name)\\n -- A use of C implies a use of T,\\n -- if C was brought into scope by T(..) or T(C)\\n where\\n name = greName gre0\\n\\n -- Filter out the ones that are\\n -- (a) defined in this module, and\\n -- (b) not defined by a \'deriving\' clause\\n -- The latter have an Internal Name, so we can filter them out easily\\n unused_locals :: NameSet -> [GlobalRdrElt]\\n unused_locals keep =\\n let -- Note that defined_and_used, defined_but_not_used\\n -- are both [GRE]; that\'s why we need defined_and_used\\n -- rather than just used_names\\n _defined_and_used, defined_but_not_used :: [GlobalRdrElt]\\n (_defined_and_used, defined_but_not_used)\\n = partition (gre_is_used (used_names keep)) defined_names\\n\\n in filter is_unused_local defined_but_not_used\\n is_unused_local :: GlobalRdrElt -> Bool\\n is_unused_local gre = isLocalGRE gre\\n && isExternalName (greName gre)\\n\\n{- *********************************************************************\\n* *\\n Missing signatures\\n* *\\n********************************************************************* -}\\n\\n{-\\nNote [Missing signatures]\\n~~~~~~~~~~~~~~~~~~~~~~~~~\\nThere are four warning flags in play:\\n\\n * -Wmissing-exported-signatures\\n Warn about any exported top-level function/value without a type signature.\\n Does not include pattern synonyms.\\n\\n * -Wmissing-signatures\\n Warn about any top-level function/value without a type signature. Does not\\n include pattern synonyms. Takes priority over -Wmissing-exported-signatures.\\n\\n * -Wmissing-exported-pattern-synonym-signatures\\n Warn about any exported pattern synonym without a type signature.\\n\\n * -Wmissing-pattern-synonym-signatures\\n Warn about any pattern synonym without a type signature. Takes priority over\\n -Wmissing-exported-pattern-synonym-signatures.\\n\\n-}\\n\\n-- | Warn the user about top level binders that lack type signatures.\\n-- Called /after/ type inference, so that we can report the\\n-- inferred type of the function\\nwarnMissingSignatures :: TcGblEnv -> RnM ()\\nwarnMissingSignatures gbl_env\\n = do { let exports = availsToNameSet (tcg_exports gbl_env)\\n sig_ns = tcg_sigs gbl_env\\n -- We use sig_ns to exclude top-level bindings that are generated by GHC\\n binds = collectHsBindsBinders CollNoDictBinders $ tcg_binds gbl_env\\n pat_syns = tcg_patsyns gbl_env\\n\\n not_ghc_generated :: Name -> Bool\\n not_ghc_generated name = name `elemNameSet` sig_ns\\n\\n add_binding_warn :: Id -> RnM ()\\n add_binding_warn id =\\n when (not_ghc_generated name) $\\n do { env <- liftZonkM $ tcInitTidyEnv -- Why not use emptyTidyEnv?\\n ; let ty = tidyOpenType env (idType id)\\n missing = MissingTopLevelBindingSig name ty\\n diag = TcRnMissingSignature missing exported\\n ; addDiagnosticAt (getSrcSpan name) diag }\\n where\\n name = idName id\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n add_patsyn_warn :: PatSyn -> RnM ()\\n add_patsyn_warn ps =\\n when (not_ghc_generated name) $\\n addDiagnosticAt (getSrcSpan name)\\n (TcRnMissingSignature missing exported)\\n where\\n name = patSynName ps\\n missing = MissingPatSynSig ps\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n -- Warn about missing signatures\\n -- Do this only when we have a type to offer\\n -- See Note [Missing signatures]\\n ; mapM_ add_binding_warn binds\\n ; mapM_ add_patsyn_warn pat_syns\\n }\\n\\n-- | Warn the user about tycons that lack kind signatures.\\n-- Called /after/ type (and kind) inference, so that we can report the\\n-- inferred kinds.\\nwarnMissingKindSignatures :: TcGblEnv -> RnM ()\\nwarnMissingKindSignatures gbl_env\\n = do { cusks_enabled <- xoptM LangExt.CUSKs\\n ; mapM_ (add_ty_warn cusks_enabled) tcs\\n }\\n where\\n tcs = tcg_tcs gbl_env\\n ksig_ns = tcg_ksigs gbl_env\\n exports = availsToNameSet (tcg_exports gbl_env)\\n\\n has_kind_signature :: Name -> Bool\\n has_kind_signature name = name `elemNameSet` ksig_ns\\n\\n add_ty_warn :: Bool -> TyCon -> RnM ()\\n add_ty_warn cusks_enabled tyCon =\\n when (has_kind_signature name) $\\n addDiagnosticAt (getSrcSpan name) diag\\n where\\n name = tyConName tyCon\\n diag = TcRnMissingSignature missing exported\\n missing = MissingTyConKindSig tyCon cusks_enabled\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused imports}\\n* *\\n*********************************************************\\n\\nThis code finds which import declarations are unused. The\\nspecification and implementation notes are here:\\n https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/unused-imports\\n\\nSee also Note [Choosing the best import declaration] in GHC.Types.Name.Reader\\n-}\\n\\ntype ImportDeclUsage\\n = ( LImportDecl GhcRn -- The import declaration\\n , [GlobalRdrElt] -- What *is* used (normalised)\\n , [Name] -- What is imported but *not* used\\n , [NamespaceSpecifier GhcRn] ) -- Unused wildcards\\n\\nwarnUnusedImportDecls :: TcGblEnv -> HscSource -> RnM ()\\nwarnUnusedImportDecls gbl_env hsc_src\\n = do { uses <- readMutVar (tcg_used_gres gbl_env)\\n ; let imports = tcg_rn_imports gbl_env\\n rdr_env = tcg_rdr_env gbl_env\\n\\n -- We should only warn for unnecessary *user* imports, but deciding\\n -- minimal imports should take generated imports into account\\n ; let usageUserImports = findImportUsage (excludeGenerated imports) uses\\n usageAllImports = findImportUsage imports uses\\n\\n ; traceRn \\"warnUnusedImportDecls\\" $\\n (vcat [ text \\"Uses:\\" <+> ppr uses\\n , text \\"Usage all user imports: \\" <+> ppr usageUserImports\\n , text \\"Usage all imports: \\" <+> ppr usageAllImports])\\n\\n ; mapM_ (warnUnusedImport rdr_env) usageUserImports\\n\\n ; whenGOptM Opt_D_dump_minimal_imports $\\n printMinimalImports hsc_src usageAllImports }\\n\\n-- | Exclude generated imports\\nexcludeGenerated :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\nexcludeGenerated = filterOut (isGeneratedImport . ideclOrigin . ideclExt . unLoc)\\n\\nfindImportUsage :: [LImportDecl GhcRn]\\n -> [GlobalRdrElt]\\n -> [ImportDeclUsage]\\n\\nfindImportUsage imports used_gres\\n = map unused_decl imports\\n where\\n import_usage :: ImportMap\\n import_usage = mkImportMap used_gres\\n\\n unused_decl :: LImportDecl GhcRn -> ImportDeclUsage\\n unused_decl decl@(L _ (ImportDecl { ideclImportList = imps }))\\n = -- pprTrace \\"unused_decl\\" (vcat [ ppr decl\\n -- , text \\"used\\" <+> ppr used_gres\\n -- , text \\"unused\\" <+> ppr unused_names ]) $\\n (decl, used_gres, unused_names, unused_wcs)\\n where\\n used_gres = lookupImportMap decl import_usage\\n\\n used_gre_env = mkGlobalRdrEnv used_gres\\n used_parents = mkNameSet (mapMaybe greParent_maybe used_gres)\\n\\n (unused_names, unused_wcs) -- Not trivial; see eg #7454\\n = case imps of\\n Just (Exactly, imp_ies) ->\\n let unused = foldr (add_unused . unLoc) emptyUnusedNames imp_ies\\n nms = nameSetElemsStable (collectUnusedNames unused)\\n wcs = collectUnusedWildcards unused\\n in (nms, wcs)\\n _other -> ([], []) -- No explicit import list => no unused-name list\\n\\n add_unused :: IE GhcRn -> UnusedNames -> UnusedNames\\n add_unused (IEVar _ n _) acc = add_unused_name (lieWrappedName n) True acc\\n add_unused (IEThingAbs _ n _) acc = add_unused_name (lieWrappedName n) False acc\\n add_unused (IEThingAll _ _ n _) acc = add_unused_all (lieWrappedName n) acc\\n add_unused (IEThingWith _ p wc ns _) acc = add_wc_all (add_unused_with pn xs acc)\\n where pn = lieWrappedName p\\n xs = map lieWrappedName ns\\n add_wc_all = case wc of\\n NoIEWildcard -> id\\n IEWildcard _ -> add_unused_all pn\\n add_unused (IEWholeNamespace x ns_spec) acc = add_unused_wildcard ns_spec (iewn_names x) acc\\n add_unused _ acc = acc\\n\\n add_unused_name :: Name -> Bool -> UnusedNames -> UnusedNames\\n add_unused_name n is_ie_var acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | is_ie_var\\n , isFieldName n\\n -- See Note [Reporting unused imported duplicate record fields]\\n = let\\n fs = getOccFS n\\n (flds, flds_used) = lookupFsEnv acc_fs fs `orElse` (emptyNameSet, Any False)\\n acc_fs\' = extendFsEnv acc_fs fs (extendNameSet flds n, Any used S.<> flds_used)\\n in UnusedNames acc_ns acc_wcs acc_fs\'\\n\\n | used\\n = acc\\n\\n | otherwise\\n = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n where\\n used = isJust $ lookupGRE_Name used_gre_env n\\n\\n add_unused_all :: Name -> UnusedNames -> UnusedNames\\n add_unused_all n acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | Just {} <- lookupGRE_Name used_gre_env n = acc\\n | n `elemNameSet` used_parents = acc\\n | otherwise = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n\\n add_unused_with :: Name -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_with p ns acc\\n | all (`elemNameSet` acc1_ns) ns = add_unused_name p False acc1\\n | otherwise = acc1\\n where\\n acc1@(UnusedNames acc1_ns _ _) = foldr (\\\\n acc\' -> add_unused_name n False acc\') acc ns\\n -- If you use \'signum\' from Num, then the user may well have\\n -- imported Num(signum). We don\'t want to complain that\\n -- Num is not itself mentioned. Hence the two cases in add_unused_with.\\n\\n add_unused_wildcard :: NamespaceSpecifier GhcRn -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_wildcard ns_spec names acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | any_used = acc\\n | otherwise = UnusedNames acc_ns (ns_spec : acc_wcs) acc_fs\\n where\\n -- A wildcard `type ..` or `data ..` is used if at least one of\\n -- the names it expands to is used\\n any_used = any (isJust . lookupGRE_Name used_gre_env) names\\n\\n\\n-- | An accumulator for unused names in an import list.\\n--\\n-- See Note [Reporting unused imported duplicate record fields].\\ndata UnusedNames =\\n UnusedNames\\n { unused_names :: NameSet\\n -- ^ Unused \'Name\'s in an import list, not including record fields\\n -- that are plain \'IEVar\' imports (tracked by \'rec_fld_uses\')\\n -- or wildcard imports (tracked by \'unused_wildcards\').\\n , unused_wildcards :: [NamespaceSpecifier GhcRn]\\n -- ^ Unused wildcards @type ..@ or @data ..@ in an import list.\\n , rec_fld_uses :: FastStringEnv (NameSet, Any)\\n -- ^ Record fields imported without a parent (i.e. an \'IEVar\' import).\\n --\\n -- The \'Any\' value records whether any of the record fields\\n -- sharing the same underlying \'FastString\' have been used.\\n }\\n\\nemptyUnusedNames :: UnusedNames\\nemptyUnusedNames = UnusedNames emptyNameSet [] emptyFsEnv\\n\\ninstance Outputable UnusedNames where\\n ppr (UnusedNames nms wcs flds) =\\n text \\"UnusedNames\\" <+>\\n braces (ppr nms <+> ppr wcs <+> ppr (fmap (second getAny) flds))\\n\\n-- | Collect all unused names from a \'UnusedNames\' value.\\ncollectUnusedNames :: UnusedNames -> NameSet\\ncollectUnusedNames (UnusedNames { unused_names = nms, rec_fld_uses = flds })\\n = nms S.<> unused_flds\\n where\\n unused_flds = nonDetFoldFsEnv collect_unused emptyNameSet flds\\n collect_unused :: (NameSet, Any) -> NameSet -> NameSet\\n collect_unused (nms, Any at_least_one_name_is_used) acc\\n | at_least_one_name_is_used = acc\\n | otherwise = unionNameSet nms acc\\n\\ncollectUnusedWildcards :: UnusedNames -> [NamespaceSpecifier GhcRn]\\ncollectUnusedWildcards = unused_wildcards\\n\\n{- Note [Reporting unused imported duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have (#24035):\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M1 (R1(..), R2(..)) where\\n data R1 = MkR1 { fld :: Int }\\n data R2 = MkR2 { fld :: Int }\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M2 where\\n import M1 (R1(MkR1), R2, fld)\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nIn the import of \'M1\' in \'M2\', the \'fld\' import resolves to two separate GREs,\\nnamely R1(fld) and R2(fld). From the perspective of the renamer, and in particular\\nthe \'findImportUsage\' function, it\'s as if the user had imported the two names\\nseparately (even though no source syntax allows that).\\n\\nThis means that we need to be careful when reporting unused imports: the R2(fld)\\nimport is indeed unused, but because R1(fld) is used, we should not report\\nfld as unused altogether.\\n\\nTo achieve this, we keep track of record field imports without a parent (i.e.\\nusing the IEVar constructor) separately from other import items, using the\\nUnusedNames datatype.\\nOnce we have accumulated usages, we emit warnings for unused record fields\\nwithout parents one whole group (of record fields sharing the same textual name)\\nat a time, and only if *all* of the record fields in the group are unused;\\nsee \'collectUnusedNames\'.\\n\\nNote that this only applies to record fields imported without a parent. If we\\nhad:\\n\\n import M1 (R1(MkR1, fld), R2(fld))\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nthen of course we should report the second \'fld\' as unused.\\n-}\\n\\n\\n{- Note [The ImportMap]\\n~~~~~~~~~~~~~~~~~~~~~~~\\nThe ImportMap is a short-lived intermediate data structure records, for\\neach import declaration, what stuff brought into scope by that\\ndeclaration is actually used in the module.\\n\\nThe [GlobalRdrElt] are the things imported from that decl.\\n-}\\n\\ndata ImportMap = ImportMap\\n { im_imports :: Map RealSrcSpan [GlobalRdrElt]\\n -- ^ See [The ImportMap]\\n -- If loc :-> gres, then\\n -- \'loc\' = the end loc of the bestImport of each GRE in \'gres\'\\n , im_generatedImports :: Map ModuleName [GlobalRdrElt]\\n }\\n\\nmkImportMap :: [GlobalRdrElt] -> ImportMap\\n-- For each of a list of used GREs, find all the import decls that brought\\n-- it into scope; choose one of them (bestImport), and record\\n-- the RdrName in that import decl\'s entry in the ImportMap\\nmkImportMap = foldr insertImportMap $ ImportMap Map.empty Map.empty\\n\\ninsertImportMap :: GlobalRdrElt -> ImportMap -> ImportMap\\ninsertImportMap gre@(GRE { gre_imp = imp_specs }) importMap\\n | RealSrcSpan importSpan _ <- is_dloc best_imp_spec =\\n importMap{im_imports = insertElem importSpan gre $ im_imports importMap}\\n | GeneratedSrcSpan{} <- is_dloc best_imp_spec =\\n importMap{im_generatedImports = insertElem (moduleName $ is_mod best_imp_spec) gre $ im_generatedImports importMap}\\n | otherwise = importMap\\n where\\n best_imp_spec =\\n case bagToList imp_specs of\\n [] -> pprPanic \\"mkImportMap: GRE with no ImportSpecs\\" (ppr gre)\\n is:iss -> is_decl $ bestImport (is NE.:| iss)\\n\\n -- https://github.com/haskell/containers/issues/784\\n insertElem :: Ord k => k -> v -> Map k [v] -> Map k [v]\\n insertElem k v = flip Map.alter k $ \\\\case\\n Just vs -> Just (v : vs)\\n Nothing -> Just [v]\\n\\nlookupImportMap :: LImportDecl GhcRn -> ImportMap -> [GlobalRdrElt]\\nlookupImportMap (L srcSpan ImportDecl{ideclName = L _ modName}) importMap =\\n fromMaybe [] $\\n -- should match logic in insertImportMap\\n case locA srcSpan of\\n RealSrcSpan realSrcSpan _ -> realSrcSpan `Map.lookup` im_imports importMap\\n GeneratedSrcSpan{} -> modName `Map.lookup` im_generatedImports importMap\\n _ -> Nothing\\n\\nlieNames :: LIE (GhcPass p) -> [Located (IdP (GhcPass p))]\\nlieNames = _\\n\\nwarnUnusedImport :: GlobalRdrEnv -> ImportDeclUsage -> RnM ()\\nwarnUnusedImport rdr_env (L loc decl, used, unused, unused_wcs)\\n\\n -- Do not warn for \'import M()\'\\n -- See (UI1) in Note [Unused imports]\\n | Just (Exactly, _) <- ideclImportList decl\\n , null unused && null unused_wcs\\n = return ()\\n\\n -- Note [Do not warn about Prelude hiding]\\n | Just (EverythingBut, hides) <- ideclImportList decl\\n , not (null hides)\\n , pRELUDE_NAME == unLoc (ideclName decl)\\n = return ()\\n\\n -- Do not warn about import X as Rebindable\\n -- See (UI2) in Note [Unused imports]\\n | Just (L _ mod) <- ideclAs decl\\n , mod == rEBINDABLE_MOD_NAME\\n = return ()\\n\\n -- Nothing used; drop entire declaration\\n | null used\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl UnusedImportNone)\\n\\n -- Everything imported is used; nop\\n | null unused && null unused_wcs\\n = return ()\\n\\n -- Some imports are unused: make the `SrcSpan` cover only the unused\\n -- items instead of the whole import statement\\n | Just (_, imports) <- ideclImportList decl\\n , let unused_locs = [ locA loc | L loc ie <- imports\\n , name <- ieNames ie\\n , name `elem` unused ]\\n , loc1 : locs <- unused_locs\\n , let span = foldr1 combineSrcSpans ( loc1 NE.:| locs )\\n = addDiagnosticAt span (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n -- Some imports are unused\\n | otherwise\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n where\\n -- In warning message, pretty-print identifiers unqualified unconditionally\\n -- to improve the consistent for ambiguous/unambiguous identifiers.\\n -- See #14881.\\n possible_field n =\\n case lookupGRE_Name rdr_env n of\\n Just (GRE { gre_par = par, gre_info = IAmRecField info }) ->\\n let fld_occ :: OccName\\n fld_occ = nameOccName $ flSelector $ recFieldLabel info\\n in UnusedImportNameRecField par fld_occ\\n _ -> UnusedImportNameRegular n\\n\\n -- Print unused names in a deterministic (lexicographic) order\\n sort_unused :: [UnusedImportName]\\n sort_unused =\\n [ UnusedImportWildcard wc | wc <- unused_wcs ] ++\\n [ possible_field nm | nm <- sortBy (comparing nameOccName) unused ]\\n\\ngetMinimalImports :: [ImportDeclUsage] -> RnM [LImportDecl GhcRn]\\ngetMinimalImports ie_decls\\n = do { rdr_env <- getGlobalRdrEnv\\n ; fmap combine $ mapM (mk_minimal rdr_env) ie_decls }\\n where\\n mk_minimal rdr_env (L l decl, used_gres, unused, unused_wcs)\\n | null unused && null unused_wcs\\n , Just (Exactly, _) <- ideclImportList decl\\n = return (L l decl)\\n | otherwise\\n = do { let ImportDecl { ideclName = L _ mod_name\\n , ideclSource = is_boot\\n , ideclPkgQual = pkg_qual\\n , ideclExt = XImportDeclPass { ideclOrigin = origin } } = decl\\n ; iface <- loadSrcInterface doc (importDeclLookupScope origin)\\n mod_name is_boot pkg_qual\\n ; let used_avails = gresToAvailInfo used_gres\\n ; lies <- map (L l) <$> concatMapM (to_ie rdr_env iface) used_avails\\n ; return (L l (decl { ideclImportList = Just (Exactly, lies) })) }\\n where\\n doc = text \\"Compute minimal imports for\\" <+> ppr decl\\n\\n to_ie :: GlobalRdrEnv -> ModIface -> AvailInfo -> RnM [IE GhcRn]\\n -- The main trick here is that if we\'re importing all the constructors\\n -- we want to say \\"T(..)\\", but if we\'re importing only a subset we want\\n -- to say \\"T(A,B,C)\\". So we have to find out what the module exports.\\n to_ie rdr_env _ (Avail c) -- Note [Overloaded field import]\\n = do { let\\n gre = expectJust $ lookupGRE_Name rdr_env c\\n ; return $ [IEVar Nothing (to_ie_post_rn $ noLocA $ greName gre) Nothing] }\\n to_ie _ _ avail@(AvailTC n [_]) -- Exporting the main decl and nothing else\\n | availExportsDecl avail\\n = return [IEThingAbs Nothing (to_ie_post_rn $ noLocA n) Nothing]\\n to_ie rdr_env iface (AvailTC n cs) =\\n case [ xs | avail@(AvailTC x xs) <- mi_exports iface\\n , x == n\\n , availExportsDecl avail -- Note [Partial export]\\n ] of\\n [xs]\\n | all_used xs\\n -> return [IEThingAll (IEThingAllExt Nothing noAnn noAnn noAnn)\\n (NoNamespaceSpecifier noExtField)\\n (to_ie_post_rn $ noLocA n)\\n Nothing]\\n | otherwise\\n -> do { let ns_gres = map (expectJust . lookupGRE_Name rdr_env) cs\\n ns = map greName ns_gres\\n ; return [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n -- Note [Overloaded field import]\\n _other\\n -> do { let infos = map (expectJust . lookupGRE_Name rdr_env) cs\\n (ns_gres,fs_gres) = classifyGREs infos\\n ns = map greName (ns_gres ++ fs_gres)\\n fs = map fieldGREInfo fs_gres\\n ; return $\\n if all_non_overloaded fs\\n then map (\\\\nm -> IEVar Nothing (to_ie_post_rn_var $ noLocA nm) Nothing) ns\\n else [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n where\\n\\n all_used avail_cs = all (`elem` cs) avail_cs\\n\\n all_non_overloaded = all (not . flIsOverloaded . recFieldLabel)\\n\\n combine :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\n combine = map merge . NE.groupAllWith getKey\\n\\n getKey :: LImportDecl GhcRn -> (Bool, Maybe ModuleName, ModuleName)\\n getKey decl =\\n ( isImportDeclQualified . ideclQualified $ idecl -- is this qualified? (important that this be first)\\n , unLoc <$> ideclAs idecl -- what is the qualifier (inside Maybe monad)\\n , unLoc . ideclName $ idecl -- Module Name\\n )\\n where\\n idecl :: ImportDecl GhcRn\\n idecl = unLoc decl\\n\\n merge :: NonEmpty (LImportDecl GhcRn) -> LImportDecl GhcRn\\n merge decls@((L l decl) :| _) = L l (decl { ideclImportList = Just (Exactly, lies) })\\n where lies = concatMap snd $ mapMaybe (ideclImportList . unLoc) $ NE.toList decls\\n\\nclassifyGREs :: [GlobalRdrElt] -> ([GlobalRdrElt], [FieldGlobalRdrElt])\\nclassifyGREs = partition (not . isRecFldGRE)\\n\\nprintMinimalImports :: HscSource -> [ImportDeclUsage] -> RnM ()\\n-- See Note [Printing minimal imports]\\nprintMinimalImports hsc_src imports_w_usage\\n = do { imports\' <- excludeGenerated <$> getMinimalImports imports_w_usage\\n ; this_mod <- getModule\\n ; dflags <- getDynFlags\\n ; liftIO $ withFile (mkFilename dflags this_mod) WriteMode $ \\\\h ->\\n printForUser dflags h neverQualify AllTheWay (vcat (map ppr imports\'))\\n -- The neverQualify is important. We are printing Names\\n -- but they are in the context of an \'import\' decl, and\\n -- we never qualify things inside there\\n -- E.g. import Blag( f, b )\\n -- not import Blag( Blag.f, Blag.g )!\\n }\\n where\\n mkFilename dflags this_mod\\n | Just d <- dumpDir dflags = d basefn\\n | otherwise = basefn\\n where\\n suffix = case hsc_src of\\n HsBootFile -> \\".imports-boot\\"\\n HsSrcFile -> \\".imports\\"\\n HsigFile -> \\".imports\\"\\n basefn = moduleNameString (moduleName this_mod) ++ suffix\\n\\n\\nto_ie_post_rn_var :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn_var (L l n)\\n | isDataOcc $ occName n = L l (IEPattern noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n\\n\\nto_ie_post_rn :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn (L l n)\\n | isTcOcc occ && isSymOcc occ = L l (IEType noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n where occ = occName n\\n\\n{- Note [Do not warn about Prelude hiding]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWe do not warn about\\n import Prelude hiding( x, y )\\nbecause even if nothing else from Prelude is used, it may be essential to hide\\nx,y to avoid name-shadowing warnings. Example (#9061)\\n import Prelude hiding( log )\\n f x = log where log = ()\\n\\nNote [Unused imports]\\n~~~~~~~~~~~~~~~~~~~~~\\nIn `warnUnusedImport`, if we see an import with an explicit list imports, thus\\n import M( a, b )\\nand neither `a` nor `b` is used, we report the entire import decl as unused. We\\ncheck this by looking at the names that it brings into scope scope; if there are\\nno ununused names, don\'t report.\\n\\n(UI1) We don\'t want to complain about `import M()`, because that is often used to bring\\n M\'s /instances/ into scope. That is neatly dealt with by the \\"no unused\\n names\\" (nor unused wildcard imports) criterion.\\n\\n(UI2) We don\'t report a decl as unused if it has an `as Rebindable` qualifier.\\n See (KN1) in Note [Overview of known entities] in GHC.Builtin\\n\\n\\nNote [Printing minimal imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nTo print the minimal imports we walk over all import decls (both user-supplied\\nand generated), trim their import lists, then filter out generated decls.\\n\\nNB that\\n\\n * We do *not* change the \'qualified\' or \'as\' parts!\\n\\n * We do not discard a decl altogether; we might need instances\\n from it. Instead we just trim to an empty import list\\n\\nNote [Partial export]\\n~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have\\n\\n module A( op ) where\\n class C a where\\n op :: a -> a\\n\\n module B where\\n import A\\n f = ..op...\\n\\nThen the minimal import for module B is\\n import A( op )\\nnot\\n import A( C( op ) )\\nwhich we would usually generate if C was exported from B. Hence\\nthe availExportsDecl test when deciding what to generate.\\n\\n\\nNote [Overloaded field import]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nOn the other hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n data T = MkT { foo :: Int }\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( T(foo) )\\nbecause when DuplicateRecordFields is enabled, field selectors are\\nnot in scope without their enclosing datatype.\\n\\nOn the third hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n pattern MkT { foo } = Just foo\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( foo )\\nbecause foo doesn\'t have a parent. This might actually be ambiguous if A\\nexports another field called foo, but there is no good answer to return and this\\nis a very obscure corner, so it seems to be the best we can do. See\\nDRFPatSynExport for a test of this.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Errors}\\n* *\\n************************************************************************\\n-}\\n\\nbadImportItemErr\\n :: ModIface -> ImpDeclSpec -> IE GhcPs\\n -> IsSubordinateError\\n -> [AvailInfo]\\n -> TcRn (NonEmpty ImportLookupReason)\\nbadImportItemErr iface decl_spec ie sub avails = do\\n exts <- importLookupExtensions\\n let import_lookup_bad :: BadImportKind -> ImportLookupReason\\n import_lookup_bad k = ImportLookupBad k iface decl_spec ie exts\\n dflags <- getDynFlags\\n hsc_env <- getTopEnv\\n let rdr_env = mkGlobalRdrEnv\\n $ gresFromAvails hsc_env (Just imp_spec) all_avails\\n pure $ fmap import_lookup_bad (importErrorKind dflags rdr_env)\\n where\\n importErrorKind :: DynFlags -> GlobalRdrEnv -> NonEmpty BadImportKind\\n importErrorKind dflags rdr_env\\n | any checkIfTyCon avails = case sub of\\n IsNotSubordinate -> NE.singleton BadImportAvailTyCon\\n IsSubordinateError { subordinate_err_parent = gre\\n , subordinate_err_unavailable = unavailable\\n , subordinate_err_nontype = nontype\\n , subordinate_err_nondata = nondata }\\n -> NE.fromList $ catMaybes $\\n [ fmap (BadImportNotExportedSubordinates gre) (NE.nonEmpty unavailable)\\n , fmap (BadImportNonTypeSubordinates gre) (NE.nonEmpty nontype)\\n , fmap (BadImportNonDataSubordinates gre) (NE.nonEmpty nondata) ]\\n | any checkIfVarName avails = NE.singleton BadImportAvailVar\\n | Just con <- find checkIfDataCon avails = NE.singleton (BadImportAvailDataCon (availOccName con))\\n | otherwise = NE.singleton (BadImportNotExported suggs)\\n where\\n suggs = similar_suggs ++ fieldSelectorSuggestions rdr_env rdr\\n what_look = case sub of\\n IsNotSubordinate -> WL_TyCon_or_TermVar\\n IsSubordinateError { subordinate_err_parent = gre } ->\\n case greInfo gre of\\n IAmTyCon ClassFlavour\\n -> WL_TyCon_or_TermVar\\n _ -> WL_Term\\n similar_names =\\n similarNameSuggestions (Unbound.LF what_look WL_Global)\\n dflags rdr_env emptyLocalRdrEnv rdr\\n similar_suggs =\\n case NE.nonEmpty $ mapMaybe imported_item $ similar_names of\\n Just similar -> [ SuggestSimilarNames rdr similar ]\\n Nothing -> [ ]\\n\\n -- Only keep imported items, and set the \\"HowInScope\\" to\\n -- \\"Nothing\\" to avoid printing \\"imported from...\\" in the suggestion\\n -- error message.\\n imported_item (SimilarRdrName rdr_name gre (Just (ImportedBy {})))\\n = Just (SimilarRdrName rdr_name gre Nothing)\\n imported_item _ = Nothing\\n\\n checkIfDataCon = checkIfAvailMatches isDataConName\\n checkIfTyCon = checkIfAvailMatches isTyConName\\n checkIfVarName =\\n \\\\case\\n AvailTC{} -> False\\n Avail n -> importedFS == occNameFS (occName n)\\n && (isVarOcc <||> isFieldOcc) (occName n)\\n checkIfAvailMatches namePred =\\n \\\\case\\n AvailTC _ ns ->\\n case find (\\\\n -> importedFS == occNameFS (occName n)) ns of\\n Just n -> namePred n\\n Nothing -> False\\n Avail{} -> False\\n availOccName = occName . availName\\n rdr = ieName ie\\n importedFS = occNameFS $ rdrNameOcc rdr\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n all_avails = mi_exports iface\\n\\nimportLookupExtensions :: TcRn ImportLookupExtensions\\nimportLookupExtensions = do\\n ile_pattern_synonyms <- xoptM LangExt.PatternSynonyms\\n ile_explicit_namespaces <- xoptM LangExt.ExplicitNamespaces\\n return ImportLookupExtensions{ile_pattern_synonyms, ile_explicit_namespaces}\\n\\naddDupDeclErr :: NonEmpty GlobalRdrElt -> TcRn ()\\naddDupDeclErr gres@(gre :| _)\\n -- Report the error at the later location\\n = addErrAt (getSrcSpan (NE.last sorted_names)) $ (TcRnDuplicateDecls (greOccName gre) sorted_names)\\n where\\n sorted_names =\\n NE.sortBy (SrcLoc.leftmost_smallest `on` nameSrcSpan)\\n (fmap greName gres)\\n\\n-- This data decl will parse OK\\n-- data T = a Int\\n-- treating \\"a\\" as the constructor.\\n-- It is really hard to make the parser spot this malformation.\\n-- So the renamer has to check that the constructor is legal\\n--\\n-- We can get an operator as the constructor, even in the prefix form:\\n-- data T = :% Int Int\\n-- from interface files, which always print in prefix form\\n--\\n-- We also allow type constructor names, which are defined by \\"type data\\"\\n-- declarations. See Note [Type data declarations] in GHC.Rename.Module.\\n\\ncheckConName :: RdrName -> TcRn ()\\ncheckConName name\\n = checkErr (isRdrDataCon name || isRdrTc name) (TcRnIllegalDataCon name)\\n", "filetypes": ["haskell"]}}}' 2026-10-16 14:48:01,432 - DEBUG - POST b'http://127.0.0.1:37093/receive_messages' {'content-type': 'application/json', 'x-ycm-hmac': b'Rga7Yd4l4fgfufwYw+0sxzurvznImlBO0MPmgAlS4EY='} b'{"filepath": "/home/enrico/ghc/compiler/GHC/Rename/Names.hs", "line_num": 1, "column_num": 1, "working_dir": "/home/enrico/ghc", "file_data": {"/home/enrico/ghc/compiler/GHC/Rename/Names.hs": {"contents": "{-\\n(c) The GRASP/AQUA Project, Glasgow University, 1992-1998\\n\\nExtracting imported and top-level names in scope\\n-}\\n\\n{-# LANGUAGE NondecreasingIndentation #-}\\n{-# LANGUAGE TypeFamilies #-}\\n\\nmodule GHC.Rename.Names (\\n rnImports, getLocalNonValBinders, newRecordFieldLabel,\\n importsFromIface,\\n ImportUserSpec(..),\\n extendGlobalRdrEnvRn,\\n gresFromAvails,\\n calculateAvails,\\n reportUnusedNames,\\n checkConName,\\n mkChildEnv,\\n findChildren,\\n mkBadExportSubordinate,\\n findImportUsage,\\n getMinimalImports,\\n printMinimalImports,\\n renamePkgQual, renameRawPkgQual,\\n classifyGREs,\\n ImportDeclUsage,\\n rnNamespaceSpecifier\\n ) where\\n\\nimport GHC.Prelude hiding ( head, init, last, tail )\\n\\nimport GHC.Driver.Env\\nimport GHC.Driver.Session\\nimport GHC.Driver.Ppr\\n\\nimport GHC.Rename.Env\\nimport GHC.Rename.Fixity\\nimport GHC.Rename.Utils ( warnUnusedTopBinds )\\nimport GHC.Rename.Unbound\\nimport qualified GHC.Rename.Unbound as Unbound\\n\\nimport GHC.Tc.Errors.Types\\nimport GHC.Tc.Utils.Env\\nimport GHC.Tc.Utils.Monad\\nimport GHC.Tc.Types.LclEnv\\nimport GHC.Tc.Zonk.TcType ( tcInitTidyEnv )\\n\\nimport GHC.Hs\\nimport GHC.Iface.Load ( loadSrcInterface, loadSrcInterface_maybe )\\nimport GHC.Iface.Errors.Types\\n ( IfaceMessage(..), MissingInterfaceError, InterfaceLookingFor(..)\\n , LoadEssentialsReason(..) )\\nimport GHC.Iface.Syntax ( fromIfaceWarnings )\\nimport GHC.Builtin.Modules( pRELUDE_NAME, rEBINDABLE_MOD_NAME )\\nimport GHC.Parser.PostProcess ( setRdrNameSpace )\\nimport GHC.Core.TyCo.Tidy\\nimport GHC.Core.PatSyn\\nimport GHC.Core.TyCon ( TyCon, tyConName )\\nimport qualified GHC.LanguageExtensions as LangExt\\n\\nimport GHC.Utils.Outputable as Outputable\\nimport GHC.Utils.Misc as Utils\\nimport GHC.Utils.Panic\\n\\nimport GHC.Types.Fixity.Env\\nimport GHC.Types.SafeHaskell\\nimport GHC.Types.Name\\nimport GHC.Types.Name.Env\\nimport GHC.Types.Name.Set\\nimport GHC.Types.Name.Reader\\nimport GHC.Types.Avail\\nimport GHC.Types.FieldLabel\\nimport GHC.Types.Hint\\nimport GHC.Types.SourceFile\\nimport GHC.Types.SrcLoc as SrcLoc\\nimport GHC.Types.Basic (TyConFlavour (..), convImportLevel, VisArity)\\nimport GHC.Types.UnresolvedImport\\nimport GHC.Types.Id\\nimport GHC.Types.PkgQual\\nimport GHC.Types.GREInfo (ConInfo(..), ConFieldInfo (..), ConLikeInfo (ConIsData))\\n\\nimport GHC.Unit\\nimport GHC.Unit.Module.Warnings\\nimport GHC.Unit.Module.ModIface\\nimport GHC.Unit.Module.Imported\\nimport GHC.Unit.Module.Deps\\nimport GHC.Unit.Env\\n\\nimport GHC.Data.Bag\\nimport GHC.Data.FastString\\nimport GHC.Data.FastString.Env\\nimport GHC.Data.Maybe\\nimport GHC.Data.List.SetOps ( removeDups )\\n\\nimport Control.Arrow ( second )\\nimport Control.Monad\\nimport Data.Foldable ( for_ )\\nimport Data.IntMap ( IntMap )\\nimport qualified Data.IntMap as IntMap\\nimport Data.Map ( Map )\\nimport qualified Data.Map as Map\\nimport Data.Ord ( comparing )\\nimport Data.Semigroup ( Any(..) )\\nimport qualified Data.Semigroup as S\\nimport Data.List ( partition, find, sortBy )\\nimport Data.List.NonEmpty (NonEmpty(..))\\nimport qualified Data.List.NonEmpty as NE\\nimport Data.Function ( on )\\nimport qualified Data.Set as S\\nimport System.FilePath (())\\nimport System.IO\\n\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{rnImports}\\n* *\\n************************************************************************\\n\\nNote [Tracking Trust Transitively]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen we import a package as well as checking that the direct imports are safe\\naccording to the rules outlined in the Note [Safe Haskell Trust Check] in GHC.Driver.Main\\nwe must also check that these rules hold transitively for all dependent modules\\nand packages. Doing this without caching any trust information would be very\\nslow as we would need to touch all packages and interface files a module depends\\non. To avoid this we make use of the property that if a modules Safe Haskell\\nmode changes, this triggers a recompilation from that module in the dependency\\ngraph. So we can just worry mostly about direct imports.\\n\\nThere is one trust property that can change for a package though without\\nrecompilation being triggered: package trust. So we must check that all\\npackages a module transitively depends on to be trusted are still trusted when\\nwe are compiling this module (as due to recompilation avoidance some modules\\nbelow may not be considered trusted any more without recompilation being\\ntriggered).\\n\\nWe handle this by augmenting the existing transitive list of packages a module M\\ndepends on with a bool for each package that says if it must be trusted when the\\nmodule M is being checked for trust. This list of trust required packages for a\\nsingle import is gathered in the rnImportDecl function and stored in an\\nImportAvails data structure. The union of these trust required packages for all\\nimports is done by the rnImports function using the combine function which calls\\nthe plusImportAvails function that is a union operation for the ImportAvails\\ntype. This gives us in an ImportAvails structure all packages required to be\\ntrusted for the module we are currently compiling. Checking that these packages\\nare still trusted (and that direct imports are trusted) is done in\\nGHC.Driver.Main.checkSafeImports.\\n\\nSee the note below, [Trust Own Package] for a corner case in this method and\\nhow its handled.\\n\\n\\nNote [Trust Own Package]\\n~~~~~~~~~~~~~~~~~~~~~~~~\\nThere is a corner case of package trust checking that the usual transitive check\\ndoesn\'t cover. (For how the usual check operates see the Note [Tracking Trust\\nTransitively] below). The case is when you import a -XSafe module M and M\\nimports a -XTrustworthy module N. If N resides in a different package than M,\\nthen the usual check works as M will record a package dependency on N\'s package\\nand mark it as required to be trusted. If N resides in the same package as M\\nthough, then importing M should require its own package be trusted due to N\\n(since M is -XSafe so doesn\'t create this requirement by itself). The usual\\ncheck fails as a module doesn\'t record a package dependency of its own package.\\nSo instead we now have a bool field in a modules interface file that simply\\nstates if the module requires its own package to be trusted. This field avoids\\nus having to load all interface files that the module depends on to see if one\\nis trustworthy.\\n\\n\\nNote [Trust Transitive Property]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSo there is an interesting design question in regards to transitive trust\\nchecking. Say I have a module B compiled with -XSafe. B is dependent on a bunch\\nof modules and packages, some packages it requires to be trusted as its using\\n-XTrustworthy modules from them. Now if I have a module A that doesn\'t use safe\\nhaskell at all and simply imports B, should A inherit all the trust\\nrequirements from B? Should A now also require that a package p is trusted since\\nB required it?\\n\\nWe currently say no but saying yes also makes sense. The difference is, if a\\nmodule M that doesn\'t use Safe Haskell imports a module N that does, should all\\nthe trusted package requirements be dropped since M didn\'t declare that it cares\\nabout Safe Haskell (so -XSafe is more strongly associated with the module doing\\nthe importing) or should it be done still since the author of the module N that\\nuses Safe Haskell said they cared (so -XSafe is more strongly associated with\\nthe module that was compiled that used it).\\n\\nGoing with yes is a simpler semantics we think and harder for the user to stuff\\nup but it does mean that Safe Haskell will affect users who don\'t care about\\nSafe Haskell as they might grab a package from Cabal which uses safe haskell (say\\nnetwork) and that packages imports -XTrustworthy modules from another package\\n(say bytestring), so requires that package is trusted. The user may now get\\ncompilation errors in code that doesn\'t do anything with Safe Haskell simply\\nbecause they are using the network package. They will have to call \'ghc-pkg\\ntrust network\' to get everything working. Due to this invasive nature of going\\nwith yes we have gone with no for now.\\n-}\\n\\n-- | Process Import Decls. See \'rnImportDecl\' for a description of what\\n-- the return types represent.\\n-- Note: Do the non SOURCE ones first, so that we get a helpful warning\\n-- for SOURCE ones that are unnecessary\\nrnImports :: [(LImportDecl GhcPs, SDoc)]\\n -> RnM ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\nrnImports imports = do\\n tcg_env <- getGblEnv\\n -- NB: want an identity module here, because it\'s OK for a signature\\n -- module to import from its implementor\\n let this_mod = tcg_mod tcg_env\\n let (source, ordinary) = partition (is_source_import . fst) imports\\n is_source_import (d::LImportDecl GhcPs) = ideclSource (unLoc d) == IsBoot\\n stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary\\n stuff2 <- mapAndReportM (rnImportDecl this_mod) source\\n -- Safe Haskell: See Note [Tracking Trust Transitively]\\n let (decls, imp_user_spec, rdr_env, imp_avails) = combine (stuff1 ++ stuff2)\\n -- Update imp_boot_mods if imp_direct_mods mentions any of them\\n let merged_import_avail = clobberSourceImports imp_avails\\n return (decls, imp_user_spec, rdr_env, merged_import_avail)\\n\\n where\\n clobberSourceImports imp_avails =\\n imp_avails { imp_boot_mods = imp_boot_mods\' }\\n where\\n imp_boot_mods\' = mergeInstalledModuleEnv combJ id (const emptyInstalledModuleEnv)\\n (imp_boot_mods imp_avails)\\n (imp_direct_dep_mods imp_avails)\\n\\n combJ (GWIB _ IsBoot) (_, x) = Just x\\n combJ r _ = Just r\\n -- See Note [Combining ImportAvails]\\n combine :: [(LImportDecl GhcRn, ImportUserSpec, GlobalRdrEnv, ImportAvails)]\\n -> ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\n combine ss =\\n let (decls, imp_user_spec, rdr_env, imp_avails, finsts) = foldr\\n plus\\n ([], [], emptyGlobalRdrEnv, emptyImportAvails, emptyModuleSet)\\n ss\\n in (decls, imp_user_spec, rdr_env, imp_avails { imp_finsts = moduleSetElts finsts })\\n\\n plus (decl, us, gbl_env1, imp_avails1)\\n (decls, uss, gbl_env2, imp_avails2, finsts_set)\\n = ( decl:decls,\\n us:uss,\\n gbl_env1 `plusGlobalRdrEnv` gbl_env2,\\n imp_avails1\' `plusImportAvails` imp_avails2,\\n extendModuleSetList finsts_set new_finsts )\\n where\\n imp_avails1\' = imp_avails1 { imp_finsts = [] }\\n new_finsts = imp_finsts imp_avails1\\n\\n{-\\nNote [Combining ImportAvails]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nimp_finsts in ImportAvails is a list of family instance modules\\ntransitively depended on by an import. imp_finsts for a currently\\ncompiled module is a union of all the imp_finsts of imports.\\nComputing the union of two lists of size N is O(N^2) and if we\\ndo it to M imports we end up with O(M*N^2). That can get very\\nexpensive for bigger module hierarchies.\\n\\nUnion can be optimized to O(N log N) if we use a Set.\\nimp_finsts is converted back and forth between dep_finsts, so\\nchanging a type of imp_finsts means either paying for the conversions\\nor changing the type of dep_finsts as well.\\n\\nI\'ve measured that the conversions would cost 20% of allocations on my\\ntest case, so that can be ruled out.\\n\\nChanging the type of dep_finsts forces checkFamInsts to\\nget the module lists in non-deterministic order. If we wanted to restore\\nthe deterministic order, we\'d have to sort there, which is an additional\\ncost. As far as I can tell, using a non-deterministic order is fine there,\\nbut that\'s a brittle nonlocal property which I\'d like to avoid.\\n\\nAdditionally, dep_finsts is read from an interface file, so its \\"natural\\"\\ntype is a list. Which makes it a natural type for imp_finsts.\\n\\nSince rnImports.combine is really the only place that would benefit from\\nit being a Set, it makes sense to optimize the hot loop in rnImports.combine\\nwithout changing the representation.\\n\\nSo here\'s what we do: instead of naively merging ImportAvails with\\nplusImportAvails in a loop, we make plusImportAvails merge empty imp_finsts\\nand compute the union on the side using Sets. When we\'re done, we can\\nconvert it back to a list. One nice side effect of this approach is that\\nif there\'s a lot of overlap in the imp_finsts of imports, the\\nSet doesn\'t really need to grow and we don\'t need to allocate.\\n\\nRunning generateModules from #14693 with DEPTH=16, WIDTH=30 finishes in\\n23s before, and 11s after.\\n-}\\n\\n-- | Given a located import declaration @decl@ from @this_mod@,\\n-- calculate the following pieces of information:\\n--\\n-- 1. An updated \'LImportDecl\', where all unresolved \'RdrName\' in\\n-- the entity lists have been resolved into \'Name\'s,\\n--\\n-- 2. A \'GlobalRdrEnv\' representing the new identifiers that were\\n-- brought into scope (taking into account module qualification\\n-- and hiding),\\n--\\n-- 3. \'ImportAvails\' summarizing the identifiers that were imported\\n-- by this declaration, and\\n--\\n-- 4. A boolean \'AnyHpcUsage\' which is true if the imported module\\n-- used HPC.\\nrnImportDecl :: Module -> (LImportDecl GhcPs, SDoc)\\n -> RnM (LImportDecl GhcRn, ImportUserSpec , GlobalRdrEnv, ImportAvails)\\nrnImportDecl this_mod\\n (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name\\n , ideclPkgQual = raw_pkg_qual\\n , ideclSource = want_boot\\n , ideclSafe = mod_safe\\n , ideclLevelSpec = import_level\\n , ideclQualified = qual_style\\n , ideclExt = XImportDeclPass { ideclOrigin = origin }\\n , ideclAs = as_mod, ideclImportList = imp_details }), import_reason)\\n = setSrcSpanA loc $ do\\n\\n case raw_pkg_qual of\\n NoRawPkgQual -> pure ()\\n RawPkgQual {} -> do\\n pkg_imports <- xoptM LangExt.PackageImports\\n when (not pkg_imports) $ addErr TcRnPackageImportsDisabled\\n\\n let qual_only = isImportDeclQualified qual_style\\n generated = isGeneratedImport origin\\n\\n lookup_scope = importDeclLookupScope origin\\n\\n -- If there\'s an error in loadInterface, (e.g. interface\\n -- file not found) we get lots of spurious errors from \'filterImports\'\\n let imp_mod_name = unLoc loc_imp_mod_name\\n doc = ppr imp_mod_name <+> import_reason\\n\\n hsc_env <- getTopEnv\\n unit_env <- hsc_unit_env <$> getTopEnv\\n let pkg_qual = renameRawPkgQual unit_env imp_mod_name raw_pkg_qual\\n\\n -- Check for self-import, which confuses the typechecker (#9032)\\n -- ghc --make rejects self-import cycles already, but batch-mode may not\\n -- at least not until GHC.IfaceToCore.tcHiBootIface, which is too late to avoid\\n -- typechecker crashes. (Indirect self imports are not caught until\\n -- GHC.IfaceToCore, see #10337 tracking how to make this error better.)\\n --\\n -- Originally, we also allowed \'import {-# SOURCE #-} M\', but this\\n -- caused bug #10182: in one-shot mode, we should never load an hs-boot\\n -- file for the module we are compiling into the EPS. In principle,\\n -- it should be possible to support this mode of use, but we would have to\\n -- extend Provenance to support a local definition in a qualified location.\\n -- For now, we don\'t support it, but see #10336\\n when (imp_mod_name == moduleName this_mod &&\\n (case pkg_qual of -- If we have import \\"\\" M, then we should\\n -- check that \\"\\" is \\"this\\" (which is magic)\\n -- or the name of this_mod\'s package. Yurgh!\\n -- c.f. GHC.findModule, and #9997\\n NoPkgQual -> True\\n ThisPkg uid -> uid == homeUnitId_ (hsc_dflags hsc_env)\\n OtherPkg _ -> False))\\n (addErr (TcRnSelfImport imp_mod_name))\\n\\n -- Check for a missing import list (Opt_WarnMissingImportList also\\n -- checks for T(..) items but that is done in checkDodgyImport below)\\n case imp_details of\\n Just (Exactly, _) -> return () -- Explicit import list\\n _ | generated -> return () -- Do not bleat for generated imports\\n | qual_only -> return ()\\n | otherwise -> addDiagnostic (TcRnNoExplicitImportList imp_mod_name)\\n\\n\\n mb_iface <- loadSrcInterface_maybe doc lookup_scope imp_mod_name want_boot pkg_qual\\n iface <- case mb_iface of\\n Succeeded iface -> return iface\\n Failed err -> failWithTc $\\n importDeclLoadFailure origin imp_mod_name want_boot err\\n\\n -- Compiler sanity check: if the import didn\'t say\\n -- {-# SOURCE #-} we should not get a hi-boot file\\n warnPprTrace ((want_boot == NotBoot) && (mi_boot iface == IsBoot)) \\"rnImportDecl\\" (ppr imp_mod_name) $ do\\n\\n -- Issue a user warning for a redundant {- SOURCE -} import\\n -- NB that we arrange to read all the ordinary imports before\\n -- any of the {- SOURCE -} imports.\\n --\\n -- in --make and GHCi, the compilation manager checks for this,\\n -- and indeed we shouldn\'t do it here because the existence of\\n -- the non-boot module depends on the compilation order, which\\n -- is not deterministic. The hs-boot test can show this up.\\n dflags <- getDynFlags\\n warnIf ((want_boot == IsBoot) && (mi_boot iface == NotBoot) && isOneShot (ghcMode dflags))\\n (TcRnRedundantSourceImport imp_mod_name)\\n when (mod_safe && not (safeImportsOn dflags)) $\\n addErr (TcRnSafeImportsDisabled imp_mod_name)\\n\\n let imp_mod = mi_module iface\\n qual_mod_name = fmap unLoc as_mod `orElse` imp_mod_name\\n imp_spec = ImpDeclSpec { is_mod = imp_mod, is_qual = qual_only,\\n is_dloc = locA loc, is_as = qual_mod_name,\\n is_pkg_qual = pkg_qual, is_isboot = want_boot,\\n is_level = convImportLevel import_level }\\n\\n let filter_imports = do\\n -- filter the imports according to the import declaration\\n (new_imp_details, imp_user_list, gbl_env)\\n <- filterImports hsc_env iface imp_spec imp_details\\n -- for certain error messages, we\\u2019d like to know what could be\\n -- imported here, if everything were imported\\n potential_gres <- (\\\\(_,_,x) -> x) <$> filterImports hsc_env iface imp_spec Nothing\\n return (new_imp_details, imp_user_list, gbl_env, potential_gres)\\n\\n (new_imp_details, imp_user_list, gbl_env, potential_gres) <-\\n case origin of\\n ImplicitEssentialsImport ->\\n -- The implicit GHC.Essentials import does not bring anything into scope.\\n -- See Note [Finding GHC.Essentials] in GHC.Builtin.\\n return (Nothing, ImpUserDependOnly, emptyGlobalRdrEnv, emptyGlobalRdrEnv)\\n UserWrittenImport -> filter_imports\\n ImplicitPreludeImport -> filter_imports\\n PluginImport -> filter_imports\\n\\n let is_hiding | Just (EverythingBut,_) <- imp_details = True\\n | otherwise = False\\n\\n -- should the import be safe?\\n mod_safe\' = mod_safe\\n || (not generated && safeDirectImpsReq dflags)\\n || (generated && safeImplicitImpsReq dflags)\\n\\n hsc_env <- getTopEnv\\n let home_unit = hsc_home_unit hsc_env\\n other_home_units = hsc_all_home_unit_ids hsc_env\\n\\n imported_by\\n | isDependOnlyImport imp_user_list\\n = ImportedBySystem\\n | otherwise\\n = ImportedByUser $ ImportedModsVal\\n { imv_name = is_as imp_spec\\n , imv_span = locA loc\\n , imv_is_safe = mod_safe\'\\n , imv_is_hiding = is_hiding\\n , imv_all_exports = potential_gres\\n , imv_qualified = qual_only\\n , imv_is_level = convImportLevel import_level\\n }\\n imports = calculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by\\n\\n -- Complain if we import a deprecated module\\n case fromIfaceWarnings (mi_warns iface) of\\n WarnAll txt -> addDiagnostic (TcRnDeprecatedModule imp_mod_name txt)\\n _ -> return ()\\n\\n let new_imp_decl = ImportDecl\\n { ideclExt = ideclExt decl\\n , ideclName = ideclName decl\\n , ideclPkgQual = pkg_qual\\n , ideclSource = ideclSource decl\\n , ideclSafe = mod_safe\'\\n , ideclQualified = ideclQualified decl\\n , ideclAs = ideclAs decl\\n , ideclImportList = new_imp_details\\n , ideclLevelSpec = ideclLevelSpec decl\\n }\\n\\n return (L loc new_imp_decl, ImpUserSpec imp_spec imp_user_list, gbl_env, imports)\\n\\n-- | The error message to emit when we failed to load an interface.\\nimportDeclLoadFailure :: ImportDeclOrigin -> ModuleName -> IsBootInterface\\n -> MissingInterfaceError -> TcRnMessage\\nimportDeclLoadFailure ImplicitEssentialsImport _ _ err\\n = TcRnInterfaceError $ CantFindEssentials err LookingForEssentialsModule\\nimportDeclLoadFailure _ mod_name want_boot err\\n = TcRnInterfaceError $ Can\'tFindInterface err $ LookingForModule mod_name want_boot\\n\\n-- | Rename raw package imports\\nrenameRawPkgQual :: UnitEnv -> ModuleName -> RawPkgQual -> PkgQual\\nrenameRawPkgQual unit_env mn = \\\\case\\n NoRawPkgQual -> NoPkgQual\\n RawPkgQual _ fs -> renamePkgQual unit_env mn $ Just fs\\n\\n-- | Rename raw package imports\\nrenamePkgQual :: UnitEnv -> ModuleName -> Maybe FastString -> PkgQual\\nrenamePkgQual unit_env mn mb_pkg = case mb_pkg of\\n Nothing -> NoPkgQual\\n Just pkg_fs\\n | Just uid <- homeUnitId <$> ue_homeUnit unit_env\\n , pkg_fs == fsLit \\"this\\"\\n -> ThisPkg uid\\n\\n | Just (uid, _) <- find (fromMaybe False . fmap (== pkg_fs) . snd) home_names\\n -> ThisPkg uid\\n\\n | Just uid <- resolvePackageImport unit_state mn (PackageName pkg_fs)\\n -> OtherPkg uid\\n\\n | otherwise\\n -> OtherPkg (UnitId pkg_fs)\\n -- not really correct as pkg_fs is unlikely to be a valid unit-id but\\n -- we will report the failure later...\\n where\\n home_names =\\n [ (uid, mkFastString <$> thisPackageName (homeUnitEnv_dflags (ue_findHomeUnitEnv uid unit_env)))\\n | uid <- S.toList hpt_deps\\n ]\\n\\n unit_state = ue_homeUnitState unit_env\\n\\n hpt_deps :: S.Set UnitId\\n hpt_deps = homeUnitDepends unit_state\\n\\n\\n-- | Calculate the \'ImportAvails\' induced by an import of a particular\\n-- interface, but without \'imp_mods\'.\\ncalculateAvails :: HomeUnit\\n -> S.Set UnitId\\n -> ModIface\\n -> IsSafeImport\\n -> IsBootInterface\\n -> ImportedBy\\n -> ImportAvails\\ncalculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by =\\n let imp_mod = mi_module iface\\n imp_sem_mod= mi_semantic_module iface\\n orph_iface = mi_orphan iface\\n has_finsts = mi_finsts iface\\n deps = mi_deps iface\\n trust = getSafeMode $ mi_trust iface\\n trust_pkg = mi_trust_pkg iface\\n is_sig = mi_hsc_src iface == HsigFile\\n\\n -- If the module exports anything defined in this module, just\\n -- ignore it. Reason: otherwise it looks as if there are two\\n -- local definition sites for the thing, and an error gets\\n -- reported. Easiest thing is just to filter them out up\\n -- front. This situation only arises if a module imports\\n -- itself, or another module that imported it. (Necessarily,\\n -- this involves a loop.)\\n --\\n -- We do this *after* filterImports, so that if you say\\n -- module A where\\n -- import B( AType )\\n -- type AType = ...\\n --\\n -- module B( AType ) where\\n -- import {-# SOURCE #-} A( AType )\\n --\\n -- then you won\'t get a \'B does not export AType\' message.\\n\\n\\n -- Compute new transitive dependencies\\n --\\n -- \'dep_orphs\' and \'dep_finsts\' do NOT include the imported module\\n -- itself, but we DO need to include this module in \'imp_orphs\' and\\n -- \'imp_finsts\' if it defines an orphan or instance family; thus the\\n -- orph_iface/has_iface tests.\\n\\n deporphs = dep_orphs deps\\n depfinsts = dep_finsts deps\\n\\n orphans | orph_iface = assertPpr (not (imp_sem_mod `elem` deporphs)) (ppr imp_sem_mod <+> ppr deporphs) $\\n imp_sem_mod : deporphs\\n | otherwise = deporphs\\n\\n finsts | has_finsts = assertPpr (not (imp_sem_mod `elem` depfinsts)) (ppr imp_sem_mod <+> ppr depfinsts) $\\n imp_sem_mod : depfinsts\\n | otherwise = depfinsts\\n\\n -- Trusted packages are a lot like orphans.\\n trusted_pkgs | mod_safe\' = dep_trusted_pkgs deps\\n | otherwise = S.empty\\n\\n\\n pkg = moduleUnit (mi_module iface)\\n ipkg = toUnitId pkg\\n\\n -- Does this import mean we now require our own pkg\\n -- to be trusted? See Note [Trust Own Package]\\n ptrust = trust == Sf_Trustworthy || trust_pkg\\n pkg_trust_req\\n | isHomeUnit home_unit pkg = ptrust\\n | otherwise = False\\n\\n dependent_pkgs = if toUnitId pkg `S.member` other_home_units\\n then S.empty\\n else S.singleton (lvl, ipkg)\\n\\n lvl = case imported_by of\\n ImportedByUser imv -> imv_is_level imv\\n ImportedBySystem -> NormalLevel\\n\\n\\n direct_mods = if toUnitId pkg `S.member` other_home_units\\n then mkPlusModDeps (moduleUnitId imp_mod) lvl (GWIB (moduleName imp_mod) want_boot)\\n else emptyInstalledModuleEnv\\n\\n dep_boot_mods_map = mkModDeps (dep_boot_mods deps)\\n\\n\\n boot_mods\\n -- If we are looking for a boot module, it must be HPT\\n | IsBoot <- want_boot = extendInstalledModuleEnv dep_boot_mods_map (toUnitId <$> imp_mod) (GWIB (moduleName imp_mod) IsBoot)\\n -- Now we are importing A properly, so don\'t go looking for\\n -- A.hs-boot\\n | isHomeUnit home_unit pkg = dep_boot_mods_map\\n -- There\'s no boot files to find in external imports\\n | otherwise = emptyInstalledModuleEnv\\n\\n sig_mods =\\n if is_sig\\n then moduleName imp_mod : dep_sig_mods deps\\n else dep_sig_mods deps\\n\\n\\n in ImportAvails {\\n imp_mods = Map.singleton (mi_module iface) [imported_by],\\n imp_orphs = orphans,\\n imp_finsts = finsts,\\n imp_sig_mods = sig_mods,\\n imp_direct_dep_mods = direct_mods,\\n imp_dep_direct_pkgs = dependent_pkgs,\\n imp_boot_mods = boot_mods,\\n\\n -- Add in the imported modules trusted package\\n -- requirements. ONLY do this though if we import the\\n -- module as a safe import.\\n -- See Note [Tracking Trust Transitively]\\n -- and Note [Trust Transitive Property]\\n imp_trust_pkgs = trusted_pkgs,\\n -- Do we require our own pkg to be trusted?\\n -- See Note [Trust Own Package]\\n imp_trust_own_pkg = pkg_trust_req\\n }\\n\\nmkPlusModDeps :: UnitId -> ImportLevel -> ModuleNameWithIsBoot\\n -> InstalledModuleEnv (S.Set ImportLevel, ModuleNameWithIsBoot)\\nmkPlusModDeps uid st elt = extendInstalledModuleEnv emptyInstalledModuleEnv (mkModule uid (gwib_mod elt)) (S.singleton st, elt)\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{importsFromLocalDecls}\\n* *\\n************************************************************************\\n\\nFrom the top-level declarations of this module produce\\n * the lexical environment\\n * the ImportAvails\\ncreated by its bindings.\\n\\nNote [Top-level Names in Template Haskell decl quotes]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSee also: Note [Interactively-bound Ids in GHCi] in GHC.Driver.Env\\n Note [Looking up Exact RdrNames] in GHC.Rename.Env\\n\\nConsider a Template Haskell declaration quotation like this:\\n module M where\\n f x = h [d| f = 3 |]\\nWhen renaming the declarations inside [d| ...|], we treat the\\ntop level binders specially in two ways\\n\\n1. We give them an Internal Name, not (as usual) an External one.\\n This is done by GHC.Rename.Env.newTopSrcBinder.\\n\\n2. We make them *shadow* the outer bindings.\\n See Note [GlobalRdrEnv shadowing]\\n\\n3. We find out whether we are inside a [d| ... |] by testing the TH\\n level. This is a slight hack, because the level field was really\\n meant for the type checker, and here we are not interested in the\\n fields of Brack, hence the error thunks in thRnBrack.\\n-}\\n\\nextendGlobalRdrEnvRn :: [GlobalRdrElt]\\n -> MiniFixityEnv\\n -> RnM (TcGblEnv, TcLclEnv)\\n-- Updates both the GlobalRdrEnv and the FixityEnv\\n-- We return a new TcLclEnv only because we might have to\\n-- delete some bindings from it;\\n-- see Note [Top-level Names in Template Haskell decl quotes]\\n\\nextendGlobalRdrEnvRn new_gres new_fixities\\n = checkNoErrs $ -- See Note [Fail fast on duplicate definitions]\\n do { (gbl_env, lcl_env) <- getEnvs\\n ; level <- getThLevel\\n ; isGHCi <- getIsGHCi\\n ; let rdr_env = tcg_rdr_env gbl_env\\n fix_env = tcg_fix_env gbl_env\\n th_bndrs = getLclEnvThBndrs lcl_env\\n th_lvl = thLevelIndex level\\n\\n -- Delete new_occs from global and local envs\\n -- If we are in a TemplateHaskell decl bracket,\\n -- we are going to shadow them\\n -- See Note [GlobalRdrEnv shadowing]\\n inBracket = isBrackLevel level\\n\\n lcl_env_TH = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_rdr = minusLocalRdrEnv (tcl_rdr lcl_env) new_gres_env }) lcl_env\\n -- See Note [GlobalRdrEnv shadowing]\\n\\n lcl_env2 | inBracket = lcl_env_TH\\n | otherwise = lcl_env\\n\\n -- Deal with shadowing: see Note [GlobalRdrEnv shadowing]\\n want_shadowing = isGHCi || inBracket\\n rdr_env1 | want_shadowing = shadowNames False rdr_env new_gres_env\\n | otherwise = rdr_env\\n\\n lcl_env3 = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_th_bndrs = extendNameEnvList th_bndrs\\n [ ( n, (TopLevel, th_lvl) )\\n | n <- new_names ] }) lcl_env2\\n\\n ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres\\n\\n ; let fix_env\' = foldl\' extend_fix_env fix_env new_gres\\n gbl_env\' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env\' }\\n\\n ; traceRn \\"extendGlobalRdrEnvRn 2\\" (pprGlobalRdrEnv True rdr_env2)\\n ; return (gbl_env\', lcl_env3) }\\n where\\n new_names = map greName new_gres\\n new_gres_env = mkGlobalRdrEnv new_gres\\n\\n -- If there is a fixity decl for the gre, add it to the fixity env\\n extend_fix_env fix_env gre\\n | Just (L _ fi) <- lookupMiniFixityEnv new_fixities name\\n = extendNameEnv fix_env name (FixItem occ fi)\\n | otherwise\\n = fix_env\\n where\\n name = greName gre\\n occ = greOccName gre\\n\\n add_gre :: GlobalRdrEnv -> GlobalRdrElt -> RnM GlobalRdrEnv\\n -- Extend the GlobalRdrEnv with a LocalDef GRE\\n -- If there is already a LocalDef GRE with the same OccName,\\n -- report an error and discard the new GRE\\n -- This establishes INVARIANT 1 of GlobalRdrEnvs\\n add_gre env gre\\n | not (null dups) -- Same OccName defined twice\\n = do { addDupDeclErr (gre :| dups); return env }\\n\\n | otherwise\\n = return (extendGlobalRdrEnv env gre)\\n where\\n -- See Note [Reporting duplicate local declarations]\\n dups = filter isBadDupGRE\\n $ lookupGRE env (LookupOccName (greOccName gre) (RelevantGREsFOS WantBoth))\\n isBadDupGRE old_gre = isLocalGRE old_gre && greClashesWith gre old_gre\\n\\n{- Note [Fail fast on duplicate definitions]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIf there are duplicate bindings for the same thing, we want to fail\\nfast. Having two bindings for the same thing can cause follow-on errors.\\nExample (test T9975a):\\n data Test = Test { x :: Int }\\n pattern Test wat = Test { x = wat }\\nThis defines \'Test\' twice. The second defn has no field-names; and then\\nwe get an error from Test { x=wat }, saying \\"Test has no field \'x\'\\".\\n\\nEasiest thing is to bale out fast on duplicate definitions, which\\nwe do via `checkNoErrs` on `extendGlobalRdrEnvRn`.\\n\\nNote [Reporting duplicate local declarations]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn general, a single module may not define the same OccName multiple times. This\\nis checked in extendGlobalRdrEnvRn: when adding a new locally-defined GRE to the\\nGlobalRdrEnv we report an error if there are already duplicates in the\\nenvironment. This establishes INVARIANT 1 (see comments on GlobalRdrEnv in\\nGHC.Types.Name.Reader), which says that for a given OccName, all the\\nGlobalRdrElts to which it maps must have distinct \'greName\'s.\\n\\nFor example, the following will be rejected:\\n\\n f x = x\\n g x = x\\n f x = x -- Duplicate!\\n\\nUsers are allowed to introduce new GREs with the same OccName as an imported GRE,\\nas disambiguation is possible through the module system, e.g.:\\n\\n module M where\\n import N (f)\\n f x = x\\n g x = M.f x + N.f x\\n\\nIf both GREs are local, the general rule is that two GREs clash if they have\\nthe same OccName, i.e. they share a textual name and live in the same namespace.\\nHowever, there are additional clashes due to record fields:\\n\\n - a new variable clashes with previously defined record fields\\n which define field selectors,\\n\\n - a new record field shadows:\\n\\n - previously defined variables, if it defines a field selector,\\n - previously defined record fields, unless it is a duplicate record field.\\n\\nThis logic is implemented in the function \'GHC.Types.Name.Reader.greClashesWith\'.\\n\\nSee also Note [Skipping ambiguity errors at use sites of local declarations] in\\nGHC.Rename.Utils.\\n-}\\n\\n\\n{- *********************************************************************\\n* *\\n getLocalDeclBindersd@ returns the names for an HsDecl\\n It\'s used for source code.\\n\\n *** See Note [The Naming story] in GHC.Hs.Decls ****\\n* *\\n********************************************************************* -}\\n\\ngetLocalNonValBinders :: MiniFixityEnv -> HsGroup GhcPs\\n -> RnM ((TcGblEnv, TcLclEnv), NameSet)\\n-- Get all the top-level binders bound the group *except*\\n-- for value bindings, which are treated separately\\n-- Specifically we return AvailInfo for\\n-- * type decls (incl constructors and record selectors)\\n-- * class decls (including class ops)\\n-- * associated types\\n-- * foreign imports\\n-- * value signatures (in hs-boot files only)\\n\\ngetLocalNonValBinders fixity_env\\n (HsGroup { hs_valds = binds,\\n hs_tyclds = tycl_decls,\\n hs_fords = foreign_decls })\\n = do { -- Process all type/class decls *except* family instances\\n ; let inst_decls = tycl_decls >>= group_instds\\n ; dup_fields_ok <- xopt_DuplicateRecordFields <$> getDynFlags\\n ; has_sel <- xopt_FieldSelectors <$> getDynFlags\\n ; tc_gres\\n <- concatMapM\\n (new_tc dup_fields_ok has_sel)\\n (tyClGroupTyClDecls tycl_decls)\\n ; traceRn \\"getLocalNonValBinders 1\\" (ppr tc_gres)\\n ; envs <- extendGlobalRdrEnvRn tc_gres fixity_env\\n ; restoreEnvs envs $ do {\\n -- Bring these things into scope first\\n -- See Note [Looking up family names in family instances]\\n\\n -- Process all family instances\\n -- to bring new data constructors into scope\\n ; nti_gress <- mapM (new_assoc dup_fields_ok has_sel) inst_decls\\n\\n -- Finish off with value binders:\\n -- foreign decls and pattern synonyms for an ordinary module\\n -- type sigs in case of a hs-boot file only\\n ; is_boot <- tcIsHsBootOrSig\\n ; let val_bndrs\\n | is_boot = case binds of\\n ValBinds _ val_binds ->\\n -- In a hs-boot file, the value binders come from the\\n -- *signatures*, and there should be no foreign binders\\n [ L (l2l decl_loc) (unLoc n)\\n | L decl_loc (TypeSig _ _ ns _) <- (val_sigs val_binds), n <- ns]\\n _ -> panic \\"Non-ValBinds in hs-boot group\\"\\n | otherwise = for_hs_bndrs\\n ; val_gres <- mapM new_simple val_bndrs\\n\\n ; let avails = concat nti_gress ++ val_gres\\n new_bndrs = gresToNameSet avails `unionNameSet`\\n gresToNameSet tc_gres\\n ; traceRn \\"getLocalNonValBinders 2\\" (ppr avails)\\n ; envs <- extendGlobalRdrEnvRn avails fixity_env\\n ; return (envs, new_bndrs) } }\\n where\\n for_hs_bndrs :: [LocatedN RdrName]\\n for_hs_bndrs = hsForeignDeclsBinders foreign_decls\\n\\n -- the SrcSpan attached to the input should be the span of the\\n -- declaration, not just the name\\n new_simple :: LocatedN RdrName -> RnM GlobalRdrElt\\n new_simple rdr_name = do { nm <- newTopSrcBinder rdr_name\\n ; return (mkLocalVanillaGRE NoParent nm) }\\n\\n new_tc :: DuplicateRecordFields -> FieldSelectors -> LTyClDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_tc dup_fields_ok has_sel tc_decl -- NOT for type/data instances\\n = do { let TyDeclBinders (main_bndr, tc_flav) at_bndrs sig_bndrs\\n (LConsWithFields cons_with_flds flds) = hsLTyClDeclBinders tc_decl\\n ; tycon_name <- newTopSrcBinder $ la2la main_bndr\\n ; at_names <- mapM (newTopSrcBinder . la2la . fst) at_bndrs\\n ; sig_names <- mapM (newTopSrcBinder . la2la) sig_bndrs\\n ; con_names_with_flds <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst con_names_with_flds) flds\\n ; mapM_ (add_dup_fld_errs flds\') con_names_with_flds\\n ; let tc_gre = mkLocalTyConGRE (fmap (const tycon_name) tc_flav) tycon_name\\n fld_env = mk_fld_env con_names_with_flds flds\'\\n at_gres = zipWith (\\\\ (_, at_flav) at_nm -> mkLocalTyConGRE (fmap (const tycon_name) at_flav) at_nm)\\n at_bndrs at_names\\n sig_gres = map (mkLocalVanillaGRE (ParentIs tycon_name)) sig_names\\n con_gres = map (mkLocalConLikeGRE (ParentIs tycon_name)) fld_env\\n fld_gres = mkLocalFieldGREs (ParentIs tycon_name) fld_env\\n sub_gres = at_gres ++ sig_gres ++ con_gres ++ fld_gres\\n ; traceRn \\"getLocalNonValBinders new_tc\\" $\\n vcat [ text \\"tycon:\\" <+> ppr tycon_name\\n , text \\"tc_gre:\\" <+> ppr tc_gre\\n , text \\"sub_gres:\\" <+> ppr sub_gres ]\\n ; return $ tc_gre : sub_gres }\\n\\n -- Calculate the record field information, which feeds into the GlobalRdrElts\\n -- for DataCons and their fields. It\'s convenient to do this here where\\n -- we are working with a single datatype definition.\\n --\\n -- The information we needed was all set up for us:\\n -- see Note [Collecting record fields in data declarations] in GHC.Hs.Utils.\\n mk_fld_env :: [(Name, Either VisArity [Located Int])] -> IntMap FieldLabel\\n -> [(ConLikeName, ConInfo)]\\n mk_fld_env names flds =\\n [ (DataConName con, ConInfo (ConIsData (map fst names)) fld_info)\\n | (con, con_fl_indxs) <- names\\n , let fld_info = case fmap (map ((flds IntMap.!) . unLoc)) con_fl_indxs of\\n Left 0 -> ConIsNullary\\n Left arity -> ConHasPositionalArgs arity\\n Right [] -> ConIsNullary\\n Right (fld:flds) -> ConHasRecordFields $ fld NE.:| flds ]\\n\\n new_assoc :: DuplicateRecordFields -> FieldSelectors -> LInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_assoc _ _ (L _ (TyFamInstD {})) = return []\\n -- type instances don\'t bind new names\\n\\n new_assoc dup_fields_ok has_sel (L _ (DataFamInstD _ d))\\n = new_di dup_fields_ok has_sel Nothing d\\n new_assoc dup_fields_ok has_sel\\n (L _ (ClsInstD _ (ClsInstDecl { cid_poly_ty = inst_ty\\n , cid_decls = decls })))\\n = do -- First, attempt to grab the name of the class from the instance.\\n -- This step could fail if the instance is not headed by a class,\\n -- such as in the following examples:\\n --\\n -- (1) The class is headed by a bang pattern, such as in\\n -- `instance !Show Int` (#3811c)\\n -- (2) The class is headed by a type variable, such as in\\n -- `instance c` (#16385)\\n --\\n -- If looking up the class name fails, then mb_cls_gre will\\n -- be Nothing.\\n mb_cls_gre <- runMaybeT $ do\\n -- See (1) above\\n L loc cls_rdr <- MaybeT $ pure $ getLHsInstDeclClass_maybe inst_ty\\n -- See (2) above\\n MaybeT $ setSrcSpan (locA loc) $ lookupGlobalOccRn_maybe SameNameSpace cls_rdr\\n -- Assuming the previous step succeeded, process any associated data\\n -- family instances. If the previous step failed, bail out.\\n case mb_cls_gre of\\n Nothing\\n -> pure []\\n Just cls_gre\\n -> let cls_nm = greName cls_gre\\n in concatMapM (new_di dup_fields_ok has_sel (Just cls_nm) . unLoc) (data_fam_insts decls)\\n\\n data_fam_insts decls = concatMap get decls\\n where\\n get (L l (InstD _ (DataFamInstD { dfid_inst = d}))) = [L l d]\\n get _ = []\\n\\n new_di :: DuplicateRecordFields -> FieldSelectors\\n -> Maybe Name -- class name\\n -> DataFamInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_di dup_fields_ok has_sel mb_cls dfid@(DataFamInstDecl { dfid_eqn = ti_decl })\\n = do { main_name <- unLoc <$> lookupFamInstName mb_cls (feqn_tycon ti_decl)\\n ; let LConsWithFields cons_with_flds flds = hsDataFamInstBinders dfid\\n ; sub_names <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst sub_names) flds\\n ; mapM_ (add_dup_fld_errs flds\') sub_names\\n ; let fld_env = mk_fld_env sub_names flds\'\\n con_gres = map (mkLocalConLikeGRE (ParentIs main_name)) fld_env\\n field_gres = mkLocalFieldGREs (ParentIs main_name) fld_env\\n -- NB: the data family name is not bound here,\\n -- so we don\'t return a GlobalRdrElt for it here!\\n ; return $ con_gres ++ field_gres }\\n\\n -- Add errors if a constructor has a duplicate record field.\\n add_dup_fld_errs :: IntMap FieldLabel\\n -> (Name, Either VisArity [Located Int])\\n -> IOEnv (Env TcGblEnv TcLclEnv) ()\\n add_dup_fld_errs all_flds (con, con_flds_or_arity)\\n | Right con_flds <- con_flds_or_arity\\n , let (_, dups) = removeDups (comparing unLoc) con_flds\\n = for_ dups $ \\\\ dup_flds ->\\n -- Report the error at the location of the second occurrence\\n -- of the duplicate field.\\n let loc =\\n case dup_flds of\\n _ :| ( L loc _ : _) -> loc\\n L loc _ :| _ -> loc\\n dup_rdrs = fmap (nameRdrName . flSelector . (all_flds IntMap.!) . unLoc) dup_flds\\n in addErrAt loc $ TcRnDuplicateFieldName (RecordFieldDecl con) dup_rdrs\\n | otherwise\\n = return ()\\n\\nnewRecordFieldLabel :: DuplicateRecordFields -> FieldSelectors -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel\\nnewRecordFieldLabel _ _ [] _ = error \\"newRecordFieldLabel: datatype has no constructors!\\"\\nnewRecordFieldLabel dup_fields_ok has_sel (dc:_) (L loc (FieldOcc _ (L _ fld)))\\n = do { selName <- newTopSrcBinder $ L (l2l loc) $ field\\n ; return $ FieldLabel { flHasDuplicateRecordFields = dup_fields_ok\\n , flHasFieldSelector = has_sel\\n , flSelector = selName } }\\n where\\n fld_occ = rdrNameOcc fld\\n dc_fs = occNameFS $ nameOccName dc\\n field\\n -- Use an Exact RdrName as-is, to preserve the bindings\\n -- of an already renamer-resolved field and its use\\n -- sites. This is needed to correctly support record\\n -- selectors in Template Haskell. See Note [Binders in\\n -- Template Haskell] in \\"GHC.ThToHs\\" and Note [Looking up\\n -- Exact RdrNames] in \\"GHC.Rename.Env\\".\\n | isExact fld\\n = assertPpr (fieldOcc_maybe fld_occ == Just dc_fs)\\n (vcat [ text \\"newRecordFieldLabel: incorrect namespace for exact Name\\" <+> quotes (ppr fld)\\n , text \\"expected namespace:\\" <+> pprNameSpace (fieldName dc_fs)\\n , text \\" actual namespace:\\" <+> pprNameSpace (occNameSpace fld_occ) ])\\n fld\\n\\n -- Field names produced by the parser are namespaced with VarName.\\n -- Here we namespace them according to the first constructor.\\n -- See Note [Record field namespacing] in GHC.Types.Name.Occurrence.\\n | otherwise\\n = mkRdrUnqual $ varToRecFieldOcc dc_fs fld_occ\\n\\n{-\\nNote [Looking up family names in family instances]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider\\n\\n module M where\\n type family T a :: *\\n type instance M.T Int = Bool\\n\\nWe might think that we can simply use \'lookupOccRn\' when processing the type\\ninstance to look up \'M.T\'. Alas, we can\'t! The type family declaration is in\\nthe *same* HsGroup as the type instance declaration. Hence, as we are\\ncurrently collecting the binders declared in that HsGroup, these binders will\\nnot have been added to the global environment yet.\\n\\nSolution is simple: process the type family declarations first, extend\\nthe environment, and then process the type instances.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Filtering imports}\\n* *\\n************************************************************************\\n\\n@filterImports@ takes the @ExportEnv@ telling what the imported module makes\\navailable, and filters it through the import spec (if any).\\n\\nNote [Dealing with imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nFor import M( ies ), we take each AvailInfo from the mi_exports of M, and make\\n\\n imp_occ_env :: OccEnv (NameEnv ImpOccItem)\\n\\nThis map contains one entry for each OccName that M exports, mapping each OccName\\nto the following information:\\n\\n 1. the GlobalRdrElt corresponding to the OccName,\\n 2. whether this GlobalRdrElt was the parent in the AvailInfo we found\\n the OccName in.\\n 3. the GlobalRdrElts that were bundled together in the AvailInfo we found\\n this OccName in (not including the parent),\\n\\nWe need (2) and (3) during the construction of the OccEnv because of associated\\ntypes and bundled pattern synonyms, respectively.\\n(3) is explained in Note [Importing PatternSynonyms].\\n\\nTo explain (2), consider for example:\\n\\n module M where\\n class C a where { data T a }\\n instance C Int where { data T Int = T1 | T2 }\\n instance C Bool where { data T Int = T3 }\\n\\nHere, M\'s exports avails are (recalling the AvailTC invariant from GHC.Types.Avail)\\n\\n C(C,T), T(T,T1,T2,T3)\\n\\nNotice that T appears *twice*, once as a child and once as a parent. From\\nthese two exports, respectively, during construction of the imp_occ_env, we begin\\nby associating the following two elements with the key T:\\n\\n T -> ImpOccItem { imp_item = gre1, imp_bundled = [C,T] , imp_is_parent = False }\\n T -> ImpOccItem { imp_item = gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nwhere `gre1`, `gre2` are two GlobalRdrElts with greName T.\\nWe combine these (in function \'combine\' in \'mkImportOccEnv\') by discarding the\\nnon-parent item, thusly:\\n\\n T -> IE_ITem { imp_item = gre1 `plusGRE` gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nNote the `plusGRE`: this ensures we don\'t drop parent information;\\nsee Note [Preserve parent information when combining import OccEnvs].\\n\\nSo the overall imp_occ_env is:\\n\\n C -> ImpOccItem { imp_item = C, imp_bundled = [T ], imp_is_parent = True }\\n T -> ImpOccItem { imp_item = T , imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n T1 -> ImpOccItem { imp_item = T1, imp_bundled = [T1,T2,T3], imp_is_parent = False }\\n -- similarly for T2, T3\\n\\nNote that the imp_occ_env will have entries for data constructors too,\\nalthough we never look up data constructors.\\n\\nNote [Importing PatternSynonyms]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nAs described in Note [Dealing with imports], associated types can lead to the\\nsame Name appearing twice, both as a child and once as a parent, when\\nconstructing the imp_occ_env. The same thing can happen with pattern synonyms\\nif they are exported bundled with a type.\\n\\nA simplified example, based on #11959:\\n\\n {-# LANGUAGE PatternSynonyms #-}\\n module M (T(P), pattern P) where -- Duplicate export warning, but allowed\\n data T = MkT\\n pattern P = MkT\\n\\nHere we have T(P) and P in export_avails, and respectively construct both\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n P -> ImpOccItem { imp_item = P, imp_bundled = [] , imp_is_parent = False }\\n\\nWe combine these by dropping the one with no siblings, leaving us with:\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n\\nThat is, we simply discard the non-bundled Avail.\\n\\nNote [Importing DuplicateRecordFields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn filterImports, another complicating factor is DuplicateRecordFields.\\nSuppose we have:\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (S(foo), T(foo)) where\\n data S = MkS { foo :: Int }\\n data T = MkT { foo :: Int }\\n\\n module N where\\n import M (foo) -- this is allowed (A)\\n import M (S(foo)) -- this is allowed (B)\\n\\nHere M exports \'foo\' at two different OccNames, with different namespaces for\\nthe two construtors MkS and MkT. Then, when we look up \'foo\' in lookup_names\\nfor case (A), we have a variable foo but must look in all the record field\\nnamespaces to find the two fields (and hence two different Avails).\\nWhereas in case (B) we reach the lookup_ie case for IEThingWith,\\nwhich looks up \'S\' and then finds the unique \'foo\' amongst its children.\\n\\nSee T16745 for a test of this.\\n\\nNote [Preserve parent information when combining import OccEnvs]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen discarding one ImpOccItem in favour of another, as described in\\nNote [Dealing with imports], we must make sure to combine the GREs so that\\nwe don\'t lose information.\\n\\nConsider for example #24084:\\n\\n module M1 where { class C a where { type T a } }\\n module M2 ( module M1 ) where { import M1 }\\n module M3 where { import M2 ( C, T ); instance C () where T () = () }\\n\\nWhen processing the import list of `M3`, we will have two `Avail`s attached\\nto `T`, namely `C(C, T)` and `T(T)`. We combine them in the `combine` function\\nof `mkImportOccEnv`; as described in Note [Dealing with imports] we discard\\n`C(C, T)` in favour of `T(T)`. However, in doing so, we **must not**\\ndiscard the information want that `C` is the parent of `T`. Indeed,\\nlosing track of this information can cause errors when importing,\\nas we could get an error of the form\\n\\n \\u2018T\\u2019 is not a (visible) associated type of class \\u2018C\\u2019\\n\\nThis explains why we use `plusGRE` when combining the two ImpOccItems, even\\nthough we are discarding one in favour of the other.\\n-}\\n\\n-- | All the \'GlobalRdrElt\'s associated with an \'AvailInfo\'.\\ngresFromAvail :: HasDebugCallStack\\n => HscEnv -> Maybe ImportSpec -> AvailInfo -> [GlobalRdrElt]\\ngresFromAvail hsc_env prov avail =\\n [ mk_gre nm info\\n | nm <- availNames avail\\n , let info = lookupGREInfo hsc_env nm ]\\n where\\n\\n mk_gre n info\\n = case prov of\\n -- Nothing => bound locally\\n -- Just is => imported from \'is\'\\n Nothing -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = True, gre_imp = emptyBag\\n , gre_info = info }\\n Just is -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = False, gre_imp = unitBag is\\n , gre_info = info }\\n\\n-- | All the \'GlobalRdrElt\'s associated with a collection of \'AvailInfo\'s.\\ngresFromAvails :: HscEnv -> Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]\\ngresFromAvails hsc_env prov = concatMap (gresFromAvail hsc_env prov)\\n\\nimportsFromIface :: HscEnv -> ModIface -> ImpDeclSpec -> Maybe NameSet -> GlobalRdrEnv\\nimportsFromIface hsc_env iface decl_spec hidden = mkGlobalRdrEnv $ case hidden of\\n Nothing -> all_gres\\n Just hidden_names -> filter (not . (`elemNameSet` hidden_names) . greName) all_gres\\n where\\n all_gres = gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\nrnNamespaceSpecifier :: NamespaceSpecifier GhcPs -> NamespaceSpecifier GhcRn\\nrnNamespaceSpecifier (NoNamespaceSpecifier _) = NoNamespaceSpecifier noExtField\\nrnNamespaceSpecifier (TypeNamespaceSpecifier x) = TypeNamespaceSpecifier x\\nrnNamespaceSpecifier (DataNamespaceSpecifier x) = DataNamespaceSpecifier x\\n\\nfilterImports\\n :: HasDebugCallStack\\n => HscEnv\\n -> ModIface\\n -> ImpDeclSpec\\n -- ^ Import spec\\n -> Maybe (ImportListInterpretation, [LIE GhcPs])\\n -- ^ Whether this is a \\"hiding\\" import list\\n -> RnM (Maybe (ImportListInterpretation, [LIE GhcRn]), -- Import spec w/ Names\\n ImpUserList, -- same, but designed for storage in interfaces\\n GlobalRdrEnv) -- Same again, but in GRE form\\nfilterImports hsc_env iface decl_spec Nothing\\n = return (Nothing, ImpUserAll, importsFromIface hsc_env iface decl_spec Nothing)\\nfilterImports hsc_env iface decl_spec (Just (want_hiding, import_items))\\n = do -- check for errors, convert RdrNames to Names\\n items1 <- mapM lookup_lie import_items\\n\\n let items2 :: [(LIE GhcRn, [GlobalRdrElt])]\\n items2 = concat items1\\n -- NB we may have duplicates, and several items\\n -- for the same parent; e.g N(x) and N(y)\\n\\n (gres, imp_user_list) = case want_hiding of\\n Exactly ->\\n let gres = concatMap (gresFromIE decl_spec) items2\\n gre_env = mkGlobalRdrEnv gres\\n implicit_parents = mkNameSet $ mapMaybe parentOfImplicitlyImportedGRE gres\\n in (gre_env, ImpUserExplicit (gresToAvailInfo $ globalRdrEnvElts $ gre_env) implicit_parents)\\n EverythingBut ->\\n let hidden_names = mkNameSet $ concatMap (map greName . snd) items2\\n in (importsFromIface hsc_env iface decl_spec (Just hidden_names), ImpUserEverythingBut hidden_names)\\n\\n return (Just (want_hiding, map fst items2), imp_user_list, gres)\\n where\\n import_mod = mi_module iface\\n all_avails = mi_exports iface\\n imp_occ_env = mkImportOccEnv hsc_env decl_spec all_avails\\n\\n -- Look up a parent (type constructor, class or data constructor)\\n -- in an import.\\n lookup_parent :: IE GhcPs -> RdrName -> IELookupM ImpOccItem\\n lookup_parent ie rdr =\\n assertPpr (not $ isVarNameSpace ns)\\n (vcat [ text \\"filterImports lookup_parent: unexpected variable\\"\\n , text \\"rdr:\\" <+> ppr rdr\\n , text \\"namespace:\\" <+> pprNameSpace ns ]) $\\n do { xs <- lookup_names ie rdr\\n ; case xs of\\n cax :| [] -> return cax\\n _ -> pprPanic \\"filter_imports lookup_parent ambiguous\\" $\\n vcat [ text \\"rdr:\\" <+> ppr rdr\\n , text \\"lookups:\\" <+> ppr (fmap imp_item xs) ] }\\n -- Looking up non-variables is always unambiguous,\\n -- as there can be at most one corresponding item\\n -- in the imp_occ_env.\\n -- See item (1) of Note [Exporting duplicate declarations]\\n -- in GHC.Tc.Gen.Export.\\n where\\n occ = rdrNameOcc rdr\\n ns = occNameSpace occ\\n\\n -- Look up a RdrName used in an import, returning multiple values if there\\n -- are several fields with the same name exposed by the module\\n lookup_names :: IE GhcPs -> RdrName -> IELookupM (NonEmpty ImpOccItem)\\n lookup_names ie rdr\\n | isQual rdr\\n = failLookupWith (QualImportError rdr)\\n | otherwise\\n = case lookups of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n item:items -> return $ item :| items\\n where\\n lookups = concatMap nonDetNameEnvElts\\n $ lookupImpOccEnv (RelevantGREsFOS WantNormal) imp_occ_env (rdrNameOcc rdr)\\n\\n lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, [GlobalRdrElt])]\\n lookup_lie (L loc ieRdr)\\n = setSrcSpanA loc $\\n do (stuff, warns) <- run_lookup ([],[]) (lookup_ie ieRdr)\\n mapM_ (addTcRnDiagnostic <=< warning_msg) warns\\n return [ (L loc ie, gres) | (ie,gres) <- stuff ]\\n where\\n\\n -- Warn when importing T(..) and no children are brought in scope\\n warning_msg (DodgyImport reason) =\\n pure (TcRnDodgyImports reason)\\n warning_msg MissingImportList =\\n pure (TcRnMissingImportList ieRdr)\\n warning_msg (BadImportW ie sub) = do\\n -- \'BadImportW\' is only constructed below in \'bad_import_w\', in\\n -- the \'EverythingBut\' case, so here we assume a \'hiding\' clause.\\n (reason :| _) <- badImportItemErr iface decl_spec ie sub all_avails\\n pure (TcRnDodgyImports (DodgyImportsHiding reason))\\n warning_msg (DeprecatedExport n w) =\\n pure $ TcRnPragmaWarning\\n PragmaWarningExport\\n { pwarn_occname = occName n\\n , pwarn_impmod = moduleName import_mod }\\n w\\n\\n run_lookup :: a -> IELookupM a -> TcRn a\\n run_lookup def m = case m of\\n Failed err -> do\\n msgs <- lookup_err_msgs err\\n forM_ msgs $ \\\\msg -> addErr (TcRnImportLookup msg)\\n return def\\n Succeeded a -> return a\\n\\n lookup_err_msgs err = case err of\\n BadImport ie sub -> badImportItemErr iface decl_spec ie sub all_avails\\n IllegalImport -> pure $ NE.singleton ImportLookupIllegal\\n QualImportError rdr -> pure $ NE.singleton (ImportLookupQualified rdr)\\n\\n -- For each import item, we convert its RdrNames to Names,\\n -- and at the same time compute all the GlobalRdrElt corresponding\\n -- to what is actually imported by this item.\\n -- Returns Nothing on error.\\n --\\n -- Returns a list because, with DuplicateRecordFields, a naked\\n -- import/export of a record field can correspond to multiple\\n -- different GlobalRdrElts. See Note [Importing DuplicateRecordFields].\\n lookup_ie :: IE GhcPs\\n -> IELookupM ([(IE GhcRn, [GlobalRdrElt])], [IELookupWarning])\\n lookup_ie ie = handle_bad_import $\\n case ie of\\n IEVar _ (L l n) _ -> do\\n -- See Note [Importing DuplicateRecordFields]\\n xs <- lookup_names ie (ieWrappedName n)\\n let gres = map imp_item $ NE.toList xs\\n export_depr_warns\\n | want_hiding == Exactly\\n = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ( [ (IEVar Nothing (L l (replaceWrappedName n name)) noDocstring, [gre])\\n | gre <- gres\\n , let name = greName gre ]\\n , export_depr_warns )\\n\\n IEThingAll x ns_spec (L l tc) _ -> do\\n ImpOccItem { imp_item = gre\\n , imp_bundled = bundled_gres\\n , imp_is_parent = is_par\\n }\\n <- lookup_parent ie $ ieWrappedName tc\\n let name = greName gre\\n\\n child_gres :: [GlobalRdrElt]\\n child_gres\\n | is_par = filterByNamespaceSpecifierGREs ns_spec bundled_gres\\n | otherwise = []\\n\\n imp_list_warn\\n\\n | null child_gres\\n -- e.g. f(..) or T(..) where T is a type synonym\\n = [DodgyImport (DodgyImportsEmptyParent ie ns_spec gre)]\\n\\n -- e.g. import M( T(..) )\\n | not (is_qual decl_spec)\\n = [MissingImportList]\\n\\n | otherwise\\n = []\\n\\n renamed_ie = IEThingAll (x { ieta_warning = Nothing })\\n (rnNamespaceSpecifier ns_spec)\\n (L l (replaceWrappedName tc name))\\n noDocstring\\n export_depr_warn\\n | want_hiding == Exactly\\n = maybeToList $ mk_depr_export_warning gre\\n -- We don\'t want to warn about the children as they\\n -- are not explicitly mentioned; the warning will\\n -- be emitted later on if they are used\\n | otherwise = []\\n\\n return ( [(renamed_ie, gre:child_gres)]\\n , imp_list_warn ++ export_depr_warn)\\n\\n\\n IEThingAbs _ (L l tc\') _\\n | want_hiding == EverythingBut -- hiding ( C )\\n -- Here the \'C\' can be a data constructor\\n -- *or* a type/class, or even both\\n -> let tc = ieWrappedName tc\'\\n tc_name = lookup_parent ie tc\\n dc_name = lookup_parent ie (setRdrNameSpace tc srcDataName)\\n in\\n case catIELookupM [ tc_name, dc_name ] of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n names -> return ( [mkIEThingAbs tc\' l (imp_item name) | name <- names], [])\\n | otherwise\\n -> do ImpOccItem { imp_item = gre } <- lookup_parent ie (ieWrappedName tc\')\\n return ( [mkIEThingAbs tc\' l gre]\\n , maybeToList $ mk_depr_export_warning gre)\\n\\n IEThingWith (deprecation, ann) ltc@(L l rdr_tc) wc rdr_ns _ -> do\\n ImpOccItem { imp_item = gre, imp_bundled = subnames }\\n <- lookup_parent (IEThingAbs Nothing ltc noDocstring) (ieWrappedName rdr_tc)\\n let name = greName gre\\n\\n -- Look up the children in the sub-names of the parent\\n -- See Note [Importing DuplicateRecordFields]\\n let (children_errs, childnames) = lookupChildren subnames rdr_ns\\n\\n bad_import_warns <-\\n if null children_errs then return [] else\\n let items = map lce_wrapped_name children_errs\\n ie = IEThingWith (deprecation, ann) ltc wc items noDocstring\\n -- We are trying to import T( a,b,c,d ), and failed\\n -- to find \'b\' and \'d\'. So we make up an import item\\n -- to report as failing, namely T( b, d ).\\n -- c.f. #15413\\n subordinate_err = mkSubordinateError gre children_errs\\n in bad_import_w ie subordinate_err\\n\\n let name\' = replaceWrappedName rdr_tc name\\n childnames\' = map (to_ie_post_rn . fmap greName) childnames\\n gres = gre : map unLoc childnames\\n export_depr_warns\\n | want_hiding == Exactly = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ([ (IEThingWith (Nothing, ann) (L l name\') wc childnames\' noDocstring\\n ,gres)]\\n , bad_import_warns ++ export_depr_warns)\\n\\n IEWholeNamespace x ns_spec -> do\\n let mod_name = moduleName import_mod\\n names = map greName gres\\n renamed_ie = IEWholeNamespace x { iewn_warning = Nothing\\n , iewn_names = names }\\n (rnNamespaceSpecifier ns_spec)\\n gres = filterByNamespaceSpecifierGREs ns_spec $\\n gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n dodgy_warn\\n | null gres = [DodgyImport (DodgyImportsWildcard mod_name ns_spec)]\\n | otherwise = []\\n return ([(renamed_ie, gres)],\\n dodgy_warn)\\n\\n _other -> failLookupWith IllegalImport\\n -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed...\\n -- all of those constitute errors.\\n\\n where\\n mkIEThingAbs tc l gre\\n = (IEThingAbs Nothing (L l (replaceWrappedName tc n)) noDocstring, [gre])\\n where n = greName gre\\n\\n -- N.B. imports never have docstrings\\n noDocstring = Nothing\\n\\n handle_bad_import m = catchIELookup m $ \\\\case\\n BadImport ie sub -> do\\n ws <- bad_import_w ie sub\\n return ([], ws)\\n err -> failLookupWith err\\n\\n bad_import_w :: IE GhcPs -> IsSubordinateError -> IELookupM [IELookupWarning]\\n bad_import_w ie sub\\n | want_hiding == EverythingBut = return [BadImportW ie sub]\\n | otherwise = failLookupWith (BadImport ie sub)\\n\\n mk_depr_export_warning gre\\n = DeprecatedExport name <$> mi_export_warn_fn iface name\\n where\\n name = greName gre\\n\\n-- | Assuming a subordinate item could not be found, do another lookup for a\\n-- more specific error message.\\nmkBadExportSubordinate :: [GlobalRdrElt] -> LIEWrappedName GhcPs -> BadExportSubordinate\\nmkBadExportSubordinate child_gres n =\\n case lookupChildren child_gres [n] of\\n (LookupChildNonType {lce_nontype_item = g} : _, _) -> BadExportSubordinateNonType g\\n (LookupChildNonData {lce_nondata_item = g} : _, _) -> BadExportSubordinateNonData g\\n _ -> BadExportSubordinateNotFound n\\n\\ntype IELookupM = MaybeErr IELookupError\\n\\ndata IELookupWarning\\n = BadImportW (IE GhcPs) IsSubordinateError\\n | MissingImportList\\n | DodgyImport DodgyImportsReason\\n | DeprecatedExport Name (WarningTxt GhcRn)\\n\\n-- | Is this import/export item a subordinate or not?\\ndata IsSubordinateError\\n = IsSubordinateError { subordinate_err_parent :: !GlobalRdrElt\\n , subordinate_err_unavailable :: [FastString]\\n , subordinate_err_nontype :: [GlobalRdrElt]\\n , subordinate_err_nondata :: [GlobalRdrElt] }\\n | IsNotSubordinate\\n\\nmkSubordinateError :: GlobalRdrElt -> [LookupChildError] -> IsSubordinateError\\nmkSubordinateError gre children_errs = foldr add init_acc children_errs\\n where\\n init_acc :: IsSubordinateError\\n init_acc = IsSubordinateError gre [] [] []\\n\\n add :: LookupChildError -> IsSubordinateError -> IsSubordinateError\\n add children_err sub@IsSubordinateError{} =\\n case children_err of\\n LookupChildNonType{lce_nontype_item = g} ->\\n sub { subordinate_err_nontype = g : subordinate_err_nontype sub }\\n LookupChildNonData{lce_nondata_item = g} ->\\n sub { subordinate_err_nondata = g : subordinate_err_nondata sub }\\n LookupChildNotFound (L _ wname) ->\\n let fs = (occNameFS . rdrNameOcc . ieWrappedName) wname\\n in sub { subordinate_err_unavailable = fs : subordinate_err_unavailable sub }\\n add _ IsNotSubordinate = panic \\"mkSubordinateError: IsNotSubordinate\\"\\n\\ndata IELookupError\\n = QualImportError RdrName\\n | BadImport (IE GhcPs) IsSubordinateError\\n | IllegalImport\\n\\nfailLookupWith :: IELookupError -> IELookupM a\\nfailLookupWith err = Failed err\\n\\ncatchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a\\ncatchIELookup m h = case m of\\n Succeeded r -> return r\\n Failed err -> h err\\n\\ncatIELookupM :: [IELookupM a] -> [a]\\ncatIELookupM ms = [ a | Succeeded a <- ms ]\\n\\n-- | Information associated to an \'AvailInfo\' used in constructing\\n-- an \'OccEnv\' corresponding to imports.\\n--\\n-- See Note [Dealing with imports].\\ndata ImpOccItem\\n = ImpOccItem\\n { imp_item :: GlobalRdrElt\\n -- ^ The import item\\n , imp_bundled :: [GlobalRdrElt]\\n -- ^ Items bundled in the Avail this import item came from,\\n -- not including the import item itself if it is a parent.\\n , imp_is_parent :: Bool\\n -- ^ Is the import item a parent? See Note [Dealing with imports].\\n }\\n\\ninstance Outputable ImpOccItem where\\n ppr (ImpOccItem { imp_item = item, imp_bundled = bundled, imp_is_parent = is_par })\\n = braces $ hsep\\n [ text \\"ImpOccItem\\"\\n , if is_par then text \\"[is_par]\\" else empty\\n , ppr (greName item) <+> ppr (greParent item)\\n , braces $ text \\"bundled:\\" <+> ppr (map greName bundled) ]\\n\\n-- | Make an \'OccEnv\' of all the imports.\\n--\\n-- Complicated by the fact that associated data types and pattern synonyms\\n-- can appear twice. See Note [Dealing with imports].\\nmkImportOccEnv :: HscEnv -> ImpDeclSpec -> [IfaceExport] -> OccEnv (NameEnv ImpOccItem)\\nmkImportOccEnv hsc_env decl_spec all_avails =\\n mkOccEnv_C (plusNameEnv_C combine)\\n [ (occ, mkNameEnv [(nm, item)])\\n | avail <- all_avails\\n , let gres = gresFromAvail hsc_env (Just hiding_spec) avail\\n , gre <- gres\\n , let nm = greName gre\\n occ = greOccName gre\\n (is_parent, bundled) = case avail of\\n AvailTC c _\\n | c == nm -- (Recall the AvailTC invariant from GHC.Types.AvailInfo)\\n -> ( True, drop 1 gres ) -- \\"drop 1\\": don\'t include the parent itself.\\n | otherwise\\n -> ( False, gres )\\n _ -> ( False, [] )\\n item = ImpOccItem\\n { imp_item = gre\\n , imp_bundled = bundled\\n , imp_is_parent = is_parent }\\n ]\\n where\\n\\n hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\n -- See Note [Dealing with imports]\\n -- \'combine\' may be called for associated data types which appear\\n -- twice in the all_avails. In the example, we have two Avails for T,\\n -- namely T(T,T1,T2,T3) and C(C,T), and we combine them by dropping the\\n -- latter, in which T is not the parent.\\n combine :: ImpOccItem -> ImpOccItem -> ImpOccItem\\n combine item1@(ImpOccItem { imp_item = gre1, imp_is_parent = is_parent1 })\\n item2@(ImpOccItem { imp_item = gre2, imp_is_parent = is_parent2 })\\n | is_parent1 || is_parent2\\n , not (isRecFldGRE gre1 || isRecFldGRE gre2) -- NB: does not force GREInfo.\\n , let name1 = greName gre1\\n name2 = greName gre2\\n gre = gre1 `plusGRE` gre2\\n -- See Note [Preserve parent information when combining import OccEnvs]\\n = assertPpr (name1 == name2)\\n (ppr name1 <+> ppr name2) $\\n if is_parent1\\n then item1 { imp_item = gre }\\n else item2 { imp_item = gre }\\n -- Discard C(C,T) in favour of T(T, T1, T2, T3).\\n\\n -- \'combine\' may also be called for pattern synonyms which appear both\\n -- unassociated and associated (see Note [Importing PatternSynonyms]).\\n combine item1@(ImpOccItem { imp_item = c1, imp_bundled = kids1 })\\n item2@(ImpOccItem { imp_item = c2, imp_bundled = kids2 })\\n = assertPpr (greName c1 == greName c2\\n && (not (null kids1 && null kids2)))\\n (ppr c1 <+> ppr c2 <+> ppr kids1 <+> ppr kids2) $\\n if null kids1\\n then item2\\n else item1\\n -- Discard standalone pattern P in favour of T(P).\\n\\n-- | Essentially like @lookupGRE env (LookupOccName occ which_gres)@,\\n-- but working with \'ImpOccItem\'s instead of \'GlobalRdrElt\'s.\\nlookupImpOccEnv :: WhichGREs GREInfo\\n -> OccEnv (NameEnv ImpOccItem) -> OccName -> [NameEnv ImpOccItem]\\nlookupImpOccEnv which_gres env occ =\\n mapMaybe relevant_items $ lookupOccEnv_AllNameSpaces env occ\\n where\\n is_relevant :: ImpOccItem -> Bool\\n is_relevant (ImpOccItem { imp_item = gre }) =\\n greIsRelevant which_gres (occNameSpace occ) gre\\n relevant_items :: NameEnv ImpOccItem -> Maybe (NameEnv ImpOccItem)\\n relevant_items nms\\n | let nms\' = filterNameEnv is_relevant nms\\n = if isEmptyNameEnv nms\'\\n then Nothing\\n else Just nms\'\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{Import/Export Utils}\\n* *\\n************************************************************************\\n-}\\n\\n-- | Given an import\\\\/export spec, appropriately set the @gre_imp@ field\\n-- for the \'GlobalRdrElt\'s.\\ngresFromIE :: ImpDeclSpec -> (LIE GhcRn, [GlobalRdrElt]) -> [GlobalRdrElt]\\ngresFromIE decl_spec (L loc ie, gres)\\n = map set_gre_imp gres\\n where\\n is_explicit = case ie of\\n IEThingAll _ _ name _ -> \\\\n -> n == lieWrappedName name\\n IEWholeNamespace _ _ -> \\\\_ -> False\\n _ -> \\\\_ -> True\\n prov_fn name\\n = ImpSpec { is_decl = decl_spec, is_item = item_spec }\\n where\\n item_spec = ImpSome { is_explicit = is_explicit name\\n , is_iloc = locA loc }\\n set_gre_imp gre@( GRE { gre_name = nm } )\\n = gre { gre_imp = unitBag $ prov_fn nm }\\n\\nparentOfImplicitlyImportedGRE :: Outputable info => GlobalRdrEltX info -> Maybe Name\\nparentOfImplicitlyImportedGRE gre =\\n if any (explicit_import . is_item) $ gre_imp gre\\n then Nothing\\n else greParent_maybe gre\\n where\\n explicit_import :: ImpItemSpec -> Bool\\n explicit_import (ImpAll {}) =\\n pprPanic \\"parentOfImplicitlyImportedGRE: ImpAll\\" (ppr gre)\\n explicit_import (ImpSome { is_explicit }) = is_explicit\\n\\n{- Note [Children for duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider the module\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (F(foo, MkFInt, MkFBool)) where\\n data family F a\\n data instance F Int = MkFInt { foo :: Int }\\n data instance F Bool = MkFBool { foo :: Bool }\\n\\nThe `foo` in the export list refers to *both* selectors! For this\\nreason, lookupChildren builds an environment that maps the FastString\\nto a list of items, rather than a single item.\\n-}\\n\\nmkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]\\nmkChildEnv gres = foldr add emptyNameEnv gres\\n where\\n add gre env = case greParent gre of\\n ParentIs p -> extendNameEnv_Acc (:) Utils.singleton env p gre\\n NoParent -> env\\n\\nfindChildren :: NameEnv [a] -> Name -> [a]\\nfindChildren env n = lookupNameEnv env n `orElse` []\\n\\ndata LookupChildError\\n = LookupChildNotFound { lce_wrapped_name :: !(LIEWrappedName GhcPs) }\\n | LookupChildNonType { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nontype_item :: !GlobalRdrElt }\\n | LookupChildNonData { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nondata_item :: !GlobalRdrElt }\\n\\nlookupChildren :: [GlobalRdrElt]\\n -> [LIEWrappedName GhcPs]\\n -> ( [LookupChildError] -- The ones for which the lookup failed\\n , [LocatedA GlobalRdrElt] )\\n-- (lookupChildren all_kids rdr_items) maps each rdr_item to its\\n-- corresponding Name in all_kids, if the former exists\\n-- The matching is done by FastString, not OccName, so that\\n-- Cls( meth, AssocTy )\\n-- will correctly find AssocTy among the all_kids of Cls, even though\\n-- the RdrName for AssocTy may have a (bogus) DataName namespace\\n-- (Really the rdr_items should be FastStrings in the first place.)\\nlookupChildren all_kids rdr_items = (fails, successes)\\n where\\n mb_xs = map do_one rdr_items\\n fails = [ err | Failed err <- mb_xs ]\\n successes = [ ok | Succeeded oks <- mb_xs, ok <- NE.toList oks ]\\n\\n do_one :: LIEWrappedName GhcPs -> MaybeErr LookupChildError (NonEmpty (LocatedA GlobalRdrElt))\\n do_one item@(L l r) =\\n case r of\\n IEName{}\\n -- IEName (unadorned name) places no restriction on the namespace of\\n -- the imported entity, so we look in both `val_gres` and `typ_gres`.\\n -- In case of conflict (punning), the value namespace takes priority.\\n -- See Note [Prioritise the value namespace in subordinate import lists]\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEType{}\\n -- IEType (\'type\' namespace specifier) restricts the lookup to the\\n -- type namespace, i.e. to `typ_gres`. In case of failure, we check\\n -- `val_gres` to produce a more helpful error message.\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- val_gres -> Failed $ LookupChildNonType item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEData{}\\n -- IEData (\'data\' namespace specifier) restricts the lookup to the\\n -- data namespace, i.e. to `val_gres`. In case of failure, we check\\n -- `typ_gres` to produce a more helpful error message.\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- typ_gres -> Failed $ LookupChildNonData item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEPattern{} -> panic \\"lookupChildren: IEPattern\\" -- Never happens (invalid syntax)\\n IEDefault{} -> panic \\"lookupChildren: IEDefault\\" -- Never happens (invalid syntax)\\n where\\n fs = (occNameFS . rdrNameOcc . ieWrappedName) r\\n gres = fromMaybe [] (lookupFsEnv kid_env fs)\\n (val_gres, typ_gres) = partition (isValNameSpace . greNameSpace) gres\\n\\n -- See Note [Children for duplicate record fields]\\n kid_env :: FastStringEnv [GlobalRdrElt]\\n kid_env = extendFsEnvList_C (++) emptyFsEnv\\n [(occNameFS (occName x), [x]) | x <- all_kids]\\n\\n\\n{- Note [Prioritise the value namespace in subordinate import lists]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider this program that defines a class that has both an associated type\\nnamed (#) and a method named (#)\\n\\n module M_assoc where\\n class C a b where\\n type a # b\\n (#) :: a -> b -> ()\\n module N_assoc where\\n import M_assoc( C((#)) )\\n\\nIn the import declaration, when we see the unadorned name (#) in the subordinate\\nimport list of C, which children should we bring into scope? Our options are:\\n\\n a) only the method (#)\\n b) only the associated type (#)\\n c) both the method and the associated type\\n\\nTo follow the precedent established by top-level items, we go with option (a).\\nIndeed, consider a slightly different program\\n\\n module M_top where\\n type family a # b\\n a # b = ()\\n module N_top where\\n import M_top( (#) )\\n\\nHere the import brings only the function (#) into scope, and one has to say\\n`type (#)` to get the type family.\\n-}\\n\\n-------------------------------\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused names}\\n* *\\n*********************************************************\\n-}\\n\\nreportUnusedNames :: TcGblEnv -> HscSource -> RnM ()\\nreportUnusedNames gbl_env hsc_src\\n = do { keep <- readTcRef (tcg_keep gbl_env)\\n ; traceRn \\"RUN\\" (ppr (tcg_dus gbl_env))\\n ; warnUnusedImportDecls gbl_env hsc_src\\n ; warnUnusedTopBinds $ unused_locals keep\\n ; warnMissingSignatures gbl_env\\n ; warnMissingKindSignatures gbl_env }\\n where\\n used_names :: NameSet -> NameSet\\n used_names keep = findUses (tcg_dus gbl_env) emptyNameSet `unionNameSet` keep\\n -- NB: currently, if f x = g, we only treat \'g\' as used if \'f\' is used\\n -- Hence findUses\\n\\n -- Collect the defined names from the in-scope environment\\n defined_names :: [GlobalRdrElt]\\n defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)\\n\\n kids_env = mkChildEnv defined_names\\n -- This is done in mkExports too; duplicated work\\n\\n gre_is_used :: NameSet -> GlobalRdrElt -> Bool\\n gre_is_used used_names gre0\\n = name `elemNameSet` used_names\\n || any (\\\\ gre -> greName gre `elemNameSet` used_names) (findChildren kids_env name)\\n -- A use of C implies a use of T,\\n -- if C was brought into scope by T(..) or T(C)\\n where\\n name = greName gre0\\n\\n -- Filter out the ones that are\\n -- (a) defined in this module, and\\n -- (b) not defined by a \'deriving\' clause\\n -- The latter have an Internal Name, so we can filter them out easily\\n unused_locals :: NameSet -> [GlobalRdrElt]\\n unused_locals keep =\\n let -- Note that defined_and_used, defined_but_not_used\\n -- are both [GRE]; that\'s why we need defined_and_used\\n -- rather than just used_names\\n _defined_and_used, defined_but_not_used :: [GlobalRdrElt]\\n (_defined_and_used, defined_but_not_used)\\n = partition (gre_is_used (used_names keep)) defined_names\\n\\n in filter is_unused_local defined_but_not_used\\n is_unused_local :: GlobalRdrElt -> Bool\\n is_unused_local gre = isLocalGRE gre\\n && isExternalName (greName gre)\\n\\n{- *********************************************************************\\n* *\\n Missing signatures\\n* *\\n********************************************************************* -}\\n\\n{-\\nNote [Missing signatures]\\n~~~~~~~~~~~~~~~~~~~~~~~~~\\nThere are four warning flags in play:\\n\\n * -Wmissing-exported-signatures\\n Warn about any exported top-level function/value without a type signature.\\n Does not include pattern synonyms.\\n\\n * -Wmissing-signatures\\n Warn about any top-level function/value without a type signature. Does not\\n include pattern synonyms. Takes priority over -Wmissing-exported-signatures.\\n\\n * -Wmissing-exported-pattern-synonym-signatures\\n Warn about any exported pattern synonym without a type signature.\\n\\n * -Wmissing-pattern-synonym-signatures\\n Warn about any pattern synonym without a type signature. Takes priority over\\n -Wmissing-exported-pattern-synonym-signatures.\\n\\n-}\\n\\n-- | Warn the user about top level binders that lack type signatures.\\n-- Called /after/ type inference, so that we can report the\\n-- inferred type of the function\\nwarnMissingSignatures :: TcGblEnv -> RnM ()\\nwarnMissingSignatures gbl_env\\n = do { let exports = availsToNameSet (tcg_exports gbl_env)\\n sig_ns = tcg_sigs gbl_env\\n -- We use sig_ns to exclude top-level bindings that are generated by GHC\\n binds = collectHsBindsBinders CollNoDictBinders $ tcg_binds gbl_env\\n pat_syns = tcg_patsyns gbl_env\\n\\n not_ghc_generated :: Name -> Bool\\n not_ghc_generated name = name `elemNameSet` sig_ns\\n\\n add_binding_warn :: Id -> RnM ()\\n add_binding_warn id =\\n when (not_ghc_generated name) $\\n do { env <- liftZonkM $ tcInitTidyEnv -- Why not use emptyTidyEnv?\\n ; let ty = tidyOpenType env (idType id)\\n missing = MissingTopLevelBindingSig name ty\\n diag = TcRnMissingSignature missing exported\\n ; addDiagnosticAt (getSrcSpan name) diag }\\n where\\n name = idName id\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n add_patsyn_warn :: PatSyn -> RnM ()\\n add_patsyn_warn ps =\\n when (not_ghc_generated name) $\\n addDiagnosticAt (getSrcSpan name)\\n (TcRnMissingSignature missing exported)\\n where\\n name = patSynName ps\\n missing = MissingPatSynSig ps\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n -- Warn about missing signatures\\n -- Do this only when we have a type to offer\\n -- See Note [Missing signatures]\\n ; mapM_ add_binding_warn binds\\n ; mapM_ add_patsyn_warn pat_syns\\n }\\n\\n-- | Warn the user about tycons that lack kind signatures.\\n-- Called /after/ type (and kind) inference, so that we can report the\\n-- inferred kinds.\\nwarnMissingKindSignatures :: TcGblEnv -> RnM ()\\nwarnMissingKindSignatures gbl_env\\n = do { cusks_enabled <- xoptM LangExt.CUSKs\\n ; mapM_ (add_ty_warn cusks_enabled) tcs\\n }\\n where\\n tcs = tcg_tcs gbl_env\\n ksig_ns = tcg_ksigs gbl_env\\n exports = availsToNameSet (tcg_exports gbl_env)\\n\\n has_kind_signature :: Name -> Bool\\n has_kind_signature name = name `elemNameSet` ksig_ns\\n\\n add_ty_warn :: Bool -> TyCon -> RnM ()\\n add_ty_warn cusks_enabled tyCon =\\n when (has_kind_signature name) $\\n addDiagnosticAt (getSrcSpan name) diag\\n where\\n name = tyConName tyCon\\n diag = TcRnMissingSignature missing exported\\n missing = MissingTyConKindSig tyCon cusks_enabled\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused imports}\\n* *\\n*********************************************************\\n\\nThis code finds which import declarations are unused. The\\nspecification and implementation notes are here:\\n https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/unused-imports\\n\\nSee also Note [Choosing the best import declaration] in GHC.Types.Name.Reader\\n-}\\n\\ntype ImportDeclUsage\\n = ( LImportDecl GhcRn -- The import declaration\\n , [GlobalRdrElt] -- What *is* used (normalised)\\n , [Name] -- What is imported but *not* used\\n , [NamespaceSpecifier GhcRn] ) -- Unused wildcards\\n\\nwarnUnusedImportDecls :: TcGblEnv -> HscSource -> RnM ()\\nwarnUnusedImportDecls gbl_env hsc_src\\n = do { uses <- readMutVar (tcg_used_gres gbl_env)\\n ; let imports = tcg_rn_imports gbl_env\\n rdr_env = tcg_rdr_env gbl_env\\n\\n -- We should only warn for unnecessary *user* imports, but deciding\\n -- minimal imports should take generated imports into account\\n ; let usageUserImports = findImportUsage (excludeGenerated imports) uses\\n usageAllImports = findImportUsage imports uses\\n\\n ; traceRn \\"warnUnusedImportDecls\\" $\\n (vcat [ text \\"Uses:\\" <+> ppr uses\\n , text \\"Usage all user imports: \\" <+> ppr usageUserImports\\n , text \\"Usage all imports: \\" <+> ppr usageAllImports])\\n\\n ; mapM_ (warnUnusedImport rdr_env) usageUserImports\\n\\n ; whenGOptM Opt_D_dump_minimal_imports $\\n printMinimalImports hsc_src usageAllImports }\\n\\n-- | Exclude generated imports\\nexcludeGenerated :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\nexcludeGenerated = filterOut (isGeneratedImport . ideclOrigin . ideclExt . unLoc)\\n\\nfindImportUsage :: [LImportDecl GhcRn]\\n -> [GlobalRdrElt]\\n -> [ImportDeclUsage]\\n\\nfindImportUsage imports used_gres\\n = map unused_decl imports\\n where\\n import_usage :: ImportMap\\n import_usage = mkImportMap used_gres\\n\\n unused_decl :: LImportDecl GhcRn -> ImportDeclUsage\\n unused_decl decl@(L _ (ImportDecl { ideclImportList = imps }))\\n = -- pprTrace \\"unused_decl\\" (vcat [ ppr decl\\n -- , text \\"used\\" <+> ppr used_gres\\n -- , text \\"unused\\" <+> ppr unused_names ]) $\\n (decl, used_gres, unused_names, unused_wcs)\\n where\\n used_gres = lookupImportMap decl import_usage\\n\\n used_gre_env = mkGlobalRdrEnv used_gres\\n used_parents = mkNameSet (mapMaybe greParent_maybe used_gres)\\n\\n (unused_names, unused_wcs) -- Not trivial; see eg #7454\\n = case imps of\\n Just (Exactly, imp_ies) ->\\n let unused = foldr (add_unused . unLoc) emptyUnusedNames imp_ies\\n nms = nameSetElemsStable (collectUnusedNames unused)\\n wcs = collectUnusedWildcards unused\\n in (nms, wcs)\\n _other -> ([], []) -- No explicit import list => no unused-name list\\n\\n add_unused :: IE GhcRn -> UnusedNames -> UnusedNames\\n add_unused (IEVar _ n _) acc = add_unused_name (lieWrappedName n) True acc\\n add_unused (IEThingAbs _ n _) acc = add_unused_name (lieWrappedName n) False acc\\n add_unused (IEThingAll _ _ n _) acc = add_unused_all (lieWrappedName n) acc\\n add_unused (IEThingWith _ p wc ns _) acc = add_wc_all (add_unused_with pn xs acc)\\n where pn = lieWrappedName p\\n xs = map lieWrappedName ns\\n add_wc_all = case wc of\\n NoIEWildcard -> id\\n IEWildcard _ -> add_unused_all pn\\n add_unused (IEWholeNamespace x ns_spec) acc = add_unused_wildcard ns_spec (iewn_names x) acc\\n add_unused _ acc = acc\\n\\n add_unused_name :: Name -> Bool -> UnusedNames -> UnusedNames\\n add_unused_name n is_ie_var acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | is_ie_var\\n , isFieldName n\\n -- See Note [Reporting unused imported duplicate record fields]\\n = let\\n fs = getOccFS n\\n (flds, flds_used) = lookupFsEnv acc_fs fs `orElse` (emptyNameSet, Any False)\\n acc_fs\' = extendFsEnv acc_fs fs (extendNameSet flds n, Any used S.<> flds_used)\\n in UnusedNames acc_ns acc_wcs acc_fs\'\\n\\n | used\\n = acc\\n\\n | otherwise\\n = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n where\\n used = isJust $ lookupGRE_Name used_gre_env n\\n\\n add_unused_all :: Name -> UnusedNames -> UnusedNames\\n add_unused_all n acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | Just {} <- lookupGRE_Name used_gre_env n = acc\\n | n `elemNameSet` used_parents = acc\\n | otherwise = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n\\n add_unused_with :: Name -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_with p ns acc\\n | all (`elemNameSet` acc1_ns) ns = add_unused_name p False acc1\\n | otherwise = acc1\\n where\\n acc1@(UnusedNames acc1_ns _ _) = foldr (\\\\n acc\' -> add_unused_name n False acc\') acc ns\\n -- If you use \'signum\' from Num, then the user may well have\\n -- imported Num(signum). We don\'t want to complain that\\n -- Num is not itself mentioned. Hence the two cases in add_unused_with.\\n\\n add_unused_wildcard :: NamespaceSpecifier GhcRn -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_wildcard ns_spec names acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | any_used = acc\\n | otherwise = UnusedNames acc_ns (ns_spec : acc_wcs) acc_fs\\n where\\n -- A wildcard `type ..` or `data ..` is used if at least one of\\n -- the names it expands to is used\\n any_used = any (isJust . lookupGRE_Name used_gre_env) names\\n\\n\\n-- | An accumulator for unused names in an import list.\\n--\\n-- See Note [Reporting unused imported duplicate record fields].\\ndata UnusedNames =\\n UnusedNames\\n { unused_names :: NameSet\\n -- ^ Unused \'Name\'s in an import list, not including record fields\\n -- that are plain \'IEVar\' imports (tracked by \'rec_fld_uses\')\\n -- or wildcard imports (tracked by \'unused_wildcards\').\\n , unused_wildcards :: [NamespaceSpecifier GhcRn]\\n -- ^ Unused wildcards @type ..@ or @data ..@ in an import list.\\n , rec_fld_uses :: FastStringEnv (NameSet, Any)\\n -- ^ Record fields imported without a parent (i.e. an \'IEVar\' import).\\n --\\n -- The \'Any\' value records whether any of the record fields\\n -- sharing the same underlying \'FastString\' have been used.\\n }\\n\\nemptyUnusedNames :: UnusedNames\\nemptyUnusedNames = UnusedNames emptyNameSet [] emptyFsEnv\\n\\ninstance Outputable UnusedNames where\\n ppr (UnusedNames nms wcs flds) =\\n text \\"UnusedNames\\" <+>\\n braces (ppr nms <+> ppr wcs <+> ppr (fmap (second getAny) flds))\\n\\n-- | Collect all unused names from a \'UnusedNames\' value.\\ncollectUnusedNames :: UnusedNames -> NameSet\\ncollectUnusedNames (UnusedNames { unused_names = nms, rec_fld_uses = flds })\\n = nms S.<> unused_flds\\n where\\n unused_flds = nonDetFoldFsEnv collect_unused emptyNameSet flds\\n collect_unused :: (NameSet, Any) -> NameSet -> NameSet\\n collect_unused (nms, Any at_least_one_name_is_used) acc\\n | at_least_one_name_is_used = acc\\n | otherwise = unionNameSet nms acc\\n\\ncollectUnusedWildcards :: UnusedNames -> [NamespaceSpecifier GhcRn]\\ncollectUnusedWildcards = unused_wildcards\\n\\n{- Note [Reporting unused imported duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have (#24035):\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M1 (R1(..), R2(..)) where\\n data R1 = MkR1 { fld :: Int }\\n data R2 = MkR2 { fld :: Int }\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M2 where\\n import M1 (R1(MkR1), R2, fld)\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nIn the import of \'M1\' in \'M2\', the \'fld\' import resolves to two separate GREs,\\nnamely R1(fld) and R2(fld). From the perspective of the renamer, and in particular\\nthe \'findImportUsage\' function, it\'s as if the user had imported the two names\\nseparately (even though no source syntax allows that).\\n\\nThis means that we need to be careful when reporting unused imports: the R2(fld)\\nimport is indeed unused, but because R1(fld) is used, we should not report\\nfld as unused altogether.\\n\\nTo achieve this, we keep track of record field imports without a parent (i.e.\\nusing the IEVar constructor) separately from other import items, using the\\nUnusedNames datatype.\\nOnce we have accumulated usages, we emit warnings for unused record fields\\nwithout parents one whole group (of record fields sharing the same textual name)\\nat a time, and only if *all* of the record fields in the group are unused;\\nsee \'collectUnusedNames\'.\\n\\nNote that this only applies to record fields imported without a parent. If we\\nhad:\\n\\n import M1 (R1(MkR1, fld), R2(fld))\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nthen of course we should report the second \'fld\' as unused.\\n-}\\n\\n\\n{- Note [The ImportMap]\\n~~~~~~~~~~~~~~~~~~~~~~~\\nThe ImportMap is a short-lived intermediate data structure records, for\\neach import declaration, what stuff brought into scope by that\\ndeclaration is actually used in the module.\\n\\nThe [GlobalRdrElt] are the things imported from that decl.\\n-}\\n\\ndata ImportMap = ImportMap\\n { im_imports :: Map RealSrcSpan [GlobalRdrElt]\\n -- ^ See [The ImportMap]\\n -- If loc :-> gres, then\\n -- \'loc\' = the end loc of the bestImport of each GRE in \'gres\'\\n , im_generatedImports :: Map ModuleName [GlobalRdrElt]\\n }\\n\\nmkImportMap :: [GlobalRdrElt] -> ImportMap\\n-- For each of a list of used GREs, find all the import decls that brought\\n-- it into scope; choose one of them (bestImport), and record\\n-- the RdrName in that import decl\'s entry in the ImportMap\\nmkImportMap = foldr insertImportMap $ ImportMap Map.empty Map.empty\\n\\ninsertImportMap :: GlobalRdrElt -> ImportMap -> ImportMap\\ninsertImportMap gre@(GRE { gre_imp = imp_specs }) importMap\\n | RealSrcSpan importSpan _ <- is_dloc best_imp_spec =\\n importMap{im_imports = insertElem importSpan gre $ im_imports importMap}\\n | GeneratedSrcSpan{} <- is_dloc best_imp_spec =\\n importMap{im_generatedImports = insertElem (moduleName $ is_mod best_imp_spec) gre $ im_generatedImports importMap}\\n | otherwise = importMap\\n where\\n best_imp_spec =\\n case bagToList imp_specs of\\n [] -> pprPanic \\"mkImportMap: GRE with no ImportSpecs\\" (ppr gre)\\n is:iss -> is_decl $ bestImport (is NE.:| iss)\\n\\n -- https://github.com/haskell/containers/issues/784\\n insertElem :: Ord k => k -> v -> Map k [v] -> Map k [v]\\n insertElem k v = flip Map.alter k $ \\\\case\\n Just vs -> Just (v : vs)\\n Nothing -> Just [v]\\n\\nlookupImportMap :: LImportDecl GhcRn -> ImportMap -> [GlobalRdrElt]\\nlookupImportMap (L srcSpan ImportDecl{ideclName = L _ modName}) importMap =\\n fromMaybe [] $\\n -- should match logic in insertImportMap\\n case locA srcSpan of\\n RealSrcSpan realSrcSpan _ -> realSrcSpan `Map.lookup` im_imports importMap\\n GeneratedSrcSpan{} -> modName `Map.lookup` im_generatedImports importMap\\n _ -> Nothing\\n\\nlieNames :: LIE (GhcPass p) -> [Located (IdP (GhcPass p))]\\nlieNames = _\\n\\nwarnUnusedImport :: GlobalRdrEnv -> ImportDeclUsage -> RnM ()\\nwarnUnusedImport rdr_env (L loc decl, used, unused, unused_wcs)\\n\\n -- Do not warn for \'import M()\'\\n -- See (UI1) in Note [Unused imports]\\n | Just (Exactly, _) <- ideclImportList decl\\n , null unused && null unused_wcs\\n = return ()\\n\\n -- Note [Do not warn about Prelude hiding]\\n | Just (EverythingBut, hides) <- ideclImportList decl\\n , not (null hides)\\n , pRELUDE_NAME == unLoc (ideclName decl)\\n = return ()\\n\\n -- Do not warn about import X as Rebindable\\n -- See (UI2) in Note [Unused imports]\\n | Just (L _ mod) <- ideclAs decl\\n , mod == rEBINDABLE_MOD_NAME\\n = return ()\\n\\n -- Nothing used; drop entire declaration\\n | null used\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl UnusedImportNone)\\n\\n -- Everything imported is used; nop\\n | null unused && null unused_wcs\\n = return ()\\n\\n -- Some imports are unused: make the `SrcSpan` cover only the unused\\n -- items instead of the whole import statement\\n | Just (_, imports) <- ideclImportList decl\\n , let unused_locs = [ locA loc | L loc ie <- imports\\n , name <- ieNames ie\\n , name `elem` unused ]\\n , loc1 : locs <- unused_locs\\n , let span = foldr1 combineSrcSpans ( loc1 NE.:| locs )\\n = addDiagnosticAt span (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n -- Some imports are unused\\n | otherwise\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n where\\n -- In warning message, pretty-print identifiers unqualified unconditionally\\n -- to improve the consistent for ambiguous/unambiguous identifiers.\\n -- See #14881.\\n possible_field n =\\n case lookupGRE_Name rdr_env n of\\n Just (GRE { gre_par = par, gre_info = IAmRecField info }) ->\\n let fld_occ :: OccName\\n fld_occ = nameOccName $ flSelector $ recFieldLabel info\\n in UnusedImportNameRecField par fld_occ\\n _ -> UnusedImportNameRegular n\\n\\n -- Print unused names in a deterministic (lexicographic) order\\n sort_unused :: [UnusedImportName]\\n sort_unused =\\n [ UnusedImportWildcard wc | wc <- unused_wcs ] ++\\n [ possible_field nm | nm <- sortBy (comparing nameOccName) unused ]\\n\\ngetMinimalImports :: [ImportDeclUsage] -> RnM [LImportDecl GhcRn]\\ngetMinimalImports ie_decls\\n = do { rdr_env <- getGlobalRdrEnv\\n ; fmap combine $ mapM (mk_minimal rdr_env) ie_decls }\\n where\\n mk_minimal rdr_env (L l decl, used_gres, unused, unused_wcs)\\n | null unused && null unused_wcs\\n , Just (Exactly, _) <- ideclImportList decl\\n = return (L l decl)\\n | otherwise\\n = do { let ImportDecl { ideclName = L _ mod_name\\n , ideclSource = is_boot\\n , ideclPkgQual = pkg_qual\\n , ideclExt = XImportDeclPass { ideclOrigin = origin } } = decl\\n ; iface <- loadSrcInterface doc (importDeclLookupScope origin)\\n mod_name is_boot pkg_qual\\n ; let used_avails = gresToAvailInfo used_gres\\n ; lies <- map (L l) <$> concatMapM (to_ie rdr_env iface) used_avails\\n ; return (L l (decl { ideclImportList = Just (Exactly, lies) })) }\\n where\\n doc = text \\"Compute minimal imports for\\" <+> ppr decl\\n\\n to_ie :: GlobalRdrEnv -> ModIface -> AvailInfo -> RnM [IE GhcRn]\\n -- The main trick here is that if we\'re importing all the constructors\\n -- we want to say \\"T(..)\\", but if we\'re importing only a subset we want\\n -- to say \\"T(A,B,C)\\". So we have to find out what the module exports.\\n to_ie rdr_env _ (Avail c) -- Note [Overloaded field import]\\n = do { let\\n gre = expectJust $ lookupGRE_Name rdr_env c\\n ; return $ [IEVar Nothing (to_ie_post_rn $ noLocA $ greName gre) Nothing] }\\n to_ie _ _ avail@(AvailTC n [_]) -- Exporting the main decl and nothing else\\n | availExportsDecl avail\\n = return [IEThingAbs Nothing (to_ie_post_rn $ noLocA n) Nothing]\\n to_ie rdr_env iface (AvailTC n cs) =\\n case [ xs | avail@(AvailTC x xs) <- mi_exports iface\\n , x == n\\n , availExportsDecl avail -- Note [Partial export]\\n ] of\\n [xs]\\n | all_used xs\\n -> return [IEThingAll (IEThingAllExt Nothing noAnn noAnn noAnn)\\n (NoNamespaceSpecifier noExtField)\\n (to_ie_post_rn $ noLocA n)\\n Nothing]\\n | otherwise\\n -> do { let ns_gres = map (expectJust . lookupGRE_Name rdr_env) cs\\n ns = map greName ns_gres\\n ; return [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n -- Note [Overloaded field import]\\n _other\\n -> do { let infos = map (expectJust . lookupGRE_Name rdr_env) cs\\n (ns_gres,fs_gres) = classifyGREs infos\\n ns = map greName (ns_gres ++ fs_gres)\\n fs = map fieldGREInfo fs_gres\\n ; return $\\n if all_non_overloaded fs\\n then map (\\\\nm -> IEVar Nothing (to_ie_post_rn_var $ noLocA nm) Nothing) ns\\n else [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n where\\n\\n all_used avail_cs = all (`elem` cs) avail_cs\\n\\n all_non_overloaded = all (not . flIsOverloaded . recFieldLabel)\\n\\n combine :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\n combine = map merge . NE.groupAllWith getKey\\n\\n getKey :: LImportDecl GhcRn -> (Bool, Maybe ModuleName, ModuleName)\\n getKey decl =\\n ( isImportDeclQualified . ideclQualified $ idecl -- is this qualified? (important that this be first)\\n , unLoc <$> ideclAs idecl -- what is the qualifier (inside Maybe monad)\\n , unLoc . ideclName $ idecl -- Module Name\\n )\\n where\\n idecl :: ImportDecl GhcRn\\n idecl = unLoc decl\\n\\n merge :: NonEmpty (LImportDecl GhcRn) -> LImportDecl GhcRn\\n merge decls@((L l decl) :| _) = L l (decl { ideclImportList = Just (Exactly, lies) })\\n where lies = concatMap snd $ mapMaybe (ideclImportList . unLoc) $ NE.toList decls\\n\\nclassifyGREs :: [GlobalRdrElt] -> ([GlobalRdrElt], [FieldGlobalRdrElt])\\nclassifyGREs = partition (not . isRecFldGRE)\\n\\nprintMinimalImports :: HscSource -> [ImportDeclUsage] -> RnM ()\\n-- See Note [Printing minimal imports]\\nprintMinimalImports hsc_src imports_w_usage\\n = do { imports\' <- excludeGenerated <$> getMinimalImports imports_w_usage\\n ; this_mod <- getModule\\n ; dflags <- getDynFlags\\n ; liftIO $ withFile (mkFilename dflags this_mod) WriteMode $ \\\\h ->\\n printForUser dflags h neverQualify AllTheWay (vcat (map ppr imports\'))\\n -- The neverQualify is important. We are printing Names\\n -- but they are in the context of an \'import\' decl, and\\n -- we never qualify things inside there\\n -- E.g. import Blag( f, b )\\n -- not import Blag( Blag.f, Blag.g )!\\n }\\n where\\n mkFilename dflags this_mod\\n | Just d <- dumpDir dflags = d basefn\\n | otherwise = basefn\\n where\\n suffix = case hsc_src of\\n HsBootFile -> \\".imports-boot\\"\\n HsSrcFile -> \\".imports\\"\\n HsigFile -> \\".imports\\"\\n basefn = moduleNameString (moduleName this_mod) ++ suffix\\n\\n\\nto_ie_post_rn_var :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn_var (L l n)\\n | isDataOcc $ occName n = L l (IEPattern noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n\\n\\nto_ie_post_rn :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn (L l n)\\n | isTcOcc occ && isSymOcc occ = L l (IEType noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n where occ = occName n\\n\\n{- Note [Do not warn about Prelude hiding]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWe do not warn about\\n import Prelude hiding( x, y )\\nbecause even if nothing else from Prelude is used, it may be essential to hide\\nx,y to avoid name-shadowing warnings. Example (#9061)\\n import Prelude hiding( log )\\n f x = log where log = ()\\n\\nNote [Unused imports]\\n~~~~~~~~~~~~~~~~~~~~~\\nIn `warnUnusedImport`, if we see an import with an explicit list imports, thus\\n import M( a, b )\\nand neither `a` nor `b` is used, we report the entire import decl as unused. We\\ncheck this by looking at the names that it brings into scope scope; if there are\\nno ununused names, don\'t report.\\n\\n(UI1) We don\'t want to complain about `import M()`, because that is often used to bring\\n M\'s /instances/ into scope. That is neatly dealt with by the \\"no unused\\n names\\" (nor unused wildcard imports) criterion.\\n\\n(UI2) We don\'t report a decl as unused if it has an `as Rebindable` qualifier.\\n See (KN1) in Note [Overview of known entities] in GHC.Builtin\\n\\n\\nNote [Printing minimal imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nTo print the minimal imports we walk over all import decls (both user-supplied\\nand generated), trim their import lists, then filter out generated decls.\\n\\nNB that\\n\\n * We do *not* change the \'qualified\' or \'as\' parts!\\n\\n * We do not discard a decl altogether; we might need instances\\n from it. Instead we just trim to an empty import list\\n\\nNote [Partial export]\\n~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have\\n\\n module A( op ) where\\n class C a where\\n op :: a -> a\\n\\n module B where\\n import A\\n f = ..op...\\n\\nThen the minimal import for module B is\\n import A( op )\\nnot\\n import A( C( op ) )\\nwhich we would usually generate if C was exported from B. Hence\\nthe availExportsDecl test when deciding what to generate.\\n\\n\\nNote [Overloaded field import]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nOn the other hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n data T = MkT { foo :: Int }\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( T(foo) )\\nbecause when DuplicateRecordFields is enabled, field selectors are\\nnot in scope without their enclosing datatype.\\n\\nOn the third hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n pattern MkT { foo } = Just foo\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( foo )\\nbecause foo doesn\'t have a parent. This might actually be ambiguous if A\\nexports another field called foo, but there is no good answer to return and this\\nis a very obscure corner, so it seems to be the best we can do. See\\nDRFPatSynExport for a test of this.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Errors}\\n* *\\n************************************************************************\\n-}\\n\\nbadImportItemErr\\n :: ModIface -> ImpDeclSpec -> IE GhcPs\\n -> IsSubordinateError\\n -> [AvailInfo]\\n -> TcRn (NonEmpty ImportLookupReason)\\nbadImportItemErr iface decl_spec ie sub avails = do\\n exts <- importLookupExtensions\\n let import_lookup_bad :: BadImportKind -> ImportLookupReason\\n import_lookup_bad k = ImportLookupBad k iface decl_spec ie exts\\n dflags <- getDynFlags\\n hsc_env <- getTopEnv\\n let rdr_env = mkGlobalRdrEnv\\n $ gresFromAvails hsc_env (Just imp_spec) all_avails\\n pure $ fmap import_lookup_bad (importErrorKind dflags rdr_env)\\n where\\n importErrorKind :: DynFlags -> GlobalRdrEnv -> NonEmpty BadImportKind\\n importErrorKind dflags rdr_env\\n | any checkIfTyCon avails = case sub of\\n IsNotSubordinate -> NE.singleton BadImportAvailTyCon\\n IsSubordinateError { subordinate_err_parent = gre\\n , subordinate_err_unavailable = unavailable\\n , subordinate_err_nontype = nontype\\n , subordinate_err_nondata = nondata }\\n -> NE.fromList $ catMaybes $\\n [ fmap (BadImportNotExportedSubordinates gre) (NE.nonEmpty unavailable)\\n , fmap (BadImportNonTypeSubordinates gre) (NE.nonEmpty nontype)\\n , fmap (BadImportNonDataSubordinates gre) (NE.nonEmpty nondata) ]\\n | any checkIfVarName avails = NE.singleton BadImportAvailVar\\n | Just con <- find checkIfDataCon avails = NE.singleton (BadImportAvailDataCon (availOccName con))\\n | otherwise = NE.singleton (BadImportNotExported suggs)\\n where\\n suggs = similar_suggs ++ fieldSelectorSuggestions rdr_env rdr\\n what_look = case sub of\\n IsNotSubordinate -> WL_TyCon_or_TermVar\\n IsSubordinateError { subordinate_err_parent = gre } ->\\n case greInfo gre of\\n IAmTyCon ClassFlavour\\n -> WL_TyCon_or_TermVar\\n _ -> WL_Term\\n similar_names =\\n similarNameSuggestions (Unbound.LF what_look WL_Global)\\n dflags rdr_env emptyLocalRdrEnv rdr\\n similar_suggs =\\n case NE.nonEmpty $ mapMaybe imported_item $ similar_names of\\n Just similar -> [ SuggestSimilarNames rdr similar ]\\n Nothing -> [ ]\\n\\n -- Only keep imported items, and set the \\"HowInScope\\" to\\n -- \\"Nothing\\" to avoid printing \\"imported from...\\" in the suggestion\\n -- error message.\\n imported_item (SimilarRdrName rdr_name gre (Just (ImportedBy {})))\\n = Just (SimilarRdrName rdr_name gre Nothing)\\n imported_item _ = Nothing\\n\\n checkIfDataCon = checkIfAvailMatches isDataConName\\n checkIfTyCon = checkIfAvailMatches isTyConName\\n checkIfVarName =\\n \\\\case\\n AvailTC{} -> False\\n Avail n -> importedFS == occNameFS (occName n)\\n && (isVarOcc <||> isFieldOcc) (occName n)\\n checkIfAvailMatches namePred =\\n \\\\case\\n AvailTC _ ns ->\\n case find (\\\\n -> importedFS == occNameFS (occName n)) ns of\\n Just n -> namePred n\\n Nothing -> False\\n Avail{} -> False\\n availOccName = occName . availName\\n rdr = ieName ie\\n importedFS = occNameFS $ rdrNameOcc rdr\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n all_avails = mi_exports iface\\n\\nimportLookupExtensions :: TcRn ImportLookupExtensions\\nimportLookupExtensions = do\\n ile_pattern_synonyms <- xoptM LangExt.PatternSynonyms\\n ile_explicit_namespaces <- xoptM LangExt.ExplicitNamespaces\\n return ImportLookupExtensions{ile_pattern_synonyms, ile_explicit_namespaces}\\n\\naddDupDeclErr :: NonEmpty GlobalRdrElt -> TcRn ()\\naddDupDeclErr gres@(gre :| _)\\n -- Report the error at the later location\\n = addErrAt (getSrcSpan (NE.last sorted_names)) $ (TcRnDuplicateDecls (greOccName gre) sorted_names)\\n where\\n sorted_names =\\n NE.sortBy (SrcLoc.leftmost_smallest `on` nameSrcSpan)\\n (fmap greName gres)\\n\\n-- This data decl will parse OK\\n-- data T = a Int\\n-- treating \\"a\\" as the constructor.\\n-- It is really hard to make the parser spot this malformation.\\n-- So the renamer has to check that the constructor is legal\\n--\\n-- We can get an operator as the constructor, even in the prefix form:\\n-- data T = :% Int Int\\n-- from interface files, which always print in prefix form\\n--\\n-- We also allow type constructor names, which are defined by \\"type data\\"\\n-- declarations. See Note [Type data declarations] in GHC.Rename.Module.\\n\\ncheckConName :: RdrName -> TcRn ()\\ncheckConName name\\n = checkErr (isRdrDataCon name || isRdrTc name) (TcRnIllegalDataCon name)\\n", "filetypes": ["haskell"]}}}' 2026-10-16 14:48:11,498 - DEBUG - POST b'http://127.0.0.1:37093/receive_messages' {'content-type': 'application/json', 'x-ycm-hmac': b'Rga7Yd4l4fgfufwYw+0sxzurvznImlBO0MPmgAlS4EY='} b'{"filepath": "/home/enrico/ghc/compiler/GHC/Rename/Names.hs", "line_num": 1, "column_num": 1, "working_dir": "/home/enrico/ghc", "file_data": {"/home/enrico/ghc/compiler/GHC/Rename/Names.hs": {"contents": "{-\\n(c) The GRASP/AQUA Project, Glasgow University, 1992-1998\\n\\nExtracting imported and top-level names in scope\\n-}\\n\\n{-# LANGUAGE NondecreasingIndentation #-}\\n{-# LANGUAGE TypeFamilies #-}\\n\\nmodule GHC.Rename.Names (\\n rnImports, getLocalNonValBinders, newRecordFieldLabel,\\n importsFromIface,\\n ImportUserSpec(..),\\n extendGlobalRdrEnvRn,\\n gresFromAvails,\\n calculateAvails,\\n reportUnusedNames,\\n checkConName,\\n mkChildEnv,\\n findChildren,\\n mkBadExportSubordinate,\\n findImportUsage,\\n getMinimalImports,\\n printMinimalImports,\\n renamePkgQual, renameRawPkgQual,\\n classifyGREs,\\n ImportDeclUsage,\\n rnNamespaceSpecifier\\n ) where\\n\\nimport GHC.Prelude hiding ( head, init, last, tail )\\n\\nimport GHC.Driver.Env\\nimport GHC.Driver.Session\\nimport GHC.Driver.Ppr\\n\\nimport GHC.Rename.Env\\nimport GHC.Rename.Fixity\\nimport GHC.Rename.Utils ( warnUnusedTopBinds )\\nimport GHC.Rename.Unbound\\nimport qualified GHC.Rename.Unbound as Unbound\\n\\nimport GHC.Tc.Errors.Types\\nimport GHC.Tc.Utils.Env\\nimport GHC.Tc.Utils.Monad\\nimport GHC.Tc.Types.LclEnv\\nimport GHC.Tc.Zonk.TcType ( tcInitTidyEnv )\\n\\nimport GHC.Hs\\nimport GHC.Iface.Load ( loadSrcInterface, loadSrcInterface_maybe )\\nimport GHC.Iface.Errors.Types\\n ( IfaceMessage(..), MissingInterfaceError, InterfaceLookingFor(..)\\n , LoadEssentialsReason(..) )\\nimport GHC.Iface.Syntax ( fromIfaceWarnings )\\nimport GHC.Builtin.Modules( pRELUDE_NAME, rEBINDABLE_MOD_NAME )\\nimport GHC.Parser.PostProcess ( setRdrNameSpace )\\nimport GHC.Core.TyCo.Tidy\\nimport GHC.Core.PatSyn\\nimport GHC.Core.TyCon ( TyCon, tyConName )\\nimport qualified GHC.LanguageExtensions as LangExt\\n\\nimport GHC.Utils.Outputable as Outputable\\nimport GHC.Utils.Misc as Utils\\nimport GHC.Utils.Panic\\n\\nimport GHC.Types.Fixity.Env\\nimport GHC.Types.SafeHaskell\\nimport GHC.Types.Name\\nimport GHC.Types.Name.Env\\nimport GHC.Types.Name.Set\\nimport GHC.Types.Name.Reader\\nimport GHC.Types.Avail\\nimport GHC.Types.FieldLabel\\nimport GHC.Types.Hint\\nimport GHC.Types.SourceFile\\nimport GHC.Types.SrcLoc as SrcLoc\\nimport GHC.Types.Basic (TyConFlavour (..), convImportLevel, VisArity)\\nimport GHC.Types.UnresolvedImport\\nimport GHC.Types.Id\\nimport GHC.Types.PkgQual\\nimport GHC.Types.GREInfo (ConInfo(..), ConFieldInfo (..), ConLikeInfo (ConIsData))\\n\\nimport GHC.Unit\\nimport GHC.Unit.Module.Warnings\\nimport GHC.Unit.Module.ModIface\\nimport GHC.Unit.Module.Imported\\nimport GHC.Unit.Module.Deps\\nimport GHC.Unit.Env\\n\\nimport GHC.Data.Bag\\nimport GHC.Data.FastString\\nimport GHC.Data.FastString.Env\\nimport GHC.Data.Maybe\\nimport GHC.Data.List.SetOps ( removeDups )\\n\\nimport Control.Arrow ( second )\\nimport Control.Monad\\nimport Data.Foldable ( for_ )\\nimport Data.IntMap ( IntMap )\\nimport qualified Data.IntMap as IntMap\\nimport Data.Map ( Map )\\nimport qualified Data.Map as Map\\nimport Data.Ord ( comparing )\\nimport Data.Semigroup ( Any(..) )\\nimport qualified Data.Semigroup as S\\nimport Data.List ( partition, find, sortBy )\\nimport Data.List.NonEmpty (NonEmpty(..))\\nimport qualified Data.List.NonEmpty as NE\\nimport Data.Function ( on )\\nimport qualified Data.Set as S\\nimport System.FilePath (())\\nimport System.IO\\n\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{rnImports}\\n* *\\n************************************************************************\\n\\nNote [Tracking Trust Transitively]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen we import a package as well as checking that the direct imports are safe\\naccording to the rules outlined in the Note [Safe Haskell Trust Check] in GHC.Driver.Main\\nwe must also check that these rules hold transitively for all dependent modules\\nand packages. Doing this without caching any trust information would be very\\nslow as we would need to touch all packages and interface files a module depends\\non. To avoid this we make use of the property that if a modules Safe Haskell\\nmode changes, this triggers a recompilation from that module in the dependency\\ngraph. So we can just worry mostly about direct imports.\\n\\nThere is one trust property that can change for a package though without\\nrecompilation being triggered: package trust. So we must check that all\\npackages a module transitively depends on to be trusted are still trusted when\\nwe are compiling this module (as due to recompilation avoidance some modules\\nbelow may not be considered trusted any more without recompilation being\\ntriggered).\\n\\nWe handle this by augmenting the existing transitive list of packages a module M\\ndepends on with a bool for each package that says if it must be trusted when the\\nmodule M is being checked for trust. This list of trust required packages for a\\nsingle import is gathered in the rnImportDecl function and stored in an\\nImportAvails data structure. The union of these trust required packages for all\\nimports is done by the rnImports function using the combine function which calls\\nthe plusImportAvails function that is a union operation for the ImportAvails\\ntype. This gives us in an ImportAvails structure all packages required to be\\ntrusted for the module we are currently compiling. Checking that these packages\\nare still trusted (and that direct imports are trusted) is done in\\nGHC.Driver.Main.checkSafeImports.\\n\\nSee the note below, [Trust Own Package] for a corner case in this method and\\nhow its handled.\\n\\n\\nNote [Trust Own Package]\\n~~~~~~~~~~~~~~~~~~~~~~~~\\nThere is a corner case of package trust checking that the usual transitive check\\ndoesn\'t cover. (For how the usual check operates see the Note [Tracking Trust\\nTransitively] below). The case is when you import a -XSafe module M and M\\nimports a -XTrustworthy module N. If N resides in a different package than M,\\nthen the usual check works as M will record a package dependency on N\'s package\\nand mark it as required to be trusted. If N resides in the same package as M\\nthough, then importing M should require its own package be trusted due to N\\n(since M is -XSafe so doesn\'t create this requirement by itself). The usual\\ncheck fails as a module doesn\'t record a package dependency of its own package.\\nSo instead we now have a bool field in a modules interface file that simply\\nstates if the module requires its own package to be trusted. This field avoids\\nus having to load all interface files that the module depends on to see if one\\nis trustworthy.\\n\\n\\nNote [Trust Transitive Property]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSo there is an interesting design question in regards to transitive trust\\nchecking. Say I have a module B compiled with -XSafe. B is dependent on a bunch\\nof modules and packages, some packages it requires to be trusted as its using\\n-XTrustworthy modules from them. Now if I have a module A that doesn\'t use safe\\nhaskell at all and simply imports B, should A inherit all the trust\\nrequirements from B? Should A now also require that a package p is trusted since\\nB required it?\\n\\nWe currently say no but saying yes also makes sense. The difference is, if a\\nmodule M that doesn\'t use Safe Haskell imports a module N that does, should all\\nthe trusted package requirements be dropped since M didn\'t declare that it cares\\nabout Safe Haskell (so -XSafe is more strongly associated with the module doing\\nthe importing) or should it be done still since the author of the module N that\\nuses Safe Haskell said they cared (so -XSafe is more strongly associated with\\nthe module that was compiled that used it).\\n\\nGoing with yes is a simpler semantics we think and harder for the user to stuff\\nup but it does mean that Safe Haskell will affect users who don\'t care about\\nSafe Haskell as they might grab a package from Cabal which uses safe haskell (say\\nnetwork) and that packages imports -XTrustworthy modules from another package\\n(say bytestring), so requires that package is trusted. The user may now get\\ncompilation errors in code that doesn\'t do anything with Safe Haskell simply\\nbecause they are using the network package. They will have to call \'ghc-pkg\\ntrust network\' to get everything working. Due to this invasive nature of going\\nwith yes we have gone with no for now.\\n-}\\n\\n-- | Process Import Decls. See \'rnImportDecl\' for a description of what\\n-- the return types represent.\\n-- Note: Do the non SOURCE ones first, so that we get a helpful warning\\n-- for SOURCE ones that are unnecessary\\nrnImports :: [(LImportDecl GhcPs, SDoc)]\\n -> RnM ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\nrnImports imports = do\\n tcg_env <- getGblEnv\\n -- NB: want an identity module here, because it\'s OK for a signature\\n -- module to import from its implementor\\n let this_mod = tcg_mod tcg_env\\n let (source, ordinary) = partition (is_source_import . fst) imports\\n is_source_import (d::LImportDecl GhcPs) = ideclSource (unLoc d) == IsBoot\\n stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary\\n stuff2 <- mapAndReportM (rnImportDecl this_mod) source\\n -- Safe Haskell: See Note [Tracking Trust Transitively]\\n let (decls, imp_user_spec, rdr_env, imp_avails) = combine (stuff1 ++ stuff2)\\n -- Update imp_boot_mods if imp_direct_mods mentions any of them\\n let merged_import_avail = clobberSourceImports imp_avails\\n return (decls, imp_user_spec, rdr_env, merged_import_avail)\\n\\n where\\n clobberSourceImports imp_avails =\\n imp_avails { imp_boot_mods = imp_boot_mods\' }\\n where\\n imp_boot_mods\' = mergeInstalledModuleEnv combJ id (const emptyInstalledModuleEnv)\\n (imp_boot_mods imp_avails)\\n (imp_direct_dep_mods imp_avails)\\n\\n combJ (GWIB _ IsBoot) (_, x) = Just x\\n combJ r _ = Just r\\n -- See Note [Combining ImportAvails]\\n combine :: [(LImportDecl GhcRn, ImportUserSpec, GlobalRdrEnv, ImportAvails)]\\n -> ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\n combine ss =\\n let (decls, imp_user_spec, rdr_env, imp_avails, finsts) = foldr\\n plus\\n ([], [], emptyGlobalRdrEnv, emptyImportAvails, emptyModuleSet)\\n ss\\n in (decls, imp_user_spec, rdr_env, imp_avails { imp_finsts = moduleSetElts finsts })\\n\\n plus (decl, us, gbl_env1, imp_avails1)\\n (decls, uss, gbl_env2, imp_avails2, finsts_set)\\n = ( decl:decls,\\n us:uss,\\n gbl_env1 `plusGlobalRdrEnv` gbl_env2,\\n imp_avails1\' `plusImportAvails` imp_avails2,\\n extendModuleSetList finsts_set new_finsts )\\n where\\n imp_avails1\' = imp_avails1 { imp_finsts = [] }\\n new_finsts = imp_finsts imp_avails1\\n\\n{-\\nNote [Combining ImportAvails]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nimp_finsts in ImportAvails is a list of family instance modules\\ntransitively depended on by an import. imp_finsts for a currently\\ncompiled module is a union of all the imp_finsts of imports.\\nComputing the union of two lists of size N is O(N^2) and if we\\ndo it to M imports we end up with O(M*N^2). That can get very\\nexpensive for bigger module hierarchies.\\n\\nUnion can be optimized to O(N log N) if we use a Set.\\nimp_finsts is converted back and forth between dep_finsts, so\\nchanging a type of imp_finsts means either paying for the conversions\\nor changing the type of dep_finsts as well.\\n\\nI\'ve measured that the conversions would cost 20% of allocations on my\\ntest case, so that can be ruled out.\\n\\nChanging the type of dep_finsts forces checkFamInsts to\\nget the module lists in non-deterministic order. If we wanted to restore\\nthe deterministic order, we\'d have to sort there, which is an additional\\ncost. As far as I can tell, using a non-deterministic order is fine there,\\nbut that\'s a brittle nonlocal property which I\'d like to avoid.\\n\\nAdditionally, dep_finsts is read from an interface file, so its \\"natural\\"\\ntype is a list. Which makes it a natural type for imp_finsts.\\n\\nSince rnImports.combine is really the only place that would benefit from\\nit being a Set, it makes sense to optimize the hot loop in rnImports.combine\\nwithout changing the representation.\\n\\nSo here\'s what we do: instead of naively merging ImportAvails with\\nplusImportAvails in a loop, we make plusImportAvails merge empty imp_finsts\\nand compute the union on the side using Sets. When we\'re done, we can\\nconvert it back to a list. One nice side effect of this approach is that\\nif there\'s a lot of overlap in the imp_finsts of imports, the\\nSet doesn\'t really need to grow and we don\'t need to allocate.\\n\\nRunning generateModules from #14693 with DEPTH=16, WIDTH=30 finishes in\\n23s before, and 11s after.\\n-}\\n\\n-- | Given a located import declaration @decl@ from @this_mod@,\\n-- calculate the following pieces of information:\\n--\\n-- 1. An updated \'LImportDecl\', where all unresolved \'RdrName\' in\\n-- the entity lists have been resolved into \'Name\'s,\\n--\\n-- 2. A \'GlobalRdrEnv\' representing the new identifiers that were\\n-- brought into scope (taking into account module qualification\\n-- and hiding),\\n--\\n-- 3. \'ImportAvails\' summarizing the identifiers that were imported\\n-- by this declaration, and\\n--\\n-- 4. A boolean \'AnyHpcUsage\' which is true if the imported module\\n-- used HPC.\\nrnImportDecl :: Module -> (LImportDecl GhcPs, SDoc)\\n -> RnM (LImportDecl GhcRn, ImportUserSpec , GlobalRdrEnv, ImportAvails)\\nrnImportDecl this_mod\\n (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name\\n , ideclPkgQual = raw_pkg_qual\\n , ideclSource = want_boot\\n , ideclSafe = mod_safe\\n , ideclLevelSpec = import_level\\n , ideclQualified = qual_style\\n , ideclExt = XImportDeclPass { ideclOrigin = origin }\\n , ideclAs = as_mod, ideclImportList = imp_details }), import_reason)\\n = setSrcSpanA loc $ do\\n\\n case raw_pkg_qual of\\n NoRawPkgQual -> pure ()\\n RawPkgQual {} -> do\\n pkg_imports <- xoptM LangExt.PackageImports\\n when (not pkg_imports) $ addErr TcRnPackageImportsDisabled\\n\\n let qual_only = isImportDeclQualified qual_style\\n generated = isGeneratedImport origin\\n\\n lookup_scope = importDeclLookupScope origin\\n\\n -- If there\'s an error in loadInterface, (e.g. interface\\n -- file not found) we get lots of spurious errors from \'filterImports\'\\n let imp_mod_name = unLoc loc_imp_mod_name\\n doc = ppr imp_mod_name <+> import_reason\\n\\n hsc_env <- getTopEnv\\n unit_env <- hsc_unit_env <$> getTopEnv\\n let pkg_qual = renameRawPkgQual unit_env imp_mod_name raw_pkg_qual\\n\\n -- Check for self-import, which confuses the typechecker (#9032)\\n -- ghc --make rejects self-import cycles already, but batch-mode may not\\n -- at least not until GHC.IfaceToCore.tcHiBootIface, which is too late to avoid\\n -- typechecker crashes. (Indirect self imports are not caught until\\n -- GHC.IfaceToCore, see #10337 tracking how to make this error better.)\\n --\\n -- Originally, we also allowed \'import {-# SOURCE #-} M\', but this\\n -- caused bug #10182: in one-shot mode, we should never load an hs-boot\\n -- file for the module we are compiling into the EPS. In principle,\\n -- it should be possible to support this mode of use, but we would have to\\n -- extend Provenance to support a local definition in a qualified location.\\n -- For now, we don\'t support it, but see #10336\\n when (imp_mod_name == moduleName this_mod &&\\n (case pkg_qual of -- If we have import \\"\\" M, then we should\\n -- check that \\"\\" is \\"this\\" (which is magic)\\n -- or the name of this_mod\'s package. Yurgh!\\n -- c.f. GHC.findModule, and #9997\\n NoPkgQual -> True\\n ThisPkg uid -> uid == homeUnitId_ (hsc_dflags hsc_env)\\n OtherPkg _ -> False))\\n (addErr (TcRnSelfImport imp_mod_name))\\n\\n -- Check for a missing import list (Opt_WarnMissingImportList also\\n -- checks for T(..) items but that is done in checkDodgyImport below)\\n case imp_details of\\n Just (Exactly, _) -> return () -- Explicit import list\\n _ | generated -> return () -- Do not bleat for generated imports\\n | qual_only -> return ()\\n | otherwise -> addDiagnostic (TcRnNoExplicitImportList imp_mod_name)\\n\\n\\n mb_iface <- loadSrcInterface_maybe doc lookup_scope imp_mod_name want_boot pkg_qual\\n iface <- case mb_iface of\\n Succeeded iface -> return iface\\n Failed err -> failWithTc $\\n importDeclLoadFailure origin imp_mod_name want_boot err\\n\\n -- Compiler sanity check: if the import didn\'t say\\n -- {-# SOURCE #-} we should not get a hi-boot file\\n warnPprTrace ((want_boot == NotBoot) && (mi_boot iface == IsBoot)) \\"rnImportDecl\\" (ppr imp_mod_name) $ do\\n\\n -- Issue a user warning for a redundant {- SOURCE -} import\\n -- NB that we arrange to read all the ordinary imports before\\n -- any of the {- SOURCE -} imports.\\n --\\n -- in --make and GHCi, the compilation manager checks for this,\\n -- and indeed we shouldn\'t do it here because the existence of\\n -- the non-boot module depends on the compilation order, which\\n -- is not deterministic. The hs-boot test can show this up.\\n dflags <- getDynFlags\\n warnIf ((want_boot == IsBoot) && (mi_boot iface == NotBoot) && isOneShot (ghcMode dflags))\\n (TcRnRedundantSourceImport imp_mod_name)\\n when (mod_safe && not (safeImportsOn dflags)) $\\n addErr (TcRnSafeImportsDisabled imp_mod_name)\\n\\n let imp_mod = mi_module iface\\n qual_mod_name = fmap unLoc as_mod `orElse` imp_mod_name\\n imp_spec = ImpDeclSpec { is_mod = imp_mod, is_qual = qual_only,\\n is_dloc = locA loc, is_as = qual_mod_name,\\n is_pkg_qual = pkg_qual, is_isboot = want_boot,\\n is_level = convImportLevel import_level }\\n\\n let filter_imports = do\\n -- filter the imports according to the import declaration\\n (new_imp_details, imp_user_list, gbl_env)\\n <- filterImports hsc_env iface imp_spec imp_details\\n -- for certain error messages, we\\u2019d like to know what could be\\n -- imported here, if everything were imported\\n potential_gres <- (\\\\(_,_,x) -> x) <$> filterImports hsc_env iface imp_spec Nothing\\n return (new_imp_details, imp_user_list, gbl_env, potential_gres)\\n\\n (new_imp_details, imp_user_list, gbl_env, potential_gres) <-\\n case origin of\\n ImplicitEssentialsImport ->\\n -- The implicit GHC.Essentials import does not bring anything into scope.\\n -- See Note [Finding GHC.Essentials] in GHC.Builtin.\\n return (Nothing, ImpUserDependOnly, emptyGlobalRdrEnv, emptyGlobalRdrEnv)\\n UserWrittenImport -> filter_imports\\n ImplicitPreludeImport -> filter_imports\\n PluginImport -> filter_imports\\n\\n let is_hiding | Just (EverythingBut,_) <- imp_details = True\\n | otherwise = False\\n\\n -- should the import be safe?\\n mod_safe\' = mod_safe\\n || (not generated && safeDirectImpsReq dflags)\\n || (generated && safeImplicitImpsReq dflags)\\n\\n hsc_env <- getTopEnv\\n let home_unit = hsc_home_unit hsc_env\\n other_home_units = hsc_all_home_unit_ids hsc_env\\n\\n imported_by\\n | isDependOnlyImport imp_user_list\\n = ImportedBySystem\\n | otherwise\\n = ImportedByUser $ ImportedModsVal\\n { imv_name = is_as imp_spec\\n , imv_span = locA loc\\n , imv_is_safe = mod_safe\'\\n , imv_is_hiding = is_hiding\\n , imv_all_exports = potential_gres\\n , imv_qualified = qual_only\\n , imv_is_level = convImportLevel import_level\\n }\\n imports = calculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by\\n\\n -- Complain if we import a deprecated module\\n case fromIfaceWarnings (mi_warns iface) of\\n WarnAll txt -> addDiagnostic (TcRnDeprecatedModule imp_mod_name txt)\\n _ -> return ()\\n\\n let new_imp_decl = ImportDecl\\n { ideclExt = ideclExt decl\\n , ideclName = ideclName decl\\n , ideclPkgQual = pkg_qual\\n , ideclSource = ideclSource decl\\n , ideclSafe = mod_safe\'\\n , ideclQualified = ideclQualified decl\\n , ideclAs = ideclAs decl\\n , ideclImportList = new_imp_details\\n , ideclLevelSpec = ideclLevelSpec decl\\n }\\n\\n return (L loc new_imp_decl, ImpUserSpec imp_spec imp_user_list, gbl_env, imports)\\n\\n-- | The error message to emit when we failed to load an interface.\\nimportDeclLoadFailure :: ImportDeclOrigin -> ModuleName -> IsBootInterface\\n -> MissingInterfaceError -> TcRnMessage\\nimportDeclLoadFailure ImplicitEssentialsImport _ _ err\\n = TcRnInterfaceError $ CantFindEssentials err LookingForEssentialsModule\\nimportDeclLoadFailure _ mod_name want_boot err\\n = TcRnInterfaceError $ Can\'tFindInterface err $ LookingForModule mod_name want_boot\\n\\n-- | Rename raw package imports\\nrenameRawPkgQual :: UnitEnv -> ModuleName -> RawPkgQual -> PkgQual\\nrenameRawPkgQual unit_env mn = \\\\case\\n NoRawPkgQual -> NoPkgQual\\n RawPkgQual _ fs -> renamePkgQual unit_env mn $ Just fs\\n\\n-- | Rename raw package imports\\nrenamePkgQual :: UnitEnv -> ModuleName -> Maybe FastString -> PkgQual\\nrenamePkgQual unit_env mn mb_pkg = case mb_pkg of\\n Nothing -> NoPkgQual\\n Just pkg_fs\\n | Just uid <- homeUnitId <$> ue_homeUnit unit_env\\n , pkg_fs == fsLit \\"this\\"\\n -> ThisPkg uid\\n\\n | Just (uid, _) <- find (fromMaybe False . fmap (== pkg_fs) . snd) home_names\\n -> ThisPkg uid\\n\\n | Just uid <- resolvePackageImport unit_state mn (PackageName pkg_fs)\\n -> OtherPkg uid\\n\\n | otherwise\\n -> OtherPkg (UnitId pkg_fs)\\n -- not really correct as pkg_fs is unlikely to be a valid unit-id but\\n -- we will report the failure later...\\n where\\n home_names =\\n [ (uid, mkFastString <$> thisPackageName (homeUnitEnv_dflags (ue_findHomeUnitEnv uid unit_env)))\\n | uid <- S.toList hpt_deps\\n ]\\n\\n unit_state = ue_homeUnitState unit_env\\n\\n hpt_deps :: S.Set UnitId\\n hpt_deps = homeUnitDepends unit_state\\n\\n\\n-- | Calculate the \'ImportAvails\' induced by an import of a particular\\n-- interface, but without \'imp_mods\'.\\ncalculateAvails :: HomeUnit\\n -> S.Set UnitId\\n -> ModIface\\n -> IsSafeImport\\n -> IsBootInterface\\n -> ImportedBy\\n -> ImportAvails\\ncalculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by =\\n let imp_mod = mi_module iface\\n imp_sem_mod= mi_semantic_module iface\\n orph_iface = mi_orphan iface\\n has_finsts = mi_finsts iface\\n deps = mi_deps iface\\n trust = getSafeMode $ mi_trust iface\\n trust_pkg = mi_trust_pkg iface\\n is_sig = mi_hsc_src iface == HsigFile\\n\\n -- If the module exports anything defined in this module, just\\n -- ignore it. Reason: otherwise it looks as if there are two\\n -- local definition sites for the thing, and an error gets\\n -- reported. Easiest thing is just to filter them out up\\n -- front. This situation only arises if a module imports\\n -- itself, or another module that imported it. (Necessarily,\\n -- this involves a loop.)\\n --\\n -- We do this *after* filterImports, so that if you say\\n -- module A where\\n -- import B( AType )\\n -- type AType = ...\\n --\\n -- module B( AType ) where\\n -- import {-# SOURCE #-} A( AType )\\n --\\n -- then you won\'t get a \'B does not export AType\' message.\\n\\n\\n -- Compute new transitive dependencies\\n --\\n -- \'dep_orphs\' and \'dep_finsts\' do NOT include the imported module\\n -- itself, but we DO need to include this module in \'imp_orphs\' and\\n -- \'imp_finsts\' if it defines an orphan or instance family; thus the\\n -- orph_iface/has_iface tests.\\n\\n deporphs = dep_orphs deps\\n depfinsts = dep_finsts deps\\n\\n orphans | orph_iface = assertPpr (not (imp_sem_mod `elem` deporphs)) (ppr imp_sem_mod <+> ppr deporphs) $\\n imp_sem_mod : deporphs\\n | otherwise = deporphs\\n\\n finsts | has_finsts = assertPpr (not (imp_sem_mod `elem` depfinsts)) (ppr imp_sem_mod <+> ppr depfinsts) $\\n imp_sem_mod : depfinsts\\n | otherwise = depfinsts\\n\\n -- Trusted packages are a lot like orphans.\\n trusted_pkgs | mod_safe\' = dep_trusted_pkgs deps\\n | otherwise = S.empty\\n\\n\\n pkg = moduleUnit (mi_module iface)\\n ipkg = toUnitId pkg\\n\\n -- Does this import mean we now require our own pkg\\n -- to be trusted? See Note [Trust Own Package]\\n ptrust = trust == Sf_Trustworthy || trust_pkg\\n pkg_trust_req\\n | isHomeUnit home_unit pkg = ptrust\\n | otherwise = False\\n\\n dependent_pkgs = if toUnitId pkg `S.member` other_home_units\\n then S.empty\\n else S.singleton (lvl, ipkg)\\n\\n lvl = case imported_by of\\n ImportedByUser imv -> imv_is_level imv\\n ImportedBySystem -> NormalLevel\\n\\n\\n direct_mods = if toUnitId pkg `S.member` other_home_units\\n then mkPlusModDeps (moduleUnitId imp_mod) lvl (GWIB (moduleName imp_mod) want_boot)\\n else emptyInstalledModuleEnv\\n\\n dep_boot_mods_map = mkModDeps (dep_boot_mods deps)\\n\\n\\n boot_mods\\n -- If we are looking for a boot module, it must be HPT\\n | IsBoot <- want_boot = extendInstalledModuleEnv dep_boot_mods_map (toUnitId <$> imp_mod) (GWIB (moduleName imp_mod) IsBoot)\\n -- Now we are importing A properly, so don\'t go looking for\\n -- A.hs-boot\\n | isHomeUnit home_unit pkg = dep_boot_mods_map\\n -- There\'s no boot files to find in external imports\\n | otherwise = emptyInstalledModuleEnv\\n\\n sig_mods =\\n if is_sig\\n then moduleName imp_mod : dep_sig_mods deps\\n else dep_sig_mods deps\\n\\n\\n in ImportAvails {\\n imp_mods = Map.singleton (mi_module iface) [imported_by],\\n imp_orphs = orphans,\\n imp_finsts = finsts,\\n imp_sig_mods = sig_mods,\\n imp_direct_dep_mods = direct_mods,\\n imp_dep_direct_pkgs = dependent_pkgs,\\n imp_boot_mods = boot_mods,\\n\\n -- Add in the imported modules trusted package\\n -- requirements. ONLY do this though if we import the\\n -- module as a safe import.\\n -- See Note [Tracking Trust Transitively]\\n -- and Note [Trust Transitive Property]\\n imp_trust_pkgs = trusted_pkgs,\\n -- Do we require our own pkg to be trusted?\\n -- See Note [Trust Own Package]\\n imp_trust_own_pkg = pkg_trust_req\\n }\\n\\nmkPlusModDeps :: UnitId -> ImportLevel -> ModuleNameWithIsBoot\\n -> InstalledModuleEnv (S.Set ImportLevel, ModuleNameWithIsBoot)\\nmkPlusModDeps uid st elt = extendInstalledModuleEnv emptyInstalledModuleEnv (mkModule uid (gwib_mod elt)) (S.singleton st, elt)\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{importsFromLocalDecls}\\n* *\\n************************************************************************\\n\\nFrom the top-level declarations of this module produce\\n * the lexical environment\\n * the ImportAvails\\ncreated by its bindings.\\n\\nNote [Top-level Names in Template Haskell decl quotes]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSee also: Note [Interactively-bound Ids in GHCi] in GHC.Driver.Env\\n Note [Looking up Exact RdrNames] in GHC.Rename.Env\\n\\nConsider a Template Haskell declaration quotation like this:\\n module M where\\n f x = h [d| f = 3 |]\\nWhen renaming the declarations inside [d| ...|], we treat the\\ntop level binders specially in two ways\\n\\n1. We give them an Internal Name, not (as usual) an External one.\\n This is done by GHC.Rename.Env.newTopSrcBinder.\\n\\n2. We make them *shadow* the outer bindings.\\n See Note [GlobalRdrEnv shadowing]\\n\\n3. We find out whether we are inside a [d| ... |] by testing the TH\\n level. This is a slight hack, because the level field was really\\n meant for the type checker, and here we are not interested in the\\n fields of Brack, hence the error thunks in thRnBrack.\\n-}\\n\\nextendGlobalRdrEnvRn :: [GlobalRdrElt]\\n -> MiniFixityEnv\\n -> RnM (TcGblEnv, TcLclEnv)\\n-- Updates both the GlobalRdrEnv and the FixityEnv\\n-- We return a new TcLclEnv only because we might have to\\n-- delete some bindings from it;\\n-- see Note [Top-level Names in Template Haskell decl quotes]\\n\\nextendGlobalRdrEnvRn new_gres new_fixities\\n = checkNoErrs $ -- See Note [Fail fast on duplicate definitions]\\n do { (gbl_env, lcl_env) <- getEnvs\\n ; level <- getThLevel\\n ; isGHCi <- getIsGHCi\\n ; let rdr_env = tcg_rdr_env gbl_env\\n fix_env = tcg_fix_env gbl_env\\n th_bndrs = getLclEnvThBndrs lcl_env\\n th_lvl = thLevelIndex level\\n\\n -- Delete new_occs from global and local envs\\n -- If we are in a TemplateHaskell decl bracket,\\n -- we are going to shadow them\\n -- See Note [GlobalRdrEnv shadowing]\\n inBracket = isBrackLevel level\\n\\n lcl_env_TH = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_rdr = minusLocalRdrEnv (tcl_rdr lcl_env) new_gres_env }) lcl_env\\n -- See Note [GlobalRdrEnv shadowing]\\n\\n lcl_env2 | inBracket = lcl_env_TH\\n | otherwise = lcl_env\\n\\n -- Deal with shadowing: see Note [GlobalRdrEnv shadowing]\\n want_shadowing = isGHCi || inBracket\\n rdr_env1 | want_shadowing = shadowNames False rdr_env new_gres_env\\n | otherwise = rdr_env\\n\\n lcl_env3 = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_th_bndrs = extendNameEnvList th_bndrs\\n [ ( n, (TopLevel, th_lvl) )\\n | n <- new_names ] }) lcl_env2\\n\\n ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres\\n\\n ; let fix_env\' = foldl\' extend_fix_env fix_env new_gres\\n gbl_env\' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env\' }\\n\\n ; traceRn \\"extendGlobalRdrEnvRn 2\\" (pprGlobalRdrEnv True rdr_env2)\\n ; return (gbl_env\', lcl_env3) }\\n where\\n new_names = map greName new_gres\\n new_gres_env = mkGlobalRdrEnv new_gres\\n\\n -- If there is a fixity decl for the gre, add it to the fixity env\\n extend_fix_env fix_env gre\\n | Just (L _ fi) <- lookupMiniFixityEnv new_fixities name\\n = extendNameEnv fix_env name (FixItem occ fi)\\n | otherwise\\n = fix_env\\n where\\n name = greName gre\\n occ = greOccName gre\\n\\n add_gre :: GlobalRdrEnv -> GlobalRdrElt -> RnM GlobalRdrEnv\\n -- Extend the GlobalRdrEnv with a LocalDef GRE\\n -- If there is already a LocalDef GRE with the same OccName,\\n -- report an error and discard the new GRE\\n -- This establishes INVARIANT 1 of GlobalRdrEnvs\\n add_gre env gre\\n | not (null dups) -- Same OccName defined twice\\n = do { addDupDeclErr (gre :| dups); return env }\\n\\n | otherwise\\n = return (extendGlobalRdrEnv env gre)\\n where\\n -- See Note [Reporting duplicate local declarations]\\n dups = filter isBadDupGRE\\n $ lookupGRE env (LookupOccName (greOccName gre) (RelevantGREsFOS WantBoth))\\n isBadDupGRE old_gre = isLocalGRE old_gre && greClashesWith gre old_gre\\n\\n{- Note [Fail fast on duplicate definitions]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIf there are duplicate bindings for the same thing, we want to fail\\nfast. Having two bindings for the same thing can cause follow-on errors.\\nExample (test T9975a):\\n data Test = Test { x :: Int }\\n pattern Test wat = Test { x = wat }\\nThis defines \'Test\' twice. The second defn has no field-names; and then\\nwe get an error from Test { x=wat }, saying \\"Test has no field \'x\'\\".\\n\\nEasiest thing is to bale out fast on duplicate definitions, which\\nwe do via `checkNoErrs` on `extendGlobalRdrEnvRn`.\\n\\nNote [Reporting duplicate local declarations]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn general, a single module may not define the same OccName multiple times. This\\nis checked in extendGlobalRdrEnvRn: when adding a new locally-defined GRE to the\\nGlobalRdrEnv we report an error if there are already duplicates in the\\nenvironment. This establishes INVARIANT 1 (see comments on GlobalRdrEnv in\\nGHC.Types.Name.Reader), which says that for a given OccName, all the\\nGlobalRdrElts to which it maps must have distinct \'greName\'s.\\n\\nFor example, the following will be rejected:\\n\\n f x = x\\n g x = x\\n f x = x -- Duplicate!\\n\\nUsers are allowed to introduce new GREs with the same OccName as an imported GRE,\\nas disambiguation is possible through the module system, e.g.:\\n\\n module M where\\n import N (f)\\n f x = x\\n g x = M.f x + N.f x\\n\\nIf both GREs are local, the general rule is that two GREs clash if they have\\nthe same OccName, i.e. they share a textual name and live in the same namespace.\\nHowever, there are additional clashes due to record fields:\\n\\n - a new variable clashes with previously defined record fields\\n which define field selectors,\\n\\n - a new record field shadows:\\n\\n - previously defined variables, if it defines a field selector,\\n - previously defined record fields, unless it is a duplicate record field.\\n\\nThis logic is implemented in the function \'GHC.Types.Name.Reader.greClashesWith\'.\\n\\nSee also Note [Skipping ambiguity errors at use sites of local declarations] in\\nGHC.Rename.Utils.\\n-}\\n\\n\\n{- *********************************************************************\\n* *\\n getLocalDeclBindersd@ returns the names for an HsDecl\\n It\'s used for source code.\\n\\n *** See Note [The Naming story] in GHC.Hs.Decls ****\\n* *\\n********************************************************************* -}\\n\\ngetLocalNonValBinders :: MiniFixityEnv -> HsGroup GhcPs\\n -> RnM ((TcGblEnv, TcLclEnv), NameSet)\\n-- Get all the top-level binders bound the group *except*\\n-- for value bindings, which are treated separately\\n-- Specifically we return AvailInfo for\\n-- * type decls (incl constructors and record selectors)\\n-- * class decls (including class ops)\\n-- * associated types\\n-- * foreign imports\\n-- * value signatures (in hs-boot files only)\\n\\ngetLocalNonValBinders fixity_env\\n (HsGroup { hs_valds = binds,\\n hs_tyclds = tycl_decls,\\n hs_fords = foreign_decls })\\n = do { -- Process all type/class decls *except* family instances\\n ; let inst_decls = tycl_decls >>= group_instds\\n ; dup_fields_ok <- xopt_DuplicateRecordFields <$> getDynFlags\\n ; has_sel <- xopt_FieldSelectors <$> getDynFlags\\n ; tc_gres\\n <- concatMapM\\n (new_tc dup_fields_ok has_sel)\\n (tyClGroupTyClDecls tycl_decls)\\n ; traceRn \\"getLocalNonValBinders 1\\" (ppr tc_gres)\\n ; envs <- extendGlobalRdrEnvRn tc_gres fixity_env\\n ; restoreEnvs envs $ do {\\n -- Bring these things into scope first\\n -- See Note [Looking up family names in family instances]\\n\\n -- Process all family instances\\n -- to bring new data constructors into scope\\n ; nti_gress <- mapM (new_assoc dup_fields_ok has_sel) inst_decls\\n\\n -- Finish off with value binders:\\n -- foreign decls and pattern synonyms for an ordinary module\\n -- type sigs in case of a hs-boot file only\\n ; is_boot <- tcIsHsBootOrSig\\n ; let val_bndrs\\n | is_boot = case binds of\\n ValBinds _ val_binds ->\\n -- In a hs-boot file, the value binders come from the\\n -- *signatures*, and there should be no foreign binders\\n [ L (l2l decl_loc) (unLoc n)\\n | L decl_loc (TypeSig _ _ ns _) <- (val_sigs val_binds), n <- ns]\\n _ -> panic \\"Non-ValBinds in hs-boot group\\"\\n | otherwise = for_hs_bndrs\\n ; val_gres <- mapM new_simple val_bndrs\\n\\n ; let avails = concat nti_gress ++ val_gres\\n new_bndrs = gresToNameSet avails `unionNameSet`\\n gresToNameSet tc_gres\\n ; traceRn \\"getLocalNonValBinders 2\\" (ppr avails)\\n ; envs <- extendGlobalRdrEnvRn avails fixity_env\\n ; return (envs, new_bndrs) } }\\n where\\n for_hs_bndrs :: [LocatedN RdrName]\\n for_hs_bndrs = hsForeignDeclsBinders foreign_decls\\n\\n -- the SrcSpan attached to the input should be the span of the\\n -- declaration, not just the name\\n new_simple :: LocatedN RdrName -> RnM GlobalRdrElt\\n new_simple rdr_name = do { nm <- newTopSrcBinder rdr_name\\n ; return (mkLocalVanillaGRE NoParent nm) }\\n\\n new_tc :: DuplicateRecordFields -> FieldSelectors -> LTyClDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_tc dup_fields_ok has_sel tc_decl -- NOT for type/data instances\\n = do { let TyDeclBinders (main_bndr, tc_flav) at_bndrs sig_bndrs\\n (LConsWithFields cons_with_flds flds) = hsLTyClDeclBinders tc_decl\\n ; tycon_name <- newTopSrcBinder $ la2la main_bndr\\n ; at_names <- mapM (newTopSrcBinder . la2la . fst) at_bndrs\\n ; sig_names <- mapM (newTopSrcBinder . la2la) sig_bndrs\\n ; con_names_with_flds <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst con_names_with_flds) flds\\n ; mapM_ (add_dup_fld_errs flds\') con_names_with_flds\\n ; let tc_gre = mkLocalTyConGRE (fmap (const tycon_name) tc_flav) tycon_name\\n fld_env = mk_fld_env con_names_with_flds flds\'\\n at_gres = zipWith (\\\\ (_, at_flav) at_nm -> mkLocalTyConGRE (fmap (const tycon_name) at_flav) at_nm)\\n at_bndrs at_names\\n sig_gres = map (mkLocalVanillaGRE (ParentIs tycon_name)) sig_names\\n con_gres = map (mkLocalConLikeGRE (ParentIs tycon_name)) fld_env\\n fld_gres = mkLocalFieldGREs (ParentIs tycon_name) fld_env\\n sub_gres = at_gres ++ sig_gres ++ con_gres ++ fld_gres\\n ; traceRn \\"getLocalNonValBinders new_tc\\" $\\n vcat [ text \\"tycon:\\" <+> ppr tycon_name\\n , text \\"tc_gre:\\" <+> ppr tc_gre\\n , text \\"sub_gres:\\" <+> ppr sub_gres ]\\n ; return $ tc_gre : sub_gres }\\n\\n -- Calculate the record field information, which feeds into the GlobalRdrElts\\n -- for DataCons and their fields. It\'s convenient to do this here where\\n -- we are working with a single datatype definition.\\n --\\n -- The information we needed was all set up for us:\\n -- see Note [Collecting record fields in data declarations] in GHC.Hs.Utils.\\n mk_fld_env :: [(Name, Either VisArity [Located Int])] -> IntMap FieldLabel\\n -> [(ConLikeName, ConInfo)]\\n mk_fld_env names flds =\\n [ (DataConName con, ConInfo (ConIsData (map fst names)) fld_info)\\n | (con, con_fl_indxs) <- names\\n , let fld_info = case fmap (map ((flds IntMap.!) . unLoc)) con_fl_indxs of\\n Left 0 -> ConIsNullary\\n Left arity -> ConHasPositionalArgs arity\\n Right [] -> ConIsNullary\\n Right (fld:flds) -> ConHasRecordFields $ fld NE.:| flds ]\\n\\n new_assoc :: DuplicateRecordFields -> FieldSelectors -> LInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_assoc _ _ (L _ (TyFamInstD {})) = return []\\n -- type instances don\'t bind new names\\n\\n new_assoc dup_fields_ok has_sel (L _ (DataFamInstD _ d))\\n = new_di dup_fields_ok has_sel Nothing d\\n new_assoc dup_fields_ok has_sel\\n (L _ (ClsInstD _ (ClsInstDecl { cid_poly_ty = inst_ty\\n , cid_decls = decls })))\\n = do -- First, attempt to grab the name of the class from the instance.\\n -- This step could fail if the instance is not headed by a class,\\n -- such as in the following examples:\\n --\\n -- (1) The class is headed by a bang pattern, such as in\\n -- `instance !Show Int` (#3811c)\\n -- (2) The class is headed by a type variable, such as in\\n -- `instance c` (#16385)\\n --\\n -- If looking up the class name fails, then mb_cls_gre will\\n -- be Nothing.\\n mb_cls_gre <- runMaybeT $ do\\n -- See (1) above\\n L loc cls_rdr <- MaybeT $ pure $ getLHsInstDeclClass_maybe inst_ty\\n -- See (2) above\\n MaybeT $ setSrcSpan (locA loc) $ lookupGlobalOccRn_maybe SameNameSpace cls_rdr\\n -- Assuming the previous step succeeded, process any associated data\\n -- family instances. If the previous step failed, bail out.\\n case mb_cls_gre of\\n Nothing\\n -> pure []\\n Just cls_gre\\n -> let cls_nm = greName cls_gre\\n in concatMapM (new_di dup_fields_ok has_sel (Just cls_nm) . unLoc) (data_fam_insts decls)\\n\\n data_fam_insts decls = concatMap get decls\\n where\\n get (L l (InstD _ (DataFamInstD { dfid_inst = d}))) = [L l d]\\n get _ = []\\n\\n new_di :: DuplicateRecordFields -> FieldSelectors\\n -> Maybe Name -- class name\\n -> DataFamInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_di dup_fields_ok has_sel mb_cls dfid@(DataFamInstDecl { dfid_eqn = ti_decl })\\n = do { main_name <- unLoc <$> lookupFamInstName mb_cls (feqn_tycon ti_decl)\\n ; let LConsWithFields cons_with_flds flds = hsDataFamInstBinders dfid\\n ; sub_names <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst sub_names) flds\\n ; mapM_ (add_dup_fld_errs flds\') sub_names\\n ; let fld_env = mk_fld_env sub_names flds\'\\n con_gres = map (mkLocalConLikeGRE (ParentIs main_name)) fld_env\\n field_gres = mkLocalFieldGREs (ParentIs main_name) fld_env\\n -- NB: the data family name is not bound here,\\n -- so we don\'t return a GlobalRdrElt for it here!\\n ; return $ con_gres ++ field_gres }\\n\\n -- Add errors if a constructor has a duplicate record field.\\n add_dup_fld_errs :: IntMap FieldLabel\\n -> (Name, Either VisArity [Located Int])\\n -> IOEnv (Env TcGblEnv TcLclEnv) ()\\n add_dup_fld_errs all_flds (con, con_flds_or_arity)\\n | Right con_flds <- con_flds_or_arity\\n , let (_, dups) = removeDups (comparing unLoc) con_flds\\n = for_ dups $ \\\\ dup_flds ->\\n -- Report the error at the location of the second occurrence\\n -- of the duplicate field.\\n let loc =\\n case dup_flds of\\n _ :| ( L loc _ : _) -> loc\\n L loc _ :| _ -> loc\\n dup_rdrs = fmap (nameRdrName . flSelector . (all_flds IntMap.!) . unLoc) dup_flds\\n in addErrAt loc $ TcRnDuplicateFieldName (RecordFieldDecl con) dup_rdrs\\n | otherwise\\n = return ()\\n\\nnewRecordFieldLabel :: DuplicateRecordFields -> FieldSelectors -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel\\nnewRecordFieldLabel _ _ [] _ = error \\"newRecordFieldLabel: datatype has no constructors!\\"\\nnewRecordFieldLabel dup_fields_ok has_sel (dc:_) (L loc (FieldOcc _ (L _ fld)))\\n = do { selName <- newTopSrcBinder $ L (l2l loc) $ field\\n ; return $ FieldLabel { flHasDuplicateRecordFields = dup_fields_ok\\n , flHasFieldSelector = has_sel\\n , flSelector = selName } }\\n where\\n fld_occ = rdrNameOcc fld\\n dc_fs = occNameFS $ nameOccName dc\\n field\\n -- Use an Exact RdrName as-is, to preserve the bindings\\n -- of an already renamer-resolved field and its use\\n -- sites. This is needed to correctly support record\\n -- selectors in Template Haskell. See Note [Binders in\\n -- Template Haskell] in \\"GHC.ThToHs\\" and Note [Looking up\\n -- Exact RdrNames] in \\"GHC.Rename.Env\\".\\n | isExact fld\\n = assertPpr (fieldOcc_maybe fld_occ == Just dc_fs)\\n (vcat [ text \\"newRecordFieldLabel: incorrect namespace for exact Name\\" <+> quotes (ppr fld)\\n , text \\"expected namespace:\\" <+> pprNameSpace (fieldName dc_fs)\\n , text \\" actual namespace:\\" <+> pprNameSpace (occNameSpace fld_occ) ])\\n fld\\n\\n -- Field names produced by the parser are namespaced with VarName.\\n -- Here we namespace them according to the first constructor.\\n -- See Note [Record field namespacing] in GHC.Types.Name.Occurrence.\\n | otherwise\\n = mkRdrUnqual $ varToRecFieldOcc dc_fs fld_occ\\n\\n{-\\nNote [Looking up family names in family instances]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider\\n\\n module M where\\n type family T a :: *\\n type instance M.T Int = Bool\\n\\nWe might think that we can simply use \'lookupOccRn\' when processing the type\\ninstance to look up \'M.T\'. Alas, we can\'t! The type family declaration is in\\nthe *same* HsGroup as the type instance declaration. Hence, as we are\\ncurrently collecting the binders declared in that HsGroup, these binders will\\nnot have been added to the global environment yet.\\n\\nSolution is simple: process the type family declarations first, extend\\nthe environment, and then process the type instances.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Filtering imports}\\n* *\\n************************************************************************\\n\\n@filterImports@ takes the @ExportEnv@ telling what the imported module makes\\navailable, and filters it through the import spec (if any).\\n\\nNote [Dealing with imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nFor import M( ies ), we take each AvailInfo from the mi_exports of M, and make\\n\\n imp_occ_env :: OccEnv (NameEnv ImpOccItem)\\n\\nThis map contains one entry for each OccName that M exports, mapping each OccName\\nto the following information:\\n\\n 1. the GlobalRdrElt corresponding to the OccName,\\n 2. whether this GlobalRdrElt was the parent in the AvailInfo we found\\n the OccName in.\\n 3. the GlobalRdrElts that were bundled together in the AvailInfo we found\\n this OccName in (not including the parent),\\n\\nWe need (2) and (3) during the construction of the OccEnv because of associated\\ntypes and bundled pattern synonyms, respectively.\\n(3) is explained in Note [Importing PatternSynonyms].\\n\\nTo explain (2), consider for example:\\n\\n module M where\\n class C a where { data T a }\\n instance C Int where { data T Int = T1 | T2 }\\n instance C Bool where { data T Int = T3 }\\n\\nHere, M\'s exports avails are (recalling the AvailTC invariant from GHC.Types.Avail)\\n\\n C(C,T), T(T,T1,T2,T3)\\n\\nNotice that T appears *twice*, once as a child and once as a parent. From\\nthese two exports, respectively, during construction of the imp_occ_env, we begin\\nby associating the following two elements with the key T:\\n\\n T -> ImpOccItem { imp_item = gre1, imp_bundled = [C,T] , imp_is_parent = False }\\n T -> ImpOccItem { imp_item = gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nwhere `gre1`, `gre2` are two GlobalRdrElts with greName T.\\nWe combine these (in function \'combine\' in \'mkImportOccEnv\') by discarding the\\nnon-parent item, thusly:\\n\\n T -> IE_ITem { imp_item = gre1 `plusGRE` gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nNote the `plusGRE`: this ensures we don\'t drop parent information;\\nsee Note [Preserve parent information when combining import OccEnvs].\\n\\nSo the overall imp_occ_env is:\\n\\n C -> ImpOccItem { imp_item = C, imp_bundled = [T ], imp_is_parent = True }\\n T -> ImpOccItem { imp_item = T , imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n T1 -> ImpOccItem { imp_item = T1, imp_bundled = [T1,T2,T3], imp_is_parent = False }\\n -- similarly for T2, T3\\n\\nNote that the imp_occ_env will have entries for data constructors too,\\nalthough we never look up data constructors.\\n\\nNote [Importing PatternSynonyms]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nAs described in Note [Dealing with imports], associated types can lead to the\\nsame Name appearing twice, both as a child and once as a parent, when\\nconstructing the imp_occ_env. The same thing can happen with pattern synonyms\\nif they are exported bundled with a type.\\n\\nA simplified example, based on #11959:\\n\\n {-# LANGUAGE PatternSynonyms #-}\\n module M (T(P), pattern P) where -- Duplicate export warning, but allowed\\n data T = MkT\\n pattern P = MkT\\n\\nHere we have T(P) and P in export_avails, and respectively construct both\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n P -> ImpOccItem { imp_item = P, imp_bundled = [] , imp_is_parent = False }\\n\\nWe combine these by dropping the one with no siblings, leaving us with:\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n\\nThat is, we simply discard the non-bundled Avail.\\n\\nNote [Importing DuplicateRecordFields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn filterImports, another complicating factor is DuplicateRecordFields.\\nSuppose we have:\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (S(foo), T(foo)) where\\n data S = MkS { foo :: Int }\\n data T = MkT { foo :: Int }\\n\\n module N where\\n import M (foo) -- this is allowed (A)\\n import M (S(foo)) -- this is allowed (B)\\n\\nHere M exports \'foo\' at two different OccNames, with different namespaces for\\nthe two construtors MkS and MkT. Then, when we look up \'foo\' in lookup_names\\nfor case (A), we have a variable foo but must look in all the record field\\nnamespaces to find the two fields (and hence two different Avails).\\nWhereas in case (B) we reach the lookup_ie case for IEThingWith,\\nwhich looks up \'S\' and then finds the unique \'foo\' amongst its children.\\n\\nSee T16745 for a test of this.\\n\\nNote [Preserve parent information when combining import OccEnvs]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen discarding one ImpOccItem in favour of another, as described in\\nNote [Dealing with imports], we must make sure to combine the GREs so that\\nwe don\'t lose information.\\n\\nConsider for example #24084:\\n\\n module M1 where { class C a where { type T a } }\\n module M2 ( module M1 ) where { import M1 }\\n module M3 where { import M2 ( C, T ); instance C () where T () = () }\\n\\nWhen processing the import list of `M3`, we will have two `Avail`s attached\\nto `T`, namely `C(C, T)` and `T(T)`. We combine them in the `combine` function\\nof `mkImportOccEnv`; as described in Note [Dealing with imports] we discard\\n`C(C, T)` in favour of `T(T)`. However, in doing so, we **must not**\\ndiscard the information want that `C` is the parent of `T`. Indeed,\\nlosing track of this information can cause errors when importing,\\nas we could get an error of the form\\n\\n \\u2018T\\u2019 is not a (visible) associated type of class \\u2018C\\u2019\\n\\nThis explains why we use `plusGRE` when combining the two ImpOccItems, even\\nthough we are discarding one in favour of the other.\\n-}\\n\\n-- | All the \'GlobalRdrElt\'s associated with an \'AvailInfo\'.\\ngresFromAvail :: HasDebugCallStack\\n => HscEnv -> Maybe ImportSpec -> AvailInfo -> [GlobalRdrElt]\\ngresFromAvail hsc_env prov avail =\\n [ mk_gre nm info\\n | nm <- availNames avail\\n , let info = lookupGREInfo hsc_env nm ]\\n where\\n\\n mk_gre n info\\n = case prov of\\n -- Nothing => bound locally\\n -- Just is => imported from \'is\'\\n Nothing -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = True, gre_imp = emptyBag\\n , gre_info = info }\\n Just is -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = False, gre_imp = unitBag is\\n , gre_info = info }\\n\\n-- | All the \'GlobalRdrElt\'s associated with a collection of \'AvailInfo\'s.\\ngresFromAvails :: HscEnv -> Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]\\ngresFromAvails hsc_env prov = concatMap (gresFromAvail hsc_env prov)\\n\\nimportsFromIface :: HscEnv -> ModIface -> ImpDeclSpec -> Maybe NameSet -> GlobalRdrEnv\\nimportsFromIface hsc_env iface decl_spec hidden = mkGlobalRdrEnv $ case hidden of\\n Nothing -> all_gres\\n Just hidden_names -> filter (not . (`elemNameSet` hidden_names) . greName) all_gres\\n where\\n all_gres = gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\nrnNamespaceSpecifier :: NamespaceSpecifier GhcPs -> NamespaceSpecifier GhcRn\\nrnNamespaceSpecifier (NoNamespaceSpecifier _) = NoNamespaceSpecifier noExtField\\nrnNamespaceSpecifier (TypeNamespaceSpecifier x) = TypeNamespaceSpecifier x\\nrnNamespaceSpecifier (DataNamespaceSpecifier x) = DataNamespaceSpecifier x\\n\\nfilterImports\\n :: HasDebugCallStack\\n => HscEnv\\n -> ModIface\\n -> ImpDeclSpec\\n -- ^ Import spec\\n -> Maybe (ImportListInterpretation, [LIE GhcPs])\\n -- ^ Whether this is a \\"hiding\\" import list\\n -> RnM (Maybe (ImportListInterpretation, [LIE GhcRn]), -- Import spec w/ Names\\n ImpUserList, -- same, but designed for storage in interfaces\\n GlobalRdrEnv) -- Same again, but in GRE form\\nfilterImports hsc_env iface decl_spec Nothing\\n = return (Nothing, ImpUserAll, importsFromIface hsc_env iface decl_spec Nothing)\\nfilterImports hsc_env iface decl_spec (Just (want_hiding, import_items))\\n = do -- check for errors, convert RdrNames to Names\\n items1 <- mapM lookup_lie import_items\\n\\n let items2 :: [(LIE GhcRn, [GlobalRdrElt])]\\n items2 = concat items1\\n -- NB we may have duplicates, and several items\\n -- for the same parent; e.g N(x) and N(y)\\n\\n (gres, imp_user_list) = case want_hiding of\\n Exactly ->\\n let gres = concatMap (gresFromIE decl_spec) items2\\n gre_env = mkGlobalRdrEnv gres\\n implicit_parents = mkNameSet $ mapMaybe parentOfImplicitlyImportedGRE gres\\n in (gre_env, ImpUserExplicit (gresToAvailInfo $ globalRdrEnvElts $ gre_env) implicit_parents)\\n EverythingBut ->\\n let hidden_names = mkNameSet $ concatMap (map greName . snd) items2\\n in (importsFromIface hsc_env iface decl_spec (Just hidden_names), ImpUserEverythingBut hidden_names)\\n\\n return (Just (want_hiding, map fst items2), imp_user_list, gres)\\n where\\n import_mod = mi_module iface\\n all_avails = mi_exports iface\\n imp_occ_env = mkImportOccEnv hsc_env decl_spec all_avails\\n\\n -- Look up a parent (type constructor, class or data constructor)\\n -- in an import.\\n lookup_parent :: IE GhcPs -> RdrName -> IELookupM ImpOccItem\\n lookup_parent ie rdr =\\n assertPpr (not $ isVarNameSpace ns)\\n (vcat [ text \\"filterImports lookup_parent: unexpected variable\\"\\n , text \\"rdr:\\" <+> ppr rdr\\n , text \\"namespace:\\" <+> pprNameSpace ns ]) $\\n do { xs <- lookup_names ie rdr\\n ; case xs of\\n cax :| [] -> return cax\\n _ -> pprPanic \\"filter_imports lookup_parent ambiguous\\" $\\n vcat [ text \\"rdr:\\" <+> ppr rdr\\n , text \\"lookups:\\" <+> ppr (fmap imp_item xs) ] }\\n -- Looking up non-variables is always unambiguous,\\n -- as there can be at most one corresponding item\\n -- in the imp_occ_env.\\n -- See item (1) of Note [Exporting duplicate declarations]\\n -- in GHC.Tc.Gen.Export.\\n where\\n occ = rdrNameOcc rdr\\n ns = occNameSpace occ\\n\\n -- Look up a RdrName used in an import, returning multiple values if there\\n -- are several fields with the same name exposed by the module\\n lookup_names :: IE GhcPs -> RdrName -> IELookupM (NonEmpty ImpOccItem)\\n lookup_names ie rdr\\n | isQual rdr\\n = failLookupWith (QualImportError rdr)\\n | otherwise\\n = case lookups of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n item:items -> return $ item :| items\\n where\\n lookups = concatMap nonDetNameEnvElts\\n $ lookupImpOccEnv (RelevantGREsFOS WantNormal) imp_occ_env (rdrNameOcc rdr)\\n\\n lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, [GlobalRdrElt])]\\n lookup_lie (L loc ieRdr)\\n = setSrcSpanA loc $\\n do (stuff, warns) <- run_lookup ([],[]) (lookup_ie ieRdr)\\n mapM_ (addTcRnDiagnostic <=< warning_msg) warns\\n return [ (L loc ie, gres) | (ie,gres) <- stuff ]\\n where\\n\\n -- Warn when importing T(..) and no children are brought in scope\\n warning_msg (DodgyImport reason) =\\n pure (TcRnDodgyImports reason)\\n warning_msg MissingImportList =\\n pure (TcRnMissingImportList ieRdr)\\n warning_msg (BadImportW ie sub) = do\\n -- \'BadImportW\' is only constructed below in \'bad_import_w\', in\\n -- the \'EverythingBut\' case, so here we assume a \'hiding\' clause.\\n (reason :| _) <- badImportItemErr iface decl_spec ie sub all_avails\\n pure (TcRnDodgyImports (DodgyImportsHiding reason))\\n warning_msg (DeprecatedExport n w) =\\n pure $ TcRnPragmaWarning\\n PragmaWarningExport\\n { pwarn_occname = occName n\\n , pwarn_impmod = moduleName import_mod }\\n w\\n\\n run_lookup :: a -> IELookupM a -> TcRn a\\n run_lookup def m = case m of\\n Failed err -> do\\n msgs <- lookup_err_msgs err\\n forM_ msgs $ \\\\msg -> addErr (TcRnImportLookup msg)\\n return def\\n Succeeded a -> return a\\n\\n lookup_err_msgs err = case err of\\n BadImport ie sub -> badImportItemErr iface decl_spec ie sub all_avails\\n IllegalImport -> pure $ NE.singleton ImportLookupIllegal\\n QualImportError rdr -> pure $ NE.singleton (ImportLookupQualified rdr)\\n\\n -- For each import item, we convert its RdrNames to Names,\\n -- and at the same time compute all the GlobalRdrElt corresponding\\n -- to what is actually imported by this item.\\n -- Returns Nothing on error.\\n --\\n -- Returns a list because, with DuplicateRecordFields, a naked\\n -- import/export of a record field can correspond to multiple\\n -- different GlobalRdrElts. See Note [Importing DuplicateRecordFields].\\n lookup_ie :: IE GhcPs\\n -> IELookupM ([(IE GhcRn, [GlobalRdrElt])], [IELookupWarning])\\n lookup_ie ie = handle_bad_import $\\n case ie of\\n IEVar _ (L l n) _ -> do\\n -- See Note [Importing DuplicateRecordFields]\\n xs <- lookup_names ie (ieWrappedName n)\\n let gres = map imp_item $ NE.toList xs\\n export_depr_warns\\n | want_hiding == Exactly\\n = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ( [ (IEVar Nothing (L l (replaceWrappedName n name)) noDocstring, [gre])\\n | gre <- gres\\n , let name = greName gre ]\\n , export_depr_warns )\\n\\n IEThingAll x ns_spec (L l tc) _ -> do\\n ImpOccItem { imp_item = gre\\n , imp_bundled = bundled_gres\\n , imp_is_parent = is_par\\n }\\n <- lookup_parent ie $ ieWrappedName tc\\n let name = greName gre\\n\\n child_gres :: [GlobalRdrElt]\\n child_gres\\n | is_par = filterByNamespaceSpecifierGREs ns_spec bundled_gres\\n | otherwise = []\\n\\n imp_list_warn\\n\\n | null child_gres\\n -- e.g. f(..) or T(..) where T is a type synonym\\n = [DodgyImport (DodgyImportsEmptyParent ie ns_spec gre)]\\n\\n -- e.g. import M( T(..) )\\n | not (is_qual decl_spec)\\n = [MissingImportList]\\n\\n | otherwise\\n = []\\n\\n renamed_ie = IEThingAll (x { ieta_warning = Nothing })\\n (rnNamespaceSpecifier ns_spec)\\n (L l (replaceWrappedName tc name))\\n noDocstring\\n export_depr_warn\\n | want_hiding == Exactly\\n = maybeToList $ mk_depr_export_warning gre\\n -- We don\'t want to warn about the children as they\\n -- are not explicitly mentioned; the warning will\\n -- be emitted later on if they are used\\n | otherwise = []\\n\\n return ( [(renamed_ie, gre:child_gres)]\\n , imp_list_warn ++ export_depr_warn)\\n\\n\\n IEThingAbs _ (L l tc\') _\\n | want_hiding == EverythingBut -- hiding ( C )\\n -- Here the \'C\' can be a data constructor\\n -- *or* a type/class, or even both\\n -> let tc = ieWrappedName tc\'\\n tc_name = lookup_parent ie tc\\n dc_name = lookup_parent ie (setRdrNameSpace tc srcDataName)\\n in\\n case catIELookupM [ tc_name, dc_name ] of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n names -> return ( [mkIEThingAbs tc\' l (imp_item name) | name <- names], [])\\n | otherwise\\n -> do ImpOccItem { imp_item = gre } <- lookup_parent ie (ieWrappedName tc\')\\n return ( [mkIEThingAbs tc\' l gre]\\n , maybeToList $ mk_depr_export_warning gre)\\n\\n IEThingWith (deprecation, ann) ltc@(L l rdr_tc) wc rdr_ns _ -> do\\n ImpOccItem { imp_item = gre, imp_bundled = subnames }\\n <- lookup_parent (IEThingAbs Nothing ltc noDocstring) (ieWrappedName rdr_tc)\\n let name = greName gre\\n\\n -- Look up the children in the sub-names of the parent\\n -- See Note [Importing DuplicateRecordFields]\\n let (children_errs, childnames) = lookupChildren subnames rdr_ns\\n\\n bad_import_warns <-\\n if null children_errs then return [] else\\n let items = map lce_wrapped_name children_errs\\n ie = IEThingWith (deprecation, ann) ltc wc items noDocstring\\n -- We are trying to import T( a,b,c,d ), and failed\\n -- to find \'b\' and \'d\'. So we make up an import item\\n -- to report as failing, namely T( b, d ).\\n -- c.f. #15413\\n subordinate_err = mkSubordinateError gre children_errs\\n in bad_import_w ie subordinate_err\\n\\n let name\' = replaceWrappedName rdr_tc name\\n childnames\' = map (to_ie_post_rn . fmap greName) childnames\\n gres = gre : map unLoc childnames\\n export_depr_warns\\n | want_hiding == Exactly = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ([ (IEThingWith (Nothing, ann) (L l name\') wc childnames\' noDocstring\\n ,gres)]\\n , bad_import_warns ++ export_depr_warns)\\n\\n IEWholeNamespace x ns_spec -> do\\n let mod_name = moduleName import_mod\\n names = map greName gres\\n renamed_ie = IEWholeNamespace x { iewn_warning = Nothing\\n , iewn_names = names }\\n (rnNamespaceSpecifier ns_spec)\\n gres = filterByNamespaceSpecifierGREs ns_spec $\\n gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n dodgy_warn\\n | null gres = [DodgyImport (DodgyImportsWildcard mod_name ns_spec)]\\n | otherwise = []\\n return ([(renamed_ie, gres)],\\n dodgy_warn)\\n\\n _other -> failLookupWith IllegalImport\\n -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed...\\n -- all of those constitute errors.\\n\\n where\\n mkIEThingAbs tc l gre\\n = (IEThingAbs Nothing (L l (replaceWrappedName tc n)) noDocstring, [gre])\\n where n = greName gre\\n\\n -- N.B. imports never have docstrings\\n noDocstring = Nothing\\n\\n handle_bad_import m = catchIELookup m $ \\\\case\\n BadImport ie sub -> do\\n ws <- bad_import_w ie sub\\n return ([], ws)\\n err -> failLookupWith err\\n\\n bad_import_w :: IE GhcPs -> IsSubordinateError -> IELookupM [IELookupWarning]\\n bad_import_w ie sub\\n | want_hiding == EverythingBut = return [BadImportW ie sub]\\n | otherwise = failLookupWith (BadImport ie sub)\\n\\n mk_depr_export_warning gre\\n = DeprecatedExport name <$> mi_export_warn_fn iface name\\n where\\n name = greName gre\\n\\n-- | Assuming a subordinate item could not be found, do another lookup for a\\n-- more specific error message.\\nmkBadExportSubordinate :: [GlobalRdrElt] -> LIEWrappedName GhcPs -> BadExportSubordinate\\nmkBadExportSubordinate child_gres n =\\n case lookupChildren child_gres [n] of\\n (LookupChildNonType {lce_nontype_item = g} : _, _) -> BadExportSubordinateNonType g\\n (LookupChildNonData {lce_nondata_item = g} : _, _) -> BadExportSubordinateNonData g\\n _ -> BadExportSubordinateNotFound n\\n\\ntype IELookupM = MaybeErr IELookupError\\n\\ndata IELookupWarning\\n = BadImportW (IE GhcPs) IsSubordinateError\\n | MissingImportList\\n | DodgyImport DodgyImportsReason\\n | DeprecatedExport Name (WarningTxt GhcRn)\\n\\n-- | Is this import/export item a subordinate or not?\\ndata IsSubordinateError\\n = IsSubordinateError { subordinate_err_parent :: !GlobalRdrElt\\n , subordinate_err_unavailable :: [FastString]\\n , subordinate_err_nontype :: [GlobalRdrElt]\\n , subordinate_err_nondata :: [GlobalRdrElt] }\\n | IsNotSubordinate\\n\\nmkSubordinateError :: GlobalRdrElt -> [LookupChildError] -> IsSubordinateError\\nmkSubordinateError gre children_errs = foldr add init_acc children_errs\\n where\\n init_acc :: IsSubordinateError\\n init_acc = IsSubordinateError gre [] [] []\\n\\n add :: LookupChildError -> IsSubordinateError -> IsSubordinateError\\n add children_err sub@IsSubordinateError{} =\\n case children_err of\\n LookupChildNonType{lce_nontype_item = g} ->\\n sub { subordinate_err_nontype = g : subordinate_err_nontype sub }\\n LookupChildNonData{lce_nondata_item = g} ->\\n sub { subordinate_err_nondata = g : subordinate_err_nondata sub }\\n LookupChildNotFound (L _ wname) ->\\n let fs = (occNameFS . rdrNameOcc . ieWrappedName) wname\\n in sub { subordinate_err_unavailable = fs : subordinate_err_unavailable sub }\\n add _ IsNotSubordinate = panic \\"mkSubordinateError: IsNotSubordinate\\"\\n\\ndata IELookupError\\n = QualImportError RdrName\\n | BadImport (IE GhcPs) IsSubordinateError\\n | IllegalImport\\n\\nfailLookupWith :: IELookupError -> IELookupM a\\nfailLookupWith err = Failed err\\n\\ncatchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a\\ncatchIELookup m h = case m of\\n Succeeded r -> return r\\n Failed err -> h err\\n\\ncatIELookupM :: [IELookupM a] -> [a]\\ncatIELookupM ms = [ a | Succeeded a <- ms ]\\n\\n-- | Information associated to an \'AvailInfo\' used in constructing\\n-- an \'OccEnv\' corresponding to imports.\\n--\\n-- See Note [Dealing with imports].\\ndata ImpOccItem\\n = ImpOccItem\\n { imp_item :: GlobalRdrElt\\n -- ^ The import item\\n , imp_bundled :: [GlobalRdrElt]\\n -- ^ Items bundled in the Avail this import item came from,\\n -- not including the import item itself if it is a parent.\\n , imp_is_parent :: Bool\\n -- ^ Is the import item a parent? See Note [Dealing with imports].\\n }\\n\\ninstance Outputable ImpOccItem where\\n ppr (ImpOccItem { imp_item = item, imp_bundled = bundled, imp_is_parent = is_par })\\n = braces $ hsep\\n [ text \\"ImpOccItem\\"\\n , if is_par then text \\"[is_par]\\" else empty\\n , ppr (greName item) <+> ppr (greParent item)\\n , braces $ text \\"bundled:\\" <+> ppr (map greName bundled) ]\\n\\n-- | Make an \'OccEnv\' of all the imports.\\n--\\n-- Complicated by the fact that associated data types and pattern synonyms\\n-- can appear twice. See Note [Dealing with imports].\\nmkImportOccEnv :: HscEnv -> ImpDeclSpec -> [IfaceExport] -> OccEnv (NameEnv ImpOccItem)\\nmkImportOccEnv hsc_env decl_spec all_avails =\\n mkOccEnv_C (plusNameEnv_C combine)\\n [ (occ, mkNameEnv [(nm, item)])\\n | avail <- all_avails\\n , let gres = gresFromAvail hsc_env (Just hiding_spec) avail\\n , gre <- gres\\n , let nm = greName gre\\n occ = greOccName gre\\n (is_parent, bundled) = case avail of\\n AvailTC c _\\n | c == nm -- (Recall the AvailTC invariant from GHC.Types.AvailInfo)\\n -> ( True, drop 1 gres ) -- \\"drop 1\\": don\'t include the parent itself.\\n | otherwise\\n -> ( False, gres )\\n _ -> ( False, [] )\\n item = ImpOccItem\\n { imp_item = gre\\n , imp_bundled = bundled\\n , imp_is_parent = is_parent }\\n ]\\n where\\n\\n hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\n -- See Note [Dealing with imports]\\n -- \'combine\' may be called for associated data types which appear\\n -- twice in the all_avails. In the example, we have two Avails for T,\\n -- namely T(T,T1,T2,T3) and C(C,T), and we combine them by dropping the\\n -- latter, in which T is not the parent.\\n combine :: ImpOccItem -> ImpOccItem -> ImpOccItem\\n combine item1@(ImpOccItem { imp_item = gre1, imp_is_parent = is_parent1 })\\n item2@(ImpOccItem { imp_item = gre2, imp_is_parent = is_parent2 })\\n | is_parent1 || is_parent2\\n , not (isRecFldGRE gre1 || isRecFldGRE gre2) -- NB: does not force GREInfo.\\n , let name1 = greName gre1\\n name2 = greName gre2\\n gre = gre1 `plusGRE` gre2\\n -- See Note [Preserve parent information when combining import OccEnvs]\\n = assertPpr (name1 == name2)\\n (ppr name1 <+> ppr name2) $\\n if is_parent1\\n then item1 { imp_item = gre }\\n else item2 { imp_item = gre }\\n -- Discard C(C,T) in favour of T(T, T1, T2, T3).\\n\\n -- \'combine\' may also be called for pattern synonyms which appear both\\n -- unassociated and associated (see Note [Importing PatternSynonyms]).\\n combine item1@(ImpOccItem { imp_item = c1, imp_bundled = kids1 })\\n item2@(ImpOccItem { imp_item = c2, imp_bundled = kids2 })\\n = assertPpr (greName c1 == greName c2\\n && (not (null kids1 && null kids2)))\\n (ppr c1 <+> ppr c2 <+> ppr kids1 <+> ppr kids2) $\\n if null kids1\\n then item2\\n else item1\\n -- Discard standalone pattern P in favour of T(P).\\n\\n-- | Essentially like @lookupGRE env (LookupOccName occ which_gres)@,\\n-- but working with \'ImpOccItem\'s instead of \'GlobalRdrElt\'s.\\nlookupImpOccEnv :: WhichGREs GREInfo\\n -> OccEnv (NameEnv ImpOccItem) -> OccName -> [NameEnv ImpOccItem]\\nlookupImpOccEnv which_gres env occ =\\n mapMaybe relevant_items $ lookupOccEnv_AllNameSpaces env occ\\n where\\n is_relevant :: ImpOccItem -> Bool\\n is_relevant (ImpOccItem { imp_item = gre }) =\\n greIsRelevant which_gres (occNameSpace occ) gre\\n relevant_items :: NameEnv ImpOccItem -> Maybe (NameEnv ImpOccItem)\\n relevant_items nms\\n | let nms\' = filterNameEnv is_relevant nms\\n = if isEmptyNameEnv nms\'\\n then Nothing\\n else Just nms\'\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{Import/Export Utils}\\n* *\\n************************************************************************\\n-}\\n\\n-- | Given an import\\\\/export spec, appropriately set the @gre_imp@ field\\n-- for the \'GlobalRdrElt\'s.\\ngresFromIE :: ImpDeclSpec -> (LIE GhcRn, [GlobalRdrElt]) -> [GlobalRdrElt]\\ngresFromIE decl_spec (L loc ie, gres)\\n = map set_gre_imp gres\\n where\\n is_explicit = case ie of\\n IEThingAll _ _ name _ -> \\\\n -> n == lieWrappedName name\\n IEWholeNamespace _ _ -> \\\\_ -> False\\n _ -> \\\\_ -> True\\n prov_fn name\\n = ImpSpec { is_decl = decl_spec, is_item = item_spec }\\n where\\n item_spec = ImpSome { is_explicit = is_explicit name\\n , is_iloc = locA loc }\\n set_gre_imp gre@( GRE { gre_name = nm } )\\n = gre { gre_imp = unitBag $ prov_fn nm }\\n\\nparentOfImplicitlyImportedGRE :: Outputable info => GlobalRdrEltX info -> Maybe Name\\nparentOfImplicitlyImportedGRE gre =\\n if any (explicit_import . is_item) $ gre_imp gre\\n then Nothing\\n else greParent_maybe gre\\n where\\n explicit_import :: ImpItemSpec -> Bool\\n explicit_import (ImpAll {}) =\\n pprPanic \\"parentOfImplicitlyImportedGRE: ImpAll\\" (ppr gre)\\n explicit_import (ImpSome { is_explicit }) = is_explicit\\n\\n{- Note [Children for duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider the module\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (F(foo, MkFInt, MkFBool)) where\\n data family F a\\n data instance F Int = MkFInt { foo :: Int }\\n data instance F Bool = MkFBool { foo :: Bool }\\n\\nThe `foo` in the export list refers to *both* selectors! For this\\nreason, lookupChildren builds an environment that maps the FastString\\nto a list of items, rather than a single item.\\n-}\\n\\nmkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]\\nmkChildEnv gres = foldr add emptyNameEnv gres\\n where\\n add gre env = case greParent gre of\\n ParentIs p -> extendNameEnv_Acc (:) Utils.singleton env p gre\\n NoParent -> env\\n\\nfindChildren :: NameEnv [a] -> Name -> [a]\\nfindChildren env n = lookupNameEnv env n `orElse` []\\n\\ndata LookupChildError\\n = LookupChildNotFound { lce_wrapped_name :: !(LIEWrappedName GhcPs) }\\n | LookupChildNonType { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nontype_item :: !GlobalRdrElt }\\n | LookupChildNonData { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nondata_item :: !GlobalRdrElt }\\n\\nlookupChildren :: [GlobalRdrElt]\\n -> [LIEWrappedName GhcPs]\\n -> ( [LookupChildError] -- The ones for which the lookup failed\\n , [LocatedA GlobalRdrElt] )\\n-- (lookupChildren all_kids rdr_items) maps each rdr_item to its\\n-- corresponding Name in all_kids, if the former exists\\n-- The matching is done by FastString, not OccName, so that\\n-- Cls( meth, AssocTy )\\n-- will correctly find AssocTy among the all_kids of Cls, even though\\n-- the RdrName for AssocTy may have a (bogus) DataName namespace\\n-- (Really the rdr_items should be FastStrings in the first place.)\\nlookupChildren all_kids rdr_items = (fails, successes)\\n where\\n mb_xs = map do_one rdr_items\\n fails = [ err | Failed err <- mb_xs ]\\n successes = [ ok | Succeeded oks <- mb_xs, ok <- NE.toList oks ]\\n\\n do_one :: LIEWrappedName GhcPs -> MaybeErr LookupChildError (NonEmpty (LocatedA GlobalRdrElt))\\n do_one item@(L l r) =\\n case r of\\n IEName{}\\n -- IEName (unadorned name) places no restriction on the namespace of\\n -- the imported entity, so we look in both `val_gres` and `typ_gres`.\\n -- In case of conflict (punning), the value namespace takes priority.\\n -- See Note [Prioritise the value namespace in subordinate import lists]\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEType{}\\n -- IEType (\'type\' namespace specifier) restricts the lookup to the\\n -- type namespace, i.e. to `typ_gres`. In case of failure, we check\\n -- `val_gres` to produce a more helpful error message.\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- val_gres -> Failed $ LookupChildNonType item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEData{}\\n -- IEData (\'data\' namespace specifier) restricts the lookup to the\\n -- data namespace, i.e. to `val_gres`. In case of failure, we check\\n -- `typ_gres` to produce a more helpful error message.\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- typ_gres -> Failed $ LookupChildNonData item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEPattern{} -> panic \\"lookupChildren: IEPattern\\" -- Never happens (invalid syntax)\\n IEDefault{} -> panic \\"lookupChildren: IEDefault\\" -- Never happens (invalid syntax)\\n where\\n fs = (occNameFS . rdrNameOcc . ieWrappedName) r\\n gres = fromMaybe [] (lookupFsEnv kid_env fs)\\n (val_gres, typ_gres) = partition (isValNameSpace . greNameSpace) gres\\n\\n -- See Note [Children for duplicate record fields]\\n kid_env :: FastStringEnv [GlobalRdrElt]\\n kid_env = extendFsEnvList_C (++) emptyFsEnv\\n [(occNameFS (occName x), [x]) | x <- all_kids]\\n\\n\\n{- Note [Prioritise the value namespace in subordinate import lists]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider this program that defines a class that has both an associated type\\nnamed (#) and a method named (#)\\n\\n module M_assoc where\\n class C a b where\\n type a # b\\n (#) :: a -> b -> ()\\n module N_assoc where\\n import M_assoc( C((#)) )\\n\\nIn the import declaration, when we see the unadorned name (#) in the subordinate\\nimport list of C, which children should we bring into scope? Our options are:\\n\\n a) only the method (#)\\n b) only the associated type (#)\\n c) both the method and the associated type\\n\\nTo follow the precedent established by top-level items, we go with option (a).\\nIndeed, consider a slightly different program\\n\\n module M_top where\\n type family a # b\\n a # b = ()\\n module N_top where\\n import M_top( (#) )\\n\\nHere the import brings only the function (#) into scope, and one has to say\\n`type (#)` to get the type family.\\n-}\\n\\n-------------------------------\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused names}\\n* *\\n*********************************************************\\n-}\\n\\nreportUnusedNames :: TcGblEnv -> HscSource -> RnM ()\\nreportUnusedNames gbl_env hsc_src\\n = do { keep <- readTcRef (tcg_keep gbl_env)\\n ; traceRn \\"RUN\\" (ppr (tcg_dus gbl_env))\\n ; warnUnusedImportDecls gbl_env hsc_src\\n ; warnUnusedTopBinds $ unused_locals keep\\n ; warnMissingSignatures gbl_env\\n ; warnMissingKindSignatures gbl_env }\\n where\\n used_names :: NameSet -> NameSet\\n used_names keep = findUses (tcg_dus gbl_env) emptyNameSet `unionNameSet` keep\\n -- NB: currently, if f x = g, we only treat \'g\' as used if \'f\' is used\\n -- Hence findUses\\n\\n -- Collect the defined names from the in-scope environment\\n defined_names :: [GlobalRdrElt]\\n defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)\\n\\n kids_env = mkChildEnv defined_names\\n -- This is done in mkExports too; duplicated work\\n\\n gre_is_used :: NameSet -> GlobalRdrElt -> Bool\\n gre_is_used used_names gre0\\n = name `elemNameSet` used_names\\n || any (\\\\ gre -> greName gre `elemNameSet` used_names) (findChildren kids_env name)\\n -- A use of C implies a use of T,\\n -- if C was brought into scope by T(..) or T(C)\\n where\\n name = greName gre0\\n\\n -- Filter out the ones that are\\n -- (a) defined in this module, and\\n -- (b) not defined by a \'deriving\' clause\\n -- The latter have an Internal Name, so we can filter them out easily\\n unused_locals :: NameSet -> [GlobalRdrElt]\\n unused_locals keep =\\n let -- Note that defined_and_used, defined_but_not_used\\n -- are both [GRE]; that\'s why we need defined_and_used\\n -- rather than just used_names\\n _defined_and_used, defined_but_not_used :: [GlobalRdrElt]\\n (_defined_and_used, defined_but_not_used)\\n = partition (gre_is_used (used_names keep)) defined_names\\n\\n in filter is_unused_local defined_but_not_used\\n is_unused_local :: GlobalRdrElt -> Bool\\n is_unused_local gre = isLocalGRE gre\\n && isExternalName (greName gre)\\n\\n{- *********************************************************************\\n* *\\n Missing signatures\\n* *\\n********************************************************************* -}\\n\\n{-\\nNote [Missing signatures]\\n~~~~~~~~~~~~~~~~~~~~~~~~~\\nThere are four warning flags in play:\\n\\n * -Wmissing-exported-signatures\\n Warn about any exported top-level function/value without a type signature.\\n Does not include pattern synonyms.\\n\\n * -Wmissing-signatures\\n Warn about any top-level function/value without a type signature. Does not\\n include pattern synonyms. Takes priority over -Wmissing-exported-signatures.\\n\\n * -Wmissing-exported-pattern-synonym-signatures\\n Warn about any exported pattern synonym without a type signature.\\n\\n * -Wmissing-pattern-synonym-signatures\\n Warn about any pattern synonym without a type signature. Takes priority over\\n -Wmissing-exported-pattern-synonym-signatures.\\n\\n-}\\n\\n-- | Warn the user about top level binders that lack type signatures.\\n-- Called /after/ type inference, so that we can report the\\n-- inferred type of the function\\nwarnMissingSignatures :: TcGblEnv -> RnM ()\\nwarnMissingSignatures gbl_env\\n = do { let exports = availsToNameSet (tcg_exports gbl_env)\\n sig_ns = tcg_sigs gbl_env\\n -- We use sig_ns to exclude top-level bindings that are generated by GHC\\n binds = collectHsBindsBinders CollNoDictBinders $ tcg_binds gbl_env\\n pat_syns = tcg_patsyns gbl_env\\n\\n not_ghc_generated :: Name -> Bool\\n not_ghc_generated name = name `elemNameSet` sig_ns\\n\\n add_binding_warn :: Id -> RnM ()\\n add_binding_warn id =\\n when (not_ghc_generated name) $\\n do { env <- liftZonkM $ tcInitTidyEnv -- Why not use emptyTidyEnv?\\n ; let ty = tidyOpenType env (idType id)\\n missing = MissingTopLevelBindingSig name ty\\n diag = TcRnMissingSignature missing exported\\n ; addDiagnosticAt (getSrcSpan name) diag }\\n where\\n name = idName id\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n add_patsyn_warn :: PatSyn -> RnM ()\\n add_patsyn_warn ps =\\n when (not_ghc_generated name) $\\n addDiagnosticAt (getSrcSpan name)\\n (TcRnMissingSignature missing exported)\\n where\\n name = patSynName ps\\n missing = MissingPatSynSig ps\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n -- Warn about missing signatures\\n -- Do this only when we have a type to offer\\n -- See Note [Missing signatures]\\n ; mapM_ add_binding_warn binds\\n ; mapM_ add_patsyn_warn pat_syns\\n }\\n\\n-- | Warn the user about tycons that lack kind signatures.\\n-- Called /after/ type (and kind) inference, so that we can report the\\n-- inferred kinds.\\nwarnMissingKindSignatures :: TcGblEnv -> RnM ()\\nwarnMissingKindSignatures gbl_env\\n = do { cusks_enabled <- xoptM LangExt.CUSKs\\n ; mapM_ (add_ty_warn cusks_enabled) tcs\\n }\\n where\\n tcs = tcg_tcs gbl_env\\n ksig_ns = tcg_ksigs gbl_env\\n exports = availsToNameSet (tcg_exports gbl_env)\\n\\n has_kind_signature :: Name -> Bool\\n has_kind_signature name = name `elemNameSet` ksig_ns\\n\\n add_ty_warn :: Bool -> TyCon -> RnM ()\\n add_ty_warn cusks_enabled tyCon =\\n when (has_kind_signature name) $\\n addDiagnosticAt (getSrcSpan name) diag\\n where\\n name = tyConName tyCon\\n diag = TcRnMissingSignature missing exported\\n missing = MissingTyConKindSig tyCon cusks_enabled\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused imports}\\n* *\\n*********************************************************\\n\\nThis code finds which import declarations are unused. The\\nspecification and implementation notes are here:\\n https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/unused-imports\\n\\nSee also Note [Choosing the best import declaration] in GHC.Types.Name.Reader\\n-}\\n\\ntype ImportDeclUsage\\n = ( LImportDecl GhcRn -- The import declaration\\n , [GlobalRdrElt] -- What *is* used (normalised)\\n , [Name] -- What is imported but *not* used\\n , [NamespaceSpecifier GhcRn] ) -- Unused wildcards\\n\\nwarnUnusedImportDecls :: TcGblEnv -> HscSource -> RnM ()\\nwarnUnusedImportDecls gbl_env hsc_src\\n = do { uses <- readMutVar (tcg_used_gres gbl_env)\\n ; let imports = tcg_rn_imports gbl_env\\n rdr_env = tcg_rdr_env gbl_env\\n\\n -- We should only warn for unnecessary *user* imports, but deciding\\n -- minimal imports should take generated imports into account\\n ; let usageUserImports = findImportUsage (excludeGenerated imports) uses\\n usageAllImports = findImportUsage imports uses\\n\\n ; traceRn \\"warnUnusedImportDecls\\" $\\n (vcat [ text \\"Uses:\\" <+> ppr uses\\n , text \\"Usage all user imports: \\" <+> ppr usageUserImports\\n , text \\"Usage all imports: \\" <+> ppr usageAllImports])\\n\\n ; mapM_ (warnUnusedImport rdr_env) usageUserImports\\n\\n ; whenGOptM Opt_D_dump_minimal_imports $\\n printMinimalImports hsc_src usageAllImports }\\n\\n-- | Exclude generated imports\\nexcludeGenerated :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\nexcludeGenerated = filterOut (isGeneratedImport . ideclOrigin . ideclExt . unLoc)\\n\\nfindImportUsage :: [LImportDecl GhcRn]\\n -> [GlobalRdrElt]\\n -> [ImportDeclUsage]\\n\\nfindImportUsage imports used_gres\\n = map unused_decl imports\\n where\\n import_usage :: ImportMap\\n import_usage = mkImportMap used_gres\\n\\n unused_decl :: LImportDecl GhcRn -> ImportDeclUsage\\n unused_decl decl@(L _ (ImportDecl { ideclImportList = imps }))\\n = -- pprTrace \\"unused_decl\\" (vcat [ ppr decl\\n -- , text \\"used\\" <+> ppr used_gres\\n -- , text \\"unused\\" <+> ppr unused_names ]) $\\n (decl, used_gres, unused_names, unused_wcs)\\n where\\n used_gres = lookupImportMap decl import_usage\\n\\n used_gre_env = mkGlobalRdrEnv used_gres\\n used_parents = mkNameSet (mapMaybe greParent_maybe used_gres)\\n\\n (unused_names, unused_wcs) -- Not trivial; see eg #7454\\n = case imps of\\n Just (Exactly, imp_ies) ->\\n let unused = foldr (add_unused . unLoc) emptyUnusedNames imp_ies\\n nms = nameSetElemsStable (collectUnusedNames unused)\\n wcs = collectUnusedWildcards unused\\n in (nms, wcs)\\n _other -> ([], []) -- No explicit import list => no unused-name list\\n\\n add_unused :: IE GhcRn -> UnusedNames -> UnusedNames\\n add_unused (IEVar _ n _) acc = add_unused_name (lieWrappedName n) True acc\\n add_unused (IEThingAbs _ n _) acc = add_unused_name (lieWrappedName n) False acc\\n add_unused (IEThingAll _ _ n _) acc = add_unused_all (lieWrappedName n) acc\\n add_unused (IEThingWith _ p wc ns _) acc = add_wc_all (add_unused_with pn xs acc)\\n where pn = lieWrappedName p\\n xs = map lieWrappedName ns\\n add_wc_all = case wc of\\n NoIEWildcard -> id\\n IEWildcard _ -> add_unused_all pn\\n add_unused (IEWholeNamespace x ns_spec) acc = add_unused_wildcard ns_spec (iewn_names x) acc\\n add_unused _ acc = acc\\n\\n add_unused_name :: Name -> Bool -> UnusedNames -> UnusedNames\\n add_unused_name n is_ie_var acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | is_ie_var\\n , isFieldName n\\n -- See Note [Reporting unused imported duplicate record fields]\\n = let\\n fs = getOccFS n\\n (flds, flds_used) = lookupFsEnv acc_fs fs `orElse` (emptyNameSet, Any False)\\n acc_fs\' = extendFsEnv acc_fs fs (extendNameSet flds n, Any used S.<> flds_used)\\n in UnusedNames acc_ns acc_wcs acc_fs\'\\n\\n | used\\n = acc\\n\\n | otherwise\\n = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n where\\n used = isJust $ lookupGRE_Name used_gre_env n\\n\\n add_unused_all :: Name -> UnusedNames -> UnusedNames\\n add_unused_all n acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | Just {} <- lookupGRE_Name used_gre_env n = acc\\n | n `elemNameSet` used_parents = acc\\n | otherwise = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n\\n add_unused_with :: Name -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_with p ns acc\\n | all (`elemNameSet` acc1_ns) ns = add_unused_name p False acc1\\n | otherwise = acc1\\n where\\n acc1@(UnusedNames acc1_ns _ _) = foldr (\\\\n acc\' -> add_unused_name n False acc\') acc ns\\n -- If you use \'signum\' from Num, then the user may well have\\n -- imported Num(signum). We don\'t want to complain that\\n -- Num is not itself mentioned. Hence the two cases in add_unused_with.\\n\\n add_unused_wildcard :: NamespaceSpecifier GhcRn -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_wildcard ns_spec names acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | any_used = acc\\n | otherwise = UnusedNames acc_ns (ns_spec : acc_wcs) acc_fs\\n where\\n -- A wildcard `type ..` or `data ..` is used if at least one of\\n -- the names it expands to is used\\n any_used = any (isJust . lookupGRE_Name used_gre_env) names\\n\\n\\n-- | An accumulator for unused names in an import list.\\n--\\n-- See Note [Reporting unused imported duplicate record fields].\\ndata UnusedNames =\\n UnusedNames\\n { unused_names :: NameSet\\n -- ^ Unused \'Name\'s in an import list, not including record fields\\n -- that are plain \'IEVar\' imports (tracked by \'rec_fld_uses\')\\n -- or wildcard imports (tracked by \'unused_wildcards\').\\n , unused_wildcards :: [NamespaceSpecifier GhcRn]\\n -- ^ Unused wildcards @type ..@ or @data ..@ in an import list.\\n , rec_fld_uses :: FastStringEnv (NameSet, Any)\\n -- ^ Record fields imported without a parent (i.e. an \'IEVar\' import).\\n --\\n -- The \'Any\' value records whether any of the record fields\\n -- sharing the same underlying \'FastString\' have been used.\\n }\\n\\nemptyUnusedNames :: UnusedNames\\nemptyUnusedNames = UnusedNames emptyNameSet [] emptyFsEnv\\n\\ninstance Outputable UnusedNames where\\n ppr (UnusedNames nms wcs flds) =\\n text \\"UnusedNames\\" <+>\\n braces (ppr nms <+> ppr wcs <+> ppr (fmap (second getAny) flds))\\n\\n-- | Collect all unused names from a \'UnusedNames\' value.\\ncollectUnusedNames :: UnusedNames -> NameSet\\ncollectUnusedNames (UnusedNames { unused_names = nms, rec_fld_uses = flds })\\n = nms S.<> unused_flds\\n where\\n unused_flds = nonDetFoldFsEnv collect_unused emptyNameSet flds\\n collect_unused :: (NameSet, Any) -> NameSet -> NameSet\\n collect_unused (nms, Any at_least_one_name_is_used) acc\\n | at_least_one_name_is_used = acc\\n | otherwise = unionNameSet nms acc\\n\\ncollectUnusedWildcards :: UnusedNames -> [NamespaceSpecifier GhcRn]\\ncollectUnusedWildcards = unused_wildcards\\n\\n{- Note [Reporting unused imported duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have (#24035):\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M1 (R1(..), R2(..)) where\\n data R1 = MkR1 { fld :: Int }\\n data R2 = MkR2 { fld :: Int }\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M2 where\\n import M1 (R1(MkR1), R2, fld)\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nIn the import of \'M1\' in \'M2\', the \'fld\' import resolves to two separate GREs,\\nnamely R1(fld) and R2(fld). From the perspective of the renamer, and in particular\\nthe \'findImportUsage\' function, it\'s as if the user had imported the two names\\nseparately (even though no source syntax allows that).\\n\\nThis means that we need to be careful when reporting unused imports: the R2(fld)\\nimport is indeed unused, but because R1(fld) is used, we should not report\\nfld as unused altogether.\\n\\nTo achieve this, we keep track of record field imports without a parent (i.e.\\nusing the IEVar constructor) separately from other import items, using the\\nUnusedNames datatype.\\nOnce we have accumulated usages, we emit warnings for unused record fields\\nwithout parents one whole group (of record fields sharing the same textual name)\\nat a time, and only if *all* of the record fields in the group are unused;\\nsee \'collectUnusedNames\'.\\n\\nNote that this only applies to record fields imported without a parent. If we\\nhad:\\n\\n import M1 (R1(MkR1, fld), R2(fld))\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nthen of course we should report the second \'fld\' as unused.\\n-}\\n\\n\\n{- Note [The ImportMap]\\n~~~~~~~~~~~~~~~~~~~~~~~\\nThe ImportMap is a short-lived intermediate data structure records, for\\neach import declaration, what stuff brought into scope by that\\ndeclaration is actually used in the module.\\n\\nThe [GlobalRdrElt] are the things imported from that decl.\\n-}\\n\\ndata ImportMap = ImportMap\\n { im_imports :: Map RealSrcSpan [GlobalRdrElt]\\n -- ^ See [The ImportMap]\\n -- If loc :-> gres, then\\n -- \'loc\' = the end loc of the bestImport of each GRE in \'gres\'\\n , im_generatedImports :: Map ModuleName [GlobalRdrElt]\\n }\\n\\nmkImportMap :: [GlobalRdrElt] -> ImportMap\\n-- For each of a list of used GREs, find all the import decls that brought\\n-- it into scope; choose one of them (bestImport), and record\\n-- the RdrName in that import decl\'s entry in the ImportMap\\nmkImportMap = foldr insertImportMap $ ImportMap Map.empty Map.empty\\n\\ninsertImportMap :: GlobalRdrElt -> ImportMap -> ImportMap\\ninsertImportMap gre@(GRE { gre_imp = imp_specs }) importMap\\n | RealSrcSpan importSpan _ <- is_dloc best_imp_spec =\\n importMap{im_imports = insertElem importSpan gre $ im_imports importMap}\\n | GeneratedSrcSpan{} <- is_dloc best_imp_spec =\\n importMap{im_generatedImports = insertElem (moduleName $ is_mod best_imp_spec) gre $ im_generatedImports importMap}\\n | otherwise = importMap\\n where\\n best_imp_spec =\\n case bagToList imp_specs of\\n [] -> pprPanic \\"mkImportMap: GRE with no ImportSpecs\\" (ppr gre)\\n is:iss -> is_decl $ bestImport (is NE.:| iss)\\n\\n -- https://github.com/haskell/containers/issues/784\\n insertElem :: Ord k => k -> v -> Map k [v] -> Map k [v]\\n insertElem k v = flip Map.alter k $ \\\\case\\n Just vs -> Just (v : vs)\\n Nothing -> Just [v]\\n\\nlookupImportMap :: LImportDecl GhcRn -> ImportMap -> [GlobalRdrElt]\\nlookupImportMap (L srcSpan ImportDecl{ideclName = L _ modName}) importMap =\\n fromMaybe [] $\\n -- should match logic in insertImportMap\\n case locA srcSpan of\\n RealSrcSpan realSrcSpan _ -> realSrcSpan `Map.lookup` im_imports importMap\\n GeneratedSrcSpan{} -> modName `Map.lookup` im_generatedImports importMap\\n _ -> Nothing\\n\\nlieNames :: LIE (GhcPass p) -> [Located (IdP (GhcPass p))]\\nlieNames = _\\n\\nwarnUnusedImport :: GlobalRdrEnv -> ImportDeclUsage -> RnM ()\\nwarnUnusedImport rdr_env (L loc decl, used, unused, unused_wcs)\\n\\n -- Do not warn for \'import M()\'\\n -- See (UI1) in Note [Unused imports]\\n | Just (Exactly, _) <- ideclImportList decl\\n , null unused && null unused_wcs\\n = return ()\\n\\n -- Note [Do not warn about Prelude hiding]\\n | Just (EverythingBut, hides) <- ideclImportList decl\\n , not (null hides)\\n , pRELUDE_NAME == unLoc (ideclName decl)\\n = return ()\\n\\n -- Do not warn about import X as Rebindable\\n -- See (UI2) in Note [Unused imports]\\n | Just (L _ mod) <- ideclAs decl\\n , mod == rEBINDABLE_MOD_NAME\\n = return ()\\n\\n -- Nothing used; drop entire declaration\\n | null used\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl UnusedImportNone)\\n\\n -- Everything imported is used; nop\\n | null unused && null unused_wcs\\n = return ()\\n\\n -- Some imports are unused: make the `SrcSpan` cover only the unused\\n -- items instead of the whole import statement\\n | Just (_, imports) <- ideclImportList decl\\n , let unused_locs = [ locA loc | L loc ie <- imports\\n , name <- ieNames ie\\n , name `elem` unused ]\\n , loc1 : locs <- unused_locs\\n , let span = foldr1 combineSrcSpans ( loc1 NE.:| locs )\\n = addDiagnosticAt span (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n -- Some imports are unused\\n | otherwise\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n where\\n -- In warning message, pretty-print identifiers unqualified unconditionally\\n -- to improve the consistent for ambiguous/unambiguous identifiers.\\n -- See #14881.\\n possible_field n =\\n case lookupGRE_Name rdr_env n of\\n Just (GRE { gre_par = par, gre_info = IAmRecField info }) ->\\n let fld_occ :: OccName\\n fld_occ = nameOccName $ flSelector $ recFieldLabel info\\n in UnusedImportNameRecField par fld_occ\\n _ -> UnusedImportNameRegular n\\n\\n -- Print unused names in a deterministic (lexicographic) order\\n sort_unused :: [UnusedImportName]\\n sort_unused =\\n [ UnusedImportWildcard wc | wc <- unused_wcs ] ++\\n [ possible_field nm | nm <- sortBy (comparing nameOccName) unused ]\\n\\ngetMinimalImports :: [ImportDeclUsage] -> RnM [LImportDecl GhcRn]\\ngetMinimalImports ie_decls\\n = do { rdr_env <- getGlobalRdrEnv\\n ; fmap combine $ mapM (mk_minimal rdr_env) ie_decls }\\n where\\n mk_minimal rdr_env (L l decl, used_gres, unused, unused_wcs)\\n | null unused && null unused_wcs\\n , Just (Exactly, _) <- ideclImportList decl\\n = return (L l decl)\\n | otherwise\\n = do { let ImportDecl { ideclName = L _ mod_name\\n , ideclSource = is_boot\\n , ideclPkgQual = pkg_qual\\n , ideclExt = XImportDeclPass { ideclOrigin = origin } } = decl\\n ; iface <- loadSrcInterface doc (importDeclLookupScope origin)\\n mod_name is_boot pkg_qual\\n ; let used_avails = gresToAvailInfo used_gres\\n ; lies <- map (L l) <$> concatMapM (to_ie rdr_env iface) used_avails\\n ; return (L l (decl { ideclImportList = Just (Exactly, lies) })) }\\n where\\n doc = text \\"Compute minimal imports for\\" <+> ppr decl\\n\\n to_ie :: GlobalRdrEnv -> ModIface -> AvailInfo -> RnM [IE GhcRn]\\n -- The main trick here is that if we\'re importing all the constructors\\n -- we want to say \\"T(..)\\", but if we\'re importing only a subset we want\\n -- to say \\"T(A,B,C)\\". So we have to find out what the module exports.\\n to_ie rdr_env _ (Avail c) -- Note [Overloaded field import]\\n = do { let\\n gre = expectJust $ lookupGRE_Name rdr_env c\\n ; return $ [IEVar Nothing (to_ie_post_rn $ noLocA $ greName gre) Nothing] }\\n to_ie _ _ avail@(AvailTC n [_]) -- Exporting the main decl and nothing else\\n | availExportsDecl avail\\n = return [IEThingAbs Nothing (to_ie_post_rn $ noLocA n) Nothing]\\n to_ie rdr_env iface (AvailTC n cs) =\\n case [ xs | avail@(AvailTC x xs) <- mi_exports iface\\n , x == n\\n , availExportsDecl avail -- Note [Partial export]\\n ] of\\n [xs]\\n | all_used xs\\n -> return [IEThingAll (IEThingAllExt Nothing noAnn noAnn noAnn)\\n (NoNamespaceSpecifier noExtField)\\n (to_ie_post_rn $ noLocA n)\\n Nothing]\\n | otherwise\\n -> do { let ns_gres = map (expectJust . lookupGRE_Name rdr_env) cs\\n ns = map greName ns_gres\\n ; return [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n -- Note [Overloaded field import]\\n _other\\n -> do { let infos = map (expectJust . lookupGRE_Name rdr_env) cs\\n (ns_gres,fs_gres) = classifyGREs infos\\n ns = map greName (ns_gres ++ fs_gres)\\n fs = map fieldGREInfo fs_gres\\n ; return $\\n if all_non_overloaded fs\\n then map (\\\\nm -> IEVar Nothing (to_ie_post_rn_var $ noLocA nm) Nothing) ns\\n else [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n where\\n\\n all_used avail_cs = all (`elem` cs) avail_cs\\n\\n all_non_overloaded = all (not . flIsOverloaded . recFieldLabel)\\n\\n combine :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\n combine = map merge . NE.groupAllWith getKey\\n\\n getKey :: LImportDecl GhcRn -> (Bool, Maybe ModuleName, ModuleName)\\n getKey decl =\\n ( isImportDeclQualified . ideclQualified $ idecl -- is this qualified? (important that this be first)\\n , unLoc <$> ideclAs idecl -- what is the qualifier (inside Maybe monad)\\n , unLoc . ideclName $ idecl -- Module Name\\n )\\n where\\n idecl :: ImportDecl GhcRn\\n idecl = unLoc decl\\n\\n merge :: NonEmpty (LImportDecl GhcRn) -> LImportDecl GhcRn\\n merge decls@((L l decl) :| _) = L l (decl { ideclImportList = Just (Exactly, lies) })\\n where lies = concatMap snd $ mapMaybe (ideclImportList . unLoc) $ NE.toList decls\\n\\nclassifyGREs :: [GlobalRdrElt] -> ([GlobalRdrElt], [FieldGlobalRdrElt])\\nclassifyGREs = partition (not . isRecFldGRE)\\n\\nprintMinimalImports :: HscSource -> [ImportDeclUsage] -> RnM ()\\n-- See Note [Printing minimal imports]\\nprintMinimalImports hsc_src imports_w_usage\\n = do { imports\' <- excludeGenerated <$> getMinimalImports imports_w_usage\\n ; this_mod <- getModule\\n ; dflags <- getDynFlags\\n ; liftIO $ withFile (mkFilename dflags this_mod) WriteMode $ \\\\h ->\\n printForUser dflags h neverQualify AllTheWay (vcat (map ppr imports\'))\\n -- The neverQualify is important. We are printing Names\\n -- but they are in the context of an \'import\' decl, and\\n -- we never qualify things inside there\\n -- E.g. import Blag( f, b )\\n -- not import Blag( Blag.f, Blag.g )!\\n }\\n where\\n mkFilename dflags this_mod\\n | Just d <- dumpDir dflags = d basefn\\n | otherwise = basefn\\n where\\n suffix = case hsc_src of\\n HsBootFile -> \\".imports-boot\\"\\n HsSrcFile -> \\".imports\\"\\n HsigFile -> \\".imports\\"\\n basefn = moduleNameString (moduleName this_mod) ++ suffix\\n\\n\\nto_ie_post_rn_var :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn_var (L l n)\\n | isDataOcc $ occName n = L l (IEPattern noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n\\n\\nto_ie_post_rn :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn (L l n)\\n | isTcOcc occ && isSymOcc occ = L l (IEType noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n where occ = occName n\\n\\n{- Note [Do not warn about Prelude hiding]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWe do not warn about\\n import Prelude hiding( x, y )\\nbecause even if nothing else from Prelude is used, it may be essential to hide\\nx,y to avoid name-shadowing warnings. Example (#9061)\\n import Prelude hiding( log )\\n f x = log where log = ()\\n\\nNote [Unused imports]\\n~~~~~~~~~~~~~~~~~~~~~\\nIn `warnUnusedImport`, if we see an import with an explicit list imports, thus\\n import M( a, b )\\nand neither `a` nor `b` is used, we report the entire import decl as unused. We\\ncheck this by looking at the names that it brings into scope scope; if there are\\nno ununused names, don\'t report.\\n\\n(UI1) We don\'t want to complain about `import M()`, because that is often used to bring\\n M\'s /instances/ into scope. That is neatly dealt with by the \\"no unused\\n names\\" (nor unused wildcard imports) criterion.\\n\\n(UI2) We don\'t report a decl as unused if it has an `as Rebindable` qualifier.\\n See (KN1) in Note [Overview of known entities] in GHC.Builtin\\n\\n\\nNote [Printing minimal imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nTo print the minimal imports we walk over all import decls (both user-supplied\\nand generated), trim their import lists, then filter out generated decls.\\n\\nNB that\\n\\n * We do *not* change the \'qualified\' or \'as\' parts!\\n\\n * We do not discard a decl altogether; we might need instances\\n from it. Instead we just trim to an empty import list\\n\\nNote [Partial export]\\n~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have\\n\\n module A( op ) where\\n class C a where\\n op :: a -> a\\n\\n module B where\\n import A\\n f = ..op...\\n\\nThen the minimal import for module B is\\n import A( op )\\nnot\\n import A( C( op ) )\\nwhich we would usually generate if C was exported from B. Hence\\nthe availExportsDecl test when deciding what to generate.\\n\\n\\nNote [Overloaded field import]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nOn the other hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n data T = MkT { foo :: Int }\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( T(foo) )\\nbecause when DuplicateRecordFields is enabled, field selectors are\\nnot in scope without their enclosing datatype.\\n\\nOn the third hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n pattern MkT { foo } = Just foo\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( foo )\\nbecause foo doesn\'t have a parent. This might actually be ambiguous if A\\nexports another field called foo, but there is no good answer to return and this\\nis a very obscure corner, so it seems to be the best we can do. See\\nDRFPatSynExport for a test of this.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Errors}\\n* *\\n************************************************************************\\n-}\\n\\nbadImportItemErr\\n :: ModIface -> ImpDeclSpec -> IE GhcPs\\n -> IsSubordinateError\\n -> [AvailInfo]\\n -> TcRn (NonEmpty ImportLookupReason)\\nbadImportItemErr iface decl_spec ie sub avails = do\\n exts <- importLookupExtensions\\n let import_lookup_bad :: BadImportKind -> ImportLookupReason\\n import_lookup_bad k = ImportLookupBad k iface decl_spec ie exts\\n dflags <- getDynFlags\\n hsc_env <- getTopEnv\\n let rdr_env = mkGlobalRdrEnv\\n $ gresFromAvails hsc_env (Just imp_spec) all_avails\\n pure $ fmap import_lookup_bad (importErrorKind dflags rdr_env)\\n where\\n importErrorKind :: DynFlags -> GlobalRdrEnv -> NonEmpty BadImportKind\\n importErrorKind dflags rdr_env\\n | any checkIfTyCon avails = case sub of\\n IsNotSubordinate -> NE.singleton BadImportAvailTyCon\\n IsSubordinateError { subordinate_err_parent = gre\\n , subordinate_err_unavailable = unavailable\\n , subordinate_err_nontype = nontype\\n , subordinate_err_nondata = nondata }\\n -> NE.fromList $ catMaybes $\\n [ fmap (BadImportNotExportedSubordinates gre) (NE.nonEmpty unavailable)\\n , fmap (BadImportNonTypeSubordinates gre) (NE.nonEmpty nontype)\\n , fmap (BadImportNonDataSubordinates gre) (NE.nonEmpty nondata) ]\\n | any checkIfVarName avails = NE.singleton BadImportAvailVar\\n | Just con <- find checkIfDataCon avails = NE.singleton (BadImportAvailDataCon (availOccName con))\\n | otherwise = NE.singleton (BadImportNotExported suggs)\\n where\\n suggs = similar_suggs ++ fieldSelectorSuggestions rdr_env rdr\\n what_look = case sub of\\n IsNotSubordinate -> WL_TyCon_or_TermVar\\n IsSubordinateError { subordinate_err_parent = gre } ->\\n case greInfo gre of\\n IAmTyCon ClassFlavour\\n -> WL_TyCon_or_TermVar\\n _ -> WL_Term\\n similar_names =\\n similarNameSuggestions (Unbound.LF what_look WL_Global)\\n dflags rdr_env emptyLocalRdrEnv rdr\\n similar_suggs =\\n case NE.nonEmpty $ mapMaybe imported_item $ similar_names of\\n Just similar -> [ SuggestSimilarNames rdr similar ]\\n Nothing -> [ ]\\n\\n -- Only keep imported items, and set the \\"HowInScope\\" to\\n -- \\"Nothing\\" to avoid printing \\"imported from...\\" in the suggestion\\n -- error message.\\n imported_item (SimilarRdrName rdr_name gre (Just (ImportedBy {})))\\n = Just (SimilarRdrName rdr_name gre Nothing)\\n imported_item _ = Nothing\\n\\n checkIfDataCon = checkIfAvailMatches isDataConName\\n checkIfTyCon = checkIfAvailMatches isTyConName\\n checkIfVarName =\\n \\\\case\\n AvailTC{} -> False\\n Avail n -> importedFS == occNameFS (occName n)\\n && (isVarOcc <||> isFieldOcc) (occName n)\\n checkIfAvailMatches namePred =\\n \\\\case\\n AvailTC _ ns ->\\n case find (\\\\n -> importedFS == occNameFS (occName n)) ns of\\n Just n -> namePred n\\n Nothing -> False\\n Avail{} -> False\\n availOccName = occName . availName\\n rdr = ieName ie\\n importedFS = occNameFS $ rdrNameOcc rdr\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n all_avails = mi_exports iface\\n\\nimportLookupExtensions :: TcRn ImportLookupExtensions\\nimportLookupExtensions = do\\n ile_pattern_synonyms <- xoptM LangExt.PatternSynonyms\\n ile_explicit_namespaces <- xoptM LangExt.ExplicitNamespaces\\n return ImportLookupExtensions{ile_pattern_synonyms, ile_explicit_namespaces}\\n\\naddDupDeclErr :: NonEmpty GlobalRdrElt -> TcRn ()\\naddDupDeclErr gres@(gre :| _)\\n -- Report the error at the later location\\n = addErrAt (getSrcSpan (NE.last sorted_names)) $ (TcRnDuplicateDecls (greOccName gre) sorted_names)\\n where\\n sorted_names =\\n NE.sortBy (SrcLoc.leftmost_smallest `on` nameSrcSpan)\\n (fmap greName gres)\\n\\n-- This data decl will parse OK\\n-- data T = a Int\\n-- treating \\"a\\" as the constructor.\\n-- It is really hard to make the parser spot this malformation.\\n-- So the renamer has to check that the constructor is legal\\n--\\n-- We can get an operator as the constructor, even in the prefix form:\\n-- data T = :% Int Int\\n-- from interface files, which always print in prefix form\\n--\\n-- We also allow type constructor names, which are defined by \\"type data\\"\\n-- declarations. See Note [Type data declarations] in GHC.Rename.Module.\\n\\ncheckConName :: RdrName -> TcRn ()\\ncheckConName name\\n = checkErr (isRdrDataCon name || isRdrTc name) (TcRnIllegalDataCon name)\\n", "filetypes": ["haskell"]}}}' 2026-10-16 14:48:21,565 - DEBUG - POST b'http://127.0.0.1:37093/receive_messages' {'content-type': 'application/json', 'x-ycm-hmac': b'Rga7Yd4l4fgfufwYw+0sxzurvznImlBO0MPmgAlS4EY='} b'{"filepath": "/home/enrico/ghc/compiler/GHC/Rename/Names.hs", "line_num": 1, "column_num": 1, "working_dir": "/home/enrico/ghc", "file_data": {"/home/enrico/ghc/compiler/GHC/Rename/Names.hs": {"contents": "{-\\n(c) The GRASP/AQUA Project, Glasgow University, 1992-1998\\n\\nExtracting imported and top-level names in scope\\n-}\\n\\n{-# LANGUAGE NondecreasingIndentation #-}\\n{-# LANGUAGE TypeFamilies #-}\\n\\nmodule GHC.Rename.Names (\\n rnImports, getLocalNonValBinders, newRecordFieldLabel,\\n importsFromIface,\\n ImportUserSpec(..),\\n extendGlobalRdrEnvRn,\\n gresFromAvails,\\n calculateAvails,\\n reportUnusedNames,\\n checkConName,\\n mkChildEnv,\\n findChildren,\\n mkBadExportSubordinate,\\n findImportUsage,\\n getMinimalImports,\\n printMinimalImports,\\n renamePkgQual, renameRawPkgQual,\\n classifyGREs,\\n ImportDeclUsage,\\n rnNamespaceSpecifier\\n ) where\\n\\nimport GHC.Prelude hiding ( head, init, last, tail )\\n\\nimport GHC.Driver.Env\\nimport GHC.Driver.Session\\nimport GHC.Driver.Ppr\\n\\nimport GHC.Rename.Env\\nimport GHC.Rename.Fixity\\nimport GHC.Rename.Utils ( warnUnusedTopBinds )\\nimport GHC.Rename.Unbound\\nimport qualified GHC.Rename.Unbound as Unbound\\n\\nimport GHC.Tc.Errors.Types\\nimport GHC.Tc.Utils.Env\\nimport GHC.Tc.Utils.Monad\\nimport GHC.Tc.Types.LclEnv\\nimport GHC.Tc.Zonk.TcType ( tcInitTidyEnv )\\n\\nimport GHC.Hs\\nimport GHC.Iface.Load ( loadSrcInterface, loadSrcInterface_maybe )\\nimport GHC.Iface.Errors.Types\\n ( IfaceMessage(..), MissingInterfaceError, InterfaceLookingFor(..)\\n , LoadEssentialsReason(..) )\\nimport GHC.Iface.Syntax ( fromIfaceWarnings )\\nimport GHC.Builtin.Modules( pRELUDE_NAME, rEBINDABLE_MOD_NAME )\\nimport GHC.Parser.PostProcess ( setRdrNameSpace )\\nimport GHC.Core.TyCo.Tidy\\nimport GHC.Core.PatSyn\\nimport GHC.Core.TyCon ( TyCon, tyConName )\\nimport qualified GHC.LanguageExtensions as LangExt\\n\\nimport GHC.Utils.Outputable as Outputable\\nimport GHC.Utils.Misc as Utils\\nimport GHC.Utils.Panic\\n\\nimport GHC.Types.Fixity.Env\\nimport GHC.Types.SafeHaskell\\nimport GHC.Types.Name\\nimport GHC.Types.Name.Env\\nimport GHC.Types.Name.Set\\nimport GHC.Types.Name.Reader\\nimport GHC.Types.Avail\\nimport GHC.Types.FieldLabel\\nimport GHC.Types.Hint\\nimport GHC.Types.SourceFile\\nimport GHC.Types.SrcLoc as SrcLoc\\nimport GHC.Types.Basic (TyConFlavour (..), convImportLevel, VisArity)\\nimport GHC.Types.UnresolvedImport\\nimport GHC.Types.Id\\nimport GHC.Types.PkgQual\\nimport GHC.Types.GREInfo (ConInfo(..), ConFieldInfo (..), ConLikeInfo (ConIsData))\\n\\nimport GHC.Unit\\nimport GHC.Unit.Module.Warnings\\nimport GHC.Unit.Module.ModIface\\nimport GHC.Unit.Module.Imported\\nimport GHC.Unit.Module.Deps\\nimport GHC.Unit.Env\\n\\nimport GHC.Data.Bag\\nimport GHC.Data.FastString\\nimport GHC.Data.FastString.Env\\nimport GHC.Data.Maybe\\nimport GHC.Data.List.SetOps ( removeDups )\\n\\nimport Control.Arrow ( second )\\nimport Control.Monad\\nimport Data.Foldable ( for_ )\\nimport Data.IntMap ( IntMap )\\nimport qualified Data.IntMap as IntMap\\nimport Data.Map ( Map )\\nimport qualified Data.Map as Map\\nimport Data.Ord ( comparing )\\nimport Data.Semigroup ( Any(..) )\\nimport qualified Data.Semigroup as S\\nimport Data.List ( partition, find, sortBy )\\nimport Data.List.NonEmpty (NonEmpty(..))\\nimport qualified Data.List.NonEmpty as NE\\nimport Data.Function ( on )\\nimport qualified Data.Set as S\\nimport System.FilePath (())\\nimport System.IO\\n\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{rnImports}\\n* *\\n************************************************************************\\n\\nNote [Tracking Trust Transitively]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen we import a package as well as checking that the direct imports are safe\\naccording to the rules outlined in the Note [Safe Haskell Trust Check] in GHC.Driver.Main\\nwe must also check that these rules hold transitively for all dependent modules\\nand packages. Doing this without caching any trust information would be very\\nslow as we would need to touch all packages and interface files a module depends\\non. To avoid this we make use of the property that if a modules Safe Haskell\\nmode changes, this triggers a recompilation from that module in the dependency\\ngraph. So we can just worry mostly about direct imports.\\n\\nThere is one trust property that can change for a package though without\\nrecompilation being triggered: package trust. So we must check that all\\npackages a module transitively depends on to be trusted are still trusted when\\nwe are compiling this module (as due to recompilation avoidance some modules\\nbelow may not be considered trusted any more without recompilation being\\ntriggered).\\n\\nWe handle this by augmenting the existing transitive list of packages a module M\\ndepends on with a bool for each package that says if it must be trusted when the\\nmodule M is being checked for trust. This list of trust required packages for a\\nsingle import is gathered in the rnImportDecl function and stored in an\\nImportAvails data structure. The union of these trust required packages for all\\nimports is done by the rnImports function using the combine function which calls\\nthe plusImportAvails function that is a union operation for the ImportAvails\\ntype. This gives us in an ImportAvails structure all packages required to be\\ntrusted for the module we are currently compiling. Checking that these packages\\nare still trusted (and that direct imports are trusted) is done in\\nGHC.Driver.Main.checkSafeImports.\\n\\nSee the note below, [Trust Own Package] for a corner case in this method and\\nhow its handled.\\n\\n\\nNote [Trust Own Package]\\n~~~~~~~~~~~~~~~~~~~~~~~~\\nThere is a corner case of package trust checking that the usual transitive check\\ndoesn\'t cover. (For how the usual check operates see the Note [Tracking Trust\\nTransitively] below). The case is when you import a -XSafe module M and M\\nimports a -XTrustworthy module N. If N resides in a different package than M,\\nthen the usual check works as M will record a package dependency on N\'s package\\nand mark it as required to be trusted. If N resides in the same package as M\\nthough, then importing M should require its own package be trusted due to N\\n(since M is -XSafe so doesn\'t create this requirement by itself). The usual\\ncheck fails as a module doesn\'t record a package dependency of its own package.\\nSo instead we now have a bool field in a modules interface file that simply\\nstates if the module requires its own package to be trusted. This field avoids\\nus having to load all interface files that the module depends on to see if one\\nis trustworthy.\\n\\n\\nNote [Trust Transitive Property]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSo there is an interesting design question in regards to transitive trust\\nchecking. Say I have a module B compiled with -XSafe. B is dependent on a bunch\\nof modules and packages, some packages it requires to be trusted as its using\\n-XTrustworthy modules from them. Now if I have a module A that doesn\'t use safe\\nhaskell at all and simply imports B, should A inherit all the trust\\nrequirements from B? Should A now also require that a package p is trusted since\\nB required it?\\n\\nWe currently say no but saying yes also makes sense. The difference is, if a\\nmodule M that doesn\'t use Safe Haskell imports a module N that does, should all\\nthe trusted package requirements be dropped since M didn\'t declare that it cares\\nabout Safe Haskell (so -XSafe is more strongly associated with the module doing\\nthe importing) or should it be done still since the author of the module N that\\nuses Safe Haskell said they cared (so -XSafe is more strongly associated with\\nthe module that was compiled that used it).\\n\\nGoing with yes is a simpler semantics we think and harder for the user to stuff\\nup but it does mean that Safe Haskell will affect users who don\'t care about\\nSafe Haskell as they might grab a package from Cabal which uses safe haskell (say\\nnetwork) and that packages imports -XTrustworthy modules from another package\\n(say bytestring), so requires that package is trusted. The user may now get\\ncompilation errors in code that doesn\'t do anything with Safe Haskell simply\\nbecause they are using the network package. They will have to call \'ghc-pkg\\ntrust network\' to get everything working. Due to this invasive nature of going\\nwith yes we have gone with no for now.\\n-}\\n\\n-- | Process Import Decls. See \'rnImportDecl\' for a description of what\\n-- the return types represent.\\n-- Note: Do the non SOURCE ones first, so that we get a helpful warning\\n-- for SOURCE ones that are unnecessary\\nrnImports :: [(LImportDecl GhcPs, SDoc)]\\n -> RnM ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\nrnImports imports = do\\n tcg_env <- getGblEnv\\n -- NB: want an identity module here, because it\'s OK for a signature\\n -- module to import from its implementor\\n let this_mod = tcg_mod tcg_env\\n let (source, ordinary) = partition (is_source_import . fst) imports\\n is_source_import (d::LImportDecl GhcPs) = ideclSource (unLoc d) == IsBoot\\n stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary\\n stuff2 <- mapAndReportM (rnImportDecl this_mod) source\\n -- Safe Haskell: See Note [Tracking Trust Transitively]\\n let (decls, imp_user_spec, rdr_env, imp_avails) = combine (stuff1 ++ stuff2)\\n -- Update imp_boot_mods if imp_direct_mods mentions any of them\\n let merged_import_avail = clobberSourceImports imp_avails\\n return (decls, imp_user_spec, rdr_env, merged_import_avail)\\n\\n where\\n clobberSourceImports imp_avails =\\n imp_avails { imp_boot_mods = imp_boot_mods\' }\\n where\\n imp_boot_mods\' = mergeInstalledModuleEnv combJ id (const emptyInstalledModuleEnv)\\n (imp_boot_mods imp_avails)\\n (imp_direct_dep_mods imp_avails)\\n\\n combJ (GWIB _ IsBoot) (_, x) = Just x\\n combJ r _ = Just r\\n -- See Note [Combining ImportAvails]\\n combine :: [(LImportDecl GhcRn, ImportUserSpec, GlobalRdrEnv, ImportAvails)]\\n -> ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\n combine ss =\\n let (decls, imp_user_spec, rdr_env, imp_avails, finsts) = foldr\\n plus\\n ([], [], emptyGlobalRdrEnv, emptyImportAvails, emptyModuleSet)\\n ss\\n in (decls, imp_user_spec, rdr_env, imp_avails { imp_finsts = moduleSetElts finsts })\\n\\n plus (decl, us, gbl_env1, imp_avails1)\\n (decls, uss, gbl_env2, imp_avails2, finsts_set)\\n = ( decl:decls,\\n us:uss,\\n gbl_env1 `plusGlobalRdrEnv` gbl_env2,\\n imp_avails1\' `plusImportAvails` imp_avails2,\\n extendModuleSetList finsts_set new_finsts )\\n where\\n imp_avails1\' = imp_avails1 { imp_finsts = [] }\\n new_finsts = imp_finsts imp_avails1\\n\\n{-\\nNote [Combining ImportAvails]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nimp_finsts in ImportAvails is a list of family instance modules\\ntransitively depended on by an import. imp_finsts for a currently\\ncompiled module is a union of all the imp_finsts of imports.\\nComputing the union of two lists of size N is O(N^2) and if we\\ndo it to M imports we end up with O(M*N^2). That can get very\\nexpensive for bigger module hierarchies.\\n\\nUnion can be optimized to O(N log N) if we use a Set.\\nimp_finsts is converted back and forth between dep_finsts, so\\nchanging a type of imp_finsts means either paying for the conversions\\nor changing the type of dep_finsts as well.\\n\\nI\'ve measured that the conversions would cost 20% of allocations on my\\ntest case, so that can be ruled out.\\n\\nChanging the type of dep_finsts forces checkFamInsts to\\nget the module lists in non-deterministic order. If we wanted to restore\\nthe deterministic order, we\'d have to sort there, which is an additional\\ncost. As far as I can tell, using a non-deterministic order is fine there,\\nbut that\'s a brittle nonlocal property which I\'d like to avoid.\\n\\nAdditionally, dep_finsts is read from an interface file, so its \\"natural\\"\\ntype is a list. Which makes it a natural type for imp_finsts.\\n\\nSince rnImports.combine is really the only place that would benefit from\\nit being a Set, it makes sense to optimize the hot loop in rnImports.combine\\nwithout changing the representation.\\n\\nSo here\'s what we do: instead of naively merging ImportAvails with\\nplusImportAvails in a loop, we make plusImportAvails merge empty imp_finsts\\nand compute the union on the side using Sets. When we\'re done, we can\\nconvert it back to a list. One nice side effect of this approach is that\\nif there\'s a lot of overlap in the imp_finsts of imports, the\\nSet doesn\'t really need to grow and we don\'t need to allocate.\\n\\nRunning generateModules from #14693 with DEPTH=16, WIDTH=30 finishes in\\n23s before, and 11s after.\\n-}\\n\\n-- | Given a located import declaration @decl@ from @this_mod@,\\n-- calculate the following pieces of information:\\n--\\n-- 1. An updated \'LImportDecl\', where all unresolved \'RdrName\' in\\n-- the entity lists have been resolved into \'Name\'s,\\n--\\n-- 2. A \'GlobalRdrEnv\' representing the new identifiers that were\\n-- brought into scope (taking into account module qualification\\n-- and hiding),\\n--\\n-- 3. \'ImportAvails\' summarizing the identifiers that were imported\\n-- by this declaration, and\\n--\\n-- 4. A boolean \'AnyHpcUsage\' which is true if the imported module\\n-- used HPC.\\nrnImportDecl :: Module -> (LImportDecl GhcPs, SDoc)\\n -> RnM (LImportDecl GhcRn, ImportUserSpec , GlobalRdrEnv, ImportAvails)\\nrnImportDecl this_mod\\n (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name\\n , ideclPkgQual = raw_pkg_qual\\n , ideclSource = want_boot\\n , ideclSafe = mod_safe\\n , ideclLevelSpec = import_level\\n , ideclQualified = qual_style\\n , ideclExt = XImportDeclPass { ideclOrigin = origin }\\n , ideclAs = as_mod, ideclImportList = imp_details }), import_reason)\\n = setSrcSpanA loc $ do\\n\\n case raw_pkg_qual of\\n NoRawPkgQual -> pure ()\\n RawPkgQual {} -> do\\n pkg_imports <- xoptM LangExt.PackageImports\\n when (not pkg_imports) $ addErr TcRnPackageImportsDisabled\\n\\n let qual_only = isImportDeclQualified qual_style\\n generated = isGeneratedImport origin\\n\\n lookup_scope = importDeclLookupScope origin\\n\\n -- If there\'s an error in loadInterface, (e.g. interface\\n -- file not found) we get lots of spurious errors from \'filterImports\'\\n let imp_mod_name = unLoc loc_imp_mod_name\\n doc = ppr imp_mod_name <+> import_reason\\n\\n hsc_env <- getTopEnv\\n unit_env <- hsc_unit_env <$> getTopEnv\\n let pkg_qual = renameRawPkgQual unit_env imp_mod_name raw_pkg_qual\\n\\n -- Check for self-import, which confuses the typechecker (#9032)\\n -- ghc --make rejects self-import cycles already, but batch-mode may not\\n -- at least not until GHC.IfaceToCore.tcHiBootIface, which is too late to avoid\\n -- typechecker crashes. (Indirect self imports are not caught until\\n -- GHC.IfaceToCore, see #10337 tracking how to make this error better.)\\n --\\n -- Originally, we also allowed \'import {-# SOURCE #-} M\', but this\\n -- caused bug #10182: in one-shot mode, we should never load an hs-boot\\n -- file for the module we are compiling into the EPS. In principle,\\n -- it should be possible to support this mode of use, but we would have to\\n -- extend Provenance to support a local definition in a qualified location.\\n -- For now, we don\'t support it, but see #10336\\n when (imp_mod_name == moduleName this_mod &&\\n (case pkg_qual of -- If we have import \\"\\" M, then we should\\n -- check that \\"\\" is \\"this\\" (which is magic)\\n -- or the name of this_mod\'s package. Yurgh!\\n -- c.f. GHC.findModule, and #9997\\n NoPkgQual -> True\\n ThisPkg uid -> uid == homeUnitId_ (hsc_dflags hsc_env)\\n OtherPkg _ -> False))\\n (addErr (TcRnSelfImport imp_mod_name))\\n\\n -- Check for a missing import list (Opt_WarnMissingImportList also\\n -- checks for T(..) items but that is done in checkDodgyImport below)\\n case imp_details of\\n Just (Exactly, _) -> return () -- Explicit import list\\n _ | generated -> return () -- Do not bleat for generated imports\\n | qual_only -> return ()\\n | otherwise -> addDiagnostic (TcRnNoExplicitImportList imp_mod_name)\\n\\n\\n mb_iface <- loadSrcInterface_maybe doc lookup_scope imp_mod_name want_boot pkg_qual\\n iface <- case mb_iface of\\n Succeeded iface -> return iface\\n Failed err -> failWithTc $\\n importDeclLoadFailure origin imp_mod_name want_boot err\\n\\n -- Compiler sanity check: if the import didn\'t say\\n -- {-# SOURCE #-} we should not get a hi-boot file\\n warnPprTrace ((want_boot == NotBoot) && (mi_boot iface == IsBoot)) \\"rnImportDecl\\" (ppr imp_mod_name) $ do\\n\\n -- Issue a user warning for a redundant {- SOURCE -} import\\n -- NB that we arrange to read all the ordinary imports before\\n -- any of the {- SOURCE -} imports.\\n --\\n -- in --make and GHCi, the compilation manager checks for this,\\n -- and indeed we shouldn\'t do it here because the existence of\\n -- the non-boot module depends on the compilation order, which\\n -- is not deterministic. The hs-boot test can show this up.\\n dflags <- getDynFlags\\n warnIf ((want_boot == IsBoot) && (mi_boot iface == NotBoot) && isOneShot (ghcMode dflags))\\n (TcRnRedundantSourceImport imp_mod_name)\\n when (mod_safe && not (safeImportsOn dflags)) $\\n addErr (TcRnSafeImportsDisabled imp_mod_name)\\n\\n let imp_mod = mi_module iface\\n qual_mod_name = fmap unLoc as_mod `orElse` imp_mod_name\\n imp_spec = ImpDeclSpec { is_mod = imp_mod, is_qual = qual_only,\\n is_dloc = locA loc, is_as = qual_mod_name,\\n is_pkg_qual = pkg_qual, is_isboot = want_boot,\\n is_level = convImportLevel import_level }\\n\\n let filter_imports = do\\n -- filter the imports according to the import declaration\\n (new_imp_details, imp_user_list, gbl_env)\\n <- filterImports hsc_env iface imp_spec imp_details\\n -- for certain error messages, we\\u2019d like to know what could be\\n -- imported here, if everything were imported\\n potential_gres <- (\\\\(_,_,x) -> x) <$> filterImports hsc_env iface imp_spec Nothing\\n return (new_imp_details, imp_user_list, gbl_env, potential_gres)\\n\\n (new_imp_details, imp_user_list, gbl_env, potential_gres) <-\\n case origin of\\n ImplicitEssentialsImport ->\\n -- The implicit GHC.Essentials import does not bring anything into scope.\\n -- See Note [Finding GHC.Essentials] in GHC.Builtin.\\n return (Nothing, ImpUserDependOnly, emptyGlobalRdrEnv, emptyGlobalRdrEnv)\\n UserWrittenImport -> filter_imports\\n ImplicitPreludeImport -> filter_imports\\n PluginImport -> filter_imports\\n\\n let is_hiding | Just (EverythingBut,_) <- imp_details = True\\n | otherwise = False\\n\\n -- should the import be safe?\\n mod_safe\' = mod_safe\\n || (not generated && safeDirectImpsReq dflags)\\n || (generated && safeImplicitImpsReq dflags)\\n\\n hsc_env <- getTopEnv\\n let home_unit = hsc_home_unit hsc_env\\n other_home_units = hsc_all_home_unit_ids hsc_env\\n\\n imported_by\\n | isDependOnlyImport imp_user_list\\n = ImportedBySystem\\n | otherwise\\n = ImportedByUser $ ImportedModsVal\\n { imv_name = is_as imp_spec\\n , imv_span = locA loc\\n , imv_is_safe = mod_safe\'\\n , imv_is_hiding = is_hiding\\n , imv_all_exports = potential_gres\\n , imv_qualified = qual_only\\n , imv_is_level = convImportLevel import_level\\n }\\n imports = calculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by\\n\\n -- Complain if we import a deprecated module\\n case fromIfaceWarnings (mi_warns iface) of\\n WarnAll txt -> addDiagnostic (TcRnDeprecatedModule imp_mod_name txt)\\n _ -> return ()\\n\\n let new_imp_decl = ImportDecl\\n { ideclExt = ideclExt decl\\n , ideclName = ideclName decl\\n , ideclPkgQual = pkg_qual\\n , ideclSource = ideclSource decl\\n , ideclSafe = mod_safe\'\\n , ideclQualified = ideclQualified decl\\n , ideclAs = ideclAs decl\\n , ideclImportList = new_imp_details\\n , ideclLevelSpec = ideclLevelSpec decl\\n }\\n\\n return (L loc new_imp_decl, ImpUserSpec imp_spec imp_user_list, gbl_env, imports)\\n\\n-- | The error message to emit when we failed to load an interface.\\nimportDeclLoadFailure :: ImportDeclOrigin -> ModuleName -> IsBootInterface\\n -> MissingInterfaceError -> TcRnMessage\\nimportDeclLoadFailure ImplicitEssentialsImport _ _ err\\n = TcRnInterfaceError $ CantFindEssentials err LookingForEssentialsModule\\nimportDeclLoadFailure _ mod_name want_boot err\\n = TcRnInterfaceError $ Can\'tFindInterface err $ LookingForModule mod_name want_boot\\n\\n-- | Rename raw package imports\\nrenameRawPkgQual :: UnitEnv -> ModuleName -> RawPkgQual -> PkgQual\\nrenameRawPkgQual unit_env mn = \\\\case\\n NoRawPkgQual -> NoPkgQual\\n RawPkgQual _ fs -> renamePkgQual unit_env mn $ Just fs\\n\\n-- | Rename raw package imports\\nrenamePkgQual :: UnitEnv -> ModuleName -> Maybe FastString -> PkgQual\\nrenamePkgQual unit_env mn mb_pkg = case mb_pkg of\\n Nothing -> NoPkgQual\\n Just pkg_fs\\n | Just uid <- homeUnitId <$> ue_homeUnit unit_env\\n , pkg_fs == fsLit \\"this\\"\\n -> ThisPkg uid\\n\\n | Just (uid, _) <- find (fromMaybe False . fmap (== pkg_fs) . snd) home_names\\n -> ThisPkg uid\\n\\n | Just uid <- resolvePackageImport unit_state mn (PackageName pkg_fs)\\n -> OtherPkg uid\\n\\n | otherwise\\n -> OtherPkg (UnitId pkg_fs)\\n -- not really correct as pkg_fs is unlikely to be a valid unit-id but\\n -- we will report the failure later...\\n where\\n home_names =\\n [ (uid, mkFastString <$> thisPackageName (homeUnitEnv_dflags (ue_findHomeUnitEnv uid unit_env)))\\n | uid <- S.toList hpt_deps\\n ]\\n\\n unit_state = ue_homeUnitState unit_env\\n\\n hpt_deps :: S.Set UnitId\\n hpt_deps = homeUnitDepends unit_state\\n\\n\\n-- | Calculate the \'ImportAvails\' induced by an import of a particular\\n-- interface, but without \'imp_mods\'.\\ncalculateAvails :: HomeUnit\\n -> S.Set UnitId\\n -> ModIface\\n -> IsSafeImport\\n -> IsBootInterface\\n -> ImportedBy\\n -> ImportAvails\\ncalculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by =\\n let imp_mod = mi_module iface\\n imp_sem_mod= mi_semantic_module iface\\n orph_iface = mi_orphan iface\\n has_finsts = mi_finsts iface\\n deps = mi_deps iface\\n trust = getSafeMode $ mi_trust iface\\n trust_pkg = mi_trust_pkg iface\\n is_sig = mi_hsc_src iface == HsigFile\\n\\n -- If the module exports anything defined in this module, just\\n -- ignore it. Reason: otherwise it looks as if there are two\\n -- local definition sites for the thing, and an error gets\\n -- reported. Easiest thing is just to filter them out up\\n -- front. This situation only arises if a module imports\\n -- itself, or another module that imported it. (Necessarily,\\n -- this involves a loop.)\\n --\\n -- We do this *after* filterImports, so that if you say\\n -- module A where\\n -- import B( AType )\\n -- type AType = ...\\n --\\n -- module B( AType ) where\\n -- import {-# SOURCE #-} A( AType )\\n --\\n -- then you won\'t get a \'B does not export AType\' message.\\n\\n\\n -- Compute new transitive dependencies\\n --\\n -- \'dep_orphs\' and \'dep_finsts\' do NOT include the imported module\\n -- itself, but we DO need to include this module in \'imp_orphs\' and\\n -- \'imp_finsts\' if it defines an orphan or instance family; thus the\\n -- orph_iface/has_iface tests.\\n\\n deporphs = dep_orphs deps\\n depfinsts = dep_finsts deps\\n\\n orphans | orph_iface = assertPpr (not (imp_sem_mod `elem` deporphs)) (ppr imp_sem_mod <+> ppr deporphs) $\\n imp_sem_mod : deporphs\\n | otherwise = deporphs\\n\\n finsts | has_finsts = assertPpr (not (imp_sem_mod `elem` depfinsts)) (ppr imp_sem_mod <+> ppr depfinsts) $\\n imp_sem_mod : depfinsts\\n | otherwise = depfinsts\\n\\n -- Trusted packages are a lot like orphans.\\n trusted_pkgs | mod_safe\' = dep_trusted_pkgs deps\\n | otherwise = S.empty\\n\\n\\n pkg = moduleUnit (mi_module iface)\\n ipkg = toUnitId pkg\\n\\n -- Does this import mean we now require our own pkg\\n -- to be trusted? See Note [Trust Own Package]\\n ptrust = trust == Sf_Trustworthy || trust_pkg\\n pkg_trust_req\\n | isHomeUnit home_unit pkg = ptrust\\n | otherwise = False\\n\\n dependent_pkgs = if toUnitId pkg `S.member` other_home_units\\n then S.empty\\n else S.singleton (lvl, ipkg)\\n\\n lvl = case imported_by of\\n ImportedByUser imv -> imv_is_level imv\\n ImportedBySystem -> NormalLevel\\n\\n\\n direct_mods = if toUnitId pkg `S.member` other_home_units\\n then mkPlusModDeps (moduleUnitId imp_mod) lvl (GWIB (moduleName imp_mod) want_boot)\\n else emptyInstalledModuleEnv\\n\\n dep_boot_mods_map = mkModDeps (dep_boot_mods deps)\\n\\n\\n boot_mods\\n -- If we are looking for a boot module, it must be HPT\\n | IsBoot <- want_boot = extendInstalledModuleEnv dep_boot_mods_map (toUnitId <$> imp_mod) (GWIB (moduleName imp_mod) IsBoot)\\n -- Now we are importing A properly, so don\'t go looking for\\n -- A.hs-boot\\n | isHomeUnit home_unit pkg = dep_boot_mods_map\\n -- There\'s no boot files to find in external imports\\n | otherwise = emptyInstalledModuleEnv\\n\\n sig_mods =\\n if is_sig\\n then moduleName imp_mod : dep_sig_mods deps\\n else dep_sig_mods deps\\n\\n\\n in ImportAvails {\\n imp_mods = Map.singleton (mi_module iface) [imported_by],\\n imp_orphs = orphans,\\n imp_finsts = finsts,\\n imp_sig_mods = sig_mods,\\n imp_direct_dep_mods = direct_mods,\\n imp_dep_direct_pkgs = dependent_pkgs,\\n imp_boot_mods = boot_mods,\\n\\n -- Add in the imported modules trusted package\\n -- requirements. ONLY do this though if we import the\\n -- module as a safe import.\\n -- See Note [Tracking Trust Transitively]\\n -- and Note [Trust Transitive Property]\\n imp_trust_pkgs = trusted_pkgs,\\n -- Do we require our own pkg to be trusted?\\n -- See Note [Trust Own Package]\\n imp_trust_own_pkg = pkg_trust_req\\n }\\n\\nmkPlusModDeps :: UnitId -> ImportLevel -> ModuleNameWithIsBoot\\n -> InstalledModuleEnv (S.Set ImportLevel, ModuleNameWithIsBoot)\\nmkPlusModDeps uid st elt = extendInstalledModuleEnv emptyInstalledModuleEnv (mkModule uid (gwib_mod elt)) (S.singleton st, elt)\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{importsFromLocalDecls}\\n* *\\n************************************************************************\\n\\nFrom the top-level declarations of this module produce\\n * the lexical environment\\n * the ImportAvails\\ncreated by its bindings.\\n\\nNote [Top-level Names in Template Haskell decl quotes]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSee also: Note [Interactively-bound Ids in GHCi] in GHC.Driver.Env\\n Note [Looking up Exact RdrNames] in GHC.Rename.Env\\n\\nConsider a Template Haskell declaration quotation like this:\\n module M where\\n f x = h [d| f = 3 |]\\nWhen renaming the declarations inside [d| ...|], we treat the\\ntop level binders specially in two ways\\n\\n1. We give them an Internal Name, not (as usual) an External one.\\n This is done by GHC.Rename.Env.newTopSrcBinder.\\n\\n2. We make them *shadow* the outer bindings.\\n See Note [GlobalRdrEnv shadowing]\\n\\n3. We find out whether we are inside a [d| ... |] by testing the TH\\n level. This is a slight hack, because the level field was really\\n meant for the type checker, and here we are not interested in the\\n fields of Brack, hence the error thunks in thRnBrack.\\n-}\\n\\nextendGlobalRdrEnvRn :: [GlobalRdrElt]\\n -> MiniFixityEnv\\n -> RnM (TcGblEnv, TcLclEnv)\\n-- Updates both the GlobalRdrEnv and the FixityEnv\\n-- We return a new TcLclEnv only because we might have to\\n-- delete some bindings from it;\\n-- see Note [Top-level Names in Template Haskell decl quotes]\\n\\nextendGlobalRdrEnvRn new_gres new_fixities\\n = checkNoErrs $ -- See Note [Fail fast on duplicate definitions]\\n do { (gbl_env, lcl_env) <- getEnvs\\n ; level <- getThLevel\\n ; isGHCi <- getIsGHCi\\n ; let rdr_env = tcg_rdr_env gbl_env\\n fix_env = tcg_fix_env gbl_env\\n th_bndrs = getLclEnvThBndrs lcl_env\\n th_lvl = thLevelIndex level\\n\\n -- Delete new_occs from global and local envs\\n -- If we are in a TemplateHaskell decl bracket,\\n -- we are going to shadow them\\n -- See Note [GlobalRdrEnv shadowing]\\n inBracket = isBrackLevel level\\n\\n lcl_env_TH = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_rdr = minusLocalRdrEnv (tcl_rdr lcl_env) new_gres_env }) lcl_env\\n -- See Note [GlobalRdrEnv shadowing]\\n\\n lcl_env2 | inBracket = lcl_env_TH\\n | otherwise = lcl_env\\n\\n -- Deal with shadowing: see Note [GlobalRdrEnv shadowing]\\n want_shadowing = isGHCi || inBracket\\n rdr_env1 | want_shadowing = shadowNames False rdr_env new_gres_env\\n | otherwise = rdr_env\\n\\n lcl_env3 = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_th_bndrs = extendNameEnvList th_bndrs\\n [ ( n, (TopLevel, th_lvl) )\\n | n <- new_names ] }) lcl_env2\\n\\n ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres\\n\\n ; let fix_env\' = foldl\' extend_fix_env fix_env new_gres\\n gbl_env\' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env\' }\\n\\n ; traceRn \\"extendGlobalRdrEnvRn 2\\" (pprGlobalRdrEnv True rdr_env2)\\n ; return (gbl_env\', lcl_env3) }\\n where\\n new_names = map greName new_gres\\n new_gres_env = mkGlobalRdrEnv new_gres\\n\\n -- If there is a fixity decl for the gre, add it to the fixity env\\n extend_fix_env fix_env gre\\n | Just (L _ fi) <- lookupMiniFixityEnv new_fixities name\\n = extendNameEnv fix_env name (FixItem occ fi)\\n | otherwise\\n = fix_env\\n where\\n name = greName gre\\n occ = greOccName gre\\n\\n add_gre :: GlobalRdrEnv -> GlobalRdrElt -> RnM GlobalRdrEnv\\n -- Extend the GlobalRdrEnv with a LocalDef GRE\\n -- If there is already a LocalDef GRE with the same OccName,\\n -- report an error and discard the new GRE\\n -- This establishes INVARIANT 1 of GlobalRdrEnvs\\n add_gre env gre\\n | not (null dups) -- Same OccName defined twice\\n = do { addDupDeclErr (gre :| dups); return env }\\n\\n | otherwise\\n = return (extendGlobalRdrEnv env gre)\\n where\\n -- See Note [Reporting duplicate local declarations]\\n dups = filter isBadDupGRE\\n $ lookupGRE env (LookupOccName (greOccName gre) (RelevantGREsFOS WantBoth))\\n isBadDupGRE old_gre = isLocalGRE old_gre && greClashesWith gre old_gre\\n\\n{- Note [Fail fast on duplicate definitions]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIf there are duplicate bindings for the same thing, we want to fail\\nfast. Having two bindings for the same thing can cause follow-on errors.\\nExample (test T9975a):\\n data Test = Test { x :: Int }\\n pattern Test wat = Test { x = wat }\\nThis defines \'Test\' twice. The second defn has no field-names; and then\\nwe get an error from Test { x=wat }, saying \\"Test has no field \'x\'\\".\\n\\nEasiest thing is to bale out fast on duplicate definitions, which\\nwe do via `checkNoErrs` on `extendGlobalRdrEnvRn`.\\n\\nNote [Reporting duplicate local declarations]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn general, a single module may not define the same OccName multiple times. This\\nis checked in extendGlobalRdrEnvRn: when adding a new locally-defined GRE to the\\nGlobalRdrEnv we report an error if there are already duplicates in the\\nenvironment. This establishes INVARIANT 1 (see comments on GlobalRdrEnv in\\nGHC.Types.Name.Reader), which says that for a given OccName, all the\\nGlobalRdrElts to which it maps must have distinct \'greName\'s.\\n\\nFor example, the following will be rejected:\\n\\n f x = x\\n g x = x\\n f x = x -- Duplicate!\\n\\nUsers are allowed to introduce new GREs with the same OccName as an imported GRE,\\nas disambiguation is possible through the module system, e.g.:\\n\\n module M where\\n import N (f)\\n f x = x\\n g x = M.f x + N.f x\\n\\nIf both GREs are local, the general rule is that two GREs clash if they have\\nthe same OccName, i.e. they share a textual name and live in the same namespace.\\nHowever, there are additional clashes due to record fields:\\n\\n - a new variable clashes with previously defined record fields\\n which define field selectors,\\n\\n - a new record field shadows:\\n\\n - previously defined variables, if it defines a field selector,\\n - previously defined record fields, unless it is a duplicate record field.\\n\\nThis logic is implemented in the function \'GHC.Types.Name.Reader.greClashesWith\'.\\n\\nSee also Note [Skipping ambiguity errors at use sites of local declarations] in\\nGHC.Rename.Utils.\\n-}\\n\\n\\n{- *********************************************************************\\n* *\\n getLocalDeclBindersd@ returns the names for an HsDecl\\n It\'s used for source code.\\n\\n *** See Note [The Naming story] in GHC.Hs.Decls ****\\n* *\\n********************************************************************* -}\\n\\ngetLocalNonValBinders :: MiniFixityEnv -> HsGroup GhcPs\\n -> RnM ((TcGblEnv, TcLclEnv), NameSet)\\n-- Get all the top-level binders bound the group *except*\\n-- for value bindings, which are treated separately\\n-- Specifically we return AvailInfo for\\n-- * type decls (incl constructors and record selectors)\\n-- * class decls (including class ops)\\n-- * associated types\\n-- * foreign imports\\n-- * value signatures (in hs-boot files only)\\n\\ngetLocalNonValBinders fixity_env\\n (HsGroup { hs_valds = binds,\\n hs_tyclds = tycl_decls,\\n hs_fords = foreign_decls })\\n = do { -- Process all type/class decls *except* family instances\\n ; let inst_decls = tycl_decls >>= group_instds\\n ; dup_fields_ok <- xopt_DuplicateRecordFields <$> getDynFlags\\n ; has_sel <- xopt_FieldSelectors <$> getDynFlags\\n ; tc_gres\\n <- concatMapM\\n (new_tc dup_fields_ok has_sel)\\n (tyClGroupTyClDecls tycl_decls)\\n ; traceRn \\"getLocalNonValBinders 1\\" (ppr tc_gres)\\n ; envs <- extendGlobalRdrEnvRn tc_gres fixity_env\\n ; restoreEnvs envs $ do {\\n -- Bring these things into scope first\\n -- See Note [Looking up family names in family instances]\\n\\n -- Process all family instances\\n -- to bring new data constructors into scope\\n ; nti_gress <- mapM (new_assoc dup_fields_ok has_sel) inst_decls\\n\\n -- Finish off with value binders:\\n -- foreign decls and pattern synonyms for an ordinary module\\n -- type sigs in case of a hs-boot file only\\n ; is_boot <- tcIsHsBootOrSig\\n ; let val_bndrs\\n | is_boot = case binds of\\n ValBinds _ val_binds ->\\n -- In a hs-boot file, the value binders come from the\\n -- *signatures*, and there should be no foreign binders\\n [ L (l2l decl_loc) (unLoc n)\\n | L decl_loc (TypeSig _ _ ns _) <- (val_sigs val_binds), n <- ns]\\n _ -> panic \\"Non-ValBinds in hs-boot group\\"\\n | otherwise = for_hs_bndrs\\n ; val_gres <- mapM new_simple val_bndrs\\n\\n ; let avails = concat nti_gress ++ val_gres\\n new_bndrs = gresToNameSet avails `unionNameSet`\\n gresToNameSet tc_gres\\n ; traceRn \\"getLocalNonValBinders 2\\" (ppr avails)\\n ; envs <- extendGlobalRdrEnvRn avails fixity_env\\n ; return (envs, new_bndrs) } }\\n where\\n for_hs_bndrs :: [LocatedN RdrName]\\n for_hs_bndrs = hsForeignDeclsBinders foreign_decls\\n\\n -- the SrcSpan attached to the input should be the span of the\\n -- declaration, not just the name\\n new_simple :: LocatedN RdrName -> RnM GlobalRdrElt\\n new_simple rdr_name = do { nm <- newTopSrcBinder rdr_name\\n ; return (mkLocalVanillaGRE NoParent nm) }\\n\\n new_tc :: DuplicateRecordFields -> FieldSelectors -> LTyClDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_tc dup_fields_ok has_sel tc_decl -- NOT for type/data instances\\n = do { let TyDeclBinders (main_bndr, tc_flav) at_bndrs sig_bndrs\\n (LConsWithFields cons_with_flds flds) = hsLTyClDeclBinders tc_decl\\n ; tycon_name <- newTopSrcBinder $ la2la main_bndr\\n ; at_names <- mapM (newTopSrcBinder . la2la . fst) at_bndrs\\n ; sig_names <- mapM (newTopSrcBinder . la2la) sig_bndrs\\n ; con_names_with_flds <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst con_names_with_flds) flds\\n ; mapM_ (add_dup_fld_errs flds\') con_names_with_flds\\n ; let tc_gre = mkLocalTyConGRE (fmap (const tycon_name) tc_flav) tycon_name\\n fld_env = mk_fld_env con_names_with_flds flds\'\\n at_gres = zipWith (\\\\ (_, at_flav) at_nm -> mkLocalTyConGRE (fmap (const tycon_name) at_flav) at_nm)\\n at_bndrs at_names\\n sig_gres = map (mkLocalVanillaGRE (ParentIs tycon_name)) sig_names\\n con_gres = map (mkLocalConLikeGRE (ParentIs tycon_name)) fld_env\\n fld_gres = mkLocalFieldGREs (ParentIs tycon_name) fld_env\\n sub_gres = at_gres ++ sig_gres ++ con_gres ++ fld_gres\\n ; traceRn \\"getLocalNonValBinders new_tc\\" $\\n vcat [ text \\"tycon:\\" <+> ppr tycon_name\\n , text \\"tc_gre:\\" <+> ppr tc_gre\\n , text \\"sub_gres:\\" <+> ppr sub_gres ]\\n ; return $ tc_gre : sub_gres }\\n\\n -- Calculate the record field information, which feeds into the GlobalRdrElts\\n -- for DataCons and their fields. It\'s convenient to do this here where\\n -- we are working with a single datatype definition.\\n --\\n -- The information we needed was all set up for us:\\n -- see Note [Collecting record fields in data declarations] in GHC.Hs.Utils.\\n mk_fld_env :: [(Name, Either VisArity [Located Int])] -> IntMap FieldLabel\\n -> [(ConLikeName, ConInfo)]\\n mk_fld_env names flds =\\n [ (DataConName con, ConInfo (ConIsData (map fst names)) fld_info)\\n | (con, con_fl_indxs) <- names\\n , let fld_info = case fmap (map ((flds IntMap.!) . unLoc)) con_fl_indxs of\\n Left 0 -> ConIsNullary\\n Left arity -> ConHasPositionalArgs arity\\n Right [] -> ConIsNullary\\n Right (fld:flds) -> ConHasRecordFields $ fld NE.:| flds ]\\n\\n new_assoc :: DuplicateRecordFields -> FieldSelectors -> LInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_assoc _ _ (L _ (TyFamInstD {})) = return []\\n -- type instances don\'t bind new names\\n\\n new_assoc dup_fields_ok has_sel (L _ (DataFamInstD _ d))\\n = new_di dup_fields_ok has_sel Nothing d\\n new_assoc dup_fields_ok has_sel\\n (L _ (ClsInstD _ (ClsInstDecl { cid_poly_ty = inst_ty\\n , cid_decls = decls })))\\n = do -- First, attempt to grab the name of the class from the instance.\\n -- This step could fail if the instance is not headed by a class,\\n -- such as in the following examples:\\n --\\n -- (1) The class is headed by a bang pattern, such as in\\n -- `instance !Show Int` (#3811c)\\n -- (2) The class is headed by a type variable, such as in\\n -- `instance c` (#16385)\\n --\\n -- If looking up the class name fails, then mb_cls_gre will\\n -- be Nothing.\\n mb_cls_gre <- runMaybeT $ do\\n -- See (1) above\\n L loc cls_rdr <- MaybeT $ pure $ getLHsInstDeclClass_maybe inst_ty\\n -- See (2) above\\n MaybeT $ setSrcSpan (locA loc) $ lookupGlobalOccRn_maybe SameNameSpace cls_rdr\\n -- Assuming the previous step succeeded, process any associated data\\n -- family instances. If the previous step failed, bail out.\\n case mb_cls_gre of\\n Nothing\\n -> pure []\\n Just cls_gre\\n -> let cls_nm = greName cls_gre\\n in concatMapM (new_di dup_fields_ok has_sel (Just cls_nm) . unLoc) (data_fam_insts decls)\\n\\n data_fam_insts decls = concatMap get decls\\n where\\n get (L l (InstD _ (DataFamInstD { dfid_inst = d}))) = [L l d]\\n get _ = []\\n\\n new_di :: DuplicateRecordFields -> FieldSelectors\\n -> Maybe Name -- class name\\n -> DataFamInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_di dup_fields_ok has_sel mb_cls dfid@(DataFamInstDecl { dfid_eqn = ti_decl })\\n = do { main_name <- unLoc <$> lookupFamInstName mb_cls (feqn_tycon ti_decl)\\n ; let LConsWithFields cons_with_flds flds = hsDataFamInstBinders dfid\\n ; sub_names <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst sub_names) flds\\n ; mapM_ (add_dup_fld_errs flds\') sub_names\\n ; let fld_env = mk_fld_env sub_names flds\'\\n con_gres = map (mkLocalConLikeGRE (ParentIs main_name)) fld_env\\n field_gres = mkLocalFieldGREs (ParentIs main_name) fld_env\\n -- NB: the data family name is not bound here,\\n -- so we don\'t return a GlobalRdrElt for it here!\\n ; return $ con_gres ++ field_gres }\\n\\n -- Add errors if a constructor has a duplicate record field.\\n add_dup_fld_errs :: IntMap FieldLabel\\n -> (Name, Either VisArity [Located Int])\\n -> IOEnv (Env TcGblEnv TcLclEnv) ()\\n add_dup_fld_errs all_flds (con, con_flds_or_arity)\\n | Right con_flds <- con_flds_or_arity\\n , let (_, dups) = removeDups (comparing unLoc) con_flds\\n = for_ dups $ \\\\ dup_flds ->\\n -- Report the error at the location of the second occurrence\\n -- of the duplicate field.\\n let loc =\\n case dup_flds of\\n _ :| ( L loc _ : _) -> loc\\n L loc _ :| _ -> loc\\n dup_rdrs = fmap (nameRdrName . flSelector . (all_flds IntMap.!) . unLoc) dup_flds\\n in addErrAt loc $ TcRnDuplicateFieldName (RecordFieldDecl con) dup_rdrs\\n | otherwise\\n = return ()\\n\\nnewRecordFieldLabel :: DuplicateRecordFields -> FieldSelectors -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel\\nnewRecordFieldLabel _ _ [] _ = error \\"newRecordFieldLabel: datatype has no constructors!\\"\\nnewRecordFieldLabel dup_fields_ok has_sel (dc:_) (L loc (FieldOcc _ (L _ fld)))\\n = do { selName <- newTopSrcBinder $ L (l2l loc) $ field\\n ; return $ FieldLabel { flHasDuplicateRecordFields = dup_fields_ok\\n , flHasFieldSelector = has_sel\\n , flSelector = selName } }\\n where\\n fld_occ = rdrNameOcc fld\\n dc_fs = occNameFS $ nameOccName dc\\n field\\n -- Use an Exact RdrName as-is, to preserve the bindings\\n -- of an already renamer-resolved field and its use\\n -- sites. This is needed to correctly support record\\n -- selectors in Template Haskell. See Note [Binders in\\n -- Template Haskell] in \\"GHC.ThToHs\\" and Note [Looking up\\n -- Exact RdrNames] in \\"GHC.Rename.Env\\".\\n | isExact fld\\n = assertPpr (fieldOcc_maybe fld_occ == Just dc_fs)\\n (vcat [ text \\"newRecordFieldLabel: incorrect namespace for exact Name\\" <+> quotes (ppr fld)\\n , text \\"expected namespace:\\" <+> pprNameSpace (fieldName dc_fs)\\n , text \\" actual namespace:\\" <+> pprNameSpace (occNameSpace fld_occ) ])\\n fld\\n\\n -- Field names produced by the parser are namespaced with VarName.\\n -- Here we namespace them according to the first constructor.\\n -- See Note [Record field namespacing] in GHC.Types.Name.Occurrence.\\n | otherwise\\n = mkRdrUnqual $ varToRecFieldOcc dc_fs fld_occ\\n\\n{-\\nNote [Looking up family names in family instances]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider\\n\\n module M where\\n type family T a :: *\\n type instance M.T Int = Bool\\n\\nWe might think that we can simply use \'lookupOccRn\' when processing the type\\ninstance to look up \'M.T\'. Alas, we can\'t! The type family declaration is in\\nthe *same* HsGroup as the type instance declaration. Hence, as we are\\ncurrently collecting the binders declared in that HsGroup, these binders will\\nnot have been added to the global environment yet.\\n\\nSolution is simple: process the type family declarations first, extend\\nthe environment, and then process the type instances.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Filtering imports}\\n* *\\n************************************************************************\\n\\n@filterImports@ takes the @ExportEnv@ telling what the imported module makes\\navailable, and filters it through the import spec (if any).\\n\\nNote [Dealing with imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nFor import M( ies ), we take each AvailInfo from the mi_exports of M, and make\\n\\n imp_occ_env :: OccEnv (NameEnv ImpOccItem)\\n\\nThis map contains one entry for each OccName that M exports, mapping each OccName\\nto the following information:\\n\\n 1. the GlobalRdrElt corresponding to the OccName,\\n 2. whether this GlobalRdrElt was the parent in the AvailInfo we found\\n the OccName in.\\n 3. the GlobalRdrElts that were bundled together in the AvailInfo we found\\n this OccName in (not including the parent),\\n\\nWe need (2) and (3) during the construction of the OccEnv because of associated\\ntypes and bundled pattern synonyms, respectively.\\n(3) is explained in Note [Importing PatternSynonyms].\\n\\nTo explain (2), consider for example:\\n\\n module M where\\n class C a where { data T a }\\n instance C Int where { data T Int = T1 | T2 }\\n instance C Bool where { data T Int = T3 }\\n\\nHere, M\'s exports avails are (recalling the AvailTC invariant from GHC.Types.Avail)\\n\\n C(C,T), T(T,T1,T2,T3)\\n\\nNotice that T appears *twice*, once as a child and once as a parent. From\\nthese two exports, respectively, during construction of the imp_occ_env, we begin\\nby associating the following two elements with the key T:\\n\\n T -> ImpOccItem { imp_item = gre1, imp_bundled = [C,T] , imp_is_parent = False }\\n T -> ImpOccItem { imp_item = gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nwhere `gre1`, `gre2` are two GlobalRdrElts with greName T.\\nWe combine these (in function \'combine\' in \'mkImportOccEnv\') by discarding the\\nnon-parent item, thusly:\\n\\n T -> IE_ITem { imp_item = gre1 `plusGRE` gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nNote the `plusGRE`: this ensures we don\'t drop parent information;\\nsee Note [Preserve parent information when combining import OccEnvs].\\n\\nSo the overall imp_occ_env is:\\n\\n C -> ImpOccItem { imp_item = C, imp_bundled = [T ], imp_is_parent = True }\\n T -> ImpOccItem { imp_item = T , imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n T1 -> ImpOccItem { imp_item = T1, imp_bundled = [T1,T2,T3], imp_is_parent = False }\\n -- similarly for T2, T3\\n\\nNote that the imp_occ_env will have entries for data constructors too,\\nalthough we never look up data constructors.\\n\\nNote [Importing PatternSynonyms]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nAs described in Note [Dealing with imports], associated types can lead to the\\nsame Name appearing twice, both as a child and once as a parent, when\\nconstructing the imp_occ_env. The same thing can happen with pattern synonyms\\nif they are exported bundled with a type.\\n\\nA simplified example, based on #11959:\\n\\n {-# LANGUAGE PatternSynonyms #-}\\n module M (T(P), pattern P) where -- Duplicate export warning, but allowed\\n data T = MkT\\n pattern P = MkT\\n\\nHere we have T(P) and P in export_avails, and respectively construct both\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n P -> ImpOccItem { imp_item = P, imp_bundled = [] , imp_is_parent = False }\\n\\nWe combine these by dropping the one with no siblings, leaving us with:\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n\\nThat is, we simply discard the non-bundled Avail.\\n\\nNote [Importing DuplicateRecordFields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn filterImports, another complicating factor is DuplicateRecordFields.\\nSuppose we have:\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (S(foo), T(foo)) where\\n data S = MkS { foo :: Int }\\n data T = MkT { foo :: Int }\\n\\n module N where\\n import M (foo) -- this is allowed (A)\\n import M (S(foo)) -- this is allowed (B)\\n\\nHere M exports \'foo\' at two different OccNames, with different namespaces for\\nthe two construtors MkS and MkT. Then, when we look up \'foo\' in lookup_names\\nfor case (A), we have a variable foo but must look in all the record field\\nnamespaces to find the two fields (and hence two different Avails).\\nWhereas in case (B) we reach the lookup_ie case for IEThingWith,\\nwhich looks up \'S\' and then finds the unique \'foo\' amongst its children.\\n\\nSee T16745 for a test of this.\\n\\nNote [Preserve parent information when combining import OccEnvs]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen discarding one ImpOccItem in favour of another, as described in\\nNote [Dealing with imports], we must make sure to combine the GREs so that\\nwe don\'t lose information.\\n\\nConsider for example #24084:\\n\\n module M1 where { class C a where { type T a } }\\n module M2 ( module M1 ) where { import M1 }\\n module M3 where { import M2 ( C, T ); instance C () where T () = () }\\n\\nWhen processing the import list of `M3`, we will have two `Avail`s attached\\nto `T`, namely `C(C, T)` and `T(T)`. We combine them in the `combine` function\\nof `mkImportOccEnv`; as described in Note [Dealing with imports] we discard\\n`C(C, T)` in favour of `T(T)`. However, in doing so, we **must not**\\ndiscard the information want that `C` is the parent of `T`. Indeed,\\nlosing track of this information can cause errors when importing,\\nas we could get an error of the form\\n\\n \\u2018T\\u2019 is not a (visible) associated type of class \\u2018C\\u2019\\n\\nThis explains why we use `plusGRE` when combining the two ImpOccItems, even\\nthough we are discarding one in favour of the other.\\n-}\\n\\n-- | All the \'GlobalRdrElt\'s associated with an \'AvailInfo\'.\\ngresFromAvail :: HasDebugCallStack\\n => HscEnv -> Maybe ImportSpec -> AvailInfo -> [GlobalRdrElt]\\ngresFromAvail hsc_env prov avail =\\n [ mk_gre nm info\\n | nm <- availNames avail\\n , let info = lookupGREInfo hsc_env nm ]\\n where\\n\\n mk_gre n info\\n = case prov of\\n -- Nothing => bound locally\\n -- Just is => imported from \'is\'\\n Nothing -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = True, gre_imp = emptyBag\\n , gre_info = info }\\n Just is -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = False, gre_imp = unitBag is\\n , gre_info = info }\\n\\n-- | All the \'GlobalRdrElt\'s associated with a collection of \'AvailInfo\'s.\\ngresFromAvails :: HscEnv -> Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]\\ngresFromAvails hsc_env prov = concatMap (gresFromAvail hsc_env prov)\\n\\nimportsFromIface :: HscEnv -> ModIface -> ImpDeclSpec -> Maybe NameSet -> GlobalRdrEnv\\nimportsFromIface hsc_env iface decl_spec hidden = mkGlobalRdrEnv $ case hidden of\\n Nothing -> all_gres\\n Just hidden_names -> filter (not . (`elemNameSet` hidden_names) . greName) all_gres\\n where\\n all_gres = gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\nrnNamespaceSpecifier :: NamespaceSpecifier GhcPs -> NamespaceSpecifier GhcRn\\nrnNamespaceSpecifier (NoNamespaceSpecifier _) = NoNamespaceSpecifier noExtField\\nrnNamespaceSpecifier (TypeNamespaceSpecifier x) = TypeNamespaceSpecifier x\\nrnNamespaceSpecifier (DataNamespaceSpecifier x) = DataNamespaceSpecifier x\\n\\nfilterImports\\n :: HasDebugCallStack\\n => HscEnv\\n -> ModIface\\n -> ImpDeclSpec\\n -- ^ Import spec\\n -> Maybe (ImportListInterpretation, [LIE GhcPs])\\n -- ^ Whether this is a \\"hiding\\" import list\\n -> RnM (Maybe (ImportListInterpretation, [LIE GhcRn]), -- Import spec w/ Names\\n ImpUserList, -- same, but designed for storage in interfaces\\n GlobalRdrEnv) -- Same again, but in GRE form\\nfilterImports hsc_env iface decl_spec Nothing\\n = return (Nothing, ImpUserAll, importsFromIface hsc_env iface decl_spec Nothing)\\nfilterImports hsc_env iface decl_spec (Just (want_hiding, import_items))\\n = do -- check for errors, convert RdrNames to Names\\n items1 <- mapM lookup_lie import_items\\n\\n let items2 :: [(LIE GhcRn, [GlobalRdrElt])]\\n items2 = concat items1\\n -- NB we may have duplicates, and several items\\n -- for the same parent; e.g N(x) and N(y)\\n\\n (gres, imp_user_list) = case want_hiding of\\n Exactly ->\\n let gres = concatMap (gresFromIE decl_spec) items2\\n gre_env = mkGlobalRdrEnv gres\\n implicit_parents = mkNameSet $ mapMaybe parentOfImplicitlyImportedGRE gres\\n in (gre_env, ImpUserExplicit (gresToAvailInfo $ globalRdrEnvElts $ gre_env) implicit_parents)\\n EverythingBut ->\\n let hidden_names = mkNameSet $ concatMap (map greName . snd) items2\\n in (importsFromIface hsc_env iface decl_spec (Just hidden_names), ImpUserEverythingBut hidden_names)\\n\\n return (Just (want_hiding, map fst items2), imp_user_list, gres)\\n where\\n import_mod = mi_module iface\\n all_avails = mi_exports iface\\n imp_occ_env = mkImportOccEnv hsc_env decl_spec all_avails\\n\\n -- Look up a parent (type constructor, class or data constructor)\\n -- in an import.\\n lookup_parent :: IE GhcPs -> RdrName -> IELookupM ImpOccItem\\n lookup_parent ie rdr =\\n assertPpr (not $ isVarNameSpace ns)\\n (vcat [ text \\"filterImports lookup_parent: unexpected variable\\"\\n , text \\"rdr:\\" <+> ppr rdr\\n , text \\"namespace:\\" <+> pprNameSpace ns ]) $\\n do { xs <- lookup_names ie rdr\\n ; case xs of\\n cax :| [] -> return cax\\n _ -> pprPanic \\"filter_imports lookup_parent ambiguous\\" $\\n vcat [ text \\"rdr:\\" <+> ppr rdr\\n , text \\"lookups:\\" <+> ppr (fmap imp_item xs) ] }\\n -- Looking up non-variables is always unambiguous,\\n -- as there can be at most one corresponding item\\n -- in the imp_occ_env.\\n -- See item (1) of Note [Exporting duplicate declarations]\\n -- in GHC.Tc.Gen.Export.\\n where\\n occ = rdrNameOcc rdr\\n ns = occNameSpace occ\\n\\n -- Look up a RdrName used in an import, returning multiple values if there\\n -- are several fields with the same name exposed by the module\\n lookup_names :: IE GhcPs -> RdrName -> IELookupM (NonEmpty ImpOccItem)\\n lookup_names ie rdr\\n | isQual rdr\\n = failLookupWith (QualImportError rdr)\\n | otherwise\\n = case lookups of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n item:items -> return $ item :| items\\n where\\n lookups = concatMap nonDetNameEnvElts\\n $ lookupImpOccEnv (RelevantGREsFOS WantNormal) imp_occ_env (rdrNameOcc rdr)\\n\\n lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, [GlobalRdrElt])]\\n lookup_lie (L loc ieRdr)\\n = setSrcSpanA loc $\\n do (stuff, warns) <- run_lookup ([],[]) (lookup_ie ieRdr)\\n mapM_ (addTcRnDiagnostic <=< warning_msg) warns\\n return [ (L loc ie, gres) | (ie,gres) <- stuff ]\\n where\\n\\n -- Warn when importing T(..) and no children are brought in scope\\n warning_msg (DodgyImport reason) =\\n pure (TcRnDodgyImports reason)\\n warning_msg MissingImportList =\\n pure (TcRnMissingImportList ieRdr)\\n warning_msg (BadImportW ie sub) = do\\n -- \'BadImportW\' is only constructed below in \'bad_import_w\', in\\n -- the \'EverythingBut\' case, so here we assume a \'hiding\' clause.\\n (reason :| _) <- badImportItemErr iface decl_spec ie sub all_avails\\n pure (TcRnDodgyImports (DodgyImportsHiding reason))\\n warning_msg (DeprecatedExport n w) =\\n pure $ TcRnPragmaWarning\\n PragmaWarningExport\\n { pwarn_occname = occName n\\n , pwarn_impmod = moduleName import_mod }\\n w\\n\\n run_lookup :: a -> IELookupM a -> TcRn a\\n run_lookup def m = case m of\\n Failed err -> do\\n msgs <- lookup_err_msgs err\\n forM_ msgs $ \\\\msg -> addErr (TcRnImportLookup msg)\\n return def\\n Succeeded a -> return a\\n\\n lookup_err_msgs err = case err of\\n BadImport ie sub -> badImportItemErr iface decl_spec ie sub all_avails\\n IllegalImport -> pure $ NE.singleton ImportLookupIllegal\\n QualImportError rdr -> pure $ NE.singleton (ImportLookupQualified rdr)\\n\\n -- For each import item, we convert its RdrNames to Names,\\n -- and at the same time compute all the GlobalRdrElt corresponding\\n -- to what is actually imported by this item.\\n -- Returns Nothing on error.\\n --\\n -- Returns a list because, with DuplicateRecordFields, a naked\\n -- import/export of a record field can correspond to multiple\\n -- different GlobalRdrElts. See Note [Importing DuplicateRecordFields].\\n lookup_ie :: IE GhcPs\\n -> IELookupM ([(IE GhcRn, [GlobalRdrElt])], [IELookupWarning])\\n lookup_ie ie = handle_bad_import $\\n case ie of\\n IEVar _ (L l n) _ -> do\\n -- See Note [Importing DuplicateRecordFields]\\n xs <- lookup_names ie (ieWrappedName n)\\n let gres = map imp_item $ NE.toList xs\\n export_depr_warns\\n | want_hiding == Exactly\\n = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ( [ (IEVar Nothing (L l (replaceWrappedName n name)) noDocstring, [gre])\\n | gre <- gres\\n , let name = greName gre ]\\n , export_depr_warns )\\n\\n IEThingAll x ns_spec (L l tc) _ -> do\\n ImpOccItem { imp_item = gre\\n , imp_bundled = bundled_gres\\n , imp_is_parent = is_par\\n }\\n <- lookup_parent ie $ ieWrappedName tc\\n let name = greName gre\\n\\n child_gres :: [GlobalRdrElt]\\n child_gres\\n | is_par = filterByNamespaceSpecifierGREs ns_spec bundled_gres\\n | otherwise = []\\n\\n imp_list_warn\\n\\n | null child_gres\\n -- e.g. f(..) or T(..) where T is a type synonym\\n = [DodgyImport (DodgyImportsEmptyParent ie ns_spec gre)]\\n\\n -- e.g. import M( T(..) )\\n | not (is_qual decl_spec)\\n = [MissingImportList]\\n\\n | otherwise\\n = []\\n\\n renamed_ie = IEThingAll (x { ieta_warning = Nothing })\\n (rnNamespaceSpecifier ns_spec)\\n (L l (replaceWrappedName tc name))\\n noDocstring\\n export_depr_warn\\n | want_hiding == Exactly\\n = maybeToList $ mk_depr_export_warning gre\\n -- We don\'t want to warn about the children as they\\n -- are not explicitly mentioned; the warning will\\n -- be emitted later on if they are used\\n | otherwise = []\\n\\n return ( [(renamed_ie, gre:child_gres)]\\n , imp_list_warn ++ export_depr_warn)\\n\\n\\n IEThingAbs _ (L l tc\') _\\n | want_hiding == EverythingBut -- hiding ( C )\\n -- Here the \'C\' can be a data constructor\\n -- *or* a type/class, or even both\\n -> let tc = ieWrappedName tc\'\\n tc_name = lookup_parent ie tc\\n dc_name = lookup_parent ie (setRdrNameSpace tc srcDataName)\\n in\\n case catIELookupM [ tc_name, dc_name ] of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n names -> return ( [mkIEThingAbs tc\' l (imp_item name) | name <- names], [])\\n | otherwise\\n -> do ImpOccItem { imp_item = gre } <- lookup_parent ie (ieWrappedName tc\')\\n return ( [mkIEThingAbs tc\' l gre]\\n , maybeToList $ mk_depr_export_warning gre)\\n\\n IEThingWith (deprecation, ann) ltc@(L l rdr_tc) wc rdr_ns _ -> do\\n ImpOccItem { imp_item = gre, imp_bundled = subnames }\\n <- lookup_parent (IEThingAbs Nothing ltc noDocstring) (ieWrappedName rdr_tc)\\n let name = greName gre\\n\\n -- Look up the children in the sub-names of the parent\\n -- See Note [Importing DuplicateRecordFields]\\n let (children_errs, childnames) = lookupChildren subnames rdr_ns\\n\\n bad_import_warns <-\\n if null children_errs then return [] else\\n let items = map lce_wrapped_name children_errs\\n ie = IEThingWith (deprecation, ann) ltc wc items noDocstring\\n -- We are trying to import T( a,b,c,d ), and failed\\n -- to find \'b\' and \'d\'. So we make up an import item\\n -- to report as failing, namely T( b, d ).\\n -- c.f. #15413\\n subordinate_err = mkSubordinateError gre children_errs\\n in bad_import_w ie subordinate_err\\n\\n let name\' = replaceWrappedName rdr_tc name\\n childnames\' = map (to_ie_post_rn . fmap greName) childnames\\n gres = gre : map unLoc childnames\\n export_depr_warns\\n | want_hiding == Exactly = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ([ (IEThingWith (Nothing, ann) (L l name\') wc childnames\' noDocstring\\n ,gres)]\\n , bad_import_warns ++ export_depr_warns)\\n\\n IEWholeNamespace x ns_spec -> do\\n let mod_name = moduleName import_mod\\n names = map greName gres\\n renamed_ie = IEWholeNamespace x { iewn_warning = Nothing\\n , iewn_names = names }\\n (rnNamespaceSpecifier ns_spec)\\n gres = filterByNamespaceSpecifierGREs ns_spec $\\n gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n dodgy_warn\\n | null gres = [DodgyImport (DodgyImportsWildcard mod_name ns_spec)]\\n | otherwise = []\\n return ([(renamed_ie, gres)],\\n dodgy_warn)\\n\\n _other -> failLookupWith IllegalImport\\n -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed...\\n -- all of those constitute errors.\\n\\n where\\n mkIEThingAbs tc l gre\\n = (IEThingAbs Nothing (L l (replaceWrappedName tc n)) noDocstring, [gre])\\n where n = greName gre\\n\\n -- N.B. imports never have docstrings\\n noDocstring = Nothing\\n\\n handle_bad_import m = catchIELookup m $ \\\\case\\n BadImport ie sub -> do\\n ws <- bad_import_w ie sub\\n return ([], ws)\\n err -> failLookupWith err\\n\\n bad_import_w :: IE GhcPs -> IsSubordinateError -> IELookupM [IELookupWarning]\\n bad_import_w ie sub\\n | want_hiding == EverythingBut = return [BadImportW ie sub]\\n | otherwise = failLookupWith (BadImport ie sub)\\n\\n mk_depr_export_warning gre\\n = DeprecatedExport name <$> mi_export_warn_fn iface name\\n where\\n name = greName gre\\n\\n-- | Assuming a subordinate item could not be found, do another lookup for a\\n-- more specific error message.\\nmkBadExportSubordinate :: [GlobalRdrElt] -> LIEWrappedName GhcPs -> BadExportSubordinate\\nmkBadExportSubordinate child_gres n =\\n case lookupChildren child_gres [n] of\\n (LookupChildNonType {lce_nontype_item = g} : _, _) -> BadExportSubordinateNonType g\\n (LookupChildNonData {lce_nondata_item = g} : _, _) -> BadExportSubordinateNonData g\\n _ -> BadExportSubordinateNotFound n\\n\\ntype IELookupM = MaybeErr IELookupError\\n\\ndata IELookupWarning\\n = BadImportW (IE GhcPs) IsSubordinateError\\n | MissingImportList\\n | DodgyImport DodgyImportsReason\\n | DeprecatedExport Name (WarningTxt GhcRn)\\n\\n-- | Is this import/export item a subordinate or not?\\ndata IsSubordinateError\\n = IsSubordinateError { subordinate_err_parent :: !GlobalRdrElt\\n , subordinate_err_unavailable :: [FastString]\\n , subordinate_err_nontype :: [GlobalRdrElt]\\n , subordinate_err_nondata :: [GlobalRdrElt] }\\n | IsNotSubordinate\\n\\nmkSubordinateError :: GlobalRdrElt -> [LookupChildError] -> IsSubordinateError\\nmkSubordinateError gre children_errs = foldr add init_acc children_errs\\n where\\n init_acc :: IsSubordinateError\\n init_acc = IsSubordinateError gre [] [] []\\n\\n add :: LookupChildError -> IsSubordinateError -> IsSubordinateError\\n add children_err sub@IsSubordinateError{} =\\n case children_err of\\n LookupChildNonType{lce_nontype_item = g} ->\\n sub { subordinate_err_nontype = g : subordinate_err_nontype sub }\\n LookupChildNonData{lce_nondata_item = g} ->\\n sub { subordinate_err_nondata = g : subordinate_err_nondata sub }\\n LookupChildNotFound (L _ wname) ->\\n let fs = (occNameFS . rdrNameOcc . ieWrappedName) wname\\n in sub { subordinate_err_unavailable = fs : subordinate_err_unavailable sub }\\n add _ IsNotSubordinate = panic \\"mkSubordinateError: IsNotSubordinate\\"\\n\\ndata IELookupError\\n = QualImportError RdrName\\n | BadImport (IE GhcPs) IsSubordinateError\\n | IllegalImport\\n\\nfailLookupWith :: IELookupError -> IELookupM a\\nfailLookupWith err = Failed err\\n\\ncatchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a\\ncatchIELookup m h = case m of\\n Succeeded r -> return r\\n Failed err -> h err\\n\\ncatIELookupM :: [IELookupM a] -> [a]\\ncatIELookupM ms = [ a | Succeeded a <- ms ]\\n\\n-- | Information associated to an \'AvailInfo\' used in constructing\\n-- an \'OccEnv\' corresponding to imports.\\n--\\n-- See Note [Dealing with imports].\\ndata ImpOccItem\\n = ImpOccItem\\n { imp_item :: GlobalRdrElt\\n -- ^ The import item\\n , imp_bundled :: [GlobalRdrElt]\\n -- ^ Items bundled in the Avail this import item came from,\\n -- not including the import item itself if it is a parent.\\n , imp_is_parent :: Bool\\n -- ^ Is the import item a parent? See Note [Dealing with imports].\\n }\\n\\ninstance Outputable ImpOccItem where\\n ppr (ImpOccItem { imp_item = item, imp_bundled = bundled, imp_is_parent = is_par })\\n = braces $ hsep\\n [ text \\"ImpOccItem\\"\\n , if is_par then text \\"[is_par]\\" else empty\\n , ppr (greName item) <+> ppr (greParent item)\\n , braces $ text \\"bundled:\\" <+> ppr (map greName bundled) ]\\n\\n-- | Make an \'OccEnv\' of all the imports.\\n--\\n-- Complicated by the fact that associated data types and pattern synonyms\\n-- can appear twice. See Note [Dealing with imports].\\nmkImportOccEnv :: HscEnv -> ImpDeclSpec -> [IfaceExport] -> OccEnv (NameEnv ImpOccItem)\\nmkImportOccEnv hsc_env decl_spec all_avails =\\n mkOccEnv_C (plusNameEnv_C combine)\\n [ (occ, mkNameEnv [(nm, item)])\\n | avail <- all_avails\\n , let gres = gresFromAvail hsc_env (Just hiding_spec) avail\\n , gre <- gres\\n , let nm = greName gre\\n occ = greOccName gre\\n (is_parent, bundled) = case avail of\\n AvailTC c _\\n | c == nm -- (Recall the AvailTC invariant from GHC.Types.AvailInfo)\\n -> ( True, drop 1 gres ) -- \\"drop 1\\": don\'t include the parent itself.\\n | otherwise\\n -> ( False, gres )\\n _ -> ( False, [] )\\n item = ImpOccItem\\n { imp_item = gre\\n , imp_bundled = bundled\\n , imp_is_parent = is_parent }\\n ]\\n where\\n\\n hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\n -- See Note [Dealing with imports]\\n -- \'combine\' may be called for associated data types which appear\\n -- twice in the all_avails. In the example, we have two Avails for T,\\n -- namely T(T,T1,T2,T3) and C(C,T), and we combine them by dropping the\\n -- latter, in which T is not the parent.\\n combine :: ImpOccItem -> ImpOccItem -> ImpOccItem\\n combine item1@(ImpOccItem { imp_item = gre1, imp_is_parent = is_parent1 })\\n item2@(ImpOccItem { imp_item = gre2, imp_is_parent = is_parent2 })\\n | is_parent1 || is_parent2\\n , not (isRecFldGRE gre1 || isRecFldGRE gre2) -- NB: does not force GREInfo.\\n , let name1 = greName gre1\\n name2 = greName gre2\\n gre = gre1 `plusGRE` gre2\\n -- See Note [Preserve parent information when combining import OccEnvs]\\n = assertPpr (name1 == name2)\\n (ppr name1 <+> ppr name2) $\\n if is_parent1\\n then item1 { imp_item = gre }\\n else item2 { imp_item = gre }\\n -- Discard C(C,T) in favour of T(T, T1, T2, T3).\\n\\n -- \'combine\' may also be called for pattern synonyms which appear both\\n -- unassociated and associated (see Note [Importing PatternSynonyms]).\\n combine item1@(ImpOccItem { imp_item = c1, imp_bundled = kids1 })\\n item2@(ImpOccItem { imp_item = c2, imp_bundled = kids2 })\\n = assertPpr (greName c1 == greName c2\\n && (not (null kids1 && null kids2)))\\n (ppr c1 <+> ppr c2 <+> ppr kids1 <+> ppr kids2) $\\n if null kids1\\n then item2\\n else item1\\n -- Discard standalone pattern P in favour of T(P).\\n\\n-- | Essentially like @lookupGRE env (LookupOccName occ which_gres)@,\\n-- but working with \'ImpOccItem\'s instead of \'GlobalRdrElt\'s.\\nlookupImpOccEnv :: WhichGREs GREInfo\\n -> OccEnv (NameEnv ImpOccItem) -> OccName -> [NameEnv ImpOccItem]\\nlookupImpOccEnv which_gres env occ =\\n mapMaybe relevant_items $ lookupOccEnv_AllNameSpaces env occ\\n where\\n is_relevant :: ImpOccItem -> Bool\\n is_relevant (ImpOccItem { imp_item = gre }) =\\n greIsRelevant which_gres (occNameSpace occ) gre\\n relevant_items :: NameEnv ImpOccItem -> Maybe (NameEnv ImpOccItem)\\n relevant_items nms\\n | let nms\' = filterNameEnv is_relevant nms\\n = if isEmptyNameEnv nms\'\\n then Nothing\\n else Just nms\'\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{Import/Export Utils}\\n* *\\n************************************************************************\\n-}\\n\\n-- | Given an import\\\\/export spec, appropriately set the @gre_imp@ field\\n-- for the \'GlobalRdrElt\'s.\\ngresFromIE :: ImpDeclSpec -> (LIE GhcRn, [GlobalRdrElt]) -> [GlobalRdrElt]\\ngresFromIE decl_spec (L loc ie, gres)\\n = map set_gre_imp gres\\n where\\n is_explicit = case ie of\\n IEThingAll _ _ name _ -> \\\\n -> n == lieWrappedName name\\n IEWholeNamespace _ _ -> \\\\_ -> False\\n _ -> \\\\_ -> True\\n prov_fn name\\n = ImpSpec { is_decl = decl_spec, is_item = item_spec }\\n where\\n item_spec = ImpSome { is_explicit = is_explicit name\\n , is_iloc = locA loc }\\n set_gre_imp gre@( GRE { gre_name = nm } )\\n = gre { gre_imp = unitBag $ prov_fn nm }\\n\\nparentOfImplicitlyImportedGRE :: Outputable info => GlobalRdrEltX info -> Maybe Name\\nparentOfImplicitlyImportedGRE gre =\\n if any (explicit_import . is_item) $ gre_imp gre\\n then Nothing\\n else greParent_maybe gre\\n where\\n explicit_import :: ImpItemSpec -> Bool\\n explicit_import (ImpAll {}) =\\n pprPanic \\"parentOfImplicitlyImportedGRE: ImpAll\\" (ppr gre)\\n explicit_import (ImpSome { is_explicit }) = is_explicit\\n\\n{- Note [Children for duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider the module\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (F(foo, MkFInt, MkFBool)) where\\n data family F a\\n data instance F Int = MkFInt { foo :: Int }\\n data instance F Bool = MkFBool { foo :: Bool }\\n\\nThe `foo` in the export list refers to *both* selectors! For this\\nreason, lookupChildren builds an environment that maps the FastString\\nto a list of items, rather than a single item.\\n-}\\n\\nmkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]\\nmkChildEnv gres = foldr add emptyNameEnv gres\\n where\\n add gre env = case greParent gre of\\n ParentIs p -> extendNameEnv_Acc (:) Utils.singleton env p gre\\n NoParent -> env\\n\\nfindChildren :: NameEnv [a] -> Name -> [a]\\nfindChildren env n = lookupNameEnv env n `orElse` []\\n\\ndata LookupChildError\\n = LookupChildNotFound { lce_wrapped_name :: !(LIEWrappedName GhcPs) }\\n | LookupChildNonType { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nontype_item :: !GlobalRdrElt }\\n | LookupChildNonData { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nondata_item :: !GlobalRdrElt }\\n\\nlookupChildren :: [GlobalRdrElt]\\n -> [LIEWrappedName GhcPs]\\n -> ( [LookupChildError] -- The ones for which the lookup failed\\n , [LocatedA GlobalRdrElt] )\\n-- (lookupChildren all_kids rdr_items) maps each rdr_item to its\\n-- corresponding Name in all_kids, if the former exists\\n-- The matching is done by FastString, not OccName, so that\\n-- Cls( meth, AssocTy )\\n-- will correctly find AssocTy among the all_kids of Cls, even though\\n-- the RdrName for AssocTy may have a (bogus) DataName namespace\\n-- (Really the rdr_items should be FastStrings in the first place.)\\nlookupChildren all_kids rdr_items = (fails, successes)\\n where\\n mb_xs = map do_one rdr_items\\n fails = [ err | Failed err <- mb_xs ]\\n successes = [ ok | Succeeded oks <- mb_xs, ok <- NE.toList oks ]\\n\\n do_one :: LIEWrappedName GhcPs -> MaybeErr LookupChildError (NonEmpty (LocatedA GlobalRdrElt))\\n do_one item@(L l r) =\\n case r of\\n IEName{}\\n -- IEName (unadorned name) places no restriction on the namespace of\\n -- the imported entity, so we look in both `val_gres` and `typ_gres`.\\n -- In case of conflict (punning), the value namespace takes priority.\\n -- See Note [Prioritise the value namespace in subordinate import lists]\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEType{}\\n -- IEType (\'type\' namespace specifier) restricts the lookup to the\\n -- type namespace, i.e. to `typ_gres`. In case of failure, we check\\n -- `val_gres` to produce a more helpful error message.\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- val_gres -> Failed $ LookupChildNonType item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEData{}\\n -- IEData (\'data\' namespace specifier) restricts the lookup to the\\n -- data namespace, i.e. to `val_gres`. In case of failure, we check\\n -- `typ_gres` to produce a more helpful error message.\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- typ_gres -> Failed $ LookupChildNonData item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEPattern{} -> panic \\"lookupChildren: IEPattern\\" -- Never happens (invalid syntax)\\n IEDefault{} -> panic \\"lookupChildren: IEDefault\\" -- Never happens (invalid syntax)\\n where\\n fs = (occNameFS . rdrNameOcc . ieWrappedName) r\\n gres = fromMaybe [] (lookupFsEnv kid_env fs)\\n (val_gres, typ_gres) = partition (isValNameSpace . greNameSpace) gres\\n\\n -- See Note [Children for duplicate record fields]\\n kid_env :: FastStringEnv [GlobalRdrElt]\\n kid_env = extendFsEnvList_C (++) emptyFsEnv\\n [(occNameFS (occName x), [x]) | x <- all_kids]\\n\\n\\n{- Note [Prioritise the value namespace in subordinate import lists]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider this program that defines a class that has both an associated type\\nnamed (#) and a method named (#)\\n\\n module M_assoc where\\n class C a b where\\n type a # b\\n (#) :: a -> b -> ()\\n module N_assoc where\\n import M_assoc( C((#)) )\\n\\nIn the import declaration, when we see the unadorned name (#) in the subordinate\\nimport list of C, which children should we bring into scope? Our options are:\\n\\n a) only the method (#)\\n b) only the associated type (#)\\n c) both the method and the associated type\\n\\nTo follow the precedent established by top-level items, we go with option (a).\\nIndeed, consider a slightly different program\\n\\n module M_top where\\n type family a # b\\n a # b = ()\\n module N_top where\\n import M_top( (#) )\\n\\nHere the import brings only the function (#) into scope, and one has to say\\n`type (#)` to get the type family.\\n-}\\n\\n-------------------------------\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused names}\\n* *\\n*********************************************************\\n-}\\n\\nreportUnusedNames :: TcGblEnv -> HscSource -> RnM ()\\nreportUnusedNames gbl_env hsc_src\\n = do { keep <- readTcRef (tcg_keep gbl_env)\\n ; traceRn \\"RUN\\" (ppr (tcg_dus gbl_env))\\n ; warnUnusedImportDecls gbl_env hsc_src\\n ; warnUnusedTopBinds $ unused_locals keep\\n ; warnMissingSignatures gbl_env\\n ; warnMissingKindSignatures gbl_env }\\n where\\n used_names :: NameSet -> NameSet\\n used_names keep = findUses (tcg_dus gbl_env) emptyNameSet `unionNameSet` keep\\n -- NB: currently, if f x = g, we only treat \'g\' as used if \'f\' is used\\n -- Hence findUses\\n\\n -- Collect the defined names from the in-scope environment\\n defined_names :: [GlobalRdrElt]\\n defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)\\n\\n kids_env = mkChildEnv defined_names\\n -- This is done in mkExports too; duplicated work\\n\\n gre_is_used :: NameSet -> GlobalRdrElt -> Bool\\n gre_is_used used_names gre0\\n = name `elemNameSet` used_names\\n || any (\\\\ gre -> greName gre `elemNameSet` used_names) (findChildren kids_env name)\\n -- A use of C implies a use of T,\\n -- if C was brought into scope by T(..) or T(C)\\n where\\n name = greName gre0\\n\\n -- Filter out the ones that are\\n -- (a) defined in this module, and\\n -- (b) not defined by a \'deriving\' clause\\n -- The latter have an Internal Name, so we can filter them out easily\\n unused_locals :: NameSet -> [GlobalRdrElt]\\n unused_locals keep =\\n let -- Note that defined_and_used, defined_but_not_used\\n -- are both [GRE]; that\'s why we need defined_and_used\\n -- rather than just used_names\\n _defined_and_used, defined_but_not_used :: [GlobalRdrElt]\\n (_defined_and_used, defined_but_not_used)\\n = partition (gre_is_used (used_names keep)) defined_names\\n\\n in filter is_unused_local defined_but_not_used\\n is_unused_local :: GlobalRdrElt -> Bool\\n is_unused_local gre = isLocalGRE gre\\n && isExternalName (greName gre)\\n\\n{- *********************************************************************\\n* *\\n Missing signatures\\n* *\\n********************************************************************* -}\\n\\n{-\\nNote [Missing signatures]\\n~~~~~~~~~~~~~~~~~~~~~~~~~\\nThere are four warning flags in play:\\n\\n * -Wmissing-exported-signatures\\n Warn about any exported top-level function/value without a type signature.\\n Does not include pattern synonyms.\\n\\n * -Wmissing-signatures\\n Warn about any top-level function/value without a type signature. Does not\\n include pattern synonyms. Takes priority over -Wmissing-exported-signatures.\\n\\n * -Wmissing-exported-pattern-synonym-signatures\\n Warn about any exported pattern synonym without a type signature.\\n\\n * -Wmissing-pattern-synonym-signatures\\n Warn about any pattern synonym without a type signature. Takes priority over\\n -Wmissing-exported-pattern-synonym-signatures.\\n\\n-}\\n\\n-- | Warn the user about top level binders that lack type signatures.\\n-- Called /after/ type inference, so that we can report the\\n-- inferred type of the function\\nwarnMissingSignatures :: TcGblEnv -> RnM ()\\nwarnMissingSignatures gbl_env\\n = do { let exports = availsToNameSet (tcg_exports gbl_env)\\n sig_ns = tcg_sigs gbl_env\\n -- We use sig_ns to exclude top-level bindings that are generated by GHC\\n binds = collectHsBindsBinders CollNoDictBinders $ tcg_binds gbl_env\\n pat_syns = tcg_patsyns gbl_env\\n\\n not_ghc_generated :: Name -> Bool\\n not_ghc_generated name = name `elemNameSet` sig_ns\\n\\n add_binding_warn :: Id -> RnM ()\\n add_binding_warn id =\\n when (not_ghc_generated name) $\\n do { env <- liftZonkM $ tcInitTidyEnv -- Why not use emptyTidyEnv?\\n ; let ty = tidyOpenType env (idType id)\\n missing = MissingTopLevelBindingSig name ty\\n diag = TcRnMissingSignature missing exported\\n ; addDiagnosticAt (getSrcSpan name) diag }\\n where\\n name = idName id\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n add_patsyn_warn :: PatSyn -> RnM ()\\n add_patsyn_warn ps =\\n when (not_ghc_generated name) $\\n addDiagnosticAt (getSrcSpan name)\\n (TcRnMissingSignature missing exported)\\n where\\n name = patSynName ps\\n missing = MissingPatSynSig ps\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n -- Warn about missing signatures\\n -- Do this only when we have a type to offer\\n -- See Note [Missing signatures]\\n ; mapM_ add_binding_warn binds\\n ; mapM_ add_patsyn_warn pat_syns\\n }\\n\\n-- | Warn the user about tycons that lack kind signatures.\\n-- Called /after/ type (and kind) inference, so that we can report the\\n-- inferred kinds.\\nwarnMissingKindSignatures :: TcGblEnv -> RnM ()\\nwarnMissingKindSignatures gbl_env\\n = do { cusks_enabled <- xoptM LangExt.CUSKs\\n ; mapM_ (add_ty_warn cusks_enabled) tcs\\n }\\n where\\n tcs = tcg_tcs gbl_env\\n ksig_ns = tcg_ksigs gbl_env\\n exports = availsToNameSet (tcg_exports gbl_env)\\n\\n has_kind_signature :: Name -> Bool\\n has_kind_signature name = name `elemNameSet` ksig_ns\\n\\n add_ty_warn :: Bool -> TyCon -> RnM ()\\n add_ty_warn cusks_enabled tyCon =\\n when (has_kind_signature name) $\\n addDiagnosticAt (getSrcSpan name) diag\\n where\\n name = tyConName tyCon\\n diag = TcRnMissingSignature missing exported\\n missing = MissingTyConKindSig tyCon cusks_enabled\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused imports}\\n* *\\n*********************************************************\\n\\nThis code finds which import declarations are unused. The\\nspecification and implementation notes are here:\\n https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/unused-imports\\n\\nSee also Note [Choosing the best import declaration] in GHC.Types.Name.Reader\\n-}\\n\\ntype ImportDeclUsage\\n = ( LImportDecl GhcRn -- The import declaration\\n , [GlobalRdrElt] -- What *is* used (normalised)\\n , [Name] -- What is imported but *not* used\\n , [NamespaceSpecifier GhcRn] ) -- Unused wildcards\\n\\nwarnUnusedImportDecls :: TcGblEnv -> HscSource -> RnM ()\\nwarnUnusedImportDecls gbl_env hsc_src\\n = do { uses <- readMutVar (tcg_used_gres gbl_env)\\n ; let imports = tcg_rn_imports gbl_env\\n rdr_env = tcg_rdr_env gbl_env\\n\\n -- We should only warn for unnecessary *user* imports, but deciding\\n -- minimal imports should take generated imports into account\\n ; let usageUserImports = findImportUsage (excludeGenerated imports) uses\\n usageAllImports = findImportUsage imports uses\\n\\n ; traceRn \\"warnUnusedImportDecls\\" $\\n (vcat [ text \\"Uses:\\" <+> ppr uses\\n , text \\"Usage all user imports: \\" <+> ppr usageUserImports\\n , text \\"Usage all imports: \\" <+> ppr usageAllImports])\\n\\n ; mapM_ (warnUnusedImport rdr_env) usageUserImports\\n\\n ; whenGOptM Opt_D_dump_minimal_imports $\\n printMinimalImports hsc_src usageAllImports }\\n\\n-- | Exclude generated imports\\nexcludeGenerated :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\nexcludeGenerated = filterOut (isGeneratedImport . ideclOrigin . ideclExt . unLoc)\\n\\nfindImportUsage :: [LImportDecl GhcRn]\\n -> [GlobalRdrElt]\\n -> [ImportDeclUsage]\\n\\nfindImportUsage imports used_gres\\n = map unused_decl imports\\n where\\n import_usage :: ImportMap\\n import_usage = mkImportMap used_gres\\n\\n unused_decl :: LImportDecl GhcRn -> ImportDeclUsage\\n unused_decl decl@(L _ (ImportDecl { ideclImportList = imps }))\\n = -- pprTrace \\"unused_decl\\" (vcat [ ppr decl\\n -- , text \\"used\\" <+> ppr used_gres\\n -- , text \\"unused\\" <+> ppr unused_names ]) $\\n (decl, used_gres, unused_names, unused_wcs)\\n where\\n used_gres = lookupImportMap decl import_usage\\n\\n used_gre_env = mkGlobalRdrEnv used_gres\\n used_parents = mkNameSet (mapMaybe greParent_maybe used_gres)\\n\\n (unused_names, unused_wcs) -- Not trivial; see eg #7454\\n = case imps of\\n Just (Exactly, imp_ies) ->\\n let unused = foldr (add_unused . unLoc) emptyUnusedNames imp_ies\\n nms = nameSetElemsStable (collectUnusedNames unused)\\n wcs = collectUnusedWildcards unused\\n in (nms, wcs)\\n _other -> ([], []) -- No explicit import list => no unused-name list\\n\\n add_unused :: IE GhcRn -> UnusedNames -> UnusedNames\\n add_unused (IEVar _ n _) acc = add_unused_name (lieWrappedName n) True acc\\n add_unused (IEThingAbs _ n _) acc = add_unused_name (lieWrappedName n) False acc\\n add_unused (IEThingAll _ _ n _) acc = add_unused_all (lieWrappedName n) acc\\n add_unused (IEThingWith _ p wc ns _) acc = add_wc_all (add_unused_with pn xs acc)\\n where pn = lieWrappedName p\\n xs = map lieWrappedName ns\\n add_wc_all = case wc of\\n NoIEWildcard -> id\\n IEWildcard _ -> add_unused_all pn\\n add_unused (IEWholeNamespace x ns_spec) acc = add_unused_wildcard ns_spec (iewn_names x) acc\\n add_unused _ acc = acc\\n\\n add_unused_name :: Name -> Bool -> UnusedNames -> UnusedNames\\n add_unused_name n is_ie_var acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | is_ie_var\\n , isFieldName n\\n -- See Note [Reporting unused imported duplicate record fields]\\n = let\\n fs = getOccFS n\\n (flds, flds_used) = lookupFsEnv acc_fs fs `orElse` (emptyNameSet, Any False)\\n acc_fs\' = extendFsEnv acc_fs fs (extendNameSet flds n, Any used S.<> flds_used)\\n in UnusedNames acc_ns acc_wcs acc_fs\'\\n\\n | used\\n = acc\\n\\n | otherwise\\n = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n where\\n used = isJust $ lookupGRE_Name used_gre_env n\\n\\n add_unused_all :: Name -> UnusedNames -> UnusedNames\\n add_unused_all n acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | Just {} <- lookupGRE_Name used_gre_env n = acc\\n | n `elemNameSet` used_parents = acc\\n | otherwise = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n\\n add_unused_with :: Name -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_with p ns acc\\n | all (`elemNameSet` acc1_ns) ns = add_unused_name p False acc1\\n | otherwise = acc1\\n where\\n acc1@(UnusedNames acc1_ns _ _) = foldr (\\\\n acc\' -> add_unused_name n False acc\') acc ns\\n -- If you use \'signum\' from Num, then the user may well have\\n -- imported Num(signum). We don\'t want to complain that\\n -- Num is not itself mentioned. Hence the two cases in add_unused_with.\\n\\n add_unused_wildcard :: NamespaceSpecifier GhcRn -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_wildcard ns_spec names acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | any_used = acc\\n | otherwise = UnusedNames acc_ns (ns_spec : acc_wcs) acc_fs\\n where\\n -- A wildcard `type ..` or `data ..` is used if at least one of\\n -- the names it expands to is used\\n any_used = any (isJust . lookupGRE_Name used_gre_env) names\\n\\n\\n-- | An accumulator for unused names in an import list.\\n--\\n-- See Note [Reporting unused imported duplicate record fields].\\ndata UnusedNames =\\n UnusedNames\\n { unused_names :: NameSet\\n -- ^ Unused \'Name\'s in an import list, not including record fields\\n -- that are plain \'IEVar\' imports (tracked by \'rec_fld_uses\')\\n -- or wildcard imports (tracked by \'unused_wildcards\').\\n , unused_wildcards :: [NamespaceSpecifier GhcRn]\\n -- ^ Unused wildcards @type ..@ or @data ..@ in an import list.\\n , rec_fld_uses :: FastStringEnv (NameSet, Any)\\n -- ^ Record fields imported without a parent (i.e. an \'IEVar\' import).\\n --\\n -- The \'Any\' value records whether any of the record fields\\n -- sharing the same underlying \'FastString\' have been used.\\n }\\n\\nemptyUnusedNames :: UnusedNames\\nemptyUnusedNames = UnusedNames emptyNameSet [] emptyFsEnv\\n\\ninstance Outputable UnusedNames where\\n ppr (UnusedNames nms wcs flds) =\\n text \\"UnusedNames\\" <+>\\n braces (ppr nms <+> ppr wcs <+> ppr (fmap (second getAny) flds))\\n\\n-- | Collect all unused names from a \'UnusedNames\' value.\\ncollectUnusedNames :: UnusedNames -> NameSet\\ncollectUnusedNames (UnusedNames { unused_names = nms, rec_fld_uses = flds })\\n = nms S.<> unused_flds\\n where\\n unused_flds = nonDetFoldFsEnv collect_unused emptyNameSet flds\\n collect_unused :: (NameSet, Any) -> NameSet -> NameSet\\n collect_unused (nms, Any at_least_one_name_is_used) acc\\n | at_least_one_name_is_used = acc\\n | otherwise = unionNameSet nms acc\\n\\ncollectUnusedWildcards :: UnusedNames -> [NamespaceSpecifier GhcRn]\\ncollectUnusedWildcards = unused_wildcards\\n\\n{- Note [Reporting unused imported duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have (#24035):\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M1 (R1(..), R2(..)) where\\n data R1 = MkR1 { fld :: Int }\\n data R2 = MkR2 { fld :: Int }\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M2 where\\n import M1 (R1(MkR1), R2, fld)\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nIn the import of \'M1\' in \'M2\', the \'fld\' import resolves to two separate GREs,\\nnamely R1(fld) and R2(fld). From the perspective of the renamer, and in particular\\nthe \'findImportUsage\' function, it\'s as if the user had imported the two names\\nseparately (even though no source syntax allows that).\\n\\nThis means that we need to be careful when reporting unused imports: the R2(fld)\\nimport is indeed unused, but because R1(fld) is used, we should not report\\nfld as unused altogether.\\n\\nTo achieve this, we keep track of record field imports without a parent (i.e.\\nusing the IEVar constructor) separately from other import items, using the\\nUnusedNames datatype.\\nOnce we have accumulated usages, we emit warnings for unused record fields\\nwithout parents one whole group (of record fields sharing the same textual name)\\nat a time, and only if *all* of the record fields in the group are unused;\\nsee \'collectUnusedNames\'.\\n\\nNote that this only applies to record fields imported without a parent. If we\\nhad:\\n\\n import M1 (R1(MkR1, fld), R2(fld))\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nthen of course we should report the second \'fld\' as unused.\\n-}\\n\\n\\n{- Note [The ImportMap]\\n~~~~~~~~~~~~~~~~~~~~~~~\\nThe ImportMap is a short-lived intermediate data structure records, for\\neach import declaration, what stuff brought into scope by that\\ndeclaration is actually used in the module.\\n\\nThe [GlobalRdrElt] are the things imported from that decl.\\n-}\\n\\ndata ImportMap = ImportMap\\n { im_imports :: Map RealSrcSpan [GlobalRdrElt]\\n -- ^ See [The ImportMap]\\n -- If loc :-> gres, then\\n -- \'loc\' = the end loc of the bestImport of each GRE in \'gres\'\\n , im_generatedImports :: Map ModuleName [GlobalRdrElt]\\n }\\n\\nmkImportMap :: [GlobalRdrElt] -> ImportMap\\n-- For each of a list of used GREs, find all the import decls that brought\\n-- it into scope; choose one of them (bestImport), and record\\n-- the RdrName in that import decl\'s entry in the ImportMap\\nmkImportMap = foldr insertImportMap $ ImportMap Map.empty Map.empty\\n\\ninsertImportMap :: GlobalRdrElt -> ImportMap -> ImportMap\\ninsertImportMap gre@(GRE { gre_imp = imp_specs }) importMap\\n | RealSrcSpan importSpan _ <- is_dloc best_imp_spec =\\n importMap{im_imports = insertElem importSpan gre $ im_imports importMap}\\n | GeneratedSrcSpan{} <- is_dloc best_imp_spec =\\n importMap{im_generatedImports = insertElem (moduleName $ is_mod best_imp_spec) gre $ im_generatedImports importMap}\\n | otherwise = importMap\\n where\\n best_imp_spec =\\n case bagToList imp_specs of\\n [] -> pprPanic \\"mkImportMap: GRE with no ImportSpecs\\" (ppr gre)\\n is:iss -> is_decl $ bestImport (is NE.:| iss)\\n\\n -- https://github.com/haskell/containers/issues/784\\n insertElem :: Ord k => k -> v -> Map k [v] -> Map k [v]\\n insertElem k v = flip Map.alter k $ \\\\case\\n Just vs -> Just (v : vs)\\n Nothing -> Just [v]\\n\\nlookupImportMap :: LImportDecl GhcRn -> ImportMap -> [GlobalRdrElt]\\nlookupImportMap (L srcSpan ImportDecl{ideclName = L _ modName}) importMap =\\n fromMaybe [] $\\n -- should match logic in insertImportMap\\n case locA srcSpan of\\n RealSrcSpan realSrcSpan _ -> realSrcSpan `Map.lookup` im_imports importMap\\n GeneratedSrcSpan{} -> modName `Map.lookup` im_generatedImports importMap\\n _ -> Nothing\\n\\nlieNames :: LIE (GhcPass p) -> [Located (IdP (GhcPass p))]\\nlieNames = _\\n\\nwarnUnusedImport :: GlobalRdrEnv -> ImportDeclUsage -> RnM ()\\nwarnUnusedImport rdr_env (L loc decl, used, unused, unused_wcs)\\n\\n -- Do not warn for \'import M()\'\\n -- See (UI1) in Note [Unused imports]\\n | Just (Exactly, _) <- ideclImportList decl\\n , null unused && null unused_wcs\\n = return ()\\n\\n -- Note [Do not warn about Prelude hiding]\\n | Just (EverythingBut, hides) <- ideclImportList decl\\n , not (null hides)\\n , pRELUDE_NAME == unLoc (ideclName decl)\\n = return ()\\n\\n -- Do not warn about import X as Rebindable\\n -- See (UI2) in Note [Unused imports]\\n | Just (L _ mod) <- ideclAs decl\\n , mod == rEBINDABLE_MOD_NAME\\n = return ()\\n\\n -- Nothing used; drop entire declaration\\n | null used\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl UnusedImportNone)\\n\\n -- Everything imported is used; nop\\n | null unused && null unused_wcs\\n = return ()\\n\\n -- Some imports are unused: make the `SrcSpan` cover only the unused\\n -- items instead of the whole import statement\\n | Just (_, imports) <- ideclImportList decl\\n , let unused_locs = [ locA loc | L loc ie <- imports\\n , name <- ieNames ie\\n , name `elem` unused ]\\n , loc1 : locs <- unused_locs\\n , let span = foldr1 combineSrcSpans ( loc1 NE.:| locs )\\n = addDiagnosticAt span (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n -- Some imports are unused\\n | otherwise\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n where\\n -- In warning message, pretty-print identifiers unqualified unconditionally\\n -- to improve the consistent for ambiguous/unambiguous identifiers.\\n -- See #14881.\\n possible_field n =\\n case lookupGRE_Name rdr_env n of\\n Just (GRE { gre_par = par, gre_info = IAmRecField info }) ->\\n let fld_occ :: OccName\\n fld_occ = nameOccName $ flSelector $ recFieldLabel info\\n in UnusedImportNameRecField par fld_occ\\n _ -> UnusedImportNameRegular n\\n\\n -- Print unused names in a deterministic (lexicographic) order\\n sort_unused :: [UnusedImportName]\\n sort_unused =\\n [ UnusedImportWildcard wc | wc <- unused_wcs ] ++\\n [ possible_field nm | nm <- sortBy (comparing nameOccName) unused ]\\n\\ngetMinimalImports :: [ImportDeclUsage] -> RnM [LImportDecl GhcRn]\\ngetMinimalImports ie_decls\\n = do { rdr_env <- getGlobalRdrEnv\\n ; fmap combine $ mapM (mk_minimal rdr_env) ie_decls }\\n where\\n mk_minimal rdr_env (L l decl, used_gres, unused, unused_wcs)\\n | null unused && null unused_wcs\\n , Just (Exactly, _) <- ideclImportList decl\\n = return (L l decl)\\n | otherwise\\n = do { let ImportDecl { ideclName = L _ mod_name\\n , ideclSource = is_boot\\n , ideclPkgQual = pkg_qual\\n , ideclExt = XImportDeclPass { ideclOrigin = origin } } = decl\\n ; iface <- loadSrcInterface doc (importDeclLookupScope origin)\\n mod_name is_boot pkg_qual\\n ; let used_avails = gresToAvailInfo used_gres\\n ; lies <- map (L l) <$> concatMapM (to_ie rdr_env iface) used_avails\\n ; return (L l (decl { ideclImportList = Just (Exactly, lies) })) }\\n where\\n doc = text \\"Compute minimal imports for\\" <+> ppr decl\\n\\n to_ie :: GlobalRdrEnv -> ModIface -> AvailInfo -> RnM [IE GhcRn]\\n -- The main trick here is that if we\'re importing all the constructors\\n -- we want to say \\"T(..)\\", but if we\'re importing only a subset we want\\n -- to say \\"T(A,B,C)\\". So we have to find out what the module exports.\\n to_ie rdr_env _ (Avail c) -- Note [Overloaded field import]\\n = do { let\\n gre = expectJust $ lookupGRE_Name rdr_env c\\n ; return $ [IEVar Nothing (to_ie_post_rn $ noLocA $ greName gre) Nothing] }\\n to_ie _ _ avail@(AvailTC n [_]) -- Exporting the main decl and nothing else\\n | availExportsDecl avail\\n = return [IEThingAbs Nothing (to_ie_post_rn $ noLocA n) Nothing]\\n to_ie rdr_env iface (AvailTC n cs) =\\n case [ xs | avail@(AvailTC x xs) <- mi_exports iface\\n , x == n\\n , availExportsDecl avail -- Note [Partial export]\\n ] of\\n [xs]\\n | all_used xs\\n -> return [IEThingAll (IEThingAllExt Nothing noAnn noAnn noAnn)\\n (NoNamespaceSpecifier noExtField)\\n (to_ie_post_rn $ noLocA n)\\n Nothing]\\n | otherwise\\n -> do { let ns_gres = map (expectJust . lookupGRE_Name rdr_env) cs\\n ns = map greName ns_gres\\n ; return [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n -- Note [Overloaded field import]\\n _other\\n -> do { let infos = map (expectJust . lookupGRE_Name rdr_env) cs\\n (ns_gres,fs_gres) = classifyGREs infos\\n ns = map greName (ns_gres ++ fs_gres)\\n fs = map fieldGREInfo fs_gres\\n ; return $\\n if all_non_overloaded fs\\n then map (\\\\nm -> IEVar Nothing (to_ie_post_rn_var $ noLocA nm) Nothing) ns\\n else [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n where\\n\\n all_used avail_cs = all (`elem` cs) avail_cs\\n\\n all_non_overloaded = all (not . flIsOverloaded . recFieldLabel)\\n\\n combine :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\n combine = map merge . NE.groupAllWith getKey\\n\\n getKey :: LImportDecl GhcRn -> (Bool, Maybe ModuleName, ModuleName)\\n getKey decl =\\n ( isImportDeclQualified . ideclQualified $ idecl -- is this qualified? (important that this be first)\\n , unLoc <$> ideclAs idecl -- what is the qualifier (inside Maybe monad)\\n , unLoc . ideclName $ idecl -- Module Name\\n )\\n where\\n idecl :: ImportDecl GhcRn\\n idecl = unLoc decl\\n\\n merge :: NonEmpty (LImportDecl GhcRn) -> LImportDecl GhcRn\\n merge decls@((L l decl) :| _) = L l (decl { ideclImportList = Just (Exactly, lies) })\\n where lies = concatMap snd $ mapMaybe (ideclImportList . unLoc) $ NE.toList decls\\n\\nclassifyGREs :: [GlobalRdrElt] -> ([GlobalRdrElt], [FieldGlobalRdrElt])\\nclassifyGREs = partition (not . isRecFldGRE)\\n\\nprintMinimalImports :: HscSource -> [ImportDeclUsage] -> RnM ()\\n-- See Note [Printing minimal imports]\\nprintMinimalImports hsc_src imports_w_usage\\n = do { imports\' <- excludeGenerated <$> getMinimalImports imports_w_usage\\n ; this_mod <- getModule\\n ; dflags <- getDynFlags\\n ; liftIO $ withFile (mkFilename dflags this_mod) WriteMode $ \\\\h ->\\n printForUser dflags h neverQualify AllTheWay (vcat (map ppr imports\'))\\n -- The neverQualify is important. We are printing Names\\n -- but they are in the context of an \'import\' decl, and\\n -- we never qualify things inside there\\n -- E.g. import Blag( f, b )\\n -- not import Blag( Blag.f, Blag.g )!\\n }\\n where\\n mkFilename dflags this_mod\\n | Just d <- dumpDir dflags = d basefn\\n | otherwise = basefn\\n where\\n suffix = case hsc_src of\\n HsBootFile -> \\".imports-boot\\"\\n HsSrcFile -> \\".imports\\"\\n HsigFile -> \\".imports\\"\\n basefn = moduleNameString (moduleName this_mod) ++ suffix\\n\\n\\nto_ie_post_rn_var :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn_var (L l n)\\n | isDataOcc $ occName n = L l (IEPattern noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n\\n\\nto_ie_post_rn :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn (L l n)\\n | isTcOcc occ && isSymOcc occ = L l (IEType noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n where occ = occName n\\n\\n{- Note [Do not warn about Prelude hiding]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWe do not warn about\\n import Prelude hiding( x, y )\\nbecause even if nothing else from Prelude is used, it may be essential to hide\\nx,y to avoid name-shadowing warnings. Example (#9061)\\n import Prelude hiding( log )\\n f x = log where log = ()\\n\\nNote [Unused imports]\\n~~~~~~~~~~~~~~~~~~~~~\\nIn `warnUnusedImport`, if we see an import with an explicit list imports, thus\\n import M( a, b )\\nand neither `a` nor `b` is used, we report the entire import decl as unused. We\\ncheck this by looking at the names that it brings into scope scope; if there are\\nno ununused names, don\'t report.\\n\\n(UI1) We don\'t want to complain about `import M()`, because that is often used to bring\\n M\'s /instances/ into scope. That is neatly dealt with by the \\"no unused\\n names\\" (nor unused wildcard imports) criterion.\\n\\n(UI2) We don\'t report a decl as unused if it has an `as Rebindable` qualifier.\\n See (KN1) in Note [Overview of known entities] in GHC.Builtin\\n\\n\\nNote [Printing minimal imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nTo print the minimal imports we walk over all import decls (both user-supplied\\nand generated), trim their import lists, then filter out generated decls.\\n\\nNB that\\n\\n * We do *not* change the \'qualified\' or \'as\' parts!\\n\\n * We do not discard a decl altogether; we might need instances\\n from it. Instead we just trim to an empty import list\\n\\nNote [Partial export]\\n~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have\\n\\n module A( op ) where\\n class C a where\\n op :: a -> a\\n\\n module B where\\n import A\\n f = ..op...\\n\\nThen the minimal import for module B is\\n import A( op )\\nnot\\n import A( C( op ) )\\nwhich we would usually generate if C was exported from B. Hence\\nthe availExportsDecl test when deciding what to generate.\\n\\n\\nNote [Overloaded field import]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nOn the other hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n data T = MkT { foo :: Int }\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( T(foo) )\\nbecause when DuplicateRecordFields is enabled, field selectors are\\nnot in scope without their enclosing datatype.\\n\\nOn the third hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n pattern MkT { foo } = Just foo\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( foo )\\nbecause foo doesn\'t have a parent. This might actually be ambiguous if A\\nexports another field called foo, but there is no good answer to return and this\\nis a very obscure corner, so it seems to be the best we can do. See\\nDRFPatSynExport for a test of this.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Errors}\\n* *\\n************************************************************************\\n-}\\n\\nbadImportItemErr\\n :: ModIface -> ImpDeclSpec -> IE GhcPs\\n -> IsSubordinateError\\n -> [AvailInfo]\\n -> TcRn (NonEmpty ImportLookupReason)\\nbadImportItemErr iface decl_spec ie sub avails = do\\n exts <- importLookupExtensions\\n let import_lookup_bad :: BadImportKind -> ImportLookupReason\\n import_lookup_bad k = ImportLookupBad k iface decl_spec ie exts\\n dflags <- getDynFlags\\n hsc_env <- getTopEnv\\n let rdr_env = mkGlobalRdrEnv\\n $ gresFromAvails hsc_env (Just imp_spec) all_avails\\n pure $ fmap import_lookup_bad (importErrorKind dflags rdr_env)\\n where\\n importErrorKind :: DynFlags -> GlobalRdrEnv -> NonEmpty BadImportKind\\n importErrorKind dflags rdr_env\\n | any checkIfTyCon avails = case sub of\\n IsNotSubordinate -> NE.singleton BadImportAvailTyCon\\n IsSubordinateError { subordinate_err_parent = gre\\n , subordinate_err_unavailable = unavailable\\n , subordinate_err_nontype = nontype\\n , subordinate_err_nondata = nondata }\\n -> NE.fromList $ catMaybes $\\n [ fmap (BadImportNotExportedSubordinates gre) (NE.nonEmpty unavailable)\\n , fmap (BadImportNonTypeSubordinates gre) (NE.nonEmpty nontype)\\n , fmap (BadImportNonDataSubordinates gre) (NE.nonEmpty nondata) ]\\n | any checkIfVarName avails = NE.singleton BadImportAvailVar\\n | Just con <- find checkIfDataCon avails = NE.singleton (BadImportAvailDataCon (availOccName con))\\n | otherwise = NE.singleton (BadImportNotExported suggs)\\n where\\n suggs = similar_suggs ++ fieldSelectorSuggestions rdr_env rdr\\n what_look = case sub of\\n IsNotSubordinate -> WL_TyCon_or_TermVar\\n IsSubordinateError { subordinate_err_parent = gre } ->\\n case greInfo gre of\\n IAmTyCon ClassFlavour\\n -> WL_TyCon_or_TermVar\\n _ -> WL_Term\\n similar_names =\\n similarNameSuggestions (Unbound.LF what_look WL_Global)\\n dflags rdr_env emptyLocalRdrEnv rdr\\n similar_suggs =\\n case NE.nonEmpty $ mapMaybe imported_item $ similar_names of\\n Just similar -> [ SuggestSimilarNames rdr similar ]\\n Nothing -> [ ]\\n\\n -- Only keep imported items, and set the \\"HowInScope\\" to\\n -- \\"Nothing\\" to avoid printing \\"imported from...\\" in the suggestion\\n -- error message.\\n imported_item (SimilarRdrName rdr_name gre (Just (ImportedBy {})))\\n = Just (SimilarRdrName rdr_name gre Nothing)\\n imported_item _ = Nothing\\n\\n checkIfDataCon = checkIfAvailMatches isDataConName\\n checkIfTyCon = checkIfAvailMatches isTyConName\\n checkIfVarName =\\n \\\\case\\n AvailTC{} -> False\\n Avail n -> importedFS == occNameFS (occName n)\\n && (isVarOcc <||> isFieldOcc) (occName n)\\n checkIfAvailMatches namePred =\\n \\\\case\\n AvailTC _ ns ->\\n case find (\\\\n -> importedFS == occNameFS (occName n)) ns of\\n Just n -> namePred n\\n Nothing -> False\\n Avail{} -> False\\n availOccName = occName . availName\\n rdr = ieName ie\\n importedFS = occNameFS $ rdrNameOcc rdr\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n all_avails = mi_exports iface\\n\\nimportLookupExtensions :: TcRn ImportLookupExtensions\\nimportLookupExtensions = do\\n ile_pattern_synonyms <- xoptM LangExt.PatternSynonyms\\n ile_explicit_namespaces <- xoptM LangExt.ExplicitNamespaces\\n return ImportLookupExtensions{ile_pattern_synonyms, ile_explicit_namespaces}\\n\\naddDupDeclErr :: NonEmpty GlobalRdrElt -> TcRn ()\\naddDupDeclErr gres@(gre :| _)\\n -- Report the error at the later location\\n = addErrAt (getSrcSpan (NE.last sorted_names)) $ (TcRnDuplicateDecls (greOccName gre) sorted_names)\\n where\\n sorted_names =\\n NE.sortBy (SrcLoc.leftmost_smallest `on` nameSrcSpan)\\n (fmap greName gres)\\n\\n-- This data decl will parse OK\\n-- data T = a Int\\n-- treating \\"a\\" as the constructor.\\n-- It is really hard to make the parser spot this malformation.\\n-- So the renamer has to check that the constructor is legal\\n--\\n-- We can get an operator as the constructor, even in the prefix form:\\n-- data T = :% Int Int\\n-- from interface files, which always print in prefix form\\n--\\n-- We also allow type constructor names, which are defined by \\"type data\\"\\n-- declarations. See Note [Type data declarations] in GHC.Rename.Module.\\n\\ncheckConName :: RdrName -> TcRn ()\\ncheckConName name\\n = checkErr (isRdrDataCon name || isRdrTc name) (TcRnIllegalDataCon name)\\n", "filetypes": ["haskell"]}}}' 2026-10-16 14:48:31,631 - DEBUG - POST b'http://127.0.0.1:37093/receive_messages' {'content-type': 'application/json', 'x-ycm-hmac': b'Rga7Yd4l4fgfufwYw+0sxzurvznImlBO0MPmgAlS4EY='} b'{"filepath": "/home/enrico/ghc/compiler/GHC/Rename/Names.hs", "line_num": 1, "column_num": 1, "working_dir": "/home/enrico/ghc", "file_data": {"/home/enrico/ghc/compiler/GHC/Rename/Names.hs": {"contents": "{-\\n(c) The GRASP/AQUA Project, Glasgow University, 1992-1998\\n\\nExtracting imported and top-level names in scope\\n-}\\n\\n{-# LANGUAGE NondecreasingIndentation #-}\\n{-# LANGUAGE TypeFamilies #-}\\n\\nmodule GHC.Rename.Names (\\n rnImports, getLocalNonValBinders, newRecordFieldLabel,\\n importsFromIface,\\n ImportUserSpec(..),\\n extendGlobalRdrEnvRn,\\n gresFromAvails,\\n calculateAvails,\\n reportUnusedNames,\\n checkConName,\\n mkChildEnv,\\n findChildren,\\n mkBadExportSubordinate,\\n findImportUsage,\\n getMinimalImports,\\n printMinimalImports,\\n renamePkgQual, renameRawPkgQual,\\n classifyGREs,\\n ImportDeclUsage,\\n rnNamespaceSpecifier\\n ) where\\n\\nimport GHC.Prelude hiding ( head, init, last, tail )\\n\\nimport GHC.Driver.Env\\nimport GHC.Driver.Session\\nimport GHC.Driver.Ppr\\n\\nimport GHC.Rename.Env\\nimport GHC.Rename.Fixity\\nimport GHC.Rename.Utils ( warnUnusedTopBinds )\\nimport GHC.Rename.Unbound\\nimport qualified GHC.Rename.Unbound as Unbound\\n\\nimport GHC.Tc.Errors.Types\\nimport GHC.Tc.Utils.Env\\nimport GHC.Tc.Utils.Monad\\nimport GHC.Tc.Types.LclEnv\\nimport GHC.Tc.Zonk.TcType ( tcInitTidyEnv )\\n\\nimport GHC.Hs\\nimport GHC.Iface.Load ( loadSrcInterface, loadSrcInterface_maybe )\\nimport GHC.Iface.Errors.Types\\n ( IfaceMessage(..), MissingInterfaceError, InterfaceLookingFor(..)\\n , LoadEssentialsReason(..) )\\nimport GHC.Iface.Syntax ( fromIfaceWarnings )\\nimport GHC.Builtin.Modules( pRELUDE_NAME, rEBINDABLE_MOD_NAME )\\nimport GHC.Parser.PostProcess ( setRdrNameSpace )\\nimport GHC.Core.TyCo.Tidy\\nimport GHC.Core.PatSyn\\nimport GHC.Core.TyCon ( TyCon, tyConName )\\nimport qualified GHC.LanguageExtensions as LangExt\\n\\nimport GHC.Utils.Outputable as Outputable\\nimport GHC.Utils.Misc as Utils\\nimport GHC.Utils.Panic\\n\\nimport GHC.Types.Fixity.Env\\nimport GHC.Types.SafeHaskell\\nimport GHC.Types.Name\\nimport GHC.Types.Name.Env\\nimport GHC.Types.Name.Set\\nimport GHC.Types.Name.Reader\\nimport GHC.Types.Avail\\nimport GHC.Types.FieldLabel\\nimport GHC.Types.Hint\\nimport GHC.Types.SourceFile\\nimport GHC.Types.SrcLoc as SrcLoc\\nimport GHC.Types.Basic (TyConFlavour (..), convImportLevel, VisArity)\\nimport GHC.Types.UnresolvedImport\\nimport GHC.Types.Id\\nimport GHC.Types.PkgQual\\nimport GHC.Types.GREInfo (ConInfo(..), ConFieldInfo (..), ConLikeInfo (ConIsData))\\n\\nimport GHC.Unit\\nimport GHC.Unit.Module.Warnings\\nimport GHC.Unit.Module.ModIface\\nimport GHC.Unit.Module.Imported\\nimport GHC.Unit.Module.Deps\\nimport GHC.Unit.Env\\n\\nimport GHC.Data.Bag\\nimport GHC.Data.FastString\\nimport GHC.Data.FastString.Env\\nimport GHC.Data.Maybe\\nimport GHC.Data.List.SetOps ( removeDups )\\n\\nimport Control.Arrow ( second )\\nimport Control.Monad\\nimport Data.Foldable ( for_ )\\nimport Data.IntMap ( IntMap )\\nimport qualified Data.IntMap as IntMap\\nimport Data.Map ( Map )\\nimport qualified Data.Map as Map\\nimport Data.Ord ( comparing )\\nimport Data.Semigroup ( Any(..) )\\nimport qualified Data.Semigroup as S\\nimport Data.List ( partition, find, sortBy )\\nimport Data.List.NonEmpty (NonEmpty(..))\\nimport qualified Data.List.NonEmpty as NE\\nimport Data.Function ( on )\\nimport qualified Data.Set as S\\nimport System.FilePath (())\\nimport System.IO\\n\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{rnImports}\\n* *\\n************************************************************************\\n\\nNote [Tracking Trust Transitively]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen we import a package as well as checking that the direct imports are safe\\naccording to the rules outlined in the Note [Safe Haskell Trust Check] in GHC.Driver.Main\\nwe must also check that these rules hold transitively for all dependent modules\\nand packages. Doing this without caching any trust information would be very\\nslow as we would need to touch all packages and interface files a module depends\\non. To avoid this we make use of the property that if a modules Safe Haskell\\nmode changes, this triggers a recompilation from that module in the dependency\\ngraph. So we can just worry mostly about direct imports.\\n\\nThere is one trust property that can change for a package though without\\nrecompilation being triggered: package trust. So we must check that all\\npackages a module transitively depends on to be trusted are still trusted when\\nwe are compiling this module (as due to recompilation avoidance some modules\\nbelow may not be considered trusted any more without recompilation being\\ntriggered).\\n\\nWe handle this by augmenting the existing transitive list of packages a module M\\ndepends on with a bool for each package that says if it must be trusted when the\\nmodule M is being checked for trust. This list of trust required packages for a\\nsingle import is gathered in the rnImportDecl function and stored in an\\nImportAvails data structure. The union of these trust required packages for all\\nimports is done by the rnImports function using the combine function which calls\\nthe plusImportAvails function that is a union operation for the ImportAvails\\ntype. This gives us in an ImportAvails structure all packages required to be\\ntrusted for the module we are currently compiling. Checking that these packages\\nare still trusted (and that direct imports are trusted) is done in\\nGHC.Driver.Main.checkSafeImports.\\n\\nSee the note below, [Trust Own Package] for a corner case in this method and\\nhow its handled.\\n\\n\\nNote [Trust Own Package]\\n~~~~~~~~~~~~~~~~~~~~~~~~\\nThere is a corner case of package trust checking that the usual transitive check\\ndoesn\'t cover. (For how the usual check operates see the Note [Tracking Trust\\nTransitively] below). The case is when you import a -XSafe module M and M\\nimports a -XTrustworthy module N. If N resides in a different package than M,\\nthen the usual check works as M will record a package dependency on N\'s package\\nand mark it as required to be trusted. If N resides in the same package as M\\nthough, then importing M should require its own package be trusted due to N\\n(since M is -XSafe so doesn\'t create this requirement by itself). The usual\\ncheck fails as a module doesn\'t record a package dependency of its own package.\\nSo instead we now have a bool field in a modules interface file that simply\\nstates if the module requires its own package to be trusted. This field avoids\\nus having to load all interface files that the module depends on to see if one\\nis trustworthy.\\n\\n\\nNote [Trust Transitive Property]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSo there is an interesting design question in regards to transitive trust\\nchecking. Say I have a module B compiled with -XSafe. B is dependent on a bunch\\nof modules and packages, some packages it requires to be trusted as its using\\n-XTrustworthy modules from them. Now if I have a module A that doesn\'t use safe\\nhaskell at all and simply imports B, should A inherit all the trust\\nrequirements from B? Should A now also require that a package p is trusted since\\nB required it?\\n\\nWe currently say no but saying yes also makes sense. The difference is, if a\\nmodule M that doesn\'t use Safe Haskell imports a module N that does, should all\\nthe trusted package requirements be dropped since M didn\'t declare that it cares\\nabout Safe Haskell (so -XSafe is more strongly associated with the module doing\\nthe importing) or should it be done still since the author of the module N that\\nuses Safe Haskell said they cared (so -XSafe is more strongly associated with\\nthe module that was compiled that used it).\\n\\nGoing with yes is a simpler semantics we think and harder for the user to stuff\\nup but it does mean that Safe Haskell will affect users who don\'t care about\\nSafe Haskell as they might grab a package from Cabal which uses safe haskell (say\\nnetwork) and that packages imports -XTrustworthy modules from another package\\n(say bytestring), so requires that package is trusted. The user may now get\\ncompilation errors in code that doesn\'t do anything with Safe Haskell simply\\nbecause they are using the network package. They will have to call \'ghc-pkg\\ntrust network\' to get everything working. Due to this invasive nature of going\\nwith yes we have gone with no for now.\\n-}\\n\\n-- | Process Import Decls. See \'rnImportDecl\' for a description of what\\n-- the return types represent.\\n-- Note: Do the non SOURCE ones first, so that we get a helpful warning\\n-- for SOURCE ones that are unnecessary\\nrnImports :: [(LImportDecl GhcPs, SDoc)]\\n -> RnM ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\nrnImports imports = do\\n tcg_env <- getGblEnv\\n -- NB: want an identity module here, because it\'s OK for a signature\\n -- module to import from its implementor\\n let this_mod = tcg_mod tcg_env\\n let (source, ordinary) = partition (is_source_import . fst) imports\\n is_source_import (d::LImportDecl GhcPs) = ideclSource (unLoc d) == IsBoot\\n stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary\\n stuff2 <- mapAndReportM (rnImportDecl this_mod) source\\n -- Safe Haskell: See Note [Tracking Trust Transitively]\\n let (decls, imp_user_spec, rdr_env, imp_avails) = combine (stuff1 ++ stuff2)\\n -- Update imp_boot_mods if imp_direct_mods mentions any of them\\n let merged_import_avail = clobberSourceImports imp_avails\\n return (decls, imp_user_spec, rdr_env, merged_import_avail)\\n\\n where\\n clobberSourceImports imp_avails =\\n imp_avails { imp_boot_mods = imp_boot_mods\' }\\n where\\n imp_boot_mods\' = mergeInstalledModuleEnv combJ id (const emptyInstalledModuleEnv)\\n (imp_boot_mods imp_avails)\\n (imp_direct_dep_mods imp_avails)\\n\\n combJ (GWIB _ IsBoot) (_, x) = Just x\\n combJ r _ = Just r\\n -- See Note [Combining ImportAvails]\\n combine :: [(LImportDecl GhcRn, ImportUserSpec, GlobalRdrEnv, ImportAvails)]\\n -> ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\n combine ss =\\n let (decls, imp_user_spec, rdr_env, imp_avails, finsts) = foldr\\n plus\\n ([], [], emptyGlobalRdrEnv, emptyImportAvails, emptyModuleSet)\\n ss\\n in (decls, imp_user_spec, rdr_env, imp_avails { imp_finsts = moduleSetElts finsts })\\n\\n plus (decl, us, gbl_env1, imp_avails1)\\n (decls, uss, gbl_env2, imp_avails2, finsts_set)\\n = ( decl:decls,\\n us:uss,\\n gbl_env1 `plusGlobalRdrEnv` gbl_env2,\\n imp_avails1\' `plusImportAvails` imp_avails2,\\n extendModuleSetList finsts_set new_finsts )\\n where\\n imp_avails1\' = imp_avails1 { imp_finsts = [] }\\n new_finsts = imp_finsts imp_avails1\\n\\n{-\\nNote [Combining ImportAvails]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nimp_finsts in ImportAvails is a list of family instance modules\\ntransitively depended on by an import. imp_finsts for a currently\\ncompiled module is a union of all the imp_finsts of imports.\\nComputing the union of two lists of size N is O(N^2) and if we\\ndo it to M imports we end up with O(M*N^2). That can get very\\nexpensive for bigger module hierarchies.\\n\\nUnion can be optimized to O(N log N) if we use a Set.\\nimp_finsts is converted back and forth between dep_finsts, so\\nchanging a type of imp_finsts means either paying for the conversions\\nor changing the type of dep_finsts as well.\\n\\nI\'ve measured that the conversions would cost 20% of allocations on my\\ntest case, so that can be ruled out.\\n\\nChanging the type of dep_finsts forces checkFamInsts to\\nget the module lists in non-deterministic order. If we wanted to restore\\nthe deterministic order, we\'d have to sort there, which is an additional\\ncost. As far as I can tell, using a non-deterministic order is fine there,\\nbut that\'s a brittle nonlocal property which I\'d like to avoid.\\n\\nAdditionally, dep_finsts is read from an interface file, so its \\"natural\\"\\ntype is a list. Which makes it a natural type for imp_finsts.\\n\\nSince rnImports.combine is really the only place that would benefit from\\nit being a Set, it makes sense to optimize the hot loop in rnImports.combine\\nwithout changing the representation.\\n\\nSo here\'s what we do: instead of naively merging ImportAvails with\\nplusImportAvails in a loop, we make plusImportAvails merge empty imp_finsts\\nand compute the union on the side using Sets. When we\'re done, we can\\nconvert it back to a list. One nice side effect of this approach is that\\nif there\'s a lot of overlap in the imp_finsts of imports, the\\nSet doesn\'t really need to grow and we don\'t need to allocate.\\n\\nRunning generateModules from #14693 with DEPTH=16, WIDTH=30 finishes in\\n23s before, and 11s after.\\n-}\\n\\n-- | Given a located import declaration @decl@ from @this_mod@,\\n-- calculate the following pieces of information:\\n--\\n-- 1. An updated \'LImportDecl\', where all unresolved \'RdrName\' in\\n-- the entity lists have been resolved into \'Name\'s,\\n--\\n-- 2. A \'GlobalRdrEnv\' representing the new identifiers that were\\n-- brought into scope (taking into account module qualification\\n-- and hiding),\\n--\\n-- 3. \'ImportAvails\' summarizing the identifiers that were imported\\n-- by this declaration, and\\n--\\n-- 4. A boolean \'AnyHpcUsage\' which is true if the imported module\\n-- used HPC.\\nrnImportDecl :: Module -> (LImportDecl GhcPs, SDoc)\\n -> RnM (LImportDecl GhcRn, ImportUserSpec , GlobalRdrEnv, ImportAvails)\\nrnImportDecl this_mod\\n (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name\\n , ideclPkgQual = raw_pkg_qual\\n , ideclSource = want_boot\\n , ideclSafe = mod_safe\\n , ideclLevelSpec = import_level\\n , ideclQualified = qual_style\\n , ideclExt = XImportDeclPass { ideclOrigin = origin }\\n , ideclAs = as_mod, ideclImportList = imp_details }), import_reason)\\n = setSrcSpanA loc $ do\\n\\n case raw_pkg_qual of\\n NoRawPkgQual -> pure ()\\n RawPkgQual {} -> do\\n pkg_imports <- xoptM LangExt.PackageImports\\n when (not pkg_imports) $ addErr TcRnPackageImportsDisabled\\n\\n let qual_only = isImportDeclQualified qual_style\\n generated = isGeneratedImport origin\\n\\n lookup_scope = importDeclLookupScope origin\\n\\n -- If there\'s an error in loadInterface, (e.g. interface\\n -- file not found) we get lots of spurious errors from \'filterImports\'\\n let imp_mod_name = unLoc loc_imp_mod_name\\n doc = ppr imp_mod_name <+> import_reason\\n\\n hsc_env <- getTopEnv\\n unit_env <- hsc_unit_env <$> getTopEnv\\n let pkg_qual = renameRawPkgQual unit_env imp_mod_name raw_pkg_qual\\n\\n -- Check for self-import, which confuses the typechecker (#9032)\\n -- ghc --make rejects self-import cycles already, but batch-mode may not\\n -- at least not until GHC.IfaceToCore.tcHiBootIface, which is too late to avoid\\n -- typechecker crashes. (Indirect self imports are not caught until\\n -- GHC.IfaceToCore, see #10337 tracking how to make this error better.)\\n --\\n -- Originally, we also allowed \'import {-# SOURCE #-} M\', but this\\n -- caused bug #10182: in one-shot mode, we should never load an hs-boot\\n -- file for the module we are compiling into the EPS. In principle,\\n -- it should be possible to support this mode of use, but we would have to\\n -- extend Provenance to support a local definition in a qualified location.\\n -- For now, we don\'t support it, but see #10336\\n when (imp_mod_name == moduleName this_mod &&\\n (case pkg_qual of -- If we have import \\"\\" M, then we should\\n -- check that \\"\\" is \\"this\\" (which is magic)\\n -- or the name of this_mod\'s package. Yurgh!\\n -- c.f. GHC.findModule, and #9997\\n NoPkgQual -> True\\n ThisPkg uid -> uid == homeUnitId_ (hsc_dflags hsc_env)\\n OtherPkg _ -> False))\\n (addErr (TcRnSelfImport imp_mod_name))\\n\\n -- Check for a missing import list (Opt_WarnMissingImportList also\\n -- checks for T(..) items but that is done in checkDodgyImport below)\\n case imp_details of\\n Just (Exactly, _) -> return () -- Explicit import list\\n _ | generated -> return () -- Do not bleat for generated imports\\n | qual_only -> return ()\\n | otherwise -> addDiagnostic (TcRnNoExplicitImportList imp_mod_name)\\n\\n\\n mb_iface <- loadSrcInterface_maybe doc lookup_scope imp_mod_name want_boot pkg_qual\\n iface <- case mb_iface of\\n Succeeded iface -> return iface\\n Failed err -> failWithTc $\\n importDeclLoadFailure origin imp_mod_name want_boot err\\n\\n -- Compiler sanity check: if the import didn\'t say\\n -- {-# SOURCE #-} we should not get a hi-boot file\\n warnPprTrace ((want_boot == NotBoot) && (mi_boot iface == IsBoot)) \\"rnImportDecl\\" (ppr imp_mod_name) $ do\\n\\n -- Issue a user warning for a redundant {- SOURCE -} import\\n -- NB that we arrange to read all the ordinary imports before\\n -- any of the {- SOURCE -} imports.\\n --\\n -- in --make and GHCi, the compilation manager checks for this,\\n -- and indeed we shouldn\'t do it here because the existence of\\n -- the non-boot module depends on the compilation order, which\\n -- is not deterministic. The hs-boot test can show this up.\\n dflags <- getDynFlags\\n warnIf ((want_boot == IsBoot) && (mi_boot iface == NotBoot) && isOneShot (ghcMode dflags))\\n (TcRnRedundantSourceImport imp_mod_name)\\n when (mod_safe && not (safeImportsOn dflags)) $\\n addErr (TcRnSafeImportsDisabled imp_mod_name)\\n\\n let imp_mod = mi_module iface\\n qual_mod_name = fmap unLoc as_mod `orElse` imp_mod_name\\n imp_spec = ImpDeclSpec { is_mod = imp_mod, is_qual = qual_only,\\n is_dloc = locA loc, is_as = qual_mod_name,\\n is_pkg_qual = pkg_qual, is_isboot = want_boot,\\n is_level = convImportLevel import_level }\\n\\n let filter_imports = do\\n -- filter the imports according to the import declaration\\n (new_imp_details, imp_user_list, gbl_env)\\n <- filterImports hsc_env iface imp_spec imp_details\\n -- for certain error messages, we\\u2019d like to know what could be\\n -- imported here, if everything were imported\\n potential_gres <- (\\\\(_,_,x) -> x) <$> filterImports hsc_env iface imp_spec Nothing\\n return (new_imp_details, imp_user_list, gbl_env, potential_gres)\\n\\n (new_imp_details, imp_user_list, gbl_env, potential_gres) <-\\n case origin of\\n ImplicitEssentialsImport ->\\n -- The implicit GHC.Essentials import does not bring anything into scope.\\n -- See Note [Finding GHC.Essentials] in GHC.Builtin.\\n return (Nothing, ImpUserDependOnly, emptyGlobalRdrEnv, emptyGlobalRdrEnv)\\n UserWrittenImport -> filter_imports\\n ImplicitPreludeImport -> filter_imports\\n PluginImport -> filter_imports\\n\\n let is_hiding | Just (EverythingBut,_) <- imp_details = True\\n | otherwise = False\\n\\n -- should the import be safe?\\n mod_safe\' = mod_safe\\n || (not generated && safeDirectImpsReq dflags)\\n || (generated && safeImplicitImpsReq dflags)\\n\\n hsc_env <- getTopEnv\\n let home_unit = hsc_home_unit hsc_env\\n other_home_units = hsc_all_home_unit_ids hsc_env\\n\\n imported_by\\n | isDependOnlyImport imp_user_list\\n = ImportedBySystem\\n | otherwise\\n = ImportedByUser $ ImportedModsVal\\n { imv_name = is_as imp_spec\\n , imv_span = locA loc\\n , imv_is_safe = mod_safe\'\\n , imv_is_hiding = is_hiding\\n , imv_all_exports = potential_gres\\n , imv_qualified = qual_only\\n , imv_is_level = convImportLevel import_level\\n }\\n imports = calculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by\\n\\n -- Complain if we import a deprecated module\\n case fromIfaceWarnings (mi_warns iface) of\\n WarnAll txt -> addDiagnostic (TcRnDeprecatedModule imp_mod_name txt)\\n _ -> return ()\\n\\n let new_imp_decl = ImportDecl\\n { ideclExt = ideclExt decl\\n , ideclName = ideclName decl\\n , ideclPkgQual = pkg_qual\\n , ideclSource = ideclSource decl\\n , ideclSafe = mod_safe\'\\n , ideclQualified = ideclQualified decl\\n , ideclAs = ideclAs decl\\n , ideclImportList = new_imp_details\\n , ideclLevelSpec = ideclLevelSpec decl\\n }\\n\\n return (L loc new_imp_decl, ImpUserSpec imp_spec imp_user_list, gbl_env, imports)\\n\\n-- | The error message to emit when we failed to load an interface.\\nimportDeclLoadFailure :: ImportDeclOrigin -> ModuleName -> IsBootInterface\\n -> MissingInterfaceError -> TcRnMessage\\nimportDeclLoadFailure ImplicitEssentialsImport _ _ err\\n = TcRnInterfaceError $ CantFindEssentials err LookingForEssentialsModule\\nimportDeclLoadFailure _ mod_name want_boot err\\n = TcRnInterfaceError $ Can\'tFindInterface err $ LookingForModule mod_name want_boot\\n\\n-- | Rename raw package imports\\nrenameRawPkgQual :: UnitEnv -> ModuleName -> RawPkgQual -> PkgQual\\nrenameRawPkgQual unit_env mn = \\\\case\\n NoRawPkgQual -> NoPkgQual\\n RawPkgQual _ fs -> renamePkgQual unit_env mn $ Just fs\\n\\n-- | Rename raw package imports\\nrenamePkgQual :: UnitEnv -> ModuleName -> Maybe FastString -> PkgQual\\nrenamePkgQual unit_env mn mb_pkg = case mb_pkg of\\n Nothing -> NoPkgQual\\n Just pkg_fs\\n | Just uid <- homeUnitId <$> ue_homeUnit unit_env\\n , pkg_fs == fsLit \\"this\\"\\n -> ThisPkg uid\\n\\n | Just (uid, _) <- find (fromMaybe False . fmap (== pkg_fs) . snd) home_names\\n -> ThisPkg uid\\n\\n | Just uid <- resolvePackageImport unit_state mn (PackageName pkg_fs)\\n -> OtherPkg uid\\n\\n | otherwise\\n -> OtherPkg (UnitId pkg_fs)\\n -- not really correct as pkg_fs is unlikely to be a valid unit-id but\\n -- we will report the failure later...\\n where\\n home_names =\\n [ (uid, mkFastString <$> thisPackageName (homeUnitEnv_dflags (ue_findHomeUnitEnv uid unit_env)))\\n | uid <- S.toList hpt_deps\\n ]\\n\\n unit_state = ue_homeUnitState unit_env\\n\\n hpt_deps :: S.Set UnitId\\n hpt_deps = homeUnitDepends unit_state\\n\\n\\n-- | Calculate the \'ImportAvails\' induced by an import of a particular\\n-- interface, but without \'imp_mods\'.\\ncalculateAvails :: HomeUnit\\n -> S.Set UnitId\\n -> ModIface\\n -> IsSafeImport\\n -> IsBootInterface\\n -> ImportedBy\\n -> ImportAvails\\ncalculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by =\\n let imp_mod = mi_module iface\\n imp_sem_mod= mi_semantic_module iface\\n orph_iface = mi_orphan iface\\n has_finsts = mi_finsts iface\\n deps = mi_deps iface\\n trust = getSafeMode $ mi_trust iface\\n trust_pkg = mi_trust_pkg iface\\n is_sig = mi_hsc_src iface == HsigFile\\n\\n -- If the module exports anything defined in this module, just\\n -- ignore it. Reason: otherwise it looks as if there are two\\n -- local definition sites for the thing, and an error gets\\n -- reported. Easiest thing is just to filter them out up\\n -- front. This situation only arises if a module imports\\n -- itself, or another module that imported it. (Necessarily,\\n -- this involves a loop.)\\n --\\n -- We do this *after* filterImports, so that if you say\\n -- module A where\\n -- import B( AType )\\n -- type AType = ...\\n --\\n -- module B( AType ) where\\n -- import {-# SOURCE #-} A( AType )\\n --\\n -- then you won\'t get a \'B does not export AType\' message.\\n\\n\\n -- Compute new transitive dependencies\\n --\\n -- \'dep_orphs\' and \'dep_finsts\' do NOT include the imported module\\n -- itself, but we DO need to include this module in \'imp_orphs\' and\\n -- \'imp_finsts\' if it defines an orphan or instance family; thus the\\n -- orph_iface/has_iface tests.\\n\\n deporphs = dep_orphs deps\\n depfinsts = dep_finsts deps\\n\\n orphans | orph_iface = assertPpr (not (imp_sem_mod `elem` deporphs)) (ppr imp_sem_mod <+> ppr deporphs) $\\n imp_sem_mod : deporphs\\n | otherwise = deporphs\\n\\n finsts | has_finsts = assertPpr (not (imp_sem_mod `elem` depfinsts)) (ppr imp_sem_mod <+> ppr depfinsts) $\\n imp_sem_mod : depfinsts\\n | otherwise = depfinsts\\n\\n -- Trusted packages are a lot like orphans.\\n trusted_pkgs | mod_safe\' = dep_trusted_pkgs deps\\n | otherwise = S.empty\\n\\n\\n pkg = moduleUnit (mi_module iface)\\n ipkg = toUnitId pkg\\n\\n -- Does this import mean we now require our own pkg\\n -- to be trusted? See Note [Trust Own Package]\\n ptrust = trust == Sf_Trustworthy || trust_pkg\\n pkg_trust_req\\n | isHomeUnit home_unit pkg = ptrust\\n | otherwise = False\\n\\n dependent_pkgs = if toUnitId pkg `S.member` other_home_units\\n then S.empty\\n else S.singleton (lvl, ipkg)\\n\\n lvl = case imported_by of\\n ImportedByUser imv -> imv_is_level imv\\n ImportedBySystem -> NormalLevel\\n\\n\\n direct_mods = if toUnitId pkg `S.member` other_home_units\\n then mkPlusModDeps (moduleUnitId imp_mod) lvl (GWIB (moduleName imp_mod) want_boot)\\n else emptyInstalledModuleEnv\\n\\n dep_boot_mods_map = mkModDeps (dep_boot_mods deps)\\n\\n\\n boot_mods\\n -- If we are looking for a boot module, it must be HPT\\n | IsBoot <- want_boot = extendInstalledModuleEnv dep_boot_mods_map (toUnitId <$> imp_mod) (GWIB (moduleName imp_mod) IsBoot)\\n -- Now we are importing A properly, so don\'t go looking for\\n -- A.hs-boot\\n | isHomeUnit home_unit pkg = dep_boot_mods_map\\n -- There\'s no boot files to find in external imports\\n | otherwise = emptyInstalledModuleEnv\\n\\n sig_mods =\\n if is_sig\\n then moduleName imp_mod : dep_sig_mods deps\\n else dep_sig_mods deps\\n\\n\\n in ImportAvails {\\n imp_mods = Map.singleton (mi_module iface) [imported_by],\\n imp_orphs = orphans,\\n imp_finsts = finsts,\\n imp_sig_mods = sig_mods,\\n imp_direct_dep_mods = direct_mods,\\n imp_dep_direct_pkgs = dependent_pkgs,\\n imp_boot_mods = boot_mods,\\n\\n -- Add in the imported modules trusted package\\n -- requirements. ONLY do this though if we import the\\n -- module as a safe import.\\n -- See Note [Tracking Trust Transitively]\\n -- and Note [Trust Transitive Property]\\n imp_trust_pkgs = trusted_pkgs,\\n -- Do we require our own pkg to be trusted?\\n -- See Note [Trust Own Package]\\n imp_trust_own_pkg = pkg_trust_req\\n }\\n\\nmkPlusModDeps :: UnitId -> ImportLevel -> ModuleNameWithIsBoot\\n -> InstalledModuleEnv (S.Set ImportLevel, ModuleNameWithIsBoot)\\nmkPlusModDeps uid st elt = extendInstalledModuleEnv emptyInstalledModuleEnv (mkModule uid (gwib_mod elt)) (S.singleton st, elt)\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{importsFromLocalDecls}\\n* *\\n************************************************************************\\n\\nFrom the top-level declarations of this module produce\\n * the lexical environment\\n * the ImportAvails\\ncreated by its bindings.\\n\\nNote [Top-level Names in Template Haskell decl quotes]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSee also: Note [Interactively-bound Ids in GHCi] in GHC.Driver.Env\\n Note [Looking up Exact RdrNames] in GHC.Rename.Env\\n\\nConsider a Template Haskell declaration quotation like this:\\n module M where\\n f x = h [d| f = 3 |]\\nWhen renaming the declarations inside [d| ...|], we treat the\\ntop level binders specially in two ways\\n\\n1. We give them an Internal Name, not (as usual) an External one.\\n This is done by GHC.Rename.Env.newTopSrcBinder.\\n\\n2. We make them *shadow* the outer bindings.\\n See Note [GlobalRdrEnv shadowing]\\n\\n3. We find out whether we are inside a [d| ... |] by testing the TH\\n level. This is a slight hack, because the level field was really\\n meant for the type checker, and here we are not interested in the\\n fields of Brack, hence the error thunks in thRnBrack.\\n-}\\n\\nextendGlobalRdrEnvRn :: [GlobalRdrElt]\\n -> MiniFixityEnv\\n -> RnM (TcGblEnv, TcLclEnv)\\n-- Updates both the GlobalRdrEnv and the FixityEnv\\n-- We return a new TcLclEnv only because we might have to\\n-- delete some bindings from it;\\n-- see Note [Top-level Names in Template Haskell decl quotes]\\n\\nextendGlobalRdrEnvRn new_gres new_fixities\\n = checkNoErrs $ -- See Note [Fail fast on duplicate definitions]\\n do { (gbl_env, lcl_env) <- getEnvs\\n ; level <- getThLevel\\n ; isGHCi <- getIsGHCi\\n ; let rdr_env = tcg_rdr_env gbl_env\\n fix_env = tcg_fix_env gbl_env\\n th_bndrs = getLclEnvThBndrs lcl_env\\n th_lvl = thLevelIndex level\\n\\n -- Delete new_occs from global and local envs\\n -- If we are in a TemplateHaskell decl bracket,\\n -- we are going to shadow them\\n -- See Note [GlobalRdrEnv shadowing]\\n inBracket = isBrackLevel level\\n\\n lcl_env_TH = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_rdr = minusLocalRdrEnv (tcl_rdr lcl_env) new_gres_env }) lcl_env\\n -- See Note [GlobalRdrEnv shadowing]\\n\\n lcl_env2 | inBracket = lcl_env_TH\\n | otherwise = lcl_env\\n\\n -- Deal with shadowing: see Note [GlobalRdrEnv shadowing]\\n want_shadowing = isGHCi || inBracket\\n rdr_env1 | want_shadowing = shadowNames False rdr_env new_gres_env\\n | otherwise = rdr_env\\n\\n lcl_env3 = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_th_bndrs = extendNameEnvList th_bndrs\\n [ ( n, (TopLevel, th_lvl) )\\n | n <- new_names ] }) lcl_env2\\n\\n ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres\\n\\n ; let fix_env\' = foldl\' extend_fix_env fix_env new_gres\\n gbl_env\' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env\' }\\n\\n ; traceRn \\"extendGlobalRdrEnvRn 2\\" (pprGlobalRdrEnv True rdr_env2)\\n ; return (gbl_env\', lcl_env3) }\\n where\\n new_names = map greName new_gres\\n new_gres_env = mkGlobalRdrEnv new_gres\\n\\n -- If there is a fixity decl for the gre, add it to the fixity env\\n extend_fix_env fix_env gre\\n | Just (L _ fi) <- lookupMiniFixityEnv new_fixities name\\n = extendNameEnv fix_env name (FixItem occ fi)\\n | otherwise\\n = fix_env\\n where\\n name = greName gre\\n occ = greOccName gre\\n\\n add_gre :: GlobalRdrEnv -> GlobalRdrElt -> RnM GlobalRdrEnv\\n -- Extend the GlobalRdrEnv with a LocalDef GRE\\n -- If there is already a LocalDef GRE with the same OccName,\\n -- report an error and discard the new GRE\\n -- This establishes INVARIANT 1 of GlobalRdrEnvs\\n add_gre env gre\\n | not (null dups) -- Same OccName defined twice\\n = do { addDupDeclErr (gre :| dups); return env }\\n\\n | otherwise\\n = return (extendGlobalRdrEnv env gre)\\n where\\n -- See Note [Reporting duplicate local declarations]\\n dups = filter isBadDupGRE\\n $ lookupGRE env (LookupOccName (greOccName gre) (RelevantGREsFOS WantBoth))\\n isBadDupGRE old_gre = isLocalGRE old_gre && greClashesWith gre old_gre\\n\\n{- Note [Fail fast on duplicate definitions]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIf there are duplicate bindings for the same thing, we want to fail\\nfast. Having two bindings for the same thing can cause follow-on errors.\\nExample (test T9975a):\\n data Test = Test { x :: Int }\\n pattern Test wat = Test { x = wat }\\nThis defines \'Test\' twice. The second defn has no field-names; and then\\nwe get an error from Test { x=wat }, saying \\"Test has no field \'x\'\\".\\n\\nEasiest thing is to bale out fast on duplicate definitions, which\\nwe do via `checkNoErrs` on `extendGlobalRdrEnvRn`.\\n\\nNote [Reporting duplicate local declarations]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn general, a single module may not define the same OccName multiple times. This\\nis checked in extendGlobalRdrEnvRn: when adding a new locally-defined GRE to the\\nGlobalRdrEnv we report an error if there are already duplicates in the\\nenvironment. This establishes INVARIANT 1 (see comments on GlobalRdrEnv in\\nGHC.Types.Name.Reader), which says that for a given OccName, all the\\nGlobalRdrElts to which it maps must have distinct \'greName\'s.\\n\\nFor example, the following will be rejected:\\n\\n f x = x\\n g x = x\\n f x = x -- Duplicate!\\n\\nUsers are allowed to introduce new GREs with the same OccName as an imported GRE,\\nas disambiguation is possible through the module system, e.g.:\\n\\n module M where\\n import N (f)\\n f x = x\\n g x = M.f x + N.f x\\n\\nIf both GREs are local, the general rule is that two GREs clash if they have\\nthe same OccName, i.e. they share a textual name and live in the same namespace.\\nHowever, there are additional clashes due to record fields:\\n\\n - a new variable clashes with previously defined record fields\\n which define field selectors,\\n\\n - a new record field shadows:\\n\\n - previously defined variables, if it defines a field selector,\\n - previously defined record fields, unless it is a duplicate record field.\\n\\nThis logic is implemented in the function \'GHC.Types.Name.Reader.greClashesWith\'.\\n\\nSee also Note [Skipping ambiguity errors at use sites of local declarations] in\\nGHC.Rename.Utils.\\n-}\\n\\n\\n{- *********************************************************************\\n* *\\n getLocalDeclBindersd@ returns the names for an HsDecl\\n It\'s used for source code.\\n\\n *** See Note [The Naming story] in GHC.Hs.Decls ****\\n* *\\n********************************************************************* -}\\n\\ngetLocalNonValBinders :: MiniFixityEnv -> HsGroup GhcPs\\n -> RnM ((TcGblEnv, TcLclEnv), NameSet)\\n-- Get all the top-level binders bound the group *except*\\n-- for value bindings, which are treated separately\\n-- Specifically we return AvailInfo for\\n-- * type decls (incl constructors and record selectors)\\n-- * class decls (including class ops)\\n-- * associated types\\n-- * foreign imports\\n-- * value signatures (in hs-boot files only)\\n\\ngetLocalNonValBinders fixity_env\\n (HsGroup { hs_valds = binds,\\n hs_tyclds = tycl_decls,\\n hs_fords = foreign_decls })\\n = do { -- Process all type/class decls *except* family instances\\n ; let inst_decls = tycl_decls >>= group_instds\\n ; dup_fields_ok <- xopt_DuplicateRecordFields <$> getDynFlags\\n ; has_sel <- xopt_FieldSelectors <$> getDynFlags\\n ; tc_gres\\n <- concatMapM\\n (new_tc dup_fields_ok has_sel)\\n (tyClGroupTyClDecls tycl_decls)\\n ; traceRn \\"getLocalNonValBinders 1\\" (ppr tc_gres)\\n ; envs <- extendGlobalRdrEnvRn tc_gres fixity_env\\n ; restoreEnvs envs $ do {\\n -- Bring these things into scope first\\n -- See Note [Looking up family names in family instances]\\n\\n -- Process all family instances\\n -- to bring new data constructors into scope\\n ; nti_gress <- mapM (new_assoc dup_fields_ok has_sel) inst_decls\\n\\n -- Finish off with value binders:\\n -- foreign decls and pattern synonyms for an ordinary module\\n -- type sigs in case of a hs-boot file only\\n ; is_boot <- tcIsHsBootOrSig\\n ; let val_bndrs\\n | is_boot = case binds of\\n ValBinds _ val_binds ->\\n -- In a hs-boot file, the value binders come from the\\n -- *signatures*, and there should be no foreign binders\\n [ L (l2l decl_loc) (unLoc n)\\n | L decl_loc (TypeSig _ _ ns _) <- (val_sigs val_binds), n <- ns]\\n _ -> panic \\"Non-ValBinds in hs-boot group\\"\\n | otherwise = for_hs_bndrs\\n ; val_gres <- mapM new_simple val_bndrs\\n\\n ; let avails = concat nti_gress ++ val_gres\\n new_bndrs = gresToNameSet avails `unionNameSet`\\n gresToNameSet tc_gres\\n ; traceRn \\"getLocalNonValBinders 2\\" (ppr avails)\\n ; envs <- extendGlobalRdrEnvRn avails fixity_env\\n ; return (envs, new_bndrs) } }\\n where\\n for_hs_bndrs :: [LocatedN RdrName]\\n for_hs_bndrs = hsForeignDeclsBinders foreign_decls\\n\\n -- the SrcSpan attached to the input should be the span of the\\n -- declaration, not just the name\\n new_simple :: LocatedN RdrName -> RnM GlobalRdrElt\\n new_simple rdr_name = do { nm <- newTopSrcBinder rdr_name\\n ; return (mkLocalVanillaGRE NoParent nm) }\\n\\n new_tc :: DuplicateRecordFields -> FieldSelectors -> LTyClDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_tc dup_fields_ok has_sel tc_decl -- NOT for type/data instances\\n = do { let TyDeclBinders (main_bndr, tc_flav) at_bndrs sig_bndrs\\n (LConsWithFields cons_with_flds flds) = hsLTyClDeclBinders tc_decl\\n ; tycon_name <- newTopSrcBinder $ la2la main_bndr\\n ; at_names <- mapM (newTopSrcBinder . la2la . fst) at_bndrs\\n ; sig_names <- mapM (newTopSrcBinder . la2la) sig_bndrs\\n ; con_names_with_flds <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst con_names_with_flds) flds\\n ; mapM_ (add_dup_fld_errs flds\') con_names_with_flds\\n ; let tc_gre = mkLocalTyConGRE (fmap (const tycon_name) tc_flav) tycon_name\\n fld_env = mk_fld_env con_names_with_flds flds\'\\n at_gres = zipWith (\\\\ (_, at_flav) at_nm -> mkLocalTyConGRE (fmap (const tycon_name) at_flav) at_nm)\\n at_bndrs at_names\\n sig_gres = map (mkLocalVanillaGRE (ParentIs tycon_name)) sig_names\\n con_gres = map (mkLocalConLikeGRE (ParentIs tycon_name)) fld_env\\n fld_gres = mkLocalFieldGREs (ParentIs tycon_name) fld_env\\n sub_gres = at_gres ++ sig_gres ++ con_gres ++ fld_gres\\n ; traceRn \\"getLocalNonValBinders new_tc\\" $\\n vcat [ text \\"tycon:\\" <+> ppr tycon_name\\n , text \\"tc_gre:\\" <+> ppr tc_gre\\n , text \\"sub_gres:\\" <+> ppr sub_gres ]\\n ; return $ tc_gre : sub_gres }\\n\\n -- Calculate the record field information, which feeds into the GlobalRdrElts\\n -- for DataCons and their fields. It\'s convenient to do this here where\\n -- we are working with a single datatype definition.\\n --\\n -- The information we needed was all set up for us:\\n -- see Note [Collecting record fields in data declarations] in GHC.Hs.Utils.\\n mk_fld_env :: [(Name, Either VisArity [Located Int])] -> IntMap FieldLabel\\n -> [(ConLikeName, ConInfo)]\\n mk_fld_env names flds =\\n [ (DataConName con, ConInfo (ConIsData (map fst names)) fld_info)\\n | (con, con_fl_indxs) <- names\\n , let fld_info = case fmap (map ((flds IntMap.!) . unLoc)) con_fl_indxs of\\n Left 0 -> ConIsNullary\\n Left arity -> ConHasPositionalArgs arity\\n Right [] -> ConIsNullary\\n Right (fld:flds) -> ConHasRecordFields $ fld NE.:| flds ]\\n\\n new_assoc :: DuplicateRecordFields -> FieldSelectors -> LInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_assoc _ _ (L _ (TyFamInstD {})) = return []\\n -- type instances don\'t bind new names\\n\\n new_assoc dup_fields_ok has_sel (L _ (DataFamInstD _ d))\\n = new_di dup_fields_ok has_sel Nothing d\\n new_assoc dup_fields_ok has_sel\\n (L _ (ClsInstD _ (ClsInstDecl { cid_poly_ty = inst_ty\\n , cid_decls = decls })))\\n = do -- First, attempt to grab the name of the class from the instance.\\n -- This step could fail if the instance is not headed by a class,\\n -- such as in the following examples:\\n --\\n -- (1) The class is headed by a bang pattern, such as in\\n -- `instance !Show Int` (#3811c)\\n -- (2) The class is headed by a type variable, such as in\\n -- `instance c` (#16385)\\n --\\n -- If looking up the class name fails, then mb_cls_gre will\\n -- be Nothing.\\n mb_cls_gre <- runMaybeT $ do\\n -- See (1) above\\n L loc cls_rdr <- MaybeT $ pure $ getLHsInstDeclClass_maybe inst_ty\\n -- See (2) above\\n MaybeT $ setSrcSpan (locA loc) $ lookupGlobalOccRn_maybe SameNameSpace cls_rdr\\n -- Assuming the previous step succeeded, process any associated data\\n -- family instances. If the previous step failed, bail out.\\n case mb_cls_gre of\\n Nothing\\n -> pure []\\n Just cls_gre\\n -> let cls_nm = greName cls_gre\\n in concatMapM (new_di dup_fields_ok has_sel (Just cls_nm) . unLoc) (data_fam_insts decls)\\n\\n data_fam_insts decls = concatMap get decls\\n where\\n get (L l (InstD _ (DataFamInstD { dfid_inst = d}))) = [L l d]\\n get _ = []\\n\\n new_di :: DuplicateRecordFields -> FieldSelectors\\n -> Maybe Name -- class name\\n -> DataFamInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_di dup_fields_ok has_sel mb_cls dfid@(DataFamInstDecl { dfid_eqn = ti_decl })\\n = do { main_name <- unLoc <$> lookupFamInstName mb_cls (feqn_tycon ti_decl)\\n ; let LConsWithFields cons_with_flds flds = hsDataFamInstBinders dfid\\n ; sub_names <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst sub_names) flds\\n ; mapM_ (add_dup_fld_errs flds\') sub_names\\n ; let fld_env = mk_fld_env sub_names flds\'\\n con_gres = map (mkLocalConLikeGRE (ParentIs main_name)) fld_env\\n field_gres = mkLocalFieldGREs (ParentIs main_name) fld_env\\n -- NB: the data family name is not bound here,\\n -- so we don\'t return a GlobalRdrElt for it here!\\n ; return $ con_gres ++ field_gres }\\n\\n -- Add errors if a constructor has a duplicate record field.\\n add_dup_fld_errs :: IntMap FieldLabel\\n -> (Name, Either VisArity [Located Int])\\n -> IOEnv (Env TcGblEnv TcLclEnv) ()\\n add_dup_fld_errs all_flds (con, con_flds_or_arity)\\n | Right con_flds <- con_flds_or_arity\\n , let (_, dups) = removeDups (comparing unLoc) con_flds\\n = for_ dups $ \\\\ dup_flds ->\\n -- Report the error at the location of the second occurrence\\n -- of the duplicate field.\\n let loc =\\n case dup_flds of\\n _ :| ( L loc _ : _) -> loc\\n L loc _ :| _ -> loc\\n dup_rdrs = fmap (nameRdrName . flSelector . (all_flds IntMap.!) . unLoc) dup_flds\\n in addErrAt loc $ TcRnDuplicateFieldName (RecordFieldDecl con) dup_rdrs\\n | otherwise\\n = return ()\\n\\nnewRecordFieldLabel :: DuplicateRecordFields -> FieldSelectors -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel\\nnewRecordFieldLabel _ _ [] _ = error \\"newRecordFieldLabel: datatype has no constructors!\\"\\nnewRecordFieldLabel dup_fields_ok has_sel (dc:_) (L loc (FieldOcc _ (L _ fld)))\\n = do { selName <- newTopSrcBinder $ L (l2l loc) $ field\\n ; return $ FieldLabel { flHasDuplicateRecordFields = dup_fields_ok\\n , flHasFieldSelector = has_sel\\n , flSelector = selName } }\\n where\\n fld_occ = rdrNameOcc fld\\n dc_fs = occNameFS $ nameOccName dc\\n field\\n -- Use an Exact RdrName as-is, to preserve the bindings\\n -- of an already renamer-resolved field and its use\\n -- sites. This is needed to correctly support record\\n -- selectors in Template Haskell. See Note [Binders in\\n -- Template Haskell] in \\"GHC.ThToHs\\" and Note [Looking up\\n -- Exact RdrNames] in \\"GHC.Rename.Env\\".\\n | isExact fld\\n = assertPpr (fieldOcc_maybe fld_occ == Just dc_fs)\\n (vcat [ text \\"newRecordFieldLabel: incorrect namespace for exact Name\\" <+> quotes (ppr fld)\\n , text \\"expected namespace:\\" <+> pprNameSpace (fieldName dc_fs)\\n , text \\" actual namespace:\\" <+> pprNameSpace (occNameSpace fld_occ) ])\\n fld\\n\\n -- Field names produced by the parser are namespaced with VarName.\\n -- Here we namespace them according to the first constructor.\\n -- See Note [Record field namespacing] in GHC.Types.Name.Occurrence.\\n | otherwise\\n = mkRdrUnqual $ varToRecFieldOcc dc_fs fld_occ\\n\\n{-\\nNote [Looking up family names in family instances]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider\\n\\n module M where\\n type family T a :: *\\n type instance M.T Int = Bool\\n\\nWe might think that we can simply use \'lookupOccRn\' when processing the type\\ninstance to look up \'M.T\'. Alas, we can\'t! The type family declaration is in\\nthe *same* HsGroup as the type instance declaration. Hence, as we are\\ncurrently collecting the binders declared in that HsGroup, these binders will\\nnot have been added to the global environment yet.\\n\\nSolution is simple: process the type family declarations first, extend\\nthe environment, and then process the type instances.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Filtering imports}\\n* *\\n************************************************************************\\n\\n@filterImports@ takes the @ExportEnv@ telling what the imported module makes\\navailable, and filters it through the import spec (if any).\\n\\nNote [Dealing with imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nFor import M( ies ), we take each AvailInfo from the mi_exports of M, and make\\n\\n imp_occ_env :: OccEnv (NameEnv ImpOccItem)\\n\\nThis map contains one entry for each OccName that M exports, mapping each OccName\\nto the following information:\\n\\n 1. the GlobalRdrElt corresponding to the OccName,\\n 2. whether this GlobalRdrElt was the parent in the AvailInfo we found\\n the OccName in.\\n 3. the GlobalRdrElts that were bundled together in the AvailInfo we found\\n this OccName in (not including the parent),\\n\\nWe need (2) and (3) during the construction of the OccEnv because of associated\\ntypes and bundled pattern synonyms, respectively.\\n(3) is explained in Note [Importing PatternSynonyms].\\n\\nTo explain (2), consider for example:\\n\\n module M where\\n class C a where { data T a }\\n instance C Int where { data T Int = T1 | T2 }\\n instance C Bool where { data T Int = T3 }\\n\\nHere, M\'s exports avails are (recalling the AvailTC invariant from GHC.Types.Avail)\\n\\n C(C,T), T(T,T1,T2,T3)\\n\\nNotice that T appears *twice*, once as a child and once as a parent. From\\nthese two exports, respectively, during construction of the imp_occ_env, we begin\\nby associating the following two elements with the key T:\\n\\n T -> ImpOccItem { imp_item = gre1, imp_bundled = [C,T] , imp_is_parent = False }\\n T -> ImpOccItem { imp_item = gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nwhere `gre1`, `gre2` are two GlobalRdrElts with greName T.\\nWe combine these (in function \'combine\' in \'mkImportOccEnv\') by discarding the\\nnon-parent item, thusly:\\n\\n T -> IE_ITem { imp_item = gre1 `plusGRE` gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nNote the `plusGRE`: this ensures we don\'t drop parent information;\\nsee Note [Preserve parent information when combining import OccEnvs].\\n\\nSo the overall imp_occ_env is:\\n\\n C -> ImpOccItem { imp_item = C, imp_bundled = [T ], imp_is_parent = True }\\n T -> ImpOccItem { imp_item = T , imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n T1 -> ImpOccItem { imp_item = T1, imp_bundled = [T1,T2,T3], imp_is_parent = False }\\n -- similarly for T2, T3\\n\\nNote that the imp_occ_env will have entries for data constructors too,\\nalthough we never look up data constructors.\\n\\nNote [Importing PatternSynonyms]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nAs described in Note [Dealing with imports], associated types can lead to the\\nsame Name appearing twice, both as a child and once as a parent, when\\nconstructing the imp_occ_env. The same thing can happen with pattern synonyms\\nif they are exported bundled with a type.\\n\\nA simplified example, based on #11959:\\n\\n {-# LANGUAGE PatternSynonyms #-}\\n module M (T(P), pattern P) where -- Duplicate export warning, but allowed\\n data T = MkT\\n pattern P = MkT\\n\\nHere we have T(P) and P in export_avails, and respectively construct both\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n P -> ImpOccItem { imp_item = P, imp_bundled = [] , imp_is_parent = False }\\n\\nWe combine these by dropping the one with no siblings, leaving us with:\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n\\nThat is, we simply discard the non-bundled Avail.\\n\\nNote [Importing DuplicateRecordFields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn filterImports, another complicating factor is DuplicateRecordFields.\\nSuppose we have:\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (S(foo), T(foo)) where\\n data S = MkS { foo :: Int }\\n data T = MkT { foo :: Int }\\n\\n module N where\\n import M (foo) -- this is allowed (A)\\n import M (S(foo)) -- this is allowed (B)\\n\\nHere M exports \'foo\' at two different OccNames, with different namespaces for\\nthe two construtors MkS and MkT. Then, when we look up \'foo\' in lookup_names\\nfor case (A), we have a variable foo but must look in all the record field\\nnamespaces to find the two fields (and hence two different Avails).\\nWhereas in case (B) we reach the lookup_ie case for IEThingWith,\\nwhich looks up \'S\' and then finds the unique \'foo\' amongst its children.\\n\\nSee T16745 for a test of this.\\n\\nNote [Preserve parent information when combining import OccEnvs]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen discarding one ImpOccItem in favour of another, as described in\\nNote [Dealing with imports], we must make sure to combine the GREs so that\\nwe don\'t lose information.\\n\\nConsider for example #24084:\\n\\n module M1 where { class C a where { type T a } }\\n module M2 ( module M1 ) where { import M1 }\\n module M3 where { import M2 ( C, T ); instance C () where T () = () }\\n\\nWhen processing the import list of `M3`, we will have two `Avail`s attached\\nto `T`, namely `C(C, T)` and `T(T)`. We combine them in the `combine` function\\nof `mkImportOccEnv`; as described in Note [Dealing with imports] we discard\\n`C(C, T)` in favour of `T(T)`. However, in doing so, we **must not**\\ndiscard the information want that `C` is the parent of `T`. Indeed,\\nlosing track of this information can cause errors when importing,\\nas we could get an error of the form\\n\\n \\u2018T\\u2019 is not a (visible) associated type of class \\u2018C\\u2019\\n\\nThis explains why we use `plusGRE` when combining the two ImpOccItems, even\\nthough we are discarding one in favour of the other.\\n-}\\n\\n-- | All the \'GlobalRdrElt\'s associated with an \'AvailInfo\'.\\ngresFromAvail :: HasDebugCallStack\\n => HscEnv -> Maybe ImportSpec -> AvailInfo -> [GlobalRdrElt]\\ngresFromAvail hsc_env prov avail =\\n [ mk_gre nm info\\n | nm <- availNames avail\\n , let info = lookupGREInfo hsc_env nm ]\\n where\\n\\n mk_gre n info\\n = case prov of\\n -- Nothing => bound locally\\n -- Just is => imported from \'is\'\\n Nothing -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = True, gre_imp = emptyBag\\n , gre_info = info }\\n Just is -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = False, gre_imp = unitBag is\\n , gre_info = info }\\n\\n-- | All the \'GlobalRdrElt\'s associated with a collection of \'AvailInfo\'s.\\ngresFromAvails :: HscEnv -> Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]\\ngresFromAvails hsc_env prov = concatMap (gresFromAvail hsc_env prov)\\n\\nimportsFromIface :: HscEnv -> ModIface -> ImpDeclSpec -> Maybe NameSet -> GlobalRdrEnv\\nimportsFromIface hsc_env iface decl_spec hidden = mkGlobalRdrEnv $ case hidden of\\n Nothing -> all_gres\\n Just hidden_names -> filter (not . (`elemNameSet` hidden_names) . greName) all_gres\\n where\\n all_gres = gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\nrnNamespaceSpecifier :: NamespaceSpecifier GhcPs -> NamespaceSpecifier GhcRn\\nrnNamespaceSpecifier (NoNamespaceSpecifier _) = NoNamespaceSpecifier noExtField\\nrnNamespaceSpecifier (TypeNamespaceSpecifier x) = TypeNamespaceSpecifier x\\nrnNamespaceSpecifier (DataNamespaceSpecifier x) = DataNamespaceSpecifier x\\n\\nfilterImports\\n :: HasDebugCallStack\\n => HscEnv\\n -> ModIface\\n -> ImpDeclSpec\\n -- ^ Import spec\\n -> Maybe (ImportListInterpretation, [LIE GhcPs])\\n -- ^ Whether this is a \\"hiding\\" import list\\n -> RnM (Maybe (ImportListInterpretation, [LIE GhcRn]), -- Import spec w/ Names\\n ImpUserList, -- same, but designed for storage in interfaces\\n GlobalRdrEnv) -- Same again, but in GRE form\\nfilterImports hsc_env iface decl_spec Nothing\\n = return (Nothing, ImpUserAll, importsFromIface hsc_env iface decl_spec Nothing)\\nfilterImports hsc_env iface decl_spec (Just (want_hiding, import_items))\\n = do -- check for errors, convert RdrNames to Names\\n items1 <- mapM lookup_lie import_items\\n\\n let items2 :: [(LIE GhcRn, [GlobalRdrElt])]\\n items2 = concat items1\\n -- NB we may have duplicates, and several items\\n -- for the same parent; e.g N(x) and N(y)\\n\\n (gres, imp_user_list) = case want_hiding of\\n Exactly ->\\n let gres = concatMap (gresFromIE decl_spec) items2\\n gre_env = mkGlobalRdrEnv gres\\n implicit_parents = mkNameSet $ mapMaybe parentOfImplicitlyImportedGRE gres\\n in (gre_env, ImpUserExplicit (gresToAvailInfo $ globalRdrEnvElts $ gre_env) implicit_parents)\\n EverythingBut ->\\n let hidden_names = mkNameSet $ concatMap (map greName . snd) items2\\n in (importsFromIface hsc_env iface decl_spec (Just hidden_names), ImpUserEverythingBut hidden_names)\\n\\n return (Just (want_hiding, map fst items2), imp_user_list, gres)\\n where\\n import_mod = mi_module iface\\n all_avails = mi_exports iface\\n imp_occ_env = mkImportOccEnv hsc_env decl_spec all_avails\\n\\n -- Look up a parent (type constructor, class or data constructor)\\n -- in an import.\\n lookup_parent :: IE GhcPs -> RdrName -> IELookupM ImpOccItem\\n lookup_parent ie rdr =\\n assertPpr (not $ isVarNameSpace ns)\\n (vcat [ text \\"filterImports lookup_parent: unexpected variable\\"\\n , text \\"rdr:\\" <+> ppr rdr\\n , text \\"namespace:\\" <+> pprNameSpace ns ]) $\\n do { xs <- lookup_names ie rdr\\n ; case xs of\\n cax :| [] -> return cax\\n _ -> pprPanic \\"filter_imports lookup_parent ambiguous\\" $\\n vcat [ text \\"rdr:\\" <+> ppr rdr\\n , text \\"lookups:\\" <+> ppr (fmap imp_item xs) ] }\\n -- Looking up non-variables is always unambiguous,\\n -- as there can be at most one corresponding item\\n -- in the imp_occ_env.\\n -- See item (1) of Note [Exporting duplicate declarations]\\n -- in GHC.Tc.Gen.Export.\\n where\\n occ = rdrNameOcc rdr\\n ns = occNameSpace occ\\n\\n -- Look up a RdrName used in an import, returning multiple values if there\\n -- are several fields with the same name exposed by the module\\n lookup_names :: IE GhcPs -> RdrName -> IELookupM (NonEmpty ImpOccItem)\\n lookup_names ie rdr\\n | isQual rdr\\n = failLookupWith (QualImportError rdr)\\n | otherwise\\n = case lookups of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n item:items -> return $ item :| items\\n where\\n lookups = concatMap nonDetNameEnvElts\\n $ lookupImpOccEnv (RelevantGREsFOS WantNormal) imp_occ_env (rdrNameOcc rdr)\\n\\n lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, [GlobalRdrElt])]\\n lookup_lie (L loc ieRdr)\\n = setSrcSpanA loc $\\n do (stuff, warns) <- run_lookup ([],[]) (lookup_ie ieRdr)\\n mapM_ (addTcRnDiagnostic <=< warning_msg) warns\\n return [ (L loc ie, gres) | (ie,gres) <- stuff ]\\n where\\n\\n -- Warn when importing T(..) and no children are brought in scope\\n warning_msg (DodgyImport reason) =\\n pure (TcRnDodgyImports reason)\\n warning_msg MissingImportList =\\n pure (TcRnMissingImportList ieRdr)\\n warning_msg (BadImportW ie sub) = do\\n -- \'BadImportW\' is only constructed below in \'bad_import_w\', in\\n -- the \'EverythingBut\' case, so here we assume a \'hiding\' clause.\\n (reason :| _) <- badImportItemErr iface decl_spec ie sub all_avails\\n pure (TcRnDodgyImports (DodgyImportsHiding reason))\\n warning_msg (DeprecatedExport n w) =\\n pure $ TcRnPragmaWarning\\n PragmaWarningExport\\n { pwarn_occname = occName n\\n , pwarn_impmod = moduleName import_mod }\\n w\\n\\n run_lookup :: a -> IELookupM a -> TcRn a\\n run_lookup def m = case m of\\n Failed err -> do\\n msgs <- lookup_err_msgs err\\n forM_ msgs $ \\\\msg -> addErr (TcRnImportLookup msg)\\n return def\\n Succeeded a -> return a\\n\\n lookup_err_msgs err = case err of\\n BadImport ie sub -> badImportItemErr iface decl_spec ie sub all_avails\\n IllegalImport -> pure $ NE.singleton ImportLookupIllegal\\n QualImportError rdr -> pure $ NE.singleton (ImportLookupQualified rdr)\\n\\n -- For each import item, we convert its RdrNames to Names,\\n -- and at the same time compute all the GlobalRdrElt corresponding\\n -- to what is actually imported by this item.\\n -- Returns Nothing on error.\\n --\\n -- Returns a list because, with DuplicateRecordFields, a naked\\n -- import/export of a record field can correspond to multiple\\n -- different GlobalRdrElts. See Note [Importing DuplicateRecordFields].\\n lookup_ie :: IE GhcPs\\n -> IELookupM ([(IE GhcRn, [GlobalRdrElt])], [IELookupWarning])\\n lookup_ie ie = handle_bad_import $\\n case ie of\\n IEVar _ (L l n) _ -> do\\n -- See Note [Importing DuplicateRecordFields]\\n xs <- lookup_names ie (ieWrappedName n)\\n let gres = map imp_item $ NE.toList xs\\n export_depr_warns\\n | want_hiding == Exactly\\n = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ( [ (IEVar Nothing (L l (replaceWrappedName n name)) noDocstring, [gre])\\n | gre <- gres\\n , let name = greName gre ]\\n , export_depr_warns )\\n\\n IEThingAll x ns_spec (L l tc) _ -> do\\n ImpOccItem { imp_item = gre\\n , imp_bundled = bundled_gres\\n , imp_is_parent = is_par\\n }\\n <- lookup_parent ie $ ieWrappedName tc\\n let name = greName gre\\n\\n child_gres :: [GlobalRdrElt]\\n child_gres\\n | is_par = filterByNamespaceSpecifierGREs ns_spec bundled_gres\\n | otherwise = []\\n\\n imp_list_warn\\n\\n | null child_gres\\n -- e.g. f(..) or T(..) where T is a type synonym\\n = [DodgyImport (DodgyImportsEmptyParent ie ns_spec gre)]\\n\\n -- e.g. import M( T(..) )\\n | not (is_qual decl_spec)\\n = [MissingImportList]\\n\\n | otherwise\\n = []\\n\\n renamed_ie = IEThingAll (x { ieta_warning = Nothing })\\n (rnNamespaceSpecifier ns_spec)\\n (L l (replaceWrappedName tc name))\\n noDocstring\\n export_depr_warn\\n | want_hiding == Exactly\\n = maybeToList $ mk_depr_export_warning gre\\n -- We don\'t want to warn about the children as they\\n -- are not explicitly mentioned; the warning will\\n -- be emitted later on if they are used\\n | otherwise = []\\n\\n return ( [(renamed_ie, gre:child_gres)]\\n , imp_list_warn ++ export_depr_warn)\\n\\n\\n IEThingAbs _ (L l tc\') _\\n | want_hiding == EverythingBut -- hiding ( C )\\n -- Here the \'C\' can be a data constructor\\n -- *or* a type/class, or even both\\n -> let tc = ieWrappedName tc\'\\n tc_name = lookup_parent ie tc\\n dc_name = lookup_parent ie (setRdrNameSpace tc srcDataName)\\n in\\n case catIELookupM [ tc_name, dc_name ] of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n names -> return ( [mkIEThingAbs tc\' l (imp_item name) | name <- names], [])\\n | otherwise\\n -> do ImpOccItem { imp_item = gre } <- lookup_parent ie (ieWrappedName tc\')\\n return ( [mkIEThingAbs tc\' l gre]\\n , maybeToList $ mk_depr_export_warning gre)\\n\\n IEThingWith (deprecation, ann) ltc@(L l rdr_tc) wc rdr_ns _ -> do\\n ImpOccItem { imp_item = gre, imp_bundled = subnames }\\n <- lookup_parent (IEThingAbs Nothing ltc noDocstring) (ieWrappedName rdr_tc)\\n let name = greName gre\\n\\n -- Look up the children in the sub-names of the parent\\n -- See Note [Importing DuplicateRecordFields]\\n let (children_errs, childnames) = lookupChildren subnames rdr_ns\\n\\n bad_import_warns <-\\n if null children_errs then return [] else\\n let items = map lce_wrapped_name children_errs\\n ie = IEThingWith (deprecation, ann) ltc wc items noDocstring\\n -- We are trying to import T( a,b,c,d ), and failed\\n -- to find \'b\' and \'d\'. So we make up an import item\\n -- to report as failing, namely T( b, d ).\\n -- c.f. #15413\\n subordinate_err = mkSubordinateError gre children_errs\\n in bad_import_w ie subordinate_err\\n\\n let name\' = replaceWrappedName rdr_tc name\\n childnames\' = map (to_ie_post_rn . fmap greName) childnames\\n gres = gre : map unLoc childnames\\n export_depr_warns\\n | want_hiding == Exactly = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ([ (IEThingWith (Nothing, ann) (L l name\') wc childnames\' noDocstring\\n ,gres)]\\n , bad_import_warns ++ export_depr_warns)\\n\\n IEWholeNamespace x ns_spec -> do\\n let mod_name = moduleName import_mod\\n names = map greName gres\\n renamed_ie = IEWholeNamespace x { iewn_warning = Nothing\\n , iewn_names = names }\\n (rnNamespaceSpecifier ns_spec)\\n gres = filterByNamespaceSpecifierGREs ns_spec $\\n gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n dodgy_warn\\n | null gres = [DodgyImport (DodgyImportsWildcard mod_name ns_spec)]\\n | otherwise = []\\n return ([(renamed_ie, gres)],\\n dodgy_warn)\\n\\n _other -> failLookupWith IllegalImport\\n -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed...\\n -- all of those constitute errors.\\n\\n where\\n mkIEThingAbs tc l gre\\n = (IEThingAbs Nothing (L l (replaceWrappedName tc n)) noDocstring, [gre])\\n where n = greName gre\\n\\n -- N.B. imports never have docstrings\\n noDocstring = Nothing\\n\\n handle_bad_import m = catchIELookup m $ \\\\case\\n BadImport ie sub -> do\\n ws <- bad_import_w ie sub\\n return ([], ws)\\n err -> failLookupWith err\\n\\n bad_import_w :: IE GhcPs -> IsSubordinateError -> IELookupM [IELookupWarning]\\n bad_import_w ie sub\\n | want_hiding == EverythingBut = return [BadImportW ie sub]\\n | otherwise = failLookupWith (BadImport ie sub)\\n\\n mk_depr_export_warning gre\\n = DeprecatedExport name <$> mi_export_warn_fn iface name\\n where\\n name = greName gre\\n\\n-- | Assuming a subordinate item could not be found, do another lookup for a\\n-- more specific error message.\\nmkBadExportSubordinate :: [GlobalRdrElt] -> LIEWrappedName GhcPs -> BadExportSubordinate\\nmkBadExportSubordinate child_gres n =\\n case lookupChildren child_gres [n] of\\n (LookupChildNonType {lce_nontype_item = g} : _, _) -> BadExportSubordinateNonType g\\n (LookupChildNonData {lce_nondata_item = g} : _, _) -> BadExportSubordinateNonData g\\n _ -> BadExportSubordinateNotFound n\\n\\ntype IELookupM = MaybeErr IELookupError\\n\\ndata IELookupWarning\\n = BadImportW (IE GhcPs) IsSubordinateError\\n | MissingImportList\\n | DodgyImport DodgyImportsReason\\n | DeprecatedExport Name (WarningTxt GhcRn)\\n\\n-- | Is this import/export item a subordinate or not?\\ndata IsSubordinateError\\n = IsSubordinateError { subordinate_err_parent :: !GlobalRdrElt\\n , subordinate_err_unavailable :: [FastString]\\n , subordinate_err_nontype :: [GlobalRdrElt]\\n , subordinate_err_nondata :: [GlobalRdrElt] }\\n | IsNotSubordinate\\n\\nmkSubordinateError :: GlobalRdrElt -> [LookupChildError] -> IsSubordinateError\\nmkSubordinateError gre children_errs = foldr add init_acc children_errs\\n where\\n init_acc :: IsSubordinateError\\n init_acc = IsSubordinateError gre [] [] []\\n\\n add :: LookupChildError -> IsSubordinateError -> IsSubordinateError\\n add children_err sub@IsSubordinateError{} =\\n case children_err of\\n LookupChildNonType{lce_nontype_item = g} ->\\n sub { subordinate_err_nontype = g : subordinate_err_nontype sub }\\n LookupChildNonData{lce_nondata_item = g} ->\\n sub { subordinate_err_nondata = g : subordinate_err_nondata sub }\\n LookupChildNotFound (L _ wname) ->\\n let fs = (occNameFS . rdrNameOcc . ieWrappedName) wname\\n in sub { subordinate_err_unavailable = fs : subordinate_err_unavailable sub }\\n add _ IsNotSubordinate = panic \\"mkSubordinateError: IsNotSubordinate\\"\\n\\ndata IELookupError\\n = QualImportError RdrName\\n | BadImport (IE GhcPs) IsSubordinateError\\n | IllegalImport\\n\\nfailLookupWith :: IELookupError -> IELookupM a\\nfailLookupWith err = Failed err\\n\\ncatchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a\\ncatchIELookup m h = case m of\\n Succeeded r -> return r\\n Failed err -> h err\\n\\ncatIELookupM :: [IELookupM a] -> [a]\\ncatIELookupM ms = [ a | Succeeded a <- ms ]\\n\\n-- | Information associated to an \'AvailInfo\' used in constructing\\n-- an \'OccEnv\' corresponding to imports.\\n--\\n-- See Note [Dealing with imports].\\ndata ImpOccItem\\n = ImpOccItem\\n { imp_item :: GlobalRdrElt\\n -- ^ The import item\\n , imp_bundled :: [GlobalRdrElt]\\n -- ^ Items bundled in the Avail this import item came from,\\n -- not including the import item itself if it is a parent.\\n , imp_is_parent :: Bool\\n -- ^ Is the import item a parent? See Note [Dealing with imports].\\n }\\n\\ninstance Outputable ImpOccItem where\\n ppr (ImpOccItem { imp_item = item, imp_bundled = bundled, imp_is_parent = is_par })\\n = braces $ hsep\\n [ text \\"ImpOccItem\\"\\n , if is_par then text \\"[is_par]\\" else empty\\n , ppr (greName item) <+> ppr (greParent item)\\n , braces $ text \\"bundled:\\" <+> ppr (map greName bundled) ]\\n\\n-- | Make an \'OccEnv\' of all the imports.\\n--\\n-- Complicated by the fact that associated data types and pattern synonyms\\n-- can appear twice. See Note [Dealing with imports].\\nmkImportOccEnv :: HscEnv -> ImpDeclSpec -> [IfaceExport] -> OccEnv (NameEnv ImpOccItem)\\nmkImportOccEnv hsc_env decl_spec all_avails =\\n mkOccEnv_C (plusNameEnv_C combine)\\n [ (occ, mkNameEnv [(nm, item)])\\n | avail <- all_avails\\n , let gres = gresFromAvail hsc_env (Just hiding_spec) avail\\n , gre <- gres\\n , let nm = greName gre\\n occ = greOccName gre\\n (is_parent, bundled) = case avail of\\n AvailTC c _\\n | c == nm -- (Recall the AvailTC invariant from GHC.Types.AvailInfo)\\n -> ( True, drop 1 gres ) -- \\"drop 1\\": don\'t include the parent itself.\\n | otherwise\\n -> ( False, gres )\\n _ -> ( False, [] )\\n item = ImpOccItem\\n { imp_item = gre\\n , imp_bundled = bundled\\n , imp_is_parent = is_parent }\\n ]\\n where\\n\\n hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\n -- See Note [Dealing with imports]\\n -- \'combine\' may be called for associated data types which appear\\n -- twice in the all_avails. In the example, we have two Avails for T,\\n -- namely T(T,T1,T2,T3) and C(C,T), and we combine them by dropping the\\n -- latter, in which T is not the parent.\\n combine :: ImpOccItem -> ImpOccItem -> ImpOccItem\\n combine item1@(ImpOccItem { imp_item = gre1, imp_is_parent = is_parent1 })\\n item2@(ImpOccItem { imp_item = gre2, imp_is_parent = is_parent2 })\\n | is_parent1 || is_parent2\\n , not (isRecFldGRE gre1 || isRecFldGRE gre2) -- NB: does not force GREInfo.\\n , let name1 = greName gre1\\n name2 = greName gre2\\n gre = gre1 `plusGRE` gre2\\n -- See Note [Preserve parent information when combining import OccEnvs]\\n = assertPpr (name1 == name2)\\n (ppr name1 <+> ppr name2) $\\n if is_parent1\\n then item1 { imp_item = gre }\\n else item2 { imp_item = gre }\\n -- Discard C(C,T) in favour of T(T, T1, T2, T3).\\n\\n -- \'combine\' may also be called for pattern synonyms which appear both\\n -- unassociated and associated (see Note [Importing PatternSynonyms]).\\n combine item1@(ImpOccItem { imp_item = c1, imp_bundled = kids1 })\\n item2@(ImpOccItem { imp_item = c2, imp_bundled = kids2 })\\n = assertPpr (greName c1 == greName c2\\n && (not (null kids1 && null kids2)))\\n (ppr c1 <+> ppr c2 <+> ppr kids1 <+> ppr kids2) $\\n if null kids1\\n then item2\\n else item1\\n -- Discard standalone pattern P in favour of T(P).\\n\\n-- | Essentially like @lookupGRE env (LookupOccName occ which_gres)@,\\n-- but working with \'ImpOccItem\'s instead of \'GlobalRdrElt\'s.\\nlookupImpOccEnv :: WhichGREs GREInfo\\n -> OccEnv (NameEnv ImpOccItem) -> OccName -> [NameEnv ImpOccItem]\\nlookupImpOccEnv which_gres env occ =\\n mapMaybe relevant_items $ lookupOccEnv_AllNameSpaces env occ\\n where\\n is_relevant :: ImpOccItem -> Bool\\n is_relevant (ImpOccItem { imp_item = gre }) =\\n greIsRelevant which_gres (occNameSpace occ) gre\\n relevant_items :: NameEnv ImpOccItem -> Maybe (NameEnv ImpOccItem)\\n relevant_items nms\\n | let nms\' = filterNameEnv is_relevant nms\\n = if isEmptyNameEnv nms\'\\n then Nothing\\n else Just nms\'\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{Import/Export Utils}\\n* *\\n************************************************************************\\n-}\\n\\n-- | Given an import\\\\/export spec, appropriately set the @gre_imp@ field\\n-- for the \'GlobalRdrElt\'s.\\ngresFromIE :: ImpDeclSpec -> (LIE GhcRn, [GlobalRdrElt]) -> [GlobalRdrElt]\\ngresFromIE decl_spec (L loc ie, gres)\\n = map set_gre_imp gres\\n where\\n is_explicit = case ie of\\n IEThingAll _ _ name _ -> \\\\n -> n == lieWrappedName name\\n IEWholeNamespace _ _ -> \\\\_ -> False\\n _ -> \\\\_ -> True\\n prov_fn name\\n = ImpSpec { is_decl = decl_spec, is_item = item_spec }\\n where\\n item_spec = ImpSome { is_explicit = is_explicit name\\n , is_iloc = locA loc }\\n set_gre_imp gre@( GRE { gre_name = nm } )\\n = gre { gre_imp = unitBag $ prov_fn nm }\\n\\nparentOfImplicitlyImportedGRE :: Outputable info => GlobalRdrEltX info -> Maybe Name\\nparentOfImplicitlyImportedGRE gre =\\n if any (explicit_import . is_item) $ gre_imp gre\\n then Nothing\\n else greParent_maybe gre\\n where\\n explicit_import :: ImpItemSpec -> Bool\\n explicit_import (ImpAll {}) =\\n pprPanic \\"parentOfImplicitlyImportedGRE: ImpAll\\" (ppr gre)\\n explicit_import (ImpSome { is_explicit }) = is_explicit\\n\\n{- Note [Children for duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider the module\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (F(foo, MkFInt, MkFBool)) where\\n data family F a\\n data instance F Int = MkFInt { foo :: Int }\\n data instance F Bool = MkFBool { foo :: Bool }\\n\\nThe `foo` in the export list refers to *both* selectors! For this\\nreason, lookupChildren builds an environment that maps the FastString\\nto a list of items, rather than a single item.\\n-}\\n\\nmkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]\\nmkChildEnv gres = foldr add emptyNameEnv gres\\n where\\n add gre env = case greParent gre of\\n ParentIs p -> extendNameEnv_Acc (:) Utils.singleton env p gre\\n NoParent -> env\\n\\nfindChildren :: NameEnv [a] -> Name -> [a]\\nfindChildren env n = lookupNameEnv env n `orElse` []\\n\\ndata LookupChildError\\n = LookupChildNotFound { lce_wrapped_name :: !(LIEWrappedName GhcPs) }\\n | LookupChildNonType { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nontype_item :: !GlobalRdrElt }\\n | LookupChildNonData { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nondata_item :: !GlobalRdrElt }\\n\\nlookupChildren :: [GlobalRdrElt]\\n -> [LIEWrappedName GhcPs]\\n -> ( [LookupChildError] -- The ones for which the lookup failed\\n , [LocatedA GlobalRdrElt] )\\n-- (lookupChildren all_kids rdr_items) maps each rdr_item to its\\n-- corresponding Name in all_kids, if the former exists\\n-- The matching is done by FastString, not OccName, so that\\n-- Cls( meth, AssocTy )\\n-- will correctly find AssocTy among the all_kids of Cls, even though\\n-- the RdrName for AssocTy may have a (bogus) DataName namespace\\n-- (Really the rdr_items should be FastStrings in the first place.)\\nlookupChildren all_kids rdr_items = (fails, successes)\\n where\\n mb_xs = map do_one rdr_items\\n fails = [ err | Failed err <- mb_xs ]\\n successes = [ ok | Succeeded oks <- mb_xs, ok <- NE.toList oks ]\\n\\n do_one :: LIEWrappedName GhcPs -> MaybeErr LookupChildError (NonEmpty (LocatedA GlobalRdrElt))\\n do_one item@(L l r) =\\n case r of\\n IEName{}\\n -- IEName (unadorned name) places no restriction on the namespace of\\n -- the imported entity, so we look in both `val_gres` and `typ_gres`.\\n -- In case of conflict (punning), the value namespace takes priority.\\n -- See Note [Prioritise the value namespace in subordinate import lists]\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEType{}\\n -- IEType (\'type\' namespace specifier) restricts the lookup to the\\n -- type namespace, i.e. to `typ_gres`. In case of failure, we check\\n -- `val_gres` to produce a more helpful error message.\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- val_gres -> Failed $ LookupChildNonType item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEData{}\\n -- IEData (\'data\' namespace specifier) restricts the lookup to the\\n -- data namespace, i.e. to `val_gres`. In case of failure, we check\\n -- `typ_gres` to produce a more helpful error message.\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- typ_gres -> Failed $ LookupChildNonData item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEPattern{} -> panic \\"lookupChildren: IEPattern\\" -- Never happens (invalid syntax)\\n IEDefault{} -> panic \\"lookupChildren: IEDefault\\" -- Never happens (invalid syntax)\\n where\\n fs = (occNameFS . rdrNameOcc . ieWrappedName) r\\n gres = fromMaybe [] (lookupFsEnv kid_env fs)\\n (val_gres, typ_gres) = partition (isValNameSpace . greNameSpace) gres\\n\\n -- See Note [Children for duplicate record fields]\\n kid_env :: FastStringEnv [GlobalRdrElt]\\n kid_env = extendFsEnvList_C (++) emptyFsEnv\\n [(occNameFS (occName x), [x]) | x <- all_kids]\\n\\n\\n{- Note [Prioritise the value namespace in subordinate import lists]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider this program that defines a class that has both an associated type\\nnamed (#) and a method named (#)\\n\\n module M_assoc where\\n class C a b where\\n type a # b\\n (#) :: a -> b -> ()\\n module N_assoc where\\n import M_assoc( C((#)) )\\n\\nIn the import declaration, when we see the unadorned name (#) in the subordinate\\nimport list of C, which children should we bring into scope? Our options are:\\n\\n a) only the method (#)\\n b) only the associated type (#)\\n c) both the method and the associated type\\n\\nTo follow the precedent established by top-level items, we go with option (a).\\nIndeed, consider a slightly different program\\n\\n module M_top where\\n type family a # b\\n a # b = ()\\n module N_top where\\n import M_top( (#) )\\n\\nHere the import brings only the function (#) into scope, and one has to say\\n`type (#)` to get the type family.\\n-}\\n\\n-------------------------------\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused names}\\n* *\\n*********************************************************\\n-}\\n\\nreportUnusedNames :: TcGblEnv -> HscSource -> RnM ()\\nreportUnusedNames gbl_env hsc_src\\n = do { keep <- readTcRef (tcg_keep gbl_env)\\n ; traceRn \\"RUN\\" (ppr (tcg_dus gbl_env))\\n ; warnUnusedImportDecls gbl_env hsc_src\\n ; warnUnusedTopBinds $ unused_locals keep\\n ; warnMissingSignatures gbl_env\\n ; warnMissingKindSignatures gbl_env }\\n where\\n used_names :: NameSet -> NameSet\\n used_names keep = findUses (tcg_dus gbl_env) emptyNameSet `unionNameSet` keep\\n -- NB: currently, if f x = g, we only treat \'g\' as used if \'f\' is used\\n -- Hence findUses\\n\\n -- Collect the defined names from the in-scope environment\\n defined_names :: [GlobalRdrElt]\\n defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)\\n\\n kids_env = mkChildEnv defined_names\\n -- This is done in mkExports too; duplicated work\\n\\n gre_is_used :: NameSet -> GlobalRdrElt -> Bool\\n gre_is_used used_names gre0\\n = name `elemNameSet` used_names\\n || any (\\\\ gre -> greName gre `elemNameSet` used_names) (findChildren kids_env name)\\n -- A use of C implies a use of T,\\n -- if C was brought into scope by T(..) or T(C)\\n where\\n name = greName gre0\\n\\n -- Filter out the ones that are\\n -- (a) defined in this module, and\\n -- (b) not defined by a \'deriving\' clause\\n -- The latter have an Internal Name, so we can filter them out easily\\n unused_locals :: NameSet -> [GlobalRdrElt]\\n unused_locals keep =\\n let -- Note that defined_and_used, defined_but_not_used\\n -- are both [GRE]; that\'s why we need defined_and_used\\n -- rather than just used_names\\n _defined_and_used, defined_but_not_used :: [GlobalRdrElt]\\n (_defined_and_used, defined_but_not_used)\\n = partition (gre_is_used (used_names keep)) defined_names\\n\\n in filter is_unused_local defined_but_not_used\\n is_unused_local :: GlobalRdrElt -> Bool\\n is_unused_local gre = isLocalGRE gre\\n && isExternalName (greName gre)\\n\\n{- *********************************************************************\\n* *\\n Missing signatures\\n* *\\n********************************************************************* -}\\n\\n{-\\nNote [Missing signatures]\\n~~~~~~~~~~~~~~~~~~~~~~~~~\\nThere are four warning flags in play:\\n\\n * -Wmissing-exported-signatures\\n Warn about any exported top-level function/value without a type signature.\\n Does not include pattern synonyms.\\n\\n * -Wmissing-signatures\\n Warn about any top-level function/value without a type signature. Does not\\n include pattern synonyms. Takes priority over -Wmissing-exported-signatures.\\n\\n * -Wmissing-exported-pattern-synonym-signatures\\n Warn about any exported pattern synonym without a type signature.\\n\\n * -Wmissing-pattern-synonym-signatures\\n Warn about any pattern synonym without a type signature. Takes priority over\\n -Wmissing-exported-pattern-synonym-signatures.\\n\\n-}\\n\\n-- | Warn the user about top level binders that lack type signatures.\\n-- Called /after/ type inference, so that we can report the\\n-- inferred type of the function\\nwarnMissingSignatures :: TcGblEnv -> RnM ()\\nwarnMissingSignatures gbl_env\\n = do { let exports = availsToNameSet (tcg_exports gbl_env)\\n sig_ns = tcg_sigs gbl_env\\n -- We use sig_ns to exclude top-level bindings that are generated by GHC\\n binds = collectHsBindsBinders CollNoDictBinders $ tcg_binds gbl_env\\n pat_syns = tcg_patsyns gbl_env\\n\\n not_ghc_generated :: Name -> Bool\\n not_ghc_generated name = name `elemNameSet` sig_ns\\n\\n add_binding_warn :: Id -> RnM ()\\n add_binding_warn id =\\n when (not_ghc_generated name) $\\n do { env <- liftZonkM $ tcInitTidyEnv -- Why not use emptyTidyEnv?\\n ; let ty = tidyOpenType env (idType id)\\n missing = MissingTopLevelBindingSig name ty\\n diag = TcRnMissingSignature missing exported\\n ; addDiagnosticAt (getSrcSpan name) diag }\\n where\\n name = idName id\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n add_patsyn_warn :: PatSyn -> RnM ()\\n add_patsyn_warn ps =\\n when (not_ghc_generated name) $\\n addDiagnosticAt (getSrcSpan name)\\n (TcRnMissingSignature missing exported)\\n where\\n name = patSynName ps\\n missing = MissingPatSynSig ps\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n -- Warn about missing signatures\\n -- Do this only when we have a type to offer\\n -- See Note [Missing signatures]\\n ; mapM_ add_binding_warn binds\\n ; mapM_ add_patsyn_warn pat_syns\\n }\\n\\n-- | Warn the user about tycons that lack kind signatures.\\n-- Called /after/ type (and kind) inference, so that we can report the\\n-- inferred kinds.\\nwarnMissingKindSignatures :: TcGblEnv -> RnM ()\\nwarnMissingKindSignatures gbl_env\\n = do { cusks_enabled <- xoptM LangExt.CUSKs\\n ; mapM_ (add_ty_warn cusks_enabled) tcs\\n }\\n where\\n tcs = tcg_tcs gbl_env\\n ksig_ns = tcg_ksigs gbl_env\\n exports = availsToNameSet (tcg_exports gbl_env)\\n\\n has_kind_signature :: Name -> Bool\\n has_kind_signature name = name `elemNameSet` ksig_ns\\n\\n add_ty_warn :: Bool -> TyCon -> RnM ()\\n add_ty_warn cusks_enabled tyCon =\\n when (has_kind_signature name) $\\n addDiagnosticAt (getSrcSpan name) diag\\n where\\n name = tyConName tyCon\\n diag = TcRnMissingSignature missing exported\\n missing = MissingTyConKindSig tyCon cusks_enabled\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused imports}\\n* *\\n*********************************************************\\n\\nThis code finds which import declarations are unused. The\\nspecification and implementation notes are here:\\n https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/unused-imports\\n\\nSee also Note [Choosing the best import declaration] in GHC.Types.Name.Reader\\n-}\\n\\ntype ImportDeclUsage\\n = ( LImportDecl GhcRn -- The import declaration\\n , [GlobalRdrElt] -- What *is* used (normalised)\\n , [Name] -- What is imported but *not* used\\n , [NamespaceSpecifier GhcRn] ) -- Unused wildcards\\n\\nwarnUnusedImportDecls :: TcGblEnv -> HscSource -> RnM ()\\nwarnUnusedImportDecls gbl_env hsc_src\\n = do { uses <- readMutVar (tcg_used_gres gbl_env)\\n ; let imports = tcg_rn_imports gbl_env\\n rdr_env = tcg_rdr_env gbl_env\\n\\n -- We should only warn for unnecessary *user* imports, but deciding\\n -- minimal imports should take generated imports into account\\n ; let usageUserImports = findImportUsage (excludeGenerated imports) uses\\n usageAllImports = findImportUsage imports uses\\n\\n ; traceRn \\"warnUnusedImportDecls\\" $\\n (vcat [ text \\"Uses:\\" <+> ppr uses\\n , text \\"Usage all user imports: \\" <+> ppr usageUserImports\\n , text \\"Usage all imports: \\" <+> ppr usageAllImports])\\n\\n ; mapM_ (warnUnusedImport rdr_env) usageUserImports\\n\\n ; whenGOptM Opt_D_dump_minimal_imports $\\n printMinimalImports hsc_src usageAllImports }\\n\\n-- | Exclude generated imports\\nexcludeGenerated :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\nexcludeGenerated = filterOut (isGeneratedImport . ideclOrigin . ideclExt . unLoc)\\n\\nfindImportUsage :: [LImportDecl GhcRn]\\n -> [GlobalRdrElt]\\n -> [ImportDeclUsage]\\n\\nfindImportUsage imports used_gres\\n = map unused_decl imports\\n where\\n import_usage :: ImportMap\\n import_usage = mkImportMap used_gres\\n\\n unused_decl :: LImportDecl GhcRn -> ImportDeclUsage\\n unused_decl decl@(L _ (ImportDecl { ideclImportList = imps }))\\n = -- pprTrace \\"unused_decl\\" (vcat [ ppr decl\\n -- , text \\"used\\" <+> ppr used_gres\\n -- , text \\"unused\\" <+> ppr unused_names ]) $\\n (decl, used_gres, unused_names, unused_wcs)\\n where\\n used_gres = lookupImportMap decl import_usage\\n\\n used_gre_env = mkGlobalRdrEnv used_gres\\n used_parents = mkNameSet (mapMaybe greParent_maybe used_gres)\\n\\n (unused_names, unused_wcs) -- Not trivial; see eg #7454\\n = case imps of\\n Just (Exactly, imp_ies) ->\\n let unused = foldr (add_unused . unLoc) emptyUnusedNames imp_ies\\n nms = nameSetElemsStable (collectUnusedNames unused)\\n wcs = collectUnusedWildcards unused\\n in (nms, wcs)\\n _other -> ([], []) -- No explicit import list => no unused-name list\\n\\n add_unused :: IE GhcRn -> UnusedNames -> UnusedNames\\n add_unused (IEVar _ n _) acc = add_unused_name (lieWrappedName n) True acc\\n add_unused (IEThingAbs _ n _) acc = add_unused_name (lieWrappedName n) False acc\\n add_unused (IEThingAll _ _ n _) acc = add_unused_all (lieWrappedName n) acc\\n add_unused (IEThingWith _ p wc ns _) acc = add_wc_all (add_unused_with pn xs acc)\\n where pn = lieWrappedName p\\n xs = map lieWrappedName ns\\n add_wc_all = case wc of\\n NoIEWildcard -> id\\n IEWildcard _ -> add_unused_all pn\\n add_unused (IEWholeNamespace x ns_spec) acc = add_unused_wildcard ns_spec (iewn_names x) acc\\n add_unused _ acc = acc\\n\\n add_unused_name :: Name -> Bool -> UnusedNames -> UnusedNames\\n add_unused_name n is_ie_var acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | is_ie_var\\n , isFieldName n\\n -- See Note [Reporting unused imported duplicate record fields]\\n = let\\n fs = getOccFS n\\n (flds, flds_used) = lookupFsEnv acc_fs fs `orElse` (emptyNameSet, Any False)\\n acc_fs\' = extendFsEnv acc_fs fs (extendNameSet flds n, Any used S.<> flds_used)\\n in UnusedNames acc_ns acc_wcs acc_fs\'\\n\\n | used\\n = acc\\n\\n | otherwise\\n = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n where\\n used = isJust $ lookupGRE_Name used_gre_env n\\n\\n add_unused_all :: Name -> UnusedNames -> UnusedNames\\n add_unused_all n acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | Just {} <- lookupGRE_Name used_gre_env n = acc\\n | n `elemNameSet` used_parents = acc\\n | otherwise = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n\\n add_unused_with :: Name -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_with p ns acc\\n | all (`elemNameSet` acc1_ns) ns = add_unused_name p False acc1\\n | otherwise = acc1\\n where\\n acc1@(UnusedNames acc1_ns _ _) = foldr (\\\\n acc\' -> add_unused_name n False acc\') acc ns\\n -- If you use \'signum\' from Num, then the user may well have\\n -- imported Num(signum). We don\'t want to complain that\\n -- Num is not itself mentioned. Hence the two cases in add_unused_with.\\n\\n add_unused_wildcard :: NamespaceSpecifier GhcRn -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_wildcard ns_spec names acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | any_used = acc\\n | otherwise = UnusedNames acc_ns (ns_spec : acc_wcs) acc_fs\\n where\\n -- A wildcard `type ..` or `data ..` is used if at least one of\\n -- the names it expands to is used\\n any_used = any (isJust . lookupGRE_Name used_gre_env) names\\n\\n\\n-- | An accumulator for unused names in an import list.\\n--\\n-- See Note [Reporting unused imported duplicate record fields].\\ndata UnusedNames =\\n UnusedNames\\n { unused_names :: NameSet\\n -- ^ Unused \'Name\'s in an import list, not including record fields\\n -- that are plain \'IEVar\' imports (tracked by \'rec_fld_uses\')\\n -- or wildcard imports (tracked by \'unused_wildcards\').\\n , unused_wildcards :: [NamespaceSpecifier GhcRn]\\n -- ^ Unused wildcards @type ..@ or @data ..@ in an import list.\\n , rec_fld_uses :: FastStringEnv (NameSet, Any)\\n -- ^ Record fields imported without a parent (i.e. an \'IEVar\' import).\\n --\\n -- The \'Any\' value records whether any of the record fields\\n -- sharing the same underlying \'FastString\' have been used.\\n }\\n\\nemptyUnusedNames :: UnusedNames\\nemptyUnusedNames = UnusedNames emptyNameSet [] emptyFsEnv\\n\\ninstance Outputable UnusedNames where\\n ppr (UnusedNames nms wcs flds) =\\n text \\"UnusedNames\\" <+>\\n braces (ppr nms <+> ppr wcs <+> ppr (fmap (second getAny) flds))\\n\\n-- | Collect all unused names from a \'UnusedNames\' value.\\ncollectUnusedNames :: UnusedNames -> NameSet\\ncollectUnusedNames (UnusedNames { unused_names = nms, rec_fld_uses = flds })\\n = nms S.<> unused_flds\\n where\\n unused_flds = nonDetFoldFsEnv collect_unused emptyNameSet flds\\n collect_unused :: (NameSet, Any) -> NameSet -> NameSet\\n collect_unused (nms, Any at_least_one_name_is_used) acc\\n | at_least_one_name_is_used = acc\\n | otherwise = unionNameSet nms acc\\n\\ncollectUnusedWildcards :: UnusedNames -> [NamespaceSpecifier GhcRn]\\ncollectUnusedWildcards = unused_wildcards\\n\\n{- Note [Reporting unused imported duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have (#24035):\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M1 (R1(..), R2(..)) where\\n data R1 = MkR1 { fld :: Int }\\n data R2 = MkR2 { fld :: Int }\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M2 where\\n import M1 (R1(MkR1), R2, fld)\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nIn the import of \'M1\' in \'M2\', the \'fld\' import resolves to two separate GREs,\\nnamely R1(fld) and R2(fld). From the perspective of the renamer, and in particular\\nthe \'findImportUsage\' function, it\'s as if the user had imported the two names\\nseparately (even though no source syntax allows that).\\n\\nThis means that we need to be careful when reporting unused imports: the R2(fld)\\nimport is indeed unused, but because R1(fld) is used, we should not report\\nfld as unused altogether.\\n\\nTo achieve this, we keep track of record field imports without a parent (i.e.\\nusing the IEVar constructor) separately from other import items, using the\\nUnusedNames datatype.\\nOnce we have accumulated usages, we emit warnings for unused record fields\\nwithout parents one whole group (of record fields sharing the same textual name)\\nat a time, and only if *all* of the record fields in the group are unused;\\nsee \'collectUnusedNames\'.\\n\\nNote that this only applies to record fields imported without a parent. If we\\nhad:\\n\\n import M1 (R1(MkR1, fld), R2(fld))\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nthen of course we should report the second \'fld\' as unused.\\n-}\\n\\n\\n{- Note [The ImportMap]\\n~~~~~~~~~~~~~~~~~~~~~~~\\nThe ImportMap is a short-lived intermediate data structure records, for\\neach import declaration, what stuff brought into scope by that\\ndeclaration is actually used in the module.\\n\\nThe [GlobalRdrElt] are the things imported from that decl.\\n-}\\n\\ndata ImportMap = ImportMap\\n { im_imports :: Map RealSrcSpan [GlobalRdrElt]\\n -- ^ See [The ImportMap]\\n -- If loc :-> gres, then\\n -- \'loc\' = the end loc of the bestImport of each GRE in \'gres\'\\n , im_generatedImports :: Map ModuleName [GlobalRdrElt]\\n }\\n\\nmkImportMap :: [GlobalRdrElt] -> ImportMap\\n-- For each of a list of used GREs, find all the import decls that brought\\n-- it into scope; choose one of them (bestImport), and record\\n-- the RdrName in that import decl\'s entry in the ImportMap\\nmkImportMap = foldr insertImportMap $ ImportMap Map.empty Map.empty\\n\\ninsertImportMap :: GlobalRdrElt -> ImportMap -> ImportMap\\ninsertImportMap gre@(GRE { gre_imp = imp_specs }) importMap\\n | RealSrcSpan importSpan _ <- is_dloc best_imp_spec =\\n importMap{im_imports = insertElem importSpan gre $ im_imports importMap}\\n | GeneratedSrcSpan{} <- is_dloc best_imp_spec =\\n importMap{im_generatedImports = insertElem (moduleName $ is_mod best_imp_spec) gre $ im_generatedImports importMap}\\n | otherwise = importMap\\n where\\n best_imp_spec =\\n case bagToList imp_specs of\\n [] -> pprPanic \\"mkImportMap: GRE with no ImportSpecs\\" (ppr gre)\\n is:iss -> is_decl $ bestImport (is NE.:| iss)\\n\\n -- https://github.com/haskell/containers/issues/784\\n insertElem :: Ord k => k -> v -> Map k [v] -> Map k [v]\\n insertElem k v = flip Map.alter k $ \\\\case\\n Just vs -> Just (v : vs)\\n Nothing -> Just [v]\\n\\nlookupImportMap :: LImportDecl GhcRn -> ImportMap -> [GlobalRdrElt]\\nlookupImportMap (L srcSpan ImportDecl{ideclName = L _ modName}) importMap =\\n fromMaybe [] $\\n -- should match logic in insertImportMap\\n case locA srcSpan of\\n RealSrcSpan realSrcSpan _ -> realSrcSpan `Map.lookup` im_imports importMap\\n GeneratedSrcSpan{} -> modName `Map.lookup` im_generatedImports importMap\\n _ -> Nothing\\n\\nlieNames :: LIE (GhcPass p) -> [Located (IdP (GhcPass p))]\\nlieNames = _\\n\\nwarnUnusedImport :: GlobalRdrEnv -> ImportDeclUsage -> RnM ()\\nwarnUnusedImport rdr_env (L loc decl, used, unused, unused_wcs)\\n\\n -- Do not warn for \'import M()\'\\n -- See (UI1) in Note [Unused imports]\\n | Just (Exactly, _) <- ideclImportList decl\\n , null unused && null unused_wcs\\n = return ()\\n\\n -- Note [Do not warn about Prelude hiding]\\n | Just (EverythingBut, hides) <- ideclImportList decl\\n , not (null hides)\\n , pRELUDE_NAME == unLoc (ideclName decl)\\n = return ()\\n\\n -- Do not warn about import X as Rebindable\\n -- See (UI2) in Note [Unused imports]\\n | Just (L _ mod) <- ideclAs decl\\n , mod == rEBINDABLE_MOD_NAME\\n = return ()\\n\\n -- Nothing used; drop entire declaration\\n | null used\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl UnusedImportNone)\\n\\n -- Everything imported is used; nop\\n | null unused && null unused_wcs\\n = return ()\\n\\n -- Some imports are unused: make the `SrcSpan` cover only the unused\\n -- items instead of the whole import statement\\n | Just (_, imports) <- ideclImportList decl\\n , let unused_locs = [ locA loc | L loc ie <- imports\\n , name <- ieNames ie\\n , name `elem` unused ]\\n , loc1 : locs <- unused_locs\\n , let span = foldr1 combineSrcSpans ( loc1 NE.:| locs )\\n = addDiagnosticAt span (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n -- Some imports are unused\\n | otherwise\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n where\\n -- In warning message, pretty-print identifiers unqualified unconditionally\\n -- to improve the consistent for ambiguous/unambiguous identifiers.\\n -- See #14881.\\n possible_field n =\\n case lookupGRE_Name rdr_env n of\\n Just (GRE { gre_par = par, gre_info = IAmRecField info }) ->\\n let fld_occ :: OccName\\n fld_occ = nameOccName $ flSelector $ recFieldLabel info\\n in UnusedImportNameRecField par fld_occ\\n _ -> UnusedImportNameRegular n\\n\\n -- Print unused names in a deterministic (lexicographic) order\\n sort_unused :: [UnusedImportName]\\n sort_unused =\\n [ UnusedImportWildcard wc | wc <- unused_wcs ] ++\\n [ possible_field nm | nm <- sortBy (comparing nameOccName) unused ]\\n\\ngetMinimalImports :: [ImportDeclUsage] -> RnM [LImportDecl GhcRn]\\ngetMinimalImports ie_decls\\n = do { rdr_env <- getGlobalRdrEnv\\n ; fmap combine $ mapM (mk_minimal rdr_env) ie_decls }\\n where\\n mk_minimal rdr_env (L l decl, used_gres, unused, unused_wcs)\\n | null unused && null unused_wcs\\n , Just (Exactly, _) <- ideclImportList decl\\n = return (L l decl)\\n | otherwise\\n = do { let ImportDecl { ideclName = L _ mod_name\\n , ideclSource = is_boot\\n , ideclPkgQual = pkg_qual\\n , ideclExt = XImportDeclPass { ideclOrigin = origin } } = decl\\n ; iface <- loadSrcInterface doc (importDeclLookupScope origin)\\n mod_name is_boot pkg_qual\\n ; let used_avails = gresToAvailInfo used_gres\\n ; lies <- map (L l) <$> concatMapM (to_ie rdr_env iface) used_avails\\n ; return (L l (decl { ideclImportList = Just (Exactly, lies) })) }\\n where\\n doc = text \\"Compute minimal imports for\\" <+> ppr decl\\n\\n to_ie :: GlobalRdrEnv -> ModIface -> AvailInfo -> RnM [IE GhcRn]\\n -- The main trick here is that if we\'re importing all the constructors\\n -- we want to say \\"T(..)\\", but if we\'re importing only a subset we want\\n -- to say \\"T(A,B,C)\\". So we have to find out what the module exports.\\n to_ie rdr_env _ (Avail c) -- Note [Overloaded field import]\\n = do { let\\n gre = expectJust $ lookupGRE_Name rdr_env c\\n ; return $ [IEVar Nothing (to_ie_post_rn $ noLocA $ greName gre) Nothing] }\\n to_ie _ _ avail@(AvailTC n [_]) -- Exporting the main decl and nothing else\\n | availExportsDecl avail\\n = return [IEThingAbs Nothing (to_ie_post_rn $ noLocA n) Nothing]\\n to_ie rdr_env iface (AvailTC n cs) =\\n case [ xs | avail@(AvailTC x xs) <- mi_exports iface\\n , x == n\\n , availExportsDecl avail -- Note [Partial export]\\n ] of\\n [xs]\\n | all_used xs\\n -> return [IEThingAll (IEThingAllExt Nothing noAnn noAnn noAnn)\\n (NoNamespaceSpecifier noExtField)\\n (to_ie_post_rn $ noLocA n)\\n Nothing]\\n | otherwise\\n -> do { let ns_gres = map (expectJust . lookupGRE_Name rdr_env) cs\\n ns = map greName ns_gres\\n ; return [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n -- Note [Overloaded field import]\\n _other\\n -> do { let infos = map (expectJust . lookupGRE_Name rdr_env) cs\\n (ns_gres,fs_gres) = classifyGREs infos\\n ns = map greName (ns_gres ++ fs_gres)\\n fs = map fieldGREInfo fs_gres\\n ; return $\\n if all_non_overloaded fs\\n then map (\\\\nm -> IEVar Nothing (to_ie_post_rn_var $ noLocA nm) Nothing) ns\\n else [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n where\\n\\n all_used avail_cs = all (`elem` cs) avail_cs\\n\\n all_non_overloaded = all (not . flIsOverloaded . recFieldLabel)\\n\\n combine :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\n combine = map merge . NE.groupAllWith getKey\\n\\n getKey :: LImportDecl GhcRn -> (Bool, Maybe ModuleName, ModuleName)\\n getKey decl =\\n ( isImportDeclQualified . ideclQualified $ idecl -- is this qualified? (important that this be first)\\n , unLoc <$> ideclAs idecl -- what is the qualifier (inside Maybe monad)\\n , unLoc . ideclName $ idecl -- Module Name\\n )\\n where\\n idecl :: ImportDecl GhcRn\\n idecl = unLoc decl\\n\\n merge :: NonEmpty (LImportDecl GhcRn) -> LImportDecl GhcRn\\n merge decls@((L l decl) :| _) = L l (decl { ideclImportList = Just (Exactly, lies) })\\n where lies = concatMap snd $ mapMaybe (ideclImportList . unLoc) $ NE.toList decls\\n\\nclassifyGREs :: [GlobalRdrElt] -> ([GlobalRdrElt], [FieldGlobalRdrElt])\\nclassifyGREs = partition (not . isRecFldGRE)\\n\\nprintMinimalImports :: HscSource -> [ImportDeclUsage] -> RnM ()\\n-- See Note [Printing minimal imports]\\nprintMinimalImports hsc_src imports_w_usage\\n = do { imports\' <- excludeGenerated <$> getMinimalImports imports_w_usage\\n ; this_mod <- getModule\\n ; dflags <- getDynFlags\\n ; liftIO $ withFile (mkFilename dflags this_mod) WriteMode $ \\\\h ->\\n printForUser dflags h neverQualify AllTheWay (vcat (map ppr imports\'))\\n -- The neverQualify is important. We are printing Names\\n -- but they are in the context of an \'import\' decl, and\\n -- we never qualify things inside there\\n -- E.g. import Blag( f, b )\\n -- not import Blag( Blag.f, Blag.g )!\\n }\\n where\\n mkFilename dflags this_mod\\n | Just d <- dumpDir dflags = d basefn\\n | otherwise = basefn\\n where\\n suffix = case hsc_src of\\n HsBootFile -> \\".imports-boot\\"\\n HsSrcFile -> \\".imports\\"\\n HsigFile -> \\".imports\\"\\n basefn = moduleNameString (moduleName this_mod) ++ suffix\\n\\n\\nto_ie_post_rn_var :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn_var (L l n)\\n | isDataOcc $ occName n = L l (IEPattern noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n\\n\\nto_ie_post_rn :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn (L l n)\\n | isTcOcc occ && isSymOcc occ = L l (IEType noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n where occ = occName n\\n\\n{- Note [Do not warn about Prelude hiding]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWe do not warn about\\n import Prelude hiding( x, y )\\nbecause even if nothing else from Prelude is used, it may be essential to hide\\nx,y to avoid name-shadowing warnings. Example (#9061)\\n import Prelude hiding( log )\\n f x = log where log = ()\\n\\nNote [Unused imports]\\n~~~~~~~~~~~~~~~~~~~~~\\nIn `warnUnusedImport`, if we see an import with an explicit list imports, thus\\n import M( a, b )\\nand neither `a` nor `b` is used, we report the entire import decl as unused. We\\ncheck this by looking at the names that it brings into scope scope; if there are\\nno ununused names, don\'t report.\\n\\n(UI1) We don\'t want to complain about `import M()`, because that is often used to bring\\n M\'s /instances/ into scope. That is neatly dealt with by the \\"no unused\\n names\\" (nor unused wildcard imports) criterion.\\n\\n(UI2) We don\'t report a decl as unused if it has an `as Rebindable` qualifier.\\n See (KN1) in Note [Overview of known entities] in GHC.Builtin\\n\\n\\nNote [Printing minimal imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nTo print the minimal imports we walk over all import decls (both user-supplied\\nand generated), trim their import lists, then filter out generated decls.\\n\\nNB that\\n\\n * We do *not* change the \'qualified\' or \'as\' parts!\\n\\n * We do not discard a decl altogether; we might need instances\\n from it. Instead we just trim to an empty import list\\n\\nNote [Partial export]\\n~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have\\n\\n module A( op ) where\\n class C a where\\n op :: a -> a\\n\\n module B where\\n import A\\n f = ..op...\\n\\nThen the minimal import for module B is\\n import A( op )\\nnot\\n import A( C( op ) )\\nwhich we would usually generate if C was exported from B. Hence\\nthe availExportsDecl test when deciding what to generate.\\n\\n\\nNote [Overloaded field import]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nOn the other hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n data T = MkT { foo :: Int }\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( T(foo) )\\nbecause when DuplicateRecordFields is enabled, field selectors are\\nnot in scope without their enclosing datatype.\\n\\nOn the third hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n pattern MkT { foo } = Just foo\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( foo )\\nbecause foo doesn\'t have a parent. This might actually be ambiguous if A\\nexports another field called foo, but there is no good answer to return and this\\nis a very obscure corner, so it seems to be the best we can do. See\\nDRFPatSynExport for a test of this.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Errors}\\n* *\\n************************************************************************\\n-}\\n\\nbadImportItemErr\\n :: ModIface -> ImpDeclSpec -> IE GhcPs\\n -> IsSubordinateError\\n -> [AvailInfo]\\n -> TcRn (NonEmpty ImportLookupReason)\\nbadImportItemErr iface decl_spec ie sub avails = do\\n exts <- importLookupExtensions\\n let import_lookup_bad :: BadImportKind -> ImportLookupReason\\n import_lookup_bad k = ImportLookupBad k iface decl_spec ie exts\\n dflags <- getDynFlags\\n hsc_env <- getTopEnv\\n let rdr_env = mkGlobalRdrEnv\\n $ gresFromAvails hsc_env (Just imp_spec) all_avails\\n pure $ fmap import_lookup_bad (importErrorKind dflags rdr_env)\\n where\\n importErrorKind :: DynFlags -> GlobalRdrEnv -> NonEmpty BadImportKind\\n importErrorKind dflags rdr_env\\n | any checkIfTyCon avails = case sub of\\n IsNotSubordinate -> NE.singleton BadImportAvailTyCon\\n IsSubordinateError { subordinate_err_parent = gre\\n , subordinate_err_unavailable = unavailable\\n , subordinate_err_nontype = nontype\\n , subordinate_err_nondata = nondata }\\n -> NE.fromList $ catMaybes $\\n [ fmap (BadImportNotExportedSubordinates gre) (NE.nonEmpty unavailable)\\n , fmap (BadImportNonTypeSubordinates gre) (NE.nonEmpty nontype)\\n , fmap (BadImportNonDataSubordinates gre) (NE.nonEmpty nondata) ]\\n | any checkIfVarName avails = NE.singleton BadImportAvailVar\\n | Just con <- find checkIfDataCon avails = NE.singleton (BadImportAvailDataCon (availOccName con))\\n | otherwise = NE.singleton (BadImportNotExported suggs)\\n where\\n suggs = similar_suggs ++ fieldSelectorSuggestions rdr_env rdr\\n what_look = case sub of\\n IsNotSubordinate -> WL_TyCon_or_TermVar\\n IsSubordinateError { subordinate_err_parent = gre } ->\\n case greInfo gre of\\n IAmTyCon ClassFlavour\\n -> WL_TyCon_or_TermVar\\n _ -> WL_Term\\n similar_names =\\n similarNameSuggestions (Unbound.LF what_look WL_Global)\\n dflags rdr_env emptyLocalRdrEnv rdr\\n similar_suggs =\\n case NE.nonEmpty $ mapMaybe imported_item $ similar_names of\\n Just similar -> [ SuggestSimilarNames rdr similar ]\\n Nothing -> [ ]\\n\\n -- Only keep imported items, and set the \\"HowInScope\\" to\\n -- \\"Nothing\\" to avoid printing \\"imported from...\\" in the suggestion\\n -- error message.\\n imported_item (SimilarRdrName rdr_name gre (Just (ImportedBy {})))\\n = Just (SimilarRdrName rdr_name gre Nothing)\\n imported_item _ = Nothing\\n\\n checkIfDataCon = checkIfAvailMatches isDataConName\\n checkIfTyCon = checkIfAvailMatches isTyConName\\n checkIfVarName =\\n \\\\case\\n AvailTC{} -> False\\n Avail n -> importedFS == occNameFS (occName n)\\n && (isVarOcc <||> isFieldOcc) (occName n)\\n checkIfAvailMatches namePred =\\n \\\\case\\n AvailTC _ ns ->\\n case find (\\\\n -> importedFS == occNameFS (occName n)) ns of\\n Just n -> namePred n\\n Nothing -> False\\n Avail{} -> False\\n availOccName = occName . availName\\n rdr = ieName ie\\n importedFS = occNameFS $ rdrNameOcc rdr\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n all_avails = mi_exports iface\\n\\nimportLookupExtensions :: TcRn ImportLookupExtensions\\nimportLookupExtensions = do\\n ile_pattern_synonyms <- xoptM LangExt.PatternSynonyms\\n ile_explicit_namespaces <- xoptM LangExt.ExplicitNamespaces\\n return ImportLookupExtensions{ile_pattern_synonyms, ile_explicit_namespaces}\\n\\naddDupDeclErr :: NonEmpty GlobalRdrElt -> TcRn ()\\naddDupDeclErr gres@(gre :| _)\\n -- Report the error at the later location\\n = addErrAt (getSrcSpan (NE.last sorted_names)) $ (TcRnDuplicateDecls (greOccName gre) sorted_names)\\n where\\n sorted_names =\\n NE.sortBy (SrcLoc.leftmost_smallest `on` nameSrcSpan)\\n (fmap greName gres)\\n\\n-- This data decl will parse OK\\n-- data T = a Int\\n-- treating \\"a\\" as the constructor.\\n-- It is really hard to make the parser spot this malformation.\\n-- So the renamer has to check that the constructor is legal\\n--\\n-- We can get an operator as the constructor, even in the prefix form:\\n-- data T = :% Int Int\\n-- from interface files, which always print in prefix form\\n--\\n-- We also allow type constructor names, which are defined by \\"type data\\"\\n-- declarations. See Note [Type data declarations] in GHC.Rename.Module.\\n\\ncheckConName :: RdrName -> TcRn ()\\ncheckConName name\\n = checkErr (isRdrDataCon name || isRdrTc name) (TcRnIllegalDataCon name)\\n", "filetypes": ["haskell"]}}}' 2026-10-16 14:48:41,703 - DEBUG - POST b'http://127.0.0.1:37093/receive_messages' {'content-type': 'application/json', 'x-ycm-hmac': b'Rga7Yd4l4fgfufwYw+0sxzurvznImlBO0MPmgAlS4EY='} b'{"filepath": "/home/enrico/ghc/compiler/GHC/Rename/Names.hs", "line_num": 1, "column_num": 1, "working_dir": "/home/enrico/ghc", "file_data": {"/home/enrico/ghc/compiler/GHC/Rename/Names.hs": {"contents": "{-\\n(c) The GRASP/AQUA Project, Glasgow University, 1992-1998\\n\\nExtracting imported and top-level names in scope\\n-}\\n\\n{-# LANGUAGE NondecreasingIndentation #-}\\n{-# LANGUAGE TypeFamilies #-}\\n\\nmodule GHC.Rename.Names (\\n rnImports, getLocalNonValBinders, newRecordFieldLabel,\\n importsFromIface,\\n ImportUserSpec(..),\\n extendGlobalRdrEnvRn,\\n gresFromAvails,\\n calculateAvails,\\n reportUnusedNames,\\n checkConName,\\n mkChildEnv,\\n findChildren,\\n mkBadExportSubordinate,\\n findImportUsage,\\n getMinimalImports,\\n printMinimalImports,\\n renamePkgQual, renameRawPkgQual,\\n classifyGREs,\\n ImportDeclUsage,\\n rnNamespaceSpecifier\\n ) where\\n\\nimport GHC.Prelude hiding ( head, init, last, tail )\\n\\nimport GHC.Driver.Env\\nimport GHC.Driver.Session\\nimport GHC.Driver.Ppr\\n\\nimport GHC.Rename.Env\\nimport GHC.Rename.Fixity\\nimport GHC.Rename.Utils ( warnUnusedTopBinds )\\nimport GHC.Rename.Unbound\\nimport qualified GHC.Rename.Unbound as Unbound\\n\\nimport GHC.Tc.Errors.Types\\nimport GHC.Tc.Utils.Env\\nimport GHC.Tc.Utils.Monad\\nimport GHC.Tc.Types.LclEnv\\nimport GHC.Tc.Zonk.TcType ( tcInitTidyEnv )\\n\\nimport GHC.Hs\\nimport GHC.Iface.Load ( loadSrcInterface, loadSrcInterface_maybe )\\nimport GHC.Iface.Errors.Types\\n ( IfaceMessage(..), MissingInterfaceError, InterfaceLookingFor(..)\\n , LoadEssentialsReason(..) )\\nimport GHC.Iface.Syntax ( fromIfaceWarnings )\\nimport GHC.Builtin.Modules( pRELUDE_NAME, rEBINDABLE_MOD_NAME )\\nimport GHC.Parser.PostProcess ( setRdrNameSpace )\\nimport GHC.Core.TyCo.Tidy\\nimport GHC.Core.PatSyn\\nimport GHC.Core.TyCon ( TyCon, tyConName )\\nimport qualified GHC.LanguageExtensions as LangExt\\n\\nimport GHC.Utils.Outputable as Outputable\\nimport GHC.Utils.Misc as Utils\\nimport GHC.Utils.Panic\\n\\nimport GHC.Types.Fixity.Env\\nimport GHC.Types.SafeHaskell\\nimport GHC.Types.Name\\nimport GHC.Types.Name.Env\\nimport GHC.Types.Name.Set\\nimport GHC.Types.Name.Reader\\nimport GHC.Types.Avail\\nimport GHC.Types.FieldLabel\\nimport GHC.Types.Hint\\nimport GHC.Types.SourceFile\\nimport GHC.Types.SrcLoc as SrcLoc\\nimport GHC.Types.Basic (TyConFlavour (..), convImportLevel, VisArity)\\nimport GHC.Types.UnresolvedImport\\nimport GHC.Types.Id\\nimport GHC.Types.PkgQual\\nimport GHC.Types.GREInfo (ConInfo(..), ConFieldInfo (..), ConLikeInfo (ConIsData))\\n\\nimport GHC.Unit\\nimport GHC.Unit.Module.Warnings\\nimport GHC.Unit.Module.ModIface\\nimport GHC.Unit.Module.Imported\\nimport GHC.Unit.Module.Deps\\nimport GHC.Unit.Env\\n\\nimport GHC.Data.Bag\\nimport GHC.Data.FastString\\nimport GHC.Data.FastString.Env\\nimport GHC.Data.Maybe\\nimport GHC.Data.List.SetOps ( removeDups )\\n\\nimport Control.Arrow ( second )\\nimport Control.Monad\\nimport Data.Foldable ( for_ )\\nimport Data.IntMap ( IntMap )\\nimport qualified Data.IntMap as IntMap\\nimport Data.Map ( Map )\\nimport qualified Data.Map as Map\\nimport Data.Ord ( comparing )\\nimport Data.Semigroup ( Any(..) )\\nimport qualified Data.Semigroup as S\\nimport Data.List ( partition, find, sortBy )\\nimport Data.List.NonEmpty (NonEmpty(..))\\nimport qualified Data.List.NonEmpty as NE\\nimport Data.Function ( on )\\nimport qualified Data.Set as S\\nimport System.FilePath (())\\nimport System.IO\\n\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{rnImports}\\n* *\\n************************************************************************\\n\\nNote [Tracking Trust Transitively]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen we import a package as well as checking that the direct imports are safe\\naccording to the rules outlined in the Note [Safe Haskell Trust Check] in GHC.Driver.Main\\nwe must also check that these rules hold transitively for all dependent modules\\nand packages. Doing this without caching any trust information would be very\\nslow as we would need to touch all packages and interface files a module depends\\non. To avoid this we make use of the property that if a modules Safe Haskell\\nmode changes, this triggers a recompilation from that module in the dependency\\ngraph. So we can just worry mostly about direct imports.\\n\\nThere is one trust property that can change for a package though without\\nrecompilation being triggered: package trust. So we must check that all\\npackages a module transitively depends on to be trusted are still trusted when\\nwe are compiling this module (as due to recompilation avoidance some modules\\nbelow may not be considered trusted any more without recompilation being\\ntriggered).\\n\\nWe handle this by augmenting the existing transitive list of packages a module M\\ndepends on with a bool for each package that says if it must be trusted when the\\nmodule M is being checked for trust. This list of trust required packages for a\\nsingle import is gathered in the rnImportDecl function and stored in an\\nImportAvails data structure. The union of these trust required packages for all\\nimports is done by the rnImports function using the combine function which calls\\nthe plusImportAvails function that is a union operation for the ImportAvails\\ntype. This gives us in an ImportAvails structure all packages required to be\\ntrusted for the module we are currently compiling. Checking that these packages\\nare still trusted (and that direct imports are trusted) is done in\\nGHC.Driver.Main.checkSafeImports.\\n\\nSee the note below, [Trust Own Package] for a corner case in this method and\\nhow its handled.\\n\\n\\nNote [Trust Own Package]\\n~~~~~~~~~~~~~~~~~~~~~~~~\\nThere is a corner case of package trust checking that the usual transitive check\\ndoesn\'t cover. (For how the usual check operates see the Note [Tracking Trust\\nTransitively] below). The case is when you import a -XSafe module M and M\\nimports a -XTrustworthy module N. If N resides in a different package than M,\\nthen the usual check works as M will record a package dependency on N\'s package\\nand mark it as required to be trusted. If N resides in the same package as M\\nthough, then importing M should require its own package be trusted due to N\\n(since M is -XSafe so doesn\'t create this requirement by itself). The usual\\ncheck fails as a module doesn\'t record a package dependency of its own package.\\nSo instead we now have a bool field in a modules interface file that simply\\nstates if the module requires its own package to be trusted. This field avoids\\nus having to load all interface files that the module depends on to see if one\\nis trustworthy.\\n\\n\\nNote [Trust Transitive Property]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSo there is an interesting design question in regards to transitive trust\\nchecking. Say I have a module B compiled with -XSafe. B is dependent on a bunch\\nof modules and packages, some packages it requires to be trusted as its using\\n-XTrustworthy modules from them. Now if I have a module A that doesn\'t use safe\\nhaskell at all and simply imports B, should A inherit all the trust\\nrequirements from B? Should A now also require that a package p is trusted since\\nB required it?\\n\\nWe currently say no but saying yes also makes sense. The difference is, if a\\nmodule M that doesn\'t use Safe Haskell imports a module N that does, should all\\nthe trusted package requirements be dropped since M didn\'t declare that it cares\\nabout Safe Haskell (so -XSafe is more strongly associated with the module doing\\nthe importing) or should it be done still since the author of the module N that\\nuses Safe Haskell said they cared (so -XSafe is more strongly associated with\\nthe module that was compiled that used it).\\n\\nGoing with yes is a simpler semantics we think and harder for the user to stuff\\nup but it does mean that Safe Haskell will affect users who don\'t care about\\nSafe Haskell as they might grab a package from Cabal which uses safe haskell (say\\nnetwork) and that packages imports -XTrustworthy modules from another package\\n(say bytestring), so requires that package is trusted. The user may now get\\ncompilation errors in code that doesn\'t do anything with Safe Haskell simply\\nbecause they are using the network package. They will have to call \'ghc-pkg\\ntrust network\' to get everything working. Due to this invasive nature of going\\nwith yes we have gone with no for now.\\n-}\\n\\n-- | Process Import Decls. See \'rnImportDecl\' for a description of what\\n-- the return types represent.\\n-- Note: Do the non SOURCE ones first, so that we get a helpful warning\\n-- for SOURCE ones that are unnecessary\\nrnImports :: [(LImportDecl GhcPs, SDoc)]\\n -> RnM ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\nrnImports imports = do\\n tcg_env <- getGblEnv\\n -- NB: want an identity module here, because it\'s OK for a signature\\n -- module to import from its implementor\\n let this_mod = tcg_mod tcg_env\\n let (source, ordinary) = partition (is_source_import . fst) imports\\n is_source_import (d::LImportDecl GhcPs) = ideclSource (unLoc d) == IsBoot\\n stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary\\n stuff2 <- mapAndReportM (rnImportDecl this_mod) source\\n -- Safe Haskell: See Note [Tracking Trust Transitively]\\n let (decls, imp_user_spec, rdr_env, imp_avails) = combine (stuff1 ++ stuff2)\\n -- Update imp_boot_mods if imp_direct_mods mentions any of them\\n let merged_import_avail = clobberSourceImports imp_avails\\n return (decls, imp_user_spec, rdr_env, merged_import_avail)\\n\\n where\\n clobberSourceImports imp_avails =\\n imp_avails { imp_boot_mods = imp_boot_mods\' }\\n where\\n imp_boot_mods\' = mergeInstalledModuleEnv combJ id (const emptyInstalledModuleEnv)\\n (imp_boot_mods imp_avails)\\n (imp_direct_dep_mods imp_avails)\\n\\n combJ (GWIB _ IsBoot) (_, x) = Just x\\n combJ r _ = Just r\\n -- See Note [Combining ImportAvails]\\n combine :: [(LImportDecl GhcRn, ImportUserSpec, GlobalRdrEnv, ImportAvails)]\\n -> ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\n combine ss =\\n let (decls, imp_user_spec, rdr_env, imp_avails, finsts) = foldr\\n plus\\n ([], [], emptyGlobalRdrEnv, emptyImportAvails, emptyModuleSet)\\n ss\\n in (decls, imp_user_spec, rdr_env, imp_avails { imp_finsts = moduleSetElts finsts })\\n\\n plus (decl, us, gbl_env1, imp_avails1)\\n (decls, uss, gbl_env2, imp_avails2, finsts_set)\\n = ( decl:decls,\\n us:uss,\\n gbl_env1 `plusGlobalRdrEnv` gbl_env2,\\n imp_avails1\' `plusImportAvails` imp_avails2,\\n extendModuleSetList finsts_set new_finsts )\\n where\\n imp_avails1\' = imp_avails1 { imp_finsts = [] }\\n new_finsts = imp_finsts imp_avails1\\n\\n{-\\nNote [Combining ImportAvails]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nimp_finsts in ImportAvails is a list of family instance modules\\ntransitively depended on by an import. imp_finsts for a currently\\ncompiled module is a union of all the imp_finsts of imports.\\nComputing the union of two lists of size N is O(N^2) and if we\\ndo it to M imports we end up with O(M*N^2). That can get very\\nexpensive for bigger module hierarchies.\\n\\nUnion can be optimized to O(N log N) if we use a Set.\\nimp_finsts is converted back and forth between dep_finsts, so\\nchanging a type of imp_finsts means either paying for the conversions\\nor changing the type of dep_finsts as well.\\n\\nI\'ve measured that the conversions would cost 20% of allocations on my\\ntest case, so that can be ruled out.\\n\\nChanging the type of dep_finsts forces checkFamInsts to\\nget the module lists in non-deterministic order. If we wanted to restore\\nthe deterministic order, we\'d have to sort there, which is an additional\\ncost. As far as I can tell, using a non-deterministic order is fine there,\\nbut that\'s a brittle nonlocal property which I\'d like to avoid.\\n\\nAdditionally, dep_finsts is read from an interface file, so its \\"natural\\"\\ntype is a list. Which makes it a natural type for imp_finsts.\\n\\nSince rnImports.combine is really the only place that would benefit from\\nit being a Set, it makes sense to optimize the hot loop in rnImports.combine\\nwithout changing the representation.\\n\\nSo here\'s what we do: instead of naively merging ImportAvails with\\nplusImportAvails in a loop, we make plusImportAvails merge empty imp_finsts\\nand compute the union on the side using Sets. When we\'re done, we can\\nconvert it back to a list. One nice side effect of this approach is that\\nif there\'s a lot of overlap in the imp_finsts of imports, the\\nSet doesn\'t really need to grow and we don\'t need to allocate.\\n\\nRunning generateModules from #14693 with DEPTH=16, WIDTH=30 finishes in\\n23s before, and 11s after.\\n-}\\n\\n-- | Given a located import declaration @decl@ from @this_mod@,\\n-- calculate the following pieces of information:\\n--\\n-- 1. An updated \'LImportDecl\', where all unresolved \'RdrName\' in\\n-- the entity lists have been resolved into \'Name\'s,\\n--\\n-- 2. A \'GlobalRdrEnv\' representing the new identifiers that were\\n-- brought into scope (taking into account module qualification\\n-- and hiding),\\n--\\n-- 3. \'ImportAvails\' summarizing the identifiers that were imported\\n-- by this declaration, and\\n--\\n-- 4. A boolean \'AnyHpcUsage\' which is true if the imported module\\n-- used HPC.\\nrnImportDecl :: Module -> (LImportDecl GhcPs, SDoc)\\n -> RnM (LImportDecl GhcRn, ImportUserSpec , GlobalRdrEnv, ImportAvails)\\nrnImportDecl this_mod\\n (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name\\n , ideclPkgQual = raw_pkg_qual\\n , ideclSource = want_boot\\n , ideclSafe = mod_safe\\n , ideclLevelSpec = import_level\\n , ideclQualified = qual_style\\n , ideclExt = XImportDeclPass { ideclOrigin = origin }\\n , ideclAs = as_mod, ideclImportList = imp_details }), import_reason)\\n = setSrcSpanA loc $ do\\n\\n case raw_pkg_qual of\\n NoRawPkgQual -> pure ()\\n RawPkgQual {} -> do\\n pkg_imports <- xoptM LangExt.PackageImports\\n when (not pkg_imports) $ addErr TcRnPackageImportsDisabled\\n\\n let qual_only = isImportDeclQualified qual_style\\n generated = isGeneratedImport origin\\n\\n lookup_scope = importDeclLookupScope origin\\n\\n -- If there\'s an error in loadInterface, (e.g. interface\\n -- file not found) we get lots of spurious errors from \'filterImports\'\\n let imp_mod_name = unLoc loc_imp_mod_name\\n doc = ppr imp_mod_name <+> import_reason\\n\\n hsc_env <- getTopEnv\\n unit_env <- hsc_unit_env <$> getTopEnv\\n let pkg_qual = renameRawPkgQual unit_env imp_mod_name raw_pkg_qual\\n\\n -- Check for self-import, which confuses the typechecker (#9032)\\n -- ghc --make rejects self-import cycles already, but batch-mode may not\\n -- at least not until GHC.IfaceToCore.tcHiBootIface, which is too late to avoid\\n -- typechecker crashes. (Indirect self imports are not caught until\\n -- GHC.IfaceToCore, see #10337 tracking how to make this error better.)\\n --\\n -- Originally, we also allowed \'import {-# SOURCE #-} M\', but this\\n -- caused bug #10182: in one-shot mode, we should never load an hs-boot\\n -- file for the module we are compiling into the EPS. In principle,\\n -- it should be possible to support this mode of use, but we would have to\\n -- extend Provenance to support a local definition in a qualified location.\\n -- For now, we don\'t support it, but see #10336\\n when (imp_mod_name == moduleName this_mod &&\\n (case pkg_qual of -- If we have import \\"\\" M, then we should\\n -- check that \\"\\" is \\"this\\" (which is magic)\\n -- or the name of this_mod\'s package. Yurgh!\\n -- c.f. GHC.findModule, and #9997\\n NoPkgQual -> True\\n ThisPkg uid -> uid == homeUnitId_ (hsc_dflags hsc_env)\\n OtherPkg _ -> False))\\n (addErr (TcRnSelfImport imp_mod_name))\\n\\n -- Check for a missing import list (Opt_WarnMissingImportList also\\n -- checks for T(..) items but that is done in checkDodgyImport below)\\n case imp_details of\\n Just (Exactly, _) -> return () -- Explicit import list\\n _ | generated -> return () -- Do not bleat for generated imports\\n | qual_only -> return ()\\n | otherwise -> addDiagnostic (TcRnNoExplicitImportList imp_mod_name)\\n\\n\\n mb_iface <- loadSrcInterface_maybe doc lookup_scope imp_mod_name want_boot pkg_qual\\n iface <- case mb_iface of\\n Succeeded iface -> return iface\\n Failed err -> failWithTc $\\n importDeclLoadFailure origin imp_mod_name want_boot err\\n\\n -- Compiler sanity check: if the import didn\'t say\\n -- {-# SOURCE #-} we should not get a hi-boot file\\n warnPprTrace ((want_boot == NotBoot) && (mi_boot iface == IsBoot)) \\"rnImportDecl\\" (ppr imp_mod_name) $ do\\n\\n -- Issue a user warning for a redundant {- SOURCE -} import\\n -- NB that we arrange to read all the ordinary imports before\\n -- any of the {- SOURCE -} imports.\\n --\\n -- in --make and GHCi, the compilation manager checks for this,\\n -- and indeed we shouldn\'t do it here because the existence of\\n -- the non-boot module depends on the compilation order, which\\n -- is not deterministic. The hs-boot test can show this up.\\n dflags <- getDynFlags\\n warnIf ((want_boot == IsBoot) && (mi_boot iface == NotBoot) && isOneShot (ghcMode dflags))\\n (TcRnRedundantSourceImport imp_mod_name)\\n when (mod_safe && not (safeImportsOn dflags)) $\\n addErr (TcRnSafeImportsDisabled imp_mod_name)\\n\\n let imp_mod = mi_module iface\\n qual_mod_name = fmap unLoc as_mod `orElse` imp_mod_name\\n imp_spec = ImpDeclSpec { is_mod = imp_mod, is_qual = qual_only,\\n is_dloc = locA loc, is_as = qual_mod_name,\\n is_pkg_qual = pkg_qual, is_isboot = want_boot,\\n is_level = convImportLevel import_level }\\n\\n let filter_imports = do\\n -- filter the imports according to the import declaration\\n (new_imp_details, imp_user_list, gbl_env)\\n <- filterImports hsc_env iface imp_spec imp_details\\n -- for certain error messages, we\\u2019d like to know what could be\\n -- imported here, if everything were imported\\n potential_gres <- (\\\\(_,_,x) -> x) <$> filterImports hsc_env iface imp_spec Nothing\\n return (new_imp_details, imp_user_list, gbl_env, potential_gres)\\n\\n (new_imp_details, imp_user_list, gbl_env, potential_gres) <-\\n case origin of\\n ImplicitEssentialsImport ->\\n -- The implicit GHC.Essentials import does not bring anything into scope.\\n -- See Note [Finding GHC.Essentials] in GHC.Builtin.\\n return (Nothing, ImpUserDependOnly, emptyGlobalRdrEnv, emptyGlobalRdrEnv)\\n UserWrittenImport -> filter_imports\\n ImplicitPreludeImport -> filter_imports\\n PluginImport -> filter_imports\\n\\n let is_hiding | Just (EverythingBut,_) <- imp_details = True\\n | otherwise = False\\n\\n -- should the import be safe?\\n mod_safe\' = mod_safe\\n || (not generated && safeDirectImpsReq dflags)\\n || (generated && safeImplicitImpsReq dflags)\\n\\n hsc_env <- getTopEnv\\n let home_unit = hsc_home_unit hsc_env\\n other_home_units = hsc_all_home_unit_ids hsc_env\\n\\n imported_by\\n | isDependOnlyImport imp_user_list\\n = ImportedBySystem\\n | otherwise\\n = ImportedByUser $ ImportedModsVal\\n { imv_name = is_as imp_spec\\n , imv_span = locA loc\\n , imv_is_safe = mod_safe\'\\n , imv_is_hiding = is_hiding\\n , imv_all_exports = potential_gres\\n , imv_qualified = qual_only\\n , imv_is_level = convImportLevel import_level\\n }\\n imports = calculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by\\n\\n -- Complain if we import a deprecated module\\n case fromIfaceWarnings (mi_warns iface) of\\n WarnAll txt -> addDiagnostic (TcRnDeprecatedModule imp_mod_name txt)\\n _ -> return ()\\n\\n let new_imp_decl = ImportDecl\\n { ideclExt = ideclExt decl\\n , ideclName = ideclName decl\\n , ideclPkgQual = pkg_qual\\n , ideclSource = ideclSource decl\\n , ideclSafe = mod_safe\'\\n , ideclQualified = ideclQualified decl\\n , ideclAs = ideclAs decl\\n , ideclImportList = new_imp_details\\n , ideclLevelSpec = ideclLevelSpec decl\\n }\\n\\n return (L loc new_imp_decl, ImpUserSpec imp_spec imp_user_list, gbl_env, imports)\\n\\n-- | The error message to emit when we failed to load an interface.\\nimportDeclLoadFailure :: ImportDeclOrigin -> ModuleName -> IsBootInterface\\n -> MissingInterfaceError -> TcRnMessage\\nimportDeclLoadFailure ImplicitEssentialsImport _ _ err\\n = TcRnInterfaceError $ CantFindEssentials err LookingForEssentialsModule\\nimportDeclLoadFailure _ mod_name want_boot err\\n = TcRnInterfaceError $ Can\'tFindInterface err $ LookingForModule mod_name want_boot\\n\\n-- | Rename raw package imports\\nrenameRawPkgQual :: UnitEnv -> ModuleName -> RawPkgQual -> PkgQual\\nrenameRawPkgQual unit_env mn = \\\\case\\n NoRawPkgQual -> NoPkgQual\\n RawPkgQual _ fs -> renamePkgQual unit_env mn $ Just fs\\n\\n-- | Rename raw package imports\\nrenamePkgQual :: UnitEnv -> ModuleName -> Maybe FastString -> PkgQual\\nrenamePkgQual unit_env mn mb_pkg = case mb_pkg of\\n Nothing -> NoPkgQual\\n Just pkg_fs\\n | Just uid <- homeUnitId <$> ue_homeUnit unit_env\\n , pkg_fs == fsLit \\"this\\"\\n -> ThisPkg uid\\n\\n | Just (uid, _) <- find (fromMaybe False . fmap (== pkg_fs) . snd) home_names\\n -> ThisPkg uid\\n\\n | Just uid <- resolvePackageImport unit_state mn (PackageName pkg_fs)\\n -> OtherPkg uid\\n\\n | otherwise\\n -> OtherPkg (UnitId pkg_fs)\\n -- not really correct as pkg_fs is unlikely to be a valid unit-id but\\n -- we will report the failure later...\\n where\\n home_names =\\n [ (uid, mkFastString <$> thisPackageName (homeUnitEnv_dflags (ue_findHomeUnitEnv uid unit_env)))\\n | uid <- S.toList hpt_deps\\n ]\\n\\n unit_state = ue_homeUnitState unit_env\\n\\n hpt_deps :: S.Set UnitId\\n hpt_deps = homeUnitDepends unit_state\\n\\n\\n-- | Calculate the \'ImportAvails\' induced by an import of a particular\\n-- interface, but without \'imp_mods\'.\\ncalculateAvails :: HomeUnit\\n -> S.Set UnitId\\n -> ModIface\\n -> IsSafeImport\\n -> IsBootInterface\\n -> ImportedBy\\n -> ImportAvails\\ncalculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by =\\n let imp_mod = mi_module iface\\n imp_sem_mod= mi_semantic_module iface\\n orph_iface = mi_orphan iface\\n has_finsts = mi_finsts iface\\n deps = mi_deps iface\\n trust = getSafeMode $ mi_trust iface\\n trust_pkg = mi_trust_pkg iface\\n is_sig = mi_hsc_src iface == HsigFile\\n\\n -- If the module exports anything defined in this module, just\\n -- ignore it. Reason: otherwise it looks as if there are two\\n -- local definition sites for the thing, and an error gets\\n -- reported. Easiest thing is just to filter them out up\\n -- front. This situation only arises if a module imports\\n -- itself, or another module that imported it. (Necessarily,\\n -- this involves a loop.)\\n --\\n -- We do this *after* filterImports, so that if you say\\n -- module A where\\n -- import B( AType )\\n -- type AType = ...\\n --\\n -- module B( AType ) where\\n -- import {-# SOURCE #-} A( AType )\\n --\\n -- then you won\'t get a \'B does not export AType\' message.\\n\\n\\n -- Compute new transitive dependencies\\n --\\n -- \'dep_orphs\' and \'dep_finsts\' do NOT include the imported module\\n -- itself, but we DO need to include this module in \'imp_orphs\' and\\n -- \'imp_finsts\' if it defines an orphan or instance family; thus the\\n -- orph_iface/has_iface tests.\\n\\n deporphs = dep_orphs deps\\n depfinsts = dep_finsts deps\\n\\n orphans | orph_iface = assertPpr (not (imp_sem_mod `elem` deporphs)) (ppr imp_sem_mod <+> ppr deporphs) $\\n imp_sem_mod : deporphs\\n | otherwise = deporphs\\n\\n finsts | has_finsts = assertPpr (not (imp_sem_mod `elem` depfinsts)) (ppr imp_sem_mod <+> ppr depfinsts) $\\n imp_sem_mod : depfinsts\\n | otherwise = depfinsts\\n\\n -- Trusted packages are a lot like orphans.\\n trusted_pkgs | mod_safe\' = dep_trusted_pkgs deps\\n | otherwise = S.empty\\n\\n\\n pkg = moduleUnit (mi_module iface)\\n ipkg = toUnitId pkg\\n\\n -- Does this import mean we now require our own pkg\\n -- to be trusted? See Note [Trust Own Package]\\n ptrust = trust == Sf_Trustworthy || trust_pkg\\n pkg_trust_req\\n | isHomeUnit home_unit pkg = ptrust\\n | otherwise = False\\n\\n dependent_pkgs = if toUnitId pkg `S.member` other_home_units\\n then S.empty\\n else S.singleton (lvl, ipkg)\\n\\n lvl = case imported_by of\\n ImportedByUser imv -> imv_is_level imv\\n ImportedBySystem -> NormalLevel\\n\\n\\n direct_mods = if toUnitId pkg `S.member` other_home_units\\n then mkPlusModDeps (moduleUnitId imp_mod) lvl (GWIB (moduleName imp_mod) want_boot)\\n else emptyInstalledModuleEnv\\n\\n dep_boot_mods_map = mkModDeps (dep_boot_mods deps)\\n\\n\\n boot_mods\\n -- If we are looking for a boot module, it must be HPT\\n | IsBoot <- want_boot = extendInstalledModuleEnv dep_boot_mods_map (toUnitId <$> imp_mod) (GWIB (moduleName imp_mod) IsBoot)\\n -- Now we are importing A properly, so don\'t go looking for\\n -- A.hs-boot\\n | isHomeUnit home_unit pkg = dep_boot_mods_map\\n -- There\'s no boot files to find in external imports\\n | otherwise = emptyInstalledModuleEnv\\n\\n sig_mods =\\n if is_sig\\n then moduleName imp_mod : dep_sig_mods deps\\n else dep_sig_mods deps\\n\\n\\n in ImportAvails {\\n imp_mods = Map.singleton (mi_module iface) [imported_by],\\n imp_orphs = orphans,\\n imp_finsts = finsts,\\n imp_sig_mods = sig_mods,\\n imp_direct_dep_mods = direct_mods,\\n imp_dep_direct_pkgs = dependent_pkgs,\\n imp_boot_mods = boot_mods,\\n\\n -- Add in the imported modules trusted package\\n -- requirements. ONLY do this though if we import the\\n -- module as a safe import.\\n -- See Note [Tracking Trust Transitively]\\n -- and Note [Trust Transitive Property]\\n imp_trust_pkgs = trusted_pkgs,\\n -- Do we require our own pkg to be trusted?\\n -- See Note [Trust Own Package]\\n imp_trust_own_pkg = pkg_trust_req\\n }\\n\\nmkPlusModDeps :: UnitId -> ImportLevel -> ModuleNameWithIsBoot\\n -> InstalledModuleEnv (S.Set ImportLevel, ModuleNameWithIsBoot)\\nmkPlusModDeps uid st elt = extendInstalledModuleEnv emptyInstalledModuleEnv (mkModule uid (gwib_mod elt)) (S.singleton st, elt)\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{importsFromLocalDecls}\\n* *\\n************************************************************************\\n\\nFrom the top-level declarations of this module produce\\n * the lexical environment\\n * the ImportAvails\\ncreated by its bindings.\\n\\nNote [Top-level Names in Template Haskell decl quotes]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSee also: Note [Interactively-bound Ids in GHCi] in GHC.Driver.Env\\n Note [Looking up Exact RdrNames] in GHC.Rename.Env\\n\\nConsider a Template Haskell declaration quotation like this:\\n module M where\\n f x = h [d| f = 3 |]\\nWhen renaming the declarations inside [d| ...|], we treat the\\ntop level binders specially in two ways\\n\\n1. We give them an Internal Name, not (as usual) an External one.\\n This is done by GHC.Rename.Env.newTopSrcBinder.\\n\\n2. We make them *shadow* the outer bindings.\\n See Note [GlobalRdrEnv shadowing]\\n\\n3. We find out whether we are inside a [d| ... |] by testing the TH\\n level. This is a slight hack, because the level field was really\\n meant for the type checker, and here we are not interested in the\\n fields of Brack, hence the error thunks in thRnBrack.\\n-}\\n\\nextendGlobalRdrEnvRn :: [GlobalRdrElt]\\n -> MiniFixityEnv\\n -> RnM (TcGblEnv, TcLclEnv)\\n-- Updates both the GlobalRdrEnv and the FixityEnv\\n-- We return a new TcLclEnv only because we might have to\\n-- delete some bindings from it;\\n-- see Note [Top-level Names in Template Haskell decl quotes]\\n\\nextendGlobalRdrEnvRn new_gres new_fixities\\n = checkNoErrs $ -- See Note [Fail fast on duplicate definitions]\\n do { (gbl_env, lcl_env) <- getEnvs\\n ; level <- getThLevel\\n ; isGHCi <- getIsGHCi\\n ; let rdr_env = tcg_rdr_env gbl_env\\n fix_env = tcg_fix_env gbl_env\\n th_bndrs = getLclEnvThBndrs lcl_env\\n th_lvl = thLevelIndex level\\n\\n -- Delete new_occs from global and local envs\\n -- If we are in a TemplateHaskell decl bracket,\\n -- we are going to shadow them\\n -- See Note [GlobalRdrEnv shadowing]\\n inBracket = isBrackLevel level\\n\\n lcl_env_TH = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_rdr = minusLocalRdrEnv (tcl_rdr lcl_env) new_gres_env }) lcl_env\\n -- See Note [GlobalRdrEnv shadowing]\\n\\n lcl_env2 | inBracket = lcl_env_TH\\n | otherwise = lcl_env\\n\\n -- Deal with shadowing: see Note [GlobalRdrEnv shadowing]\\n want_shadowing = isGHCi || inBracket\\n rdr_env1 | want_shadowing = shadowNames False rdr_env new_gres_env\\n | otherwise = rdr_env\\n\\n lcl_env3 = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_th_bndrs = extendNameEnvList th_bndrs\\n [ ( n, (TopLevel, th_lvl) )\\n | n <- new_names ] }) lcl_env2\\n\\n ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres\\n\\n ; let fix_env\' = foldl\' extend_fix_env fix_env new_gres\\n gbl_env\' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env\' }\\n\\n ; traceRn \\"extendGlobalRdrEnvRn 2\\" (pprGlobalRdrEnv True rdr_env2)\\n ; return (gbl_env\', lcl_env3) }\\n where\\n new_names = map greName new_gres\\n new_gres_env = mkGlobalRdrEnv new_gres\\n\\n -- If there is a fixity decl for the gre, add it to the fixity env\\n extend_fix_env fix_env gre\\n | Just (L _ fi) <- lookupMiniFixityEnv new_fixities name\\n = extendNameEnv fix_env name (FixItem occ fi)\\n | otherwise\\n = fix_env\\n where\\n name = greName gre\\n occ = greOccName gre\\n\\n add_gre :: GlobalRdrEnv -> GlobalRdrElt -> RnM GlobalRdrEnv\\n -- Extend the GlobalRdrEnv with a LocalDef GRE\\n -- If there is already a LocalDef GRE with the same OccName,\\n -- report an error and discard the new GRE\\n -- This establishes INVARIANT 1 of GlobalRdrEnvs\\n add_gre env gre\\n | not (null dups) -- Same OccName defined twice\\n = do { addDupDeclErr (gre :| dups); return env }\\n\\n | otherwise\\n = return (extendGlobalRdrEnv env gre)\\n where\\n -- See Note [Reporting duplicate local declarations]\\n dups = filter isBadDupGRE\\n $ lookupGRE env (LookupOccName (greOccName gre) (RelevantGREsFOS WantBoth))\\n isBadDupGRE old_gre = isLocalGRE old_gre && greClashesWith gre old_gre\\n\\n{- Note [Fail fast on duplicate definitions]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIf there are duplicate bindings for the same thing, we want to fail\\nfast. Having two bindings for the same thing can cause follow-on errors.\\nExample (test T9975a):\\n data Test = Test { x :: Int }\\n pattern Test wat = Test { x = wat }\\nThis defines \'Test\' twice. The second defn has no field-names; and then\\nwe get an error from Test { x=wat }, saying \\"Test has no field \'x\'\\".\\n\\nEasiest thing is to bale out fast on duplicate definitions, which\\nwe do via `checkNoErrs` on `extendGlobalRdrEnvRn`.\\n\\nNote [Reporting duplicate local declarations]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn general, a single module may not define the same OccName multiple times. This\\nis checked in extendGlobalRdrEnvRn: when adding a new locally-defined GRE to the\\nGlobalRdrEnv we report an error if there are already duplicates in the\\nenvironment. This establishes INVARIANT 1 (see comments on GlobalRdrEnv in\\nGHC.Types.Name.Reader), which says that for a given OccName, all the\\nGlobalRdrElts to which it maps must have distinct \'greName\'s.\\n\\nFor example, the following will be rejected:\\n\\n f x = x\\n g x = x\\n f x = x -- Duplicate!\\n\\nUsers are allowed to introduce new GREs with the same OccName as an imported GRE,\\nas disambiguation is possible through the module system, e.g.:\\n\\n module M where\\n import N (f)\\n f x = x\\n g x = M.f x + N.f x\\n\\nIf both GREs are local, the general rule is that two GREs clash if they have\\nthe same OccName, i.e. they share a textual name and live in the same namespace.\\nHowever, there are additional clashes due to record fields:\\n\\n - a new variable clashes with previously defined record fields\\n which define field selectors,\\n\\n - a new record field shadows:\\n\\n - previously defined variables, if it defines a field selector,\\n - previously defined record fields, unless it is a duplicate record field.\\n\\nThis logic is implemented in the function \'GHC.Types.Name.Reader.greClashesWith\'.\\n\\nSee also Note [Skipping ambiguity errors at use sites of local declarations] in\\nGHC.Rename.Utils.\\n-}\\n\\n\\n{- *********************************************************************\\n* *\\n getLocalDeclBindersd@ returns the names for an HsDecl\\n It\'s used for source code.\\n\\n *** See Note [The Naming story] in GHC.Hs.Decls ****\\n* *\\n********************************************************************* -}\\n\\ngetLocalNonValBinders :: MiniFixityEnv -> HsGroup GhcPs\\n -> RnM ((TcGblEnv, TcLclEnv), NameSet)\\n-- Get all the top-level binders bound the group *except*\\n-- for value bindings, which are treated separately\\n-- Specifically we return AvailInfo for\\n-- * type decls (incl constructors and record selectors)\\n-- * class decls (including class ops)\\n-- * associated types\\n-- * foreign imports\\n-- * value signatures (in hs-boot files only)\\n\\ngetLocalNonValBinders fixity_env\\n (HsGroup { hs_valds = binds,\\n hs_tyclds = tycl_decls,\\n hs_fords = foreign_decls })\\n = do { -- Process all type/class decls *except* family instances\\n ; let inst_decls = tycl_decls >>= group_instds\\n ; dup_fields_ok <- xopt_DuplicateRecordFields <$> getDynFlags\\n ; has_sel <- xopt_FieldSelectors <$> getDynFlags\\n ; tc_gres\\n <- concatMapM\\n (new_tc dup_fields_ok has_sel)\\n (tyClGroupTyClDecls tycl_decls)\\n ; traceRn \\"getLocalNonValBinders 1\\" (ppr tc_gres)\\n ; envs <- extendGlobalRdrEnvRn tc_gres fixity_env\\n ; restoreEnvs envs $ do {\\n -- Bring these things into scope first\\n -- See Note [Looking up family names in family instances]\\n\\n -- Process all family instances\\n -- to bring new data constructors into scope\\n ; nti_gress <- mapM (new_assoc dup_fields_ok has_sel) inst_decls\\n\\n -- Finish off with value binders:\\n -- foreign decls and pattern synonyms for an ordinary module\\n -- type sigs in case of a hs-boot file only\\n ; is_boot <- tcIsHsBootOrSig\\n ; let val_bndrs\\n | is_boot = case binds of\\n ValBinds _ val_binds ->\\n -- In a hs-boot file, the value binders come from the\\n -- *signatures*, and there should be no foreign binders\\n [ L (l2l decl_loc) (unLoc n)\\n | L decl_loc (TypeSig _ _ ns _) <- (val_sigs val_binds), n <- ns]\\n _ -> panic \\"Non-ValBinds in hs-boot group\\"\\n | otherwise = for_hs_bndrs\\n ; val_gres <- mapM new_simple val_bndrs\\n\\n ; let avails = concat nti_gress ++ val_gres\\n new_bndrs = gresToNameSet avails `unionNameSet`\\n gresToNameSet tc_gres\\n ; traceRn \\"getLocalNonValBinders 2\\" (ppr avails)\\n ; envs <- extendGlobalRdrEnvRn avails fixity_env\\n ; return (envs, new_bndrs) } }\\n where\\n for_hs_bndrs :: [LocatedN RdrName]\\n for_hs_bndrs = hsForeignDeclsBinders foreign_decls\\n\\n -- the SrcSpan attached to the input should be the span of the\\n -- declaration, not just the name\\n new_simple :: LocatedN RdrName -> RnM GlobalRdrElt\\n new_simple rdr_name = do { nm <- newTopSrcBinder rdr_name\\n ; return (mkLocalVanillaGRE NoParent nm) }\\n\\n new_tc :: DuplicateRecordFields -> FieldSelectors -> LTyClDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_tc dup_fields_ok has_sel tc_decl -- NOT for type/data instances\\n = do { let TyDeclBinders (main_bndr, tc_flav) at_bndrs sig_bndrs\\n (LConsWithFields cons_with_flds flds) = hsLTyClDeclBinders tc_decl\\n ; tycon_name <- newTopSrcBinder $ la2la main_bndr\\n ; at_names <- mapM (newTopSrcBinder . la2la . fst) at_bndrs\\n ; sig_names <- mapM (newTopSrcBinder . la2la) sig_bndrs\\n ; con_names_with_flds <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst con_names_with_flds) flds\\n ; mapM_ (add_dup_fld_errs flds\') con_names_with_flds\\n ; let tc_gre = mkLocalTyConGRE (fmap (const tycon_name) tc_flav) tycon_name\\n fld_env = mk_fld_env con_names_with_flds flds\'\\n at_gres = zipWith (\\\\ (_, at_flav) at_nm -> mkLocalTyConGRE (fmap (const tycon_name) at_flav) at_nm)\\n at_bndrs at_names\\n sig_gres = map (mkLocalVanillaGRE (ParentIs tycon_name)) sig_names\\n con_gres = map (mkLocalConLikeGRE (ParentIs tycon_name)) fld_env\\n fld_gres = mkLocalFieldGREs (ParentIs tycon_name) fld_env\\n sub_gres = at_gres ++ sig_gres ++ con_gres ++ fld_gres\\n ; traceRn \\"getLocalNonValBinders new_tc\\" $\\n vcat [ text \\"tycon:\\" <+> ppr tycon_name\\n , text \\"tc_gre:\\" <+> ppr tc_gre\\n , text \\"sub_gres:\\" <+> ppr sub_gres ]\\n ; return $ tc_gre : sub_gres }\\n\\n -- Calculate the record field information, which feeds into the GlobalRdrElts\\n -- for DataCons and their fields. It\'s convenient to do this here where\\n -- we are working with a single datatype definition.\\n --\\n -- The information we needed was all set up for us:\\n -- see Note [Collecting record fields in data declarations] in GHC.Hs.Utils.\\n mk_fld_env :: [(Name, Either VisArity [Located Int])] -> IntMap FieldLabel\\n -> [(ConLikeName, ConInfo)]\\n mk_fld_env names flds =\\n [ (DataConName con, ConInfo (ConIsData (map fst names)) fld_info)\\n | (con, con_fl_indxs) <- names\\n , let fld_info = case fmap (map ((flds IntMap.!) . unLoc)) con_fl_indxs of\\n Left 0 -> ConIsNullary\\n Left arity -> ConHasPositionalArgs arity\\n Right [] -> ConIsNullary\\n Right (fld:flds) -> ConHasRecordFields $ fld NE.:| flds ]\\n\\n new_assoc :: DuplicateRecordFields -> FieldSelectors -> LInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_assoc _ _ (L _ (TyFamInstD {})) = return []\\n -- type instances don\'t bind new names\\n\\n new_assoc dup_fields_ok has_sel (L _ (DataFamInstD _ d))\\n = new_di dup_fields_ok has_sel Nothing d\\n new_assoc dup_fields_ok has_sel\\n (L _ (ClsInstD _ (ClsInstDecl { cid_poly_ty = inst_ty\\n , cid_decls = decls })))\\n = do -- First, attempt to grab the name of the class from the instance.\\n -- This step could fail if the instance is not headed by a class,\\n -- such as in the following examples:\\n --\\n -- (1) The class is headed by a bang pattern, such as in\\n -- `instance !Show Int` (#3811c)\\n -- (2) The class is headed by a type variable, such as in\\n -- `instance c` (#16385)\\n --\\n -- If looking up the class name fails, then mb_cls_gre will\\n -- be Nothing.\\n mb_cls_gre <- runMaybeT $ do\\n -- See (1) above\\n L loc cls_rdr <- MaybeT $ pure $ getLHsInstDeclClass_maybe inst_ty\\n -- See (2) above\\n MaybeT $ setSrcSpan (locA loc) $ lookupGlobalOccRn_maybe SameNameSpace cls_rdr\\n -- Assuming the previous step succeeded, process any associated data\\n -- family instances. If the previous step failed, bail out.\\n case mb_cls_gre of\\n Nothing\\n -> pure []\\n Just cls_gre\\n -> let cls_nm = greName cls_gre\\n in concatMapM (new_di dup_fields_ok has_sel (Just cls_nm) . unLoc) (data_fam_insts decls)\\n\\n data_fam_insts decls = concatMap get decls\\n where\\n get (L l (InstD _ (DataFamInstD { dfid_inst = d}))) = [L l d]\\n get _ = []\\n\\n new_di :: DuplicateRecordFields -> FieldSelectors\\n -> Maybe Name -- class name\\n -> DataFamInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_di dup_fields_ok has_sel mb_cls dfid@(DataFamInstDecl { dfid_eqn = ti_decl })\\n = do { main_name <- unLoc <$> lookupFamInstName mb_cls (feqn_tycon ti_decl)\\n ; let LConsWithFields cons_with_flds flds = hsDataFamInstBinders dfid\\n ; sub_names <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst sub_names) flds\\n ; mapM_ (add_dup_fld_errs flds\') sub_names\\n ; let fld_env = mk_fld_env sub_names flds\'\\n con_gres = map (mkLocalConLikeGRE (ParentIs main_name)) fld_env\\n field_gres = mkLocalFieldGREs (ParentIs main_name) fld_env\\n -- NB: the data family name is not bound here,\\n -- so we don\'t return a GlobalRdrElt for it here!\\n ; return $ con_gres ++ field_gres }\\n\\n -- Add errors if a constructor has a duplicate record field.\\n add_dup_fld_errs :: IntMap FieldLabel\\n -> (Name, Either VisArity [Located Int])\\n -> IOEnv (Env TcGblEnv TcLclEnv) ()\\n add_dup_fld_errs all_flds (con, con_flds_or_arity)\\n | Right con_flds <- con_flds_or_arity\\n , let (_, dups) = removeDups (comparing unLoc) con_flds\\n = for_ dups $ \\\\ dup_flds ->\\n -- Report the error at the location of the second occurrence\\n -- of the duplicate field.\\n let loc =\\n case dup_flds of\\n _ :| ( L loc _ : _) -> loc\\n L loc _ :| _ -> loc\\n dup_rdrs = fmap (nameRdrName . flSelector . (all_flds IntMap.!) . unLoc) dup_flds\\n in addErrAt loc $ TcRnDuplicateFieldName (RecordFieldDecl con) dup_rdrs\\n | otherwise\\n = return ()\\n\\nnewRecordFieldLabel :: DuplicateRecordFields -> FieldSelectors -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel\\nnewRecordFieldLabel _ _ [] _ = error \\"newRecordFieldLabel: datatype has no constructors!\\"\\nnewRecordFieldLabel dup_fields_ok has_sel (dc:_) (L loc (FieldOcc _ (L _ fld)))\\n = do { selName <- newTopSrcBinder $ L (l2l loc) $ field\\n ; return $ FieldLabel { flHasDuplicateRecordFields = dup_fields_ok\\n , flHasFieldSelector = has_sel\\n , flSelector = selName } }\\n where\\n fld_occ = rdrNameOcc fld\\n dc_fs = occNameFS $ nameOccName dc\\n field\\n -- Use an Exact RdrName as-is, to preserve the bindings\\n -- of an already renamer-resolved field and its use\\n -- sites. This is needed to correctly support record\\n -- selectors in Template Haskell. See Note [Binders in\\n -- Template Haskell] in \\"GHC.ThToHs\\" and Note [Looking up\\n -- Exact RdrNames] in \\"GHC.Rename.Env\\".\\n | isExact fld\\n = assertPpr (fieldOcc_maybe fld_occ == Just dc_fs)\\n (vcat [ text \\"newRecordFieldLabel: incorrect namespace for exact Name\\" <+> quotes (ppr fld)\\n , text \\"expected namespace:\\" <+> pprNameSpace (fieldName dc_fs)\\n , text \\" actual namespace:\\" <+> pprNameSpace (occNameSpace fld_occ) ])\\n fld\\n\\n -- Field names produced by the parser are namespaced with VarName.\\n -- Here we namespace them according to the first constructor.\\n -- See Note [Record field namespacing] in GHC.Types.Name.Occurrence.\\n | otherwise\\n = mkRdrUnqual $ varToRecFieldOcc dc_fs fld_occ\\n\\n{-\\nNote [Looking up family names in family instances]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider\\n\\n module M where\\n type family T a :: *\\n type instance M.T Int = Bool\\n\\nWe might think that we can simply use \'lookupOccRn\' when processing the type\\ninstance to look up \'M.T\'. Alas, we can\'t! The type family declaration is in\\nthe *same* HsGroup as the type instance declaration. Hence, as we are\\ncurrently collecting the binders declared in that HsGroup, these binders will\\nnot have been added to the global environment yet.\\n\\nSolution is simple: process the type family declarations first, extend\\nthe environment, and then process the type instances.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Filtering imports}\\n* *\\n************************************************************************\\n\\n@filterImports@ takes the @ExportEnv@ telling what the imported module makes\\navailable, and filters it through the import spec (if any).\\n\\nNote [Dealing with imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nFor import M( ies ), we take each AvailInfo from the mi_exports of M, and make\\n\\n imp_occ_env :: OccEnv (NameEnv ImpOccItem)\\n\\nThis map contains one entry for each OccName that M exports, mapping each OccName\\nto the following information:\\n\\n 1. the GlobalRdrElt corresponding to the OccName,\\n 2. whether this GlobalRdrElt was the parent in the AvailInfo we found\\n the OccName in.\\n 3. the GlobalRdrElts that were bundled together in the AvailInfo we found\\n this OccName in (not including the parent),\\n\\nWe need (2) and (3) during the construction of the OccEnv because of associated\\ntypes and bundled pattern synonyms, respectively.\\n(3) is explained in Note [Importing PatternSynonyms].\\n\\nTo explain (2), consider for example:\\n\\n module M where\\n class C a where { data T a }\\n instance C Int where { data T Int = T1 | T2 }\\n instance C Bool where { data T Int = T3 }\\n\\nHere, M\'s exports avails are (recalling the AvailTC invariant from GHC.Types.Avail)\\n\\n C(C,T), T(T,T1,T2,T3)\\n\\nNotice that T appears *twice*, once as a child and once as a parent. From\\nthese two exports, respectively, during construction of the imp_occ_env, we begin\\nby associating the following two elements with the key T:\\n\\n T -> ImpOccItem { imp_item = gre1, imp_bundled = [C,T] , imp_is_parent = False }\\n T -> ImpOccItem { imp_item = gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nwhere `gre1`, `gre2` are two GlobalRdrElts with greName T.\\nWe combine these (in function \'combine\' in \'mkImportOccEnv\') by discarding the\\nnon-parent item, thusly:\\n\\n T -> IE_ITem { imp_item = gre1 `plusGRE` gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nNote the `plusGRE`: this ensures we don\'t drop parent information;\\nsee Note [Preserve parent information when combining import OccEnvs].\\n\\nSo the overall imp_occ_env is:\\n\\n C -> ImpOccItem { imp_item = C, imp_bundled = [T ], imp_is_parent = True }\\n T -> ImpOccItem { imp_item = T , imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n T1 -> ImpOccItem { imp_item = T1, imp_bundled = [T1,T2,T3], imp_is_parent = False }\\n -- similarly for T2, T3\\n\\nNote that the imp_occ_env will have entries for data constructors too,\\nalthough we never look up data constructors.\\n\\nNote [Importing PatternSynonyms]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nAs described in Note [Dealing with imports], associated types can lead to the\\nsame Name appearing twice, both as a child and once as a parent, when\\nconstructing the imp_occ_env. The same thing can happen with pattern synonyms\\nif they are exported bundled with a type.\\n\\nA simplified example, based on #11959:\\n\\n {-# LANGUAGE PatternSynonyms #-}\\n module M (T(P), pattern P) where -- Duplicate export warning, but allowed\\n data T = MkT\\n pattern P = MkT\\n\\nHere we have T(P) and P in export_avails, and respectively construct both\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n P -> ImpOccItem { imp_item = P, imp_bundled = [] , imp_is_parent = False }\\n\\nWe combine these by dropping the one with no siblings, leaving us with:\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n\\nThat is, we simply discard the non-bundled Avail.\\n\\nNote [Importing DuplicateRecordFields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn filterImports, another complicating factor is DuplicateRecordFields.\\nSuppose we have:\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (S(foo), T(foo)) where\\n data S = MkS { foo :: Int }\\n data T = MkT { foo :: Int }\\n\\n module N where\\n import M (foo) -- this is allowed (A)\\n import M (S(foo)) -- this is allowed (B)\\n\\nHere M exports \'foo\' at two different OccNames, with different namespaces for\\nthe two construtors MkS and MkT. Then, when we look up \'foo\' in lookup_names\\nfor case (A), we have a variable foo but must look in all the record field\\nnamespaces to find the two fields (and hence two different Avails).\\nWhereas in case (B) we reach the lookup_ie case for IEThingWith,\\nwhich looks up \'S\' and then finds the unique \'foo\' amongst its children.\\n\\nSee T16745 for a test of this.\\n\\nNote [Preserve parent information when combining import OccEnvs]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen discarding one ImpOccItem in favour of another, as described in\\nNote [Dealing with imports], we must make sure to combine the GREs so that\\nwe don\'t lose information.\\n\\nConsider for example #24084:\\n\\n module M1 where { class C a where { type T a } }\\n module M2 ( module M1 ) where { import M1 }\\n module M3 where { import M2 ( C, T ); instance C () where T () = () }\\n\\nWhen processing the import list of `M3`, we will have two `Avail`s attached\\nto `T`, namely `C(C, T)` and `T(T)`. We combine them in the `combine` function\\nof `mkImportOccEnv`; as described in Note [Dealing with imports] we discard\\n`C(C, T)` in favour of `T(T)`. However, in doing so, we **must not**\\ndiscard the information want that `C` is the parent of `T`. Indeed,\\nlosing track of this information can cause errors when importing,\\nas we could get an error of the form\\n\\n \\u2018T\\u2019 is not a (visible) associated type of class \\u2018C\\u2019\\n\\nThis explains why we use `plusGRE` when combining the two ImpOccItems, even\\nthough we are discarding one in favour of the other.\\n-}\\n\\n-- | All the \'GlobalRdrElt\'s associated with an \'AvailInfo\'.\\ngresFromAvail :: HasDebugCallStack\\n => HscEnv -> Maybe ImportSpec -> AvailInfo -> [GlobalRdrElt]\\ngresFromAvail hsc_env prov avail =\\n [ mk_gre nm info\\n | nm <- availNames avail\\n , let info = lookupGREInfo hsc_env nm ]\\n where\\n\\n mk_gre n info\\n = case prov of\\n -- Nothing => bound locally\\n -- Just is => imported from \'is\'\\n Nothing -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = True, gre_imp = emptyBag\\n , gre_info = info }\\n Just is -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = False, gre_imp = unitBag is\\n , gre_info = info }\\n\\n-- | All the \'GlobalRdrElt\'s associated with a collection of \'AvailInfo\'s.\\ngresFromAvails :: HscEnv -> Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]\\ngresFromAvails hsc_env prov = concatMap (gresFromAvail hsc_env prov)\\n\\nimportsFromIface :: HscEnv -> ModIface -> ImpDeclSpec -> Maybe NameSet -> GlobalRdrEnv\\nimportsFromIface hsc_env iface decl_spec hidden = mkGlobalRdrEnv $ case hidden of\\n Nothing -> all_gres\\n Just hidden_names -> filter (not . (`elemNameSet` hidden_names) . greName) all_gres\\n where\\n all_gres = gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\nrnNamespaceSpecifier :: NamespaceSpecifier GhcPs -> NamespaceSpecifier GhcRn\\nrnNamespaceSpecifier (NoNamespaceSpecifier _) = NoNamespaceSpecifier noExtField\\nrnNamespaceSpecifier (TypeNamespaceSpecifier x) = TypeNamespaceSpecifier x\\nrnNamespaceSpecifier (DataNamespaceSpecifier x) = DataNamespaceSpecifier x\\n\\nfilterImports\\n :: HasDebugCallStack\\n => HscEnv\\n -> ModIface\\n -> ImpDeclSpec\\n -- ^ Import spec\\n -> Maybe (ImportListInterpretation, [LIE GhcPs])\\n -- ^ Whether this is a \\"hiding\\" import list\\n -> RnM (Maybe (ImportListInterpretation, [LIE GhcRn]), -- Import spec w/ Names\\n ImpUserList, -- same, but designed for storage in interfaces\\n GlobalRdrEnv) -- Same again, but in GRE form\\nfilterImports hsc_env iface decl_spec Nothing\\n = return (Nothing, ImpUserAll, importsFromIface hsc_env iface decl_spec Nothing)\\nfilterImports hsc_env iface decl_spec (Just (want_hiding, import_items))\\n = do -- check for errors, convert RdrNames to Names\\n items1 <- mapM lookup_lie import_items\\n\\n let items2 :: [(LIE GhcRn, [GlobalRdrElt])]\\n items2 = concat items1\\n -- NB we may have duplicates, and several items\\n -- for the same parent; e.g N(x) and N(y)\\n\\n (gres, imp_user_list) = case want_hiding of\\n Exactly ->\\n let gres = concatMap (gresFromIE decl_spec) items2\\n gre_env = mkGlobalRdrEnv gres\\n implicit_parents = mkNameSet $ mapMaybe parentOfImplicitlyImportedGRE gres\\n in (gre_env, ImpUserExplicit (gresToAvailInfo $ globalRdrEnvElts $ gre_env) implicit_parents)\\n EverythingBut ->\\n let hidden_names = mkNameSet $ concatMap (map greName . snd) items2\\n in (importsFromIface hsc_env iface decl_spec (Just hidden_names), ImpUserEverythingBut hidden_names)\\n\\n return (Just (want_hiding, map fst items2), imp_user_list, gres)\\n where\\n import_mod = mi_module iface\\n all_avails = mi_exports iface\\n imp_occ_env = mkImportOccEnv hsc_env decl_spec all_avails\\n\\n -- Look up a parent (type constructor, class or data constructor)\\n -- in an import.\\n lookup_parent :: IE GhcPs -> RdrName -> IELookupM ImpOccItem\\n lookup_parent ie rdr =\\n assertPpr (not $ isVarNameSpace ns)\\n (vcat [ text \\"filterImports lookup_parent: unexpected variable\\"\\n , text \\"rdr:\\" <+> ppr rdr\\n , text \\"namespace:\\" <+> pprNameSpace ns ]) $\\n do { xs <- lookup_names ie rdr\\n ; case xs of\\n cax :| [] -> return cax\\n _ -> pprPanic \\"filter_imports lookup_parent ambiguous\\" $\\n vcat [ text \\"rdr:\\" <+> ppr rdr\\n , text \\"lookups:\\" <+> ppr (fmap imp_item xs) ] }\\n -- Looking up non-variables is always unambiguous,\\n -- as there can be at most one corresponding item\\n -- in the imp_occ_env.\\n -- See item (1) of Note [Exporting duplicate declarations]\\n -- in GHC.Tc.Gen.Export.\\n where\\n occ = rdrNameOcc rdr\\n ns = occNameSpace occ\\n\\n -- Look up a RdrName used in an import, returning multiple values if there\\n -- are several fields with the same name exposed by the module\\n lookup_names :: IE GhcPs -> RdrName -> IELookupM (NonEmpty ImpOccItem)\\n lookup_names ie rdr\\n | isQual rdr\\n = failLookupWith (QualImportError rdr)\\n | otherwise\\n = case lookups of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n item:items -> return $ item :| items\\n where\\n lookups = concatMap nonDetNameEnvElts\\n $ lookupImpOccEnv (RelevantGREsFOS WantNormal) imp_occ_env (rdrNameOcc rdr)\\n\\n lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, [GlobalRdrElt])]\\n lookup_lie (L loc ieRdr)\\n = setSrcSpanA loc $\\n do (stuff, warns) <- run_lookup ([],[]) (lookup_ie ieRdr)\\n mapM_ (addTcRnDiagnostic <=< warning_msg) warns\\n return [ (L loc ie, gres) | (ie,gres) <- stuff ]\\n where\\n\\n -- Warn when importing T(..) and no children are brought in scope\\n warning_msg (DodgyImport reason) =\\n pure (TcRnDodgyImports reason)\\n warning_msg MissingImportList =\\n pure (TcRnMissingImportList ieRdr)\\n warning_msg (BadImportW ie sub) = do\\n -- \'BadImportW\' is only constructed below in \'bad_import_w\', in\\n -- the \'EverythingBut\' case, so here we assume a \'hiding\' clause.\\n (reason :| _) <- badImportItemErr iface decl_spec ie sub all_avails\\n pure (TcRnDodgyImports (DodgyImportsHiding reason))\\n warning_msg (DeprecatedExport n w) =\\n pure $ TcRnPragmaWarning\\n PragmaWarningExport\\n { pwarn_occname = occName n\\n , pwarn_impmod = moduleName import_mod }\\n w\\n\\n run_lookup :: a -> IELookupM a -> TcRn a\\n run_lookup def m = case m of\\n Failed err -> do\\n msgs <- lookup_err_msgs err\\n forM_ msgs $ \\\\msg -> addErr (TcRnImportLookup msg)\\n return def\\n Succeeded a -> return a\\n\\n lookup_err_msgs err = case err of\\n BadImport ie sub -> badImportItemErr iface decl_spec ie sub all_avails\\n IllegalImport -> pure $ NE.singleton ImportLookupIllegal\\n QualImportError rdr -> pure $ NE.singleton (ImportLookupQualified rdr)\\n\\n -- For each import item, we convert its RdrNames to Names,\\n -- and at the same time compute all the GlobalRdrElt corresponding\\n -- to what is actually imported by this item.\\n -- Returns Nothing on error.\\n --\\n -- Returns a list because, with DuplicateRecordFields, a naked\\n -- import/export of a record field can correspond to multiple\\n -- different GlobalRdrElts. See Note [Importing DuplicateRecordFields].\\n lookup_ie :: IE GhcPs\\n -> IELookupM ([(IE GhcRn, [GlobalRdrElt])], [IELookupWarning])\\n lookup_ie ie = handle_bad_import $\\n case ie of\\n IEVar _ (L l n) _ -> do\\n -- See Note [Importing DuplicateRecordFields]\\n xs <- lookup_names ie (ieWrappedName n)\\n let gres = map imp_item $ NE.toList xs\\n export_depr_warns\\n | want_hiding == Exactly\\n = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ( [ (IEVar Nothing (L l (replaceWrappedName n name)) noDocstring, [gre])\\n | gre <- gres\\n , let name = greName gre ]\\n , export_depr_warns )\\n\\n IEThingAll x ns_spec (L l tc) _ -> do\\n ImpOccItem { imp_item = gre\\n , imp_bundled = bundled_gres\\n , imp_is_parent = is_par\\n }\\n <- lookup_parent ie $ ieWrappedName tc\\n let name = greName gre\\n\\n child_gres :: [GlobalRdrElt]\\n child_gres\\n | is_par = filterByNamespaceSpecifierGREs ns_spec bundled_gres\\n | otherwise = []\\n\\n imp_list_warn\\n\\n | null child_gres\\n -- e.g. f(..) or T(..) where T is a type synonym\\n = [DodgyImport (DodgyImportsEmptyParent ie ns_spec gre)]\\n\\n -- e.g. import M( T(..) )\\n | not (is_qual decl_spec)\\n = [MissingImportList]\\n\\n | otherwise\\n = []\\n\\n renamed_ie = IEThingAll (x { ieta_warning = Nothing })\\n (rnNamespaceSpecifier ns_spec)\\n (L l (replaceWrappedName tc name))\\n noDocstring\\n export_depr_warn\\n | want_hiding == Exactly\\n = maybeToList $ mk_depr_export_warning gre\\n -- We don\'t want to warn about the children as they\\n -- are not explicitly mentioned; the warning will\\n -- be emitted later on if they are used\\n | otherwise = []\\n\\n return ( [(renamed_ie, gre:child_gres)]\\n , imp_list_warn ++ export_depr_warn)\\n\\n\\n IEThingAbs _ (L l tc\') _\\n | want_hiding == EverythingBut -- hiding ( C )\\n -- Here the \'C\' can be a data constructor\\n -- *or* a type/class, or even both\\n -> let tc = ieWrappedName tc\'\\n tc_name = lookup_parent ie tc\\n dc_name = lookup_parent ie (setRdrNameSpace tc srcDataName)\\n in\\n case catIELookupM [ tc_name, dc_name ] of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n names -> return ( [mkIEThingAbs tc\' l (imp_item name) | name <- names], [])\\n | otherwise\\n -> do ImpOccItem { imp_item = gre } <- lookup_parent ie (ieWrappedName tc\')\\n return ( [mkIEThingAbs tc\' l gre]\\n , maybeToList $ mk_depr_export_warning gre)\\n\\n IEThingWith (deprecation, ann) ltc@(L l rdr_tc) wc rdr_ns _ -> do\\n ImpOccItem { imp_item = gre, imp_bundled = subnames }\\n <- lookup_parent (IEThingAbs Nothing ltc noDocstring) (ieWrappedName rdr_tc)\\n let name = greName gre\\n\\n -- Look up the children in the sub-names of the parent\\n -- See Note [Importing DuplicateRecordFields]\\n let (children_errs, childnames) = lookupChildren subnames rdr_ns\\n\\n bad_import_warns <-\\n if null children_errs then return [] else\\n let items = map lce_wrapped_name children_errs\\n ie = IEThingWith (deprecation, ann) ltc wc items noDocstring\\n -- We are trying to import T( a,b,c,d ), and failed\\n -- to find \'b\' and \'d\'. So we make up an import item\\n -- to report as failing, namely T( b, d ).\\n -- c.f. #15413\\n subordinate_err = mkSubordinateError gre children_errs\\n in bad_import_w ie subordinate_err\\n\\n let name\' = replaceWrappedName rdr_tc name\\n childnames\' = map (to_ie_post_rn . fmap greName) childnames\\n gres = gre : map unLoc childnames\\n export_depr_warns\\n | want_hiding == Exactly = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ([ (IEThingWith (Nothing, ann) (L l name\') wc childnames\' noDocstring\\n ,gres)]\\n , bad_import_warns ++ export_depr_warns)\\n\\n IEWholeNamespace x ns_spec -> do\\n let mod_name = moduleName import_mod\\n names = map greName gres\\n renamed_ie = IEWholeNamespace x { iewn_warning = Nothing\\n , iewn_names = names }\\n (rnNamespaceSpecifier ns_spec)\\n gres = filterByNamespaceSpecifierGREs ns_spec $\\n gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n dodgy_warn\\n | null gres = [DodgyImport (DodgyImportsWildcard mod_name ns_spec)]\\n | otherwise = []\\n return ([(renamed_ie, gres)],\\n dodgy_warn)\\n\\n _other -> failLookupWith IllegalImport\\n -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed...\\n -- all of those constitute errors.\\n\\n where\\n mkIEThingAbs tc l gre\\n = (IEThingAbs Nothing (L l (replaceWrappedName tc n)) noDocstring, [gre])\\n where n = greName gre\\n\\n -- N.B. imports never have docstrings\\n noDocstring = Nothing\\n\\n handle_bad_import m = catchIELookup m $ \\\\case\\n BadImport ie sub -> do\\n ws <- bad_import_w ie sub\\n return ([], ws)\\n err -> failLookupWith err\\n\\n bad_import_w :: IE GhcPs -> IsSubordinateError -> IELookupM [IELookupWarning]\\n bad_import_w ie sub\\n | want_hiding == EverythingBut = return [BadImportW ie sub]\\n | otherwise = failLookupWith (BadImport ie sub)\\n\\n mk_depr_export_warning gre\\n = DeprecatedExport name <$> mi_export_warn_fn iface name\\n where\\n name = greName gre\\n\\n-- | Assuming a subordinate item could not be found, do another lookup for a\\n-- more specific error message.\\nmkBadExportSubordinate :: [GlobalRdrElt] -> LIEWrappedName GhcPs -> BadExportSubordinate\\nmkBadExportSubordinate child_gres n =\\n case lookupChildren child_gres [n] of\\n (LookupChildNonType {lce_nontype_item = g} : _, _) -> BadExportSubordinateNonType g\\n (LookupChildNonData {lce_nondata_item = g} : _, _) -> BadExportSubordinateNonData g\\n _ -> BadExportSubordinateNotFound n\\n\\ntype IELookupM = MaybeErr IELookupError\\n\\ndata IELookupWarning\\n = BadImportW (IE GhcPs) IsSubordinateError\\n | MissingImportList\\n | DodgyImport DodgyImportsReason\\n | DeprecatedExport Name (WarningTxt GhcRn)\\n\\n-- | Is this import/export item a subordinate or not?\\ndata IsSubordinateError\\n = IsSubordinateError { subordinate_err_parent :: !GlobalRdrElt\\n , subordinate_err_unavailable :: [FastString]\\n , subordinate_err_nontype :: [GlobalRdrElt]\\n , subordinate_err_nondata :: [GlobalRdrElt] }\\n | IsNotSubordinate\\n\\nmkSubordinateError :: GlobalRdrElt -> [LookupChildError] -> IsSubordinateError\\nmkSubordinateError gre children_errs = foldr add init_acc children_errs\\n where\\n init_acc :: IsSubordinateError\\n init_acc = IsSubordinateError gre [] [] []\\n\\n add :: LookupChildError -> IsSubordinateError -> IsSubordinateError\\n add children_err sub@IsSubordinateError{} =\\n case children_err of\\n LookupChildNonType{lce_nontype_item = g} ->\\n sub { subordinate_err_nontype = g : subordinate_err_nontype sub }\\n LookupChildNonData{lce_nondata_item = g} ->\\n sub { subordinate_err_nondata = g : subordinate_err_nondata sub }\\n LookupChildNotFound (L _ wname) ->\\n let fs = (occNameFS . rdrNameOcc . ieWrappedName) wname\\n in sub { subordinate_err_unavailable = fs : subordinate_err_unavailable sub }\\n add _ IsNotSubordinate = panic \\"mkSubordinateError: IsNotSubordinate\\"\\n\\ndata IELookupError\\n = QualImportError RdrName\\n | BadImport (IE GhcPs) IsSubordinateError\\n | IllegalImport\\n\\nfailLookupWith :: IELookupError -> IELookupM a\\nfailLookupWith err = Failed err\\n\\ncatchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a\\ncatchIELookup m h = case m of\\n Succeeded r -> return r\\n Failed err -> h err\\n\\ncatIELookupM :: [IELookupM a] -> [a]\\ncatIELookupM ms = [ a | Succeeded a <- ms ]\\n\\n-- | Information associated to an \'AvailInfo\' used in constructing\\n-- an \'OccEnv\' corresponding to imports.\\n--\\n-- See Note [Dealing with imports].\\ndata ImpOccItem\\n = ImpOccItem\\n { imp_item :: GlobalRdrElt\\n -- ^ The import item\\n , imp_bundled :: [GlobalRdrElt]\\n -- ^ Items bundled in the Avail this import item came from,\\n -- not including the import item itself if it is a parent.\\n , imp_is_parent :: Bool\\n -- ^ Is the import item a parent? See Note [Dealing with imports].\\n }\\n\\ninstance Outputable ImpOccItem where\\n ppr (ImpOccItem { imp_item = item, imp_bundled = bundled, imp_is_parent = is_par })\\n = braces $ hsep\\n [ text \\"ImpOccItem\\"\\n , if is_par then text \\"[is_par]\\" else empty\\n , ppr (greName item) <+> ppr (greParent item)\\n , braces $ text \\"bundled:\\" <+> ppr (map greName bundled) ]\\n\\n-- | Make an \'OccEnv\' of all the imports.\\n--\\n-- Complicated by the fact that associated data types and pattern synonyms\\n-- can appear twice. See Note [Dealing with imports].\\nmkImportOccEnv :: HscEnv -> ImpDeclSpec -> [IfaceExport] -> OccEnv (NameEnv ImpOccItem)\\nmkImportOccEnv hsc_env decl_spec all_avails =\\n mkOccEnv_C (plusNameEnv_C combine)\\n [ (occ, mkNameEnv [(nm, item)])\\n | avail <- all_avails\\n , let gres = gresFromAvail hsc_env (Just hiding_spec) avail\\n , gre <- gres\\n , let nm = greName gre\\n occ = greOccName gre\\n (is_parent, bundled) = case avail of\\n AvailTC c _\\n | c == nm -- (Recall the AvailTC invariant from GHC.Types.AvailInfo)\\n -> ( True, drop 1 gres ) -- \\"drop 1\\": don\'t include the parent itself.\\n | otherwise\\n -> ( False, gres )\\n _ -> ( False, [] )\\n item = ImpOccItem\\n { imp_item = gre\\n , imp_bundled = bundled\\n , imp_is_parent = is_parent }\\n ]\\n where\\n\\n hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\n -- See Note [Dealing with imports]\\n -- \'combine\' may be called for associated data types which appear\\n -- twice in the all_avails. In the example, we have two Avails for T,\\n -- namely T(T,T1,T2,T3) and C(C,T), and we combine them by dropping the\\n -- latter, in which T is not the parent.\\n combine :: ImpOccItem -> ImpOccItem -> ImpOccItem\\n combine item1@(ImpOccItem { imp_item = gre1, imp_is_parent = is_parent1 })\\n item2@(ImpOccItem { imp_item = gre2, imp_is_parent = is_parent2 })\\n | is_parent1 || is_parent2\\n , not (isRecFldGRE gre1 || isRecFldGRE gre2) -- NB: does not force GREInfo.\\n , let name1 = greName gre1\\n name2 = greName gre2\\n gre = gre1 `plusGRE` gre2\\n -- See Note [Preserve parent information when combining import OccEnvs]\\n = assertPpr (name1 == name2)\\n (ppr name1 <+> ppr name2) $\\n if is_parent1\\n then item1 { imp_item = gre }\\n else item2 { imp_item = gre }\\n -- Discard C(C,T) in favour of T(T, T1, T2, T3).\\n\\n -- \'combine\' may also be called for pattern synonyms which appear both\\n -- unassociated and associated (see Note [Importing PatternSynonyms]).\\n combine item1@(ImpOccItem { imp_item = c1, imp_bundled = kids1 })\\n item2@(ImpOccItem { imp_item = c2, imp_bundled = kids2 })\\n = assertPpr (greName c1 == greName c2\\n && (not (null kids1 && null kids2)))\\n (ppr c1 <+> ppr c2 <+> ppr kids1 <+> ppr kids2) $\\n if null kids1\\n then item2\\n else item1\\n -- Discard standalone pattern P in favour of T(P).\\n\\n-- | Essentially like @lookupGRE env (LookupOccName occ which_gres)@,\\n-- but working with \'ImpOccItem\'s instead of \'GlobalRdrElt\'s.\\nlookupImpOccEnv :: WhichGREs GREInfo\\n -> OccEnv (NameEnv ImpOccItem) -> OccName -> [NameEnv ImpOccItem]\\nlookupImpOccEnv which_gres env occ =\\n mapMaybe relevant_items $ lookupOccEnv_AllNameSpaces env occ\\n where\\n is_relevant :: ImpOccItem -> Bool\\n is_relevant (ImpOccItem { imp_item = gre }) =\\n greIsRelevant which_gres (occNameSpace occ) gre\\n relevant_items :: NameEnv ImpOccItem -> Maybe (NameEnv ImpOccItem)\\n relevant_items nms\\n | let nms\' = filterNameEnv is_relevant nms\\n = if isEmptyNameEnv nms\'\\n then Nothing\\n else Just nms\'\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{Import/Export Utils}\\n* *\\n************************************************************************\\n-}\\n\\n-- | Given an import\\\\/export spec, appropriately set the @gre_imp@ field\\n-- for the \'GlobalRdrElt\'s.\\ngresFromIE :: ImpDeclSpec -> (LIE GhcRn, [GlobalRdrElt]) -> [GlobalRdrElt]\\ngresFromIE decl_spec (L loc ie, gres)\\n = map set_gre_imp gres\\n where\\n is_explicit = case ie of\\n IEThingAll _ _ name _ -> \\\\n -> n == lieWrappedName name\\n IEWholeNamespace _ _ -> \\\\_ -> False\\n _ -> \\\\_ -> True\\n prov_fn name\\n = ImpSpec { is_decl = decl_spec, is_item = item_spec }\\n where\\n item_spec = ImpSome { is_explicit = is_explicit name\\n , is_iloc = locA loc }\\n set_gre_imp gre@( GRE { gre_name = nm } )\\n = gre { gre_imp = unitBag $ prov_fn nm }\\n\\nparentOfImplicitlyImportedGRE :: Outputable info => GlobalRdrEltX info -> Maybe Name\\nparentOfImplicitlyImportedGRE gre =\\n if any (explicit_import . is_item) $ gre_imp gre\\n then Nothing\\n else greParent_maybe gre\\n where\\n explicit_import :: ImpItemSpec -> Bool\\n explicit_import (ImpAll {}) =\\n pprPanic \\"parentOfImplicitlyImportedGRE: ImpAll\\" (ppr gre)\\n explicit_import (ImpSome { is_explicit }) = is_explicit\\n\\n{- Note [Children for duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider the module\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (F(foo, MkFInt, MkFBool)) where\\n data family F a\\n data instance F Int = MkFInt { foo :: Int }\\n data instance F Bool = MkFBool { foo :: Bool }\\n\\nThe `foo` in the export list refers to *both* selectors! For this\\nreason, lookupChildren builds an environment that maps the FastString\\nto a list of items, rather than a single item.\\n-}\\n\\nmkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]\\nmkChildEnv gres = foldr add emptyNameEnv gres\\n where\\n add gre env = case greParent gre of\\n ParentIs p -> extendNameEnv_Acc (:) Utils.singleton env p gre\\n NoParent -> env\\n\\nfindChildren :: NameEnv [a] -> Name -> [a]\\nfindChildren env n = lookupNameEnv env n `orElse` []\\n\\ndata LookupChildError\\n = LookupChildNotFound { lce_wrapped_name :: !(LIEWrappedName GhcPs) }\\n | LookupChildNonType { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nontype_item :: !GlobalRdrElt }\\n | LookupChildNonData { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nondata_item :: !GlobalRdrElt }\\n\\nlookupChildren :: [GlobalRdrElt]\\n -> [LIEWrappedName GhcPs]\\n -> ( [LookupChildError] -- The ones for which the lookup failed\\n , [LocatedA GlobalRdrElt] )\\n-- (lookupChildren all_kids rdr_items) maps each rdr_item to its\\n-- corresponding Name in all_kids, if the former exists\\n-- The matching is done by FastString, not OccName, so that\\n-- Cls( meth, AssocTy )\\n-- will correctly find AssocTy among the all_kids of Cls, even though\\n-- the RdrName for AssocTy may have a (bogus) DataName namespace\\n-- (Really the rdr_items should be FastStrings in the first place.)\\nlookupChildren all_kids rdr_items = (fails, successes)\\n where\\n mb_xs = map do_one rdr_items\\n fails = [ err | Failed err <- mb_xs ]\\n successes = [ ok | Succeeded oks <- mb_xs, ok <- NE.toList oks ]\\n\\n do_one :: LIEWrappedName GhcPs -> MaybeErr LookupChildError (NonEmpty (LocatedA GlobalRdrElt))\\n do_one item@(L l r) =\\n case r of\\n IEName{}\\n -- IEName (unadorned name) places no restriction on the namespace of\\n -- the imported entity, so we look in both `val_gres` and `typ_gres`.\\n -- In case of conflict (punning), the value namespace takes priority.\\n -- See Note [Prioritise the value namespace in subordinate import lists]\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEType{}\\n -- IEType (\'type\' namespace specifier) restricts the lookup to the\\n -- type namespace, i.e. to `typ_gres`. In case of failure, we check\\n -- `val_gres` to produce a more helpful error message.\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- val_gres -> Failed $ LookupChildNonType item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEData{}\\n -- IEData (\'data\' namespace specifier) restricts the lookup to the\\n -- data namespace, i.e. to `val_gres`. In case of failure, we check\\n -- `typ_gres` to produce a more helpful error message.\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- typ_gres -> Failed $ LookupChildNonData item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEPattern{} -> panic \\"lookupChildren: IEPattern\\" -- Never happens (invalid syntax)\\n IEDefault{} -> panic \\"lookupChildren: IEDefault\\" -- Never happens (invalid syntax)\\n where\\n fs = (occNameFS . rdrNameOcc . ieWrappedName) r\\n gres = fromMaybe [] (lookupFsEnv kid_env fs)\\n (val_gres, typ_gres) = partition (isValNameSpace . greNameSpace) gres\\n\\n -- See Note [Children for duplicate record fields]\\n kid_env :: FastStringEnv [GlobalRdrElt]\\n kid_env = extendFsEnvList_C (++) emptyFsEnv\\n [(occNameFS (occName x), [x]) | x <- all_kids]\\n\\n\\n{- Note [Prioritise the value namespace in subordinate import lists]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider this program that defines a class that has both an associated type\\nnamed (#) and a method named (#)\\n\\n module M_assoc where\\n class C a b where\\n type a # b\\n (#) :: a -> b -> ()\\n module N_assoc where\\n import M_assoc( C((#)) )\\n\\nIn the import declaration, when we see the unadorned name (#) in the subordinate\\nimport list of C, which children should we bring into scope? Our options are:\\n\\n a) only the method (#)\\n b) only the associated type (#)\\n c) both the method and the associated type\\n\\nTo follow the precedent established by top-level items, we go with option (a).\\nIndeed, consider a slightly different program\\n\\n module M_top where\\n type family a # b\\n a # b = ()\\n module N_top where\\n import M_top( (#) )\\n\\nHere the import brings only the function (#) into scope, and one has to say\\n`type (#)` to get the type family.\\n-}\\n\\n-------------------------------\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused names}\\n* *\\n*********************************************************\\n-}\\n\\nreportUnusedNames :: TcGblEnv -> HscSource -> RnM ()\\nreportUnusedNames gbl_env hsc_src\\n = do { keep <- readTcRef (tcg_keep gbl_env)\\n ; traceRn \\"RUN\\" (ppr (tcg_dus gbl_env))\\n ; warnUnusedImportDecls gbl_env hsc_src\\n ; warnUnusedTopBinds $ unused_locals keep\\n ; warnMissingSignatures gbl_env\\n ; warnMissingKindSignatures gbl_env }\\n where\\n used_names :: NameSet -> NameSet\\n used_names keep = findUses (tcg_dus gbl_env) emptyNameSet `unionNameSet` keep\\n -- NB: currently, if f x = g, we only treat \'g\' as used if \'f\' is used\\n -- Hence findUses\\n\\n -- Collect the defined names from the in-scope environment\\n defined_names :: [GlobalRdrElt]\\n defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)\\n\\n kids_env = mkChildEnv defined_names\\n -- This is done in mkExports too; duplicated work\\n\\n gre_is_used :: NameSet -> GlobalRdrElt -> Bool\\n gre_is_used used_names gre0\\n = name `elemNameSet` used_names\\n || any (\\\\ gre -> greName gre `elemNameSet` used_names) (findChildren kids_env name)\\n -- A use of C implies a use of T,\\n -- if C was brought into scope by T(..) or T(C)\\n where\\n name = greName gre0\\n\\n -- Filter out the ones that are\\n -- (a) defined in this module, and\\n -- (b) not defined by a \'deriving\' clause\\n -- The latter have an Internal Name, so we can filter them out easily\\n unused_locals :: NameSet -> [GlobalRdrElt]\\n unused_locals keep =\\n let -- Note that defined_and_used, defined_but_not_used\\n -- are both [GRE]; that\'s why we need defined_and_used\\n -- rather than just used_names\\n _defined_and_used, defined_but_not_used :: [GlobalRdrElt]\\n (_defined_and_used, defined_but_not_used)\\n = partition (gre_is_used (used_names keep)) defined_names\\n\\n in filter is_unused_local defined_but_not_used\\n is_unused_local :: GlobalRdrElt -> Bool\\n is_unused_local gre = isLocalGRE gre\\n && isExternalName (greName gre)\\n\\n{- *********************************************************************\\n* *\\n Missing signatures\\n* *\\n********************************************************************* -}\\n\\n{-\\nNote [Missing signatures]\\n~~~~~~~~~~~~~~~~~~~~~~~~~\\nThere are four warning flags in play:\\n\\n * -Wmissing-exported-signatures\\n Warn about any exported top-level function/value without a type signature.\\n Does not include pattern synonyms.\\n\\n * -Wmissing-signatures\\n Warn about any top-level function/value without a type signature. Does not\\n include pattern synonyms. Takes priority over -Wmissing-exported-signatures.\\n\\n * -Wmissing-exported-pattern-synonym-signatures\\n Warn about any exported pattern synonym without a type signature.\\n\\n * -Wmissing-pattern-synonym-signatures\\n Warn about any pattern synonym without a type signature. Takes priority over\\n -Wmissing-exported-pattern-synonym-signatures.\\n\\n-}\\n\\n-- | Warn the user about top level binders that lack type signatures.\\n-- Called /after/ type inference, so that we can report the\\n-- inferred type of the function\\nwarnMissingSignatures :: TcGblEnv -> RnM ()\\nwarnMissingSignatures gbl_env\\n = do { let exports = availsToNameSet (tcg_exports gbl_env)\\n sig_ns = tcg_sigs gbl_env\\n -- We use sig_ns to exclude top-level bindings that are generated by GHC\\n binds = collectHsBindsBinders CollNoDictBinders $ tcg_binds gbl_env\\n pat_syns = tcg_patsyns gbl_env\\n\\n not_ghc_generated :: Name -> Bool\\n not_ghc_generated name = name `elemNameSet` sig_ns\\n\\n add_binding_warn :: Id -> RnM ()\\n add_binding_warn id =\\n when (not_ghc_generated name) $\\n do { env <- liftZonkM $ tcInitTidyEnv -- Why not use emptyTidyEnv?\\n ; let ty = tidyOpenType env (idType id)\\n missing = MissingTopLevelBindingSig name ty\\n diag = TcRnMissingSignature missing exported\\n ; addDiagnosticAt (getSrcSpan name) diag }\\n where\\n name = idName id\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n add_patsyn_warn :: PatSyn -> RnM ()\\n add_patsyn_warn ps =\\n when (not_ghc_generated name) $\\n addDiagnosticAt (getSrcSpan name)\\n (TcRnMissingSignature missing exported)\\n where\\n name = patSynName ps\\n missing = MissingPatSynSig ps\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n -- Warn about missing signatures\\n -- Do this only when we have a type to offer\\n -- See Note [Missing signatures]\\n ; mapM_ add_binding_warn binds\\n ; mapM_ add_patsyn_warn pat_syns\\n }\\n\\n-- | Warn the user about tycons that lack kind signatures.\\n-- Called /after/ type (and kind) inference, so that we can report the\\n-- inferred kinds.\\nwarnMissingKindSignatures :: TcGblEnv -> RnM ()\\nwarnMissingKindSignatures gbl_env\\n = do { cusks_enabled <- xoptM LangExt.CUSKs\\n ; mapM_ (add_ty_warn cusks_enabled) tcs\\n }\\n where\\n tcs = tcg_tcs gbl_env\\n ksig_ns = tcg_ksigs gbl_env\\n exports = availsToNameSet (tcg_exports gbl_env)\\n\\n has_kind_signature :: Name -> Bool\\n has_kind_signature name = name `elemNameSet` ksig_ns\\n\\n add_ty_warn :: Bool -> TyCon -> RnM ()\\n add_ty_warn cusks_enabled tyCon =\\n when (has_kind_signature name) $\\n addDiagnosticAt (getSrcSpan name) diag\\n where\\n name = tyConName tyCon\\n diag = TcRnMissingSignature missing exported\\n missing = MissingTyConKindSig tyCon cusks_enabled\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused imports}\\n* *\\n*********************************************************\\n\\nThis code finds which import declarations are unused. The\\nspecification and implementation notes are here:\\n https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/unused-imports\\n\\nSee also Note [Choosing the best import declaration] in GHC.Types.Name.Reader\\n-}\\n\\ntype ImportDeclUsage\\n = ( LImportDecl GhcRn -- The import declaration\\n , [GlobalRdrElt] -- What *is* used (normalised)\\n , [Name] -- What is imported but *not* used\\n , [NamespaceSpecifier GhcRn] ) -- Unused wildcards\\n\\nwarnUnusedImportDecls :: TcGblEnv -> HscSource -> RnM ()\\nwarnUnusedImportDecls gbl_env hsc_src\\n = do { uses <- readMutVar (tcg_used_gres gbl_env)\\n ; let imports = tcg_rn_imports gbl_env\\n rdr_env = tcg_rdr_env gbl_env\\n\\n -- We should only warn for unnecessary *user* imports, but deciding\\n -- minimal imports should take generated imports into account\\n ; let usageUserImports = findImportUsage (excludeGenerated imports) uses\\n usageAllImports = findImportUsage imports uses\\n\\n ; traceRn \\"warnUnusedImportDecls\\" $\\n (vcat [ text \\"Uses:\\" <+> ppr uses\\n , text \\"Usage all user imports: \\" <+> ppr usageUserImports\\n , text \\"Usage all imports: \\" <+> ppr usageAllImports])\\n\\n ; mapM_ (warnUnusedImport rdr_env) usageUserImports\\n\\n ; whenGOptM Opt_D_dump_minimal_imports $\\n printMinimalImports hsc_src usageAllImports }\\n\\n-- | Exclude generated imports\\nexcludeGenerated :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\nexcludeGenerated = filterOut (isGeneratedImport . ideclOrigin . ideclExt . unLoc)\\n\\nfindImportUsage :: [LImportDecl GhcRn]\\n -> [GlobalRdrElt]\\n -> [ImportDeclUsage]\\n\\nfindImportUsage imports used_gres\\n = map unused_decl imports\\n where\\n import_usage :: ImportMap\\n import_usage = mkImportMap used_gres\\n\\n unused_decl :: LImportDecl GhcRn -> ImportDeclUsage\\n unused_decl decl@(L _ (ImportDecl { ideclImportList = imps }))\\n = -- pprTrace \\"unused_decl\\" (vcat [ ppr decl\\n -- , text \\"used\\" <+> ppr used_gres\\n -- , text \\"unused\\" <+> ppr unused_names ]) $\\n (decl, used_gres, unused_names, unused_wcs)\\n where\\n used_gres = lookupImportMap decl import_usage\\n\\n used_gre_env = mkGlobalRdrEnv used_gres\\n used_parents = mkNameSet (mapMaybe greParent_maybe used_gres)\\n\\n (unused_names, unused_wcs) -- Not trivial; see eg #7454\\n = case imps of\\n Just (Exactly, imp_ies) ->\\n let unused = foldr (add_unused . unLoc) emptyUnusedNames imp_ies\\n nms = nameSetElemsStable (collectUnusedNames unused)\\n wcs = collectUnusedWildcards unused\\n in (nms, wcs)\\n _other -> ([], []) -- No explicit import list => no unused-name list\\n\\n add_unused :: IE GhcRn -> UnusedNames -> UnusedNames\\n add_unused (IEVar _ n _) acc = add_unused_name (lieWrappedName n) True acc\\n add_unused (IEThingAbs _ n _) acc = add_unused_name (lieWrappedName n) False acc\\n add_unused (IEThingAll _ _ n _) acc = add_unused_all (lieWrappedName n) acc\\n add_unused (IEThingWith _ p wc ns _) acc = add_wc_all (add_unused_with pn xs acc)\\n where pn = lieWrappedName p\\n xs = map lieWrappedName ns\\n add_wc_all = case wc of\\n NoIEWildcard -> id\\n IEWildcard _ -> add_unused_all pn\\n add_unused (IEWholeNamespace x ns_spec) acc = add_unused_wildcard ns_spec (iewn_names x) acc\\n add_unused _ acc = acc\\n\\n add_unused_name :: Name -> Bool -> UnusedNames -> UnusedNames\\n add_unused_name n is_ie_var acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | is_ie_var\\n , isFieldName n\\n -- See Note [Reporting unused imported duplicate record fields]\\n = let\\n fs = getOccFS n\\n (flds, flds_used) = lookupFsEnv acc_fs fs `orElse` (emptyNameSet, Any False)\\n acc_fs\' = extendFsEnv acc_fs fs (extendNameSet flds n, Any used S.<> flds_used)\\n in UnusedNames acc_ns acc_wcs acc_fs\'\\n\\n | used\\n = acc\\n\\n | otherwise\\n = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n where\\n used = isJust $ lookupGRE_Name used_gre_env n\\n\\n add_unused_all :: Name -> UnusedNames -> UnusedNames\\n add_unused_all n acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | Just {} <- lookupGRE_Name used_gre_env n = acc\\n | n `elemNameSet` used_parents = acc\\n | otherwise = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n\\n add_unused_with :: Name -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_with p ns acc\\n | all (`elemNameSet` acc1_ns) ns = add_unused_name p False acc1\\n | otherwise = acc1\\n where\\n acc1@(UnusedNames acc1_ns _ _) = foldr (\\\\n acc\' -> add_unused_name n False acc\') acc ns\\n -- If you use \'signum\' from Num, then the user may well have\\n -- imported Num(signum). We don\'t want to complain that\\n -- Num is not itself mentioned. Hence the two cases in add_unused_with.\\n\\n add_unused_wildcard :: NamespaceSpecifier GhcRn -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_wildcard ns_spec names acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | any_used = acc\\n | otherwise = UnusedNames acc_ns (ns_spec : acc_wcs) acc_fs\\n where\\n -- A wildcard `type ..` or `data ..` is used if at least one of\\n -- the names it expands to is used\\n any_used = any (isJust . lookupGRE_Name used_gre_env) names\\n\\n\\n-- | An accumulator for unused names in an import list.\\n--\\n-- See Note [Reporting unused imported duplicate record fields].\\ndata UnusedNames =\\n UnusedNames\\n { unused_names :: NameSet\\n -- ^ Unused \'Name\'s in an import list, not including record fields\\n -- that are plain \'IEVar\' imports (tracked by \'rec_fld_uses\')\\n -- or wildcard imports (tracked by \'unused_wildcards\').\\n , unused_wildcards :: [NamespaceSpecifier GhcRn]\\n -- ^ Unused wildcards @type ..@ or @data ..@ in an import list.\\n , rec_fld_uses :: FastStringEnv (NameSet, Any)\\n -- ^ Record fields imported without a parent (i.e. an \'IEVar\' import).\\n --\\n -- The \'Any\' value records whether any of the record fields\\n -- sharing the same underlying \'FastString\' have been used.\\n }\\n\\nemptyUnusedNames :: UnusedNames\\nemptyUnusedNames = UnusedNames emptyNameSet [] emptyFsEnv\\n\\ninstance Outputable UnusedNames where\\n ppr (UnusedNames nms wcs flds) =\\n text \\"UnusedNames\\" <+>\\n braces (ppr nms <+> ppr wcs <+> ppr (fmap (second getAny) flds))\\n\\n-- | Collect all unused names from a \'UnusedNames\' value.\\ncollectUnusedNames :: UnusedNames -> NameSet\\ncollectUnusedNames (UnusedNames { unused_names = nms, rec_fld_uses = flds })\\n = nms S.<> unused_flds\\n where\\n unused_flds = nonDetFoldFsEnv collect_unused emptyNameSet flds\\n collect_unused :: (NameSet, Any) -> NameSet -> NameSet\\n collect_unused (nms, Any at_least_one_name_is_used) acc\\n | at_least_one_name_is_used = acc\\n | otherwise = unionNameSet nms acc\\n\\ncollectUnusedWildcards :: UnusedNames -> [NamespaceSpecifier GhcRn]\\ncollectUnusedWildcards = unused_wildcards\\n\\n{- Note [Reporting unused imported duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have (#24035):\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M1 (R1(..), R2(..)) where\\n data R1 = MkR1 { fld :: Int }\\n data R2 = MkR2 { fld :: Int }\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M2 where\\n import M1 (R1(MkR1), R2, fld)\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nIn the import of \'M1\' in \'M2\', the \'fld\' import resolves to two separate GREs,\\nnamely R1(fld) and R2(fld). From the perspective of the renamer, and in particular\\nthe \'findImportUsage\' function, it\'s as if the user had imported the two names\\nseparately (even though no source syntax allows that).\\n\\nThis means that we need to be careful when reporting unused imports: the R2(fld)\\nimport is indeed unused, but because R1(fld) is used, we should not report\\nfld as unused altogether.\\n\\nTo achieve this, we keep track of record field imports without a parent (i.e.\\nusing the IEVar constructor) separately from other import items, using the\\nUnusedNames datatype.\\nOnce we have accumulated usages, we emit warnings for unused record fields\\nwithout parents one whole group (of record fields sharing the same textual name)\\nat a time, and only if *all* of the record fields in the group are unused;\\nsee \'collectUnusedNames\'.\\n\\nNote that this only applies to record fields imported without a parent. If we\\nhad:\\n\\n import M1 (R1(MkR1, fld), R2(fld))\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nthen of course we should report the second \'fld\' as unused.\\n-}\\n\\n\\n{- Note [The ImportMap]\\n~~~~~~~~~~~~~~~~~~~~~~~\\nThe ImportMap is a short-lived intermediate data structure records, for\\neach import declaration, what stuff brought into scope by that\\ndeclaration is actually used in the module.\\n\\nThe [GlobalRdrElt] are the things imported from that decl.\\n-}\\n\\ndata ImportMap = ImportMap\\n { im_imports :: Map RealSrcSpan [GlobalRdrElt]\\n -- ^ See [The ImportMap]\\n -- If loc :-> gres, then\\n -- \'loc\' = the end loc of the bestImport of each GRE in \'gres\'\\n , im_generatedImports :: Map ModuleName [GlobalRdrElt]\\n }\\n\\nmkImportMap :: [GlobalRdrElt] -> ImportMap\\n-- For each of a list of used GREs, find all the import decls that brought\\n-- it into scope; choose one of them (bestImport), and record\\n-- the RdrName in that import decl\'s entry in the ImportMap\\nmkImportMap = foldr insertImportMap $ ImportMap Map.empty Map.empty\\n\\ninsertImportMap :: GlobalRdrElt -> ImportMap -> ImportMap\\ninsertImportMap gre@(GRE { gre_imp = imp_specs }) importMap\\n | RealSrcSpan importSpan _ <- is_dloc best_imp_spec =\\n importMap{im_imports = insertElem importSpan gre $ im_imports importMap}\\n | GeneratedSrcSpan{} <- is_dloc best_imp_spec =\\n importMap{im_generatedImports = insertElem (moduleName $ is_mod best_imp_spec) gre $ im_generatedImports importMap}\\n | otherwise = importMap\\n where\\n best_imp_spec =\\n case bagToList imp_specs of\\n [] -> pprPanic \\"mkImportMap: GRE with no ImportSpecs\\" (ppr gre)\\n is:iss -> is_decl $ bestImport (is NE.:| iss)\\n\\n -- https://github.com/haskell/containers/issues/784\\n insertElem :: Ord k => k -> v -> Map k [v] -> Map k [v]\\n insertElem k v = flip Map.alter k $ \\\\case\\n Just vs -> Just (v : vs)\\n Nothing -> Just [v]\\n\\nlookupImportMap :: LImportDecl GhcRn -> ImportMap -> [GlobalRdrElt]\\nlookupImportMap (L srcSpan ImportDecl{ideclName = L _ modName}) importMap =\\n fromMaybe [] $\\n -- should match logic in insertImportMap\\n case locA srcSpan of\\n RealSrcSpan realSrcSpan _ -> realSrcSpan `Map.lookup` im_imports importMap\\n GeneratedSrcSpan{} -> modName `Map.lookup` im_generatedImports importMap\\n _ -> Nothing\\n\\nlieNames :: LIE (GhcPass p) -> [Located (IdP (GhcPass p))]\\nlieNames = _\\n\\nwarnUnusedImport :: GlobalRdrEnv -> ImportDeclUsage -> RnM ()\\nwarnUnusedImport rdr_env (L loc decl, used, unused, unused_wcs)\\n\\n -- Do not warn for \'import M()\'\\n -- See (UI1) in Note [Unused imports]\\n | Just (Exactly, _) <- ideclImportList decl\\n , null unused && null unused_wcs\\n = return ()\\n\\n -- Note [Do not warn about Prelude hiding]\\n | Just (EverythingBut, hides) <- ideclImportList decl\\n , not (null hides)\\n , pRELUDE_NAME == unLoc (ideclName decl)\\n = return ()\\n\\n -- Do not warn about import X as Rebindable\\n -- See (UI2) in Note [Unused imports]\\n | Just (L _ mod) <- ideclAs decl\\n , mod == rEBINDABLE_MOD_NAME\\n = return ()\\n\\n -- Nothing used; drop entire declaration\\n | null used\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl UnusedImportNone)\\n\\n -- Everything imported is used; nop\\n | null unused && null unused_wcs\\n = return ()\\n\\n -- Some imports are unused: make the `SrcSpan` cover only the unused\\n -- items instead of the whole import statement\\n | Just (_, imports) <- ideclImportList decl\\n , let unused_locs = [ locA loc | L loc ie <- imports\\n , name <- ieNames ie\\n , name `elem` unused ]\\n , loc1 : locs <- unused_locs\\n , let span = foldr1 combineSrcSpans ( loc1 NE.:| locs )\\n = addDiagnosticAt span (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n -- Some imports are unused\\n | otherwise\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n where\\n -- In warning message, pretty-print identifiers unqualified unconditionally\\n -- to improve the consistent for ambiguous/unambiguous identifiers.\\n -- See #14881.\\n possible_field n =\\n case lookupGRE_Name rdr_env n of\\n Just (GRE { gre_par = par, gre_info = IAmRecField info }) ->\\n let fld_occ :: OccName\\n fld_occ = nameOccName $ flSelector $ recFieldLabel info\\n in UnusedImportNameRecField par fld_occ\\n _ -> UnusedImportNameRegular n\\n\\n -- Print unused names in a deterministic (lexicographic) order\\n sort_unused :: [UnusedImportName]\\n sort_unused =\\n [ UnusedImportWildcard wc | wc <- unused_wcs ] ++\\n [ possible_field nm | nm <- sortBy (comparing nameOccName) unused ]\\n\\ngetMinimalImports :: [ImportDeclUsage] -> RnM [LImportDecl GhcRn]\\ngetMinimalImports ie_decls\\n = do { rdr_env <- getGlobalRdrEnv\\n ; fmap combine $ mapM (mk_minimal rdr_env) ie_decls }\\n where\\n mk_minimal rdr_env (L l decl, used_gres, unused, unused_wcs)\\n | null unused && null unused_wcs\\n , Just (Exactly, _) <- ideclImportList decl\\n = return (L l decl)\\n | otherwise\\n = do { let ImportDecl { ideclName = L _ mod_name\\n , ideclSource = is_boot\\n , ideclPkgQual = pkg_qual\\n , ideclExt = XImportDeclPass { ideclOrigin = origin } } = decl\\n ; iface <- loadSrcInterface doc (importDeclLookupScope origin)\\n mod_name is_boot pkg_qual\\n ; let used_avails = gresToAvailInfo used_gres\\n ; lies <- map (L l) <$> concatMapM (to_ie rdr_env iface) used_avails\\n ; return (L l (decl { ideclImportList = Just (Exactly, lies) })) }\\n where\\n doc = text \\"Compute minimal imports for\\" <+> ppr decl\\n\\n to_ie :: GlobalRdrEnv -> ModIface -> AvailInfo -> RnM [IE GhcRn]\\n -- The main trick here is that if we\'re importing all the constructors\\n -- we want to say \\"T(..)\\", but if we\'re importing only a subset we want\\n -- to say \\"T(A,B,C)\\". So we have to find out what the module exports.\\n to_ie rdr_env _ (Avail c) -- Note [Overloaded field import]\\n = do { let\\n gre = expectJust $ lookupGRE_Name rdr_env c\\n ; return $ [IEVar Nothing (to_ie_post_rn $ noLocA $ greName gre) Nothing] }\\n to_ie _ _ avail@(AvailTC n [_]) -- Exporting the main decl and nothing else\\n | availExportsDecl avail\\n = return [IEThingAbs Nothing (to_ie_post_rn $ noLocA n) Nothing]\\n to_ie rdr_env iface (AvailTC n cs) =\\n case [ xs | avail@(AvailTC x xs) <- mi_exports iface\\n , x == n\\n , availExportsDecl avail -- Note [Partial export]\\n ] of\\n [xs]\\n | all_used xs\\n -> return [IEThingAll (IEThingAllExt Nothing noAnn noAnn noAnn)\\n (NoNamespaceSpecifier noExtField)\\n (to_ie_post_rn $ noLocA n)\\n Nothing]\\n | otherwise\\n -> do { let ns_gres = map (expectJust . lookupGRE_Name rdr_env) cs\\n ns = map greName ns_gres\\n ; return [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n -- Note [Overloaded field import]\\n _other\\n -> do { let infos = map (expectJust . lookupGRE_Name rdr_env) cs\\n (ns_gres,fs_gres) = classifyGREs infos\\n ns = map greName (ns_gres ++ fs_gres)\\n fs = map fieldGREInfo fs_gres\\n ; return $\\n if all_non_overloaded fs\\n then map (\\\\nm -> IEVar Nothing (to_ie_post_rn_var $ noLocA nm) Nothing) ns\\n else [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n where\\n\\n all_used avail_cs = all (`elem` cs) avail_cs\\n\\n all_non_overloaded = all (not . flIsOverloaded . recFieldLabel)\\n\\n combine :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\n combine = map merge . NE.groupAllWith getKey\\n\\n getKey :: LImportDecl GhcRn -> (Bool, Maybe ModuleName, ModuleName)\\n getKey decl =\\n ( isImportDeclQualified . ideclQualified $ idecl -- is this qualified? (important that this be first)\\n , unLoc <$> ideclAs idecl -- what is the qualifier (inside Maybe monad)\\n , unLoc . ideclName $ idecl -- Module Name\\n )\\n where\\n idecl :: ImportDecl GhcRn\\n idecl = unLoc decl\\n\\n merge :: NonEmpty (LImportDecl GhcRn) -> LImportDecl GhcRn\\n merge decls@((L l decl) :| _) = L l (decl { ideclImportList = Just (Exactly, lies) })\\n where lies = concatMap snd $ mapMaybe (ideclImportList . unLoc) $ NE.toList decls\\n\\nclassifyGREs :: [GlobalRdrElt] -> ([GlobalRdrElt], [FieldGlobalRdrElt])\\nclassifyGREs = partition (not . isRecFldGRE)\\n\\nprintMinimalImports :: HscSource -> [ImportDeclUsage] -> RnM ()\\n-- See Note [Printing minimal imports]\\nprintMinimalImports hsc_src imports_w_usage\\n = do { imports\' <- excludeGenerated <$> getMinimalImports imports_w_usage\\n ; this_mod <- getModule\\n ; dflags <- getDynFlags\\n ; liftIO $ withFile (mkFilename dflags this_mod) WriteMode $ \\\\h ->\\n printForUser dflags h neverQualify AllTheWay (vcat (map ppr imports\'))\\n -- The neverQualify is important. We are printing Names\\n -- but they are in the context of an \'import\' decl, and\\n -- we never qualify things inside there\\n -- E.g. import Blag( f, b )\\n -- not import Blag( Blag.f, Blag.g )!\\n }\\n where\\n mkFilename dflags this_mod\\n | Just d <- dumpDir dflags = d basefn\\n | otherwise = basefn\\n where\\n suffix = case hsc_src of\\n HsBootFile -> \\".imports-boot\\"\\n HsSrcFile -> \\".imports\\"\\n HsigFile -> \\".imports\\"\\n basefn = moduleNameString (moduleName this_mod) ++ suffix\\n\\n\\nto_ie_post_rn_var :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn_var (L l n)\\n | isDataOcc $ occName n = L l (IEPattern noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n\\n\\nto_ie_post_rn :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn (L l n)\\n | isTcOcc occ && isSymOcc occ = L l (IEType noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n where occ = occName n\\n\\n{- Note [Do not warn about Prelude hiding]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWe do not warn about\\n import Prelude hiding( x, y )\\nbecause even if nothing else from Prelude is used, it may be essential to hide\\nx,y to avoid name-shadowing warnings. Example (#9061)\\n import Prelude hiding( log )\\n f x = log where log = ()\\n\\nNote [Unused imports]\\n~~~~~~~~~~~~~~~~~~~~~\\nIn `warnUnusedImport`, if we see an import with an explicit list imports, thus\\n import M( a, b )\\nand neither `a` nor `b` is used, we report the entire import decl as unused. We\\ncheck this by looking at the names that it brings into scope scope; if there are\\nno ununused names, don\'t report.\\n\\n(UI1) We don\'t want to complain about `import M()`, because that is often used to bring\\n M\'s /instances/ into scope. That is neatly dealt with by the \\"no unused\\n names\\" (nor unused wildcard imports) criterion.\\n\\n(UI2) We don\'t report a decl as unused if it has an `as Rebindable` qualifier.\\n See (KN1) in Note [Overview of known entities] in GHC.Builtin\\n\\n\\nNote [Printing minimal imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nTo print the minimal imports we walk over all import decls (both user-supplied\\nand generated), trim their import lists, then filter out generated decls.\\n\\nNB that\\n\\n * We do *not* change the \'qualified\' or \'as\' parts!\\n\\n * We do not discard a decl altogether; we might need instances\\n from it. Instead we just trim to an empty import list\\n\\nNote [Partial export]\\n~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have\\n\\n module A( op ) where\\n class C a where\\n op :: a -> a\\n\\n module B where\\n import A\\n f = ..op...\\n\\nThen the minimal import for module B is\\n import A( op )\\nnot\\n import A( C( op ) )\\nwhich we would usually generate if C was exported from B. Hence\\nthe availExportsDecl test when deciding what to generate.\\n\\n\\nNote [Overloaded field import]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nOn the other hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n data T = MkT { foo :: Int }\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( T(foo) )\\nbecause when DuplicateRecordFields is enabled, field selectors are\\nnot in scope without their enclosing datatype.\\n\\nOn the third hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n pattern MkT { foo } = Just foo\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( foo )\\nbecause foo doesn\'t have a parent. This might actually be ambiguous if A\\nexports another field called foo, but there is no good answer to return and this\\nis a very obscure corner, so it seems to be the best we can do. See\\nDRFPatSynExport for a test of this.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Errors}\\n* *\\n************************************************************************\\n-}\\n\\nbadImportItemErr\\n :: ModIface -> ImpDeclSpec -> IE GhcPs\\n -> IsSubordinateError\\n -> [AvailInfo]\\n -> TcRn (NonEmpty ImportLookupReason)\\nbadImportItemErr iface decl_spec ie sub avails = do\\n exts <- importLookupExtensions\\n let import_lookup_bad :: BadImportKind -> ImportLookupReason\\n import_lookup_bad k = ImportLookupBad k iface decl_spec ie exts\\n dflags <- getDynFlags\\n hsc_env <- getTopEnv\\n let rdr_env = mkGlobalRdrEnv\\n $ gresFromAvails hsc_env (Just imp_spec) all_avails\\n pure $ fmap import_lookup_bad (importErrorKind dflags rdr_env)\\n where\\n importErrorKind :: DynFlags -> GlobalRdrEnv -> NonEmpty BadImportKind\\n importErrorKind dflags rdr_env\\n | any checkIfTyCon avails = case sub of\\n IsNotSubordinate -> NE.singleton BadImportAvailTyCon\\n IsSubordinateError { subordinate_err_parent = gre\\n , subordinate_err_unavailable = unavailable\\n , subordinate_err_nontype = nontype\\n , subordinate_err_nondata = nondata }\\n -> NE.fromList $ catMaybes $\\n [ fmap (BadImportNotExportedSubordinates gre) (NE.nonEmpty unavailable)\\n , fmap (BadImportNonTypeSubordinates gre) (NE.nonEmpty nontype)\\n , fmap (BadImportNonDataSubordinates gre) (NE.nonEmpty nondata) ]\\n | any checkIfVarName avails = NE.singleton BadImportAvailVar\\n | Just con <- find checkIfDataCon avails = NE.singleton (BadImportAvailDataCon (availOccName con))\\n | otherwise = NE.singleton (BadImportNotExported suggs)\\n where\\n suggs = similar_suggs ++ fieldSelectorSuggestions rdr_env rdr\\n what_look = case sub of\\n IsNotSubordinate -> WL_TyCon_or_TermVar\\n IsSubordinateError { subordinate_err_parent = gre } ->\\n case greInfo gre of\\n IAmTyCon ClassFlavour\\n -> WL_TyCon_or_TermVar\\n _ -> WL_Term\\n similar_names =\\n similarNameSuggestions (Unbound.LF what_look WL_Global)\\n dflags rdr_env emptyLocalRdrEnv rdr\\n similar_suggs =\\n case NE.nonEmpty $ mapMaybe imported_item $ similar_names of\\n Just similar -> [ SuggestSimilarNames rdr similar ]\\n Nothing -> [ ]\\n\\n -- Only keep imported items, and set the \\"HowInScope\\" to\\n -- \\"Nothing\\" to avoid printing \\"imported from...\\" in the suggestion\\n -- error message.\\n imported_item (SimilarRdrName rdr_name gre (Just (ImportedBy {})))\\n = Just (SimilarRdrName rdr_name gre Nothing)\\n imported_item _ = Nothing\\n\\n checkIfDataCon = checkIfAvailMatches isDataConName\\n checkIfTyCon = checkIfAvailMatches isTyConName\\n checkIfVarName =\\n \\\\case\\n AvailTC{} -> False\\n Avail n -> importedFS == occNameFS (occName n)\\n && (isVarOcc <||> isFieldOcc) (occName n)\\n checkIfAvailMatches namePred =\\n \\\\case\\n AvailTC _ ns ->\\n case find (\\\\n -> importedFS == occNameFS (occName n)) ns of\\n Just n -> namePred n\\n Nothing -> False\\n Avail{} -> False\\n availOccName = occName . availName\\n rdr = ieName ie\\n importedFS = occNameFS $ rdrNameOcc rdr\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n all_avails = mi_exports iface\\n\\nimportLookupExtensions :: TcRn ImportLookupExtensions\\nimportLookupExtensions = do\\n ile_pattern_synonyms <- xoptM LangExt.PatternSynonyms\\n ile_explicit_namespaces <- xoptM LangExt.ExplicitNamespaces\\n return ImportLookupExtensions{ile_pattern_synonyms, ile_explicit_namespaces}\\n\\naddDupDeclErr :: NonEmpty GlobalRdrElt -> TcRn ()\\naddDupDeclErr gres@(gre :| _)\\n -- Report the error at the later location\\n = addErrAt (getSrcSpan (NE.last sorted_names)) $ (TcRnDuplicateDecls (greOccName gre) sorted_names)\\n where\\n sorted_names =\\n NE.sortBy (SrcLoc.leftmost_smallest `on` nameSrcSpan)\\n (fmap greName gres)\\n\\n-- This data decl will parse OK\\n-- data T = a Int\\n-- treating \\"a\\" as the constructor.\\n-- It is really hard to make the parser spot this malformation.\\n-- So the renamer has to check that the constructor is legal\\n--\\n-- We can get an operator as the constructor, even in the prefix form:\\n-- data T = :% Int Int\\n-- from interface files, which always print in prefix form\\n--\\n-- We also allow type constructor names, which are defined by \\"type data\\"\\n-- declarations. See Note [Type data declarations] in GHC.Rename.Module.\\n\\ncheckConName :: RdrName -> TcRn ()\\ncheckConName name\\n = checkErr (isRdrDataCon name || isRdrTc name) (TcRnIllegalDataCon name)\\n", "filetypes": ["haskell"]}}}' 2026-10-16 14:48:51,769 - DEBUG - POST b'http://127.0.0.1:37093/receive_messages' {'content-type': 'application/json', 'x-ycm-hmac': b'Rga7Yd4l4fgfufwYw+0sxzurvznImlBO0MPmgAlS4EY='} b'{"filepath": "/home/enrico/ghc/compiler/GHC/Rename/Names.hs", "line_num": 1, "column_num": 1, "working_dir": "/home/enrico/ghc", "file_data": {"/home/enrico/ghc/compiler/GHC/Rename/Names.hs": {"contents": "{-\\n(c) The GRASP/AQUA Project, Glasgow University, 1992-1998\\n\\nExtracting imported and top-level names in scope\\n-}\\n\\n{-# LANGUAGE NondecreasingIndentation #-}\\n{-# LANGUAGE TypeFamilies #-}\\n\\nmodule GHC.Rename.Names (\\n rnImports, getLocalNonValBinders, newRecordFieldLabel,\\n importsFromIface,\\n ImportUserSpec(..),\\n extendGlobalRdrEnvRn,\\n gresFromAvails,\\n calculateAvails,\\n reportUnusedNames,\\n checkConName,\\n mkChildEnv,\\n findChildren,\\n mkBadExportSubordinate,\\n findImportUsage,\\n getMinimalImports,\\n printMinimalImports,\\n renamePkgQual, renameRawPkgQual,\\n classifyGREs,\\n ImportDeclUsage,\\n rnNamespaceSpecifier\\n ) where\\n\\nimport GHC.Prelude hiding ( head, init, last, tail )\\n\\nimport GHC.Driver.Env\\nimport GHC.Driver.Session\\nimport GHC.Driver.Ppr\\n\\nimport GHC.Rename.Env\\nimport GHC.Rename.Fixity\\nimport GHC.Rename.Utils ( warnUnusedTopBinds )\\nimport GHC.Rename.Unbound\\nimport qualified GHC.Rename.Unbound as Unbound\\n\\nimport GHC.Tc.Errors.Types\\nimport GHC.Tc.Utils.Env\\nimport GHC.Tc.Utils.Monad\\nimport GHC.Tc.Types.LclEnv\\nimport GHC.Tc.Zonk.TcType ( tcInitTidyEnv )\\n\\nimport GHC.Hs\\nimport GHC.Iface.Load ( loadSrcInterface, loadSrcInterface_maybe )\\nimport GHC.Iface.Errors.Types\\n ( IfaceMessage(..), MissingInterfaceError, InterfaceLookingFor(..)\\n , LoadEssentialsReason(..) )\\nimport GHC.Iface.Syntax ( fromIfaceWarnings )\\nimport GHC.Builtin.Modules( pRELUDE_NAME, rEBINDABLE_MOD_NAME )\\nimport GHC.Parser.PostProcess ( setRdrNameSpace )\\nimport GHC.Core.TyCo.Tidy\\nimport GHC.Core.PatSyn\\nimport GHC.Core.TyCon ( TyCon, tyConName )\\nimport qualified GHC.LanguageExtensions as LangExt\\n\\nimport GHC.Utils.Outputable as Outputable\\nimport GHC.Utils.Misc as Utils\\nimport GHC.Utils.Panic\\n\\nimport GHC.Types.Fixity.Env\\nimport GHC.Types.SafeHaskell\\nimport GHC.Types.Name\\nimport GHC.Types.Name.Env\\nimport GHC.Types.Name.Set\\nimport GHC.Types.Name.Reader\\nimport GHC.Types.Avail\\nimport GHC.Types.FieldLabel\\nimport GHC.Types.Hint\\nimport GHC.Types.SourceFile\\nimport GHC.Types.SrcLoc as SrcLoc\\nimport GHC.Types.Basic (TyConFlavour (..), convImportLevel, VisArity)\\nimport GHC.Types.UnresolvedImport\\nimport GHC.Types.Id\\nimport GHC.Types.PkgQual\\nimport GHC.Types.GREInfo (ConInfo(..), ConFieldInfo (..), ConLikeInfo (ConIsData))\\n\\nimport GHC.Unit\\nimport GHC.Unit.Module.Warnings\\nimport GHC.Unit.Module.ModIface\\nimport GHC.Unit.Module.Imported\\nimport GHC.Unit.Module.Deps\\nimport GHC.Unit.Env\\n\\nimport GHC.Data.Bag\\nimport GHC.Data.FastString\\nimport GHC.Data.FastString.Env\\nimport GHC.Data.Maybe\\nimport GHC.Data.List.SetOps ( removeDups )\\n\\nimport Control.Arrow ( second )\\nimport Control.Monad\\nimport Data.Foldable ( for_ )\\nimport Data.IntMap ( IntMap )\\nimport qualified Data.IntMap as IntMap\\nimport Data.Map ( Map )\\nimport qualified Data.Map as Map\\nimport Data.Ord ( comparing )\\nimport Data.Semigroup ( Any(..) )\\nimport qualified Data.Semigroup as S\\nimport Data.List ( partition, find, sortBy )\\nimport Data.List.NonEmpty (NonEmpty(..))\\nimport qualified Data.List.NonEmpty as NE\\nimport Data.Function ( on )\\nimport qualified Data.Set as S\\nimport System.FilePath (())\\nimport System.IO\\n\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{rnImports}\\n* *\\n************************************************************************\\n\\nNote [Tracking Trust Transitively]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen we import a package as well as checking that the direct imports are safe\\naccording to the rules outlined in the Note [Safe Haskell Trust Check] in GHC.Driver.Main\\nwe must also check that these rules hold transitively for all dependent modules\\nand packages. Doing this without caching any trust information would be very\\nslow as we would need to touch all packages and interface files a module depends\\non. To avoid this we make use of the property that if a modules Safe Haskell\\nmode changes, this triggers a recompilation from that module in the dependency\\ngraph. So we can just worry mostly about direct imports.\\n\\nThere is one trust property that can change for a package though without\\nrecompilation being triggered: package trust. So we must check that all\\npackages a module transitively depends on to be trusted are still trusted when\\nwe are compiling this module (as due to recompilation avoidance some modules\\nbelow may not be considered trusted any more without recompilation being\\ntriggered).\\n\\nWe handle this by augmenting the existing transitive list of packages a module M\\ndepends on with a bool for each package that says if it must be trusted when the\\nmodule M is being checked for trust. This list of trust required packages for a\\nsingle import is gathered in the rnImportDecl function and stored in an\\nImportAvails data structure. The union of these trust required packages for all\\nimports is done by the rnImports function using the combine function which calls\\nthe plusImportAvails function that is a union operation for the ImportAvails\\ntype. This gives us in an ImportAvails structure all packages required to be\\ntrusted for the module we are currently compiling. Checking that these packages\\nare still trusted (and that direct imports are trusted) is done in\\nGHC.Driver.Main.checkSafeImports.\\n\\nSee the note below, [Trust Own Package] for a corner case in this method and\\nhow its handled.\\n\\n\\nNote [Trust Own Package]\\n~~~~~~~~~~~~~~~~~~~~~~~~\\nThere is a corner case of package trust checking that the usual transitive check\\ndoesn\'t cover. (For how the usual check operates see the Note [Tracking Trust\\nTransitively] below). The case is when you import a -XSafe module M and M\\nimports a -XTrustworthy module N. If N resides in a different package than M,\\nthen the usual check works as M will record a package dependency on N\'s package\\nand mark it as required to be trusted. If N resides in the same package as M\\nthough, then importing M should require its own package be trusted due to N\\n(since M is -XSafe so doesn\'t create this requirement by itself). The usual\\ncheck fails as a module doesn\'t record a package dependency of its own package.\\nSo instead we now have a bool field in a modules interface file that simply\\nstates if the module requires its own package to be trusted. This field avoids\\nus having to load all interface files that the module depends on to see if one\\nis trustworthy.\\n\\n\\nNote [Trust Transitive Property]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSo there is an interesting design question in regards to transitive trust\\nchecking. Say I have a module B compiled with -XSafe. B is dependent on a bunch\\nof modules and packages, some packages it requires to be trusted as its using\\n-XTrustworthy modules from them. Now if I have a module A that doesn\'t use safe\\nhaskell at all and simply imports B, should A inherit all the trust\\nrequirements from B? Should A now also require that a package p is trusted since\\nB required it?\\n\\nWe currently say no but saying yes also makes sense. The difference is, if a\\nmodule M that doesn\'t use Safe Haskell imports a module N that does, should all\\nthe trusted package requirements be dropped since M didn\'t declare that it cares\\nabout Safe Haskell (so -XSafe is more strongly associated with the module doing\\nthe importing) or should it be done still since the author of the module N that\\nuses Safe Haskell said they cared (so -XSafe is more strongly associated with\\nthe module that was compiled that used it).\\n\\nGoing with yes is a simpler semantics we think and harder for the user to stuff\\nup but it does mean that Safe Haskell will affect users who don\'t care about\\nSafe Haskell as they might grab a package from Cabal which uses safe haskell (say\\nnetwork) and that packages imports -XTrustworthy modules from another package\\n(say bytestring), so requires that package is trusted. The user may now get\\ncompilation errors in code that doesn\'t do anything with Safe Haskell simply\\nbecause they are using the network package. They will have to call \'ghc-pkg\\ntrust network\' to get everything working. Due to this invasive nature of going\\nwith yes we have gone with no for now.\\n-}\\n\\n-- | Process Import Decls. See \'rnImportDecl\' for a description of what\\n-- the return types represent.\\n-- Note: Do the non SOURCE ones first, so that we get a helpful warning\\n-- for SOURCE ones that are unnecessary\\nrnImports :: [(LImportDecl GhcPs, SDoc)]\\n -> RnM ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\nrnImports imports = do\\n tcg_env <- getGblEnv\\n -- NB: want an identity module here, because it\'s OK for a signature\\n -- module to import from its implementor\\n let this_mod = tcg_mod tcg_env\\n let (source, ordinary) = partition (is_source_import . fst) imports\\n is_source_import (d::LImportDecl GhcPs) = ideclSource (unLoc d) == IsBoot\\n stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary\\n stuff2 <- mapAndReportM (rnImportDecl this_mod) source\\n -- Safe Haskell: See Note [Tracking Trust Transitively]\\n let (decls, imp_user_spec, rdr_env, imp_avails) = combine (stuff1 ++ stuff2)\\n -- Update imp_boot_mods if imp_direct_mods mentions any of them\\n let merged_import_avail = clobberSourceImports imp_avails\\n return (decls, imp_user_spec, rdr_env, merged_import_avail)\\n\\n where\\n clobberSourceImports imp_avails =\\n imp_avails { imp_boot_mods = imp_boot_mods\' }\\n where\\n imp_boot_mods\' = mergeInstalledModuleEnv combJ id (const emptyInstalledModuleEnv)\\n (imp_boot_mods imp_avails)\\n (imp_direct_dep_mods imp_avails)\\n\\n combJ (GWIB _ IsBoot) (_, x) = Just x\\n combJ r _ = Just r\\n -- See Note [Combining ImportAvails]\\n combine :: [(LImportDecl GhcRn, ImportUserSpec, GlobalRdrEnv, ImportAvails)]\\n -> ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\n combine ss =\\n let (decls, imp_user_spec, rdr_env, imp_avails, finsts) = foldr\\n plus\\n ([], [], emptyGlobalRdrEnv, emptyImportAvails, emptyModuleSet)\\n ss\\n in (decls, imp_user_spec, rdr_env, imp_avails { imp_finsts = moduleSetElts finsts })\\n\\n plus (decl, us, gbl_env1, imp_avails1)\\n (decls, uss, gbl_env2, imp_avails2, finsts_set)\\n = ( decl:decls,\\n us:uss,\\n gbl_env1 `plusGlobalRdrEnv` gbl_env2,\\n imp_avails1\' `plusImportAvails` imp_avails2,\\n extendModuleSetList finsts_set new_finsts )\\n where\\n imp_avails1\' = imp_avails1 { imp_finsts = [] }\\n new_finsts = imp_finsts imp_avails1\\n\\n{-\\nNote [Combining ImportAvails]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nimp_finsts in ImportAvails is a list of family instance modules\\ntransitively depended on by an import. imp_finsts for a currently\\ncompiled module is a union of all the imp_finsts of imports.\\nComputing the union of two lists of size N is O(N^2) and if we\\ndo it to M imports we end up with O(M*N^2). That can get very\\nexpensive for bigger module hierarchies.\\n\\nUnion can be optimized to O(N log N) if we use a Set.\\nimp_finsts is converted back and forth between dep_finsts, so\\nchanging a type of imp_finsts means either paying for the conversions\\nor changing the type of dep_finsts as well.\\n\\nI\'ve measured that the conversions would cost 20% of allocations on my\\ntest case, so that can be ruled out.\\n\\nChanging the type of dep_finsts forces checkFamInsts to\\nget the module lists in non-deterministic order. If we wanted to restore\\nthe deterministic order, we\'d have to sort there, which is an additional\\ncost. As far as I can tell, using a non-deterministic order is fine there,\\nbut that\'s a brittle nonlocal property which I\'d like to avoid.\\n\\nAdditionally, dep_finsts is read from an interface file, so its \\"natural\\"\\ntype is a list. Which makes it a natural type for imp_finsts.\\n\\nSince rnImports.combine is really the only place that would benefit from\\nit being a Set, it makes sense to optimize the hot loop in rnImports.combine\\nwithout changing the representation.\\n\\nSo here\'s what we do: instead of naively merging ImportAvails with\\nplusImportAvails in a loop, we make plusImportAvails merge empty imp_finsts\\nand compute the union on the side using Sets. When we\'re done, we can\\nconvert it back to a list. One nice side effect of this approach is that\\nif there\'s a lot of overlap in the imp_finsts of imports, the\\nSet doesn\'t really need to grow and we don\'t need to allocate.\\n\\nRunning generateModules from #14693 with DEPTH=16, WIDTH=30 finishes in\\n23s before, and 11s after.\\n-}\\n\\n-- | Given a located import declaration @decl@ from @this_mod@,\\n-- calculate the following pieces of information:\\n--\\n-- 1. An updated \'LImportDecl\', where all unresolved \'RdrName\' in\\n-- the entity lists have been resolved into \'Name\'s,\\n--\\n-- 2. A \'GlobalRdrEnv\' representing the new identifiers that were\\n-- brought into scope (taking into account module qualification\\n-- and hiding),\\n--\\n-- 3. \'ImportAvails\' summarizing the identifiers that were imported\\n-- by this declaration, and\\n--\\n-- 4. A boolean \'AnyHpcUsage\' which is true if the imported module\\n-- used HPC.\\nrnImportDecl :: Module -> (LImportDecl GhcPs, SDoc)\\n -> RnM (LImportDecl GhcRn, ImportUserSpec , GlobalRdrEnv, ImportAvails)\\nrnImportDecl this_mod\\n (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name\\n , ideclPkgQual = raw_pkg_qual\\n , ideclSource = want_boot\\n , ideclSafe = mod_safe\\n , ideclLevelSpec = import_level\\n , ideclQualified = qual_style\\n , ideclExt = XImportDeclPass { ideclOrigin = origin }\\n , ideclAs = as_mod, ideclImportList = imp_details }), import_reason)\\n = setSrcSpanA loc $ do\\n\\n case raw_pkg_qual of\\n NoRawPkgQual -> pure ()\\n RawPkgQual {} -> do\\n pkg_imports <- xoptM LangExt.PackageImports\\n when (not pkg_imports) $ addErr TcRnPackageImportsDisabled\\n\\n let qual_only = isImportDeclQualified qual_style\\n generated = isGeneratedImport origin\\n\\n lookup_scope = importDeclLookupScope origin\\n\\n -- If there\'s an error in loadInterface, (e.g. interface\\n -- file not found) we get lots of spurious errors from \'filterImports\'\\n let imp_mod_name = unLoc loc_imp_mod_name\\n doc = ppr imp_mod_name <+> import_reason\\n\\n hsc_env <- getTopEnv\\n unit_env <- hsc_unit_env <$> getTopEnv\\n let pkg_qual = renameRawPkgQual unit_env imp_mod_name raw_pkg_qual\\n\\n -- Check for self-import, which confuses the typechecker (#9032)\\n -- ghc --make rejects self-import cycles already, but batch-mode may not\\n -- at least not until GHC.IfaceToCore.tcHiBootIface, which is too late to avoid\\n -- typechecker crashes. (Indirect self imports are not caught until\\n -- GHC.IfaceToCore, see #10337 tracking how to make this error better.)\\n --\\n -- Originally, we also allowed \'import {-# SOURCE #-} M\', but this\\n -- caused bug #10182: in one-shot mode, we should never load an hs-boot\\n -- file for the module we are compiling into the EPS. In principle,\\n -- it should be possible to support this mode of use, but we would have to\\n -- extend Provenance to support a local definition in a qualified location.\\n -- For now, we don\'t support it, but see #10336\\n when (imp_mod_name == moduleName this_mod &&\\n (case pkg_qual of -- If we have import \\"\\" M, then we should\\n -- check that \\"\\" is \\"this\\" (which is magic)\\n -- or the name of this_mod\'s package. Yurgh!\\n -- c.f. GHC.findModule, and #9997\\n NoPkgQual -> True\\n ThisPkg uid -> uid == homeUnitId_ (hsc_dflags hsc_env)\\n OtherPkg _ -> False))\\n (addErr (TcRnSelfImport imp_mod_name))\\n\\n -- Check for a missing import list (Opt_WarnMissingImportList also\\n -- checks for T(..) items but that is done in checkDodgyImport below)\\n case imp_details of\\n Just (Exactly, _) -> return () -- Explicit import list\\n _ | generated -> return () -- Do not bleat for generated imports\\n | qual_only -> return ()\\n | otherwise -> addDiagnostic (TcRnNoExplicitImportList imp_mod_name)\\n\\n\\n mb_iface <- loadSrcInterface_maybe doc lookup_scope imp_mod_name want_boot pkg_qual\\n iface <- case mb_iface of\\n Succeeded iface -> return iface\\n Failed err -> failWithTc $\\n importDeclLoadFailure origin imp_mod_name want_boot err\\n\\n -- Compiler sanity check: if the import didn\'t say\\n -- {-# SOURCE #-} we should not get a hi-boot file\\n warnPprTrace ((want_boot == NotBoot) && (mi_boot iface == IsBoot)) \\"rnImportDecl\\" (ppr imp_mod_name) $ do\\n\\n -- Issue a user warning for a redundant {- SOURCE -} import\\n -- NB that we arrange to read all the ordinary imports before\\n -- any of the {- SOURCE -} imports.\\n --\\n -- in --make and GHCi, the compilation manager checks for this,\\n -- and indeed we shouldn\'t do it here because the existence of\\n -- the non-boot module depends on the compilation order, which\\n -- is not deterministic. The hs-boot test can show this up.\\n dflags <- getDynFlags\\n warnIf ((want_boot == IsBoot) && (mi_boot iface == NotBoot) && isOneShot (ghcMode dflags))\\n (TcRnRedundantSourceImport imp_mod_name)\\n when (mod_safe && not (safeImportsOn dflags)) $\\n addErr (TcRnSafeImportsDisabled imp_mod_name)\\n\\n let imp_mod = mi_module iface\\n qual_mod_name = fmap unLoc as_mod `orElse` imp_mod_name\\n imp_spec = ImpDeclSpec { is_mod = imp_mod, is_qual = qual_only,\\n is_dloc = locA loc, is_as = qual_mod_name,\\n is_pkg_qual = pkg_qual, is_isboot = want_boot,\\n is_level = convImportLevel import_level }\\n\\n let filter_imports = do\\n -- filter the imports according to the import declaration\\n (new_imp_details, imp_user_list, gbl_env)\\n <- filterImports hsc_env iface imp_spec imp_details\\n -- for certain error messages, we\\u2019d like to know what could be\\n -- imported here, if everything were imported\\n potential_gres <- (\\\\(_,_,x) -> x) <$> filterImports hsc_env iface imp_spec Nothing\\n return (new_imp_details, imp_user_list, gbl_env, potential_gres)\\n\\n (new_imp_details, imp_user_list, gbl_env, potential_gres) <-\\n case origin of\\n ImplicitEssentialsImport ->\\n -- The implicit GHC.Essentials import does not bring anything into scope.\\n -- See Note [Finding GHC.Essentials] in GHC.Builtin.\\n return (Nothing, ImpUserDependOnly, emptyGlobalRdrEnv, emptyGlobalRdrEnv)\\n UserWrittenImport -> filter_imports\\n ImplicitPreludeImport -> filter_imports\\n PluginImport -> filter_imports\\n\\n let is_hiding | Just (EverythingBut,_) <- imp_details = True\\n | otherwise = False\\n\\n -- should the import be safe?\\n mod_safe\' = mod_safe\\n || (not generated && safeDirectImpsReq dflags)\\n || (generated && safeImplicitImpsReq dflags)\\n\\n hsc_env <- getTopEnv\\n let home_unit = hsc_home_unit hsc_env\\n other_home_units = hsc_all_home_unit_ids hsc_env\\n\\n imported_by\\n | isDependOnlyImport imp_user_list\\n = ImportedBySystem\\n | otherwise\\n = ImportedByUser $ ImportedModsVal\\n { imv_name = is_as imp_spec\\n , imv_span = locA loc\\n , imv_is_safe = mod_safe\'\\n , imv_is_hiding = is_hiding\\n , imv_all_exports = potential_gres\\n , imv_qualified = qual_only\\n , imv_is_level = convImportLevel import_level\\n }\\n imports = calculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by\\n\\n -- Complain if we import a deprecated module\\n case fromIfaceWarnings (mi_warns iface) of\\n WarnAll txt -> addDiagnostic (TcRnDeprecatedModule imp_mod_name txt)\\n _ -> return ()\\n\\n let new_imp_decl = ImportDecl\\n { ideclExt = ideclExt decl\\n , ideclName = ideclName decl\\n , ideclPkgQual = pkg_qual\\n , ideclSource = ideclSource decl\\n , ideclSafe = mod_safe\'\\n , ideclQualified = ideclQualified decl\\n , ideclAs = ideclAs decl\\n , ideclImportList = new_imp_details\\n , ideclLevelSpec = ideclLevelSpec decl\\n }\\n\\n return (L loc new_imp_decl, ImpUserSpec imp_spec imp_user_list, gbl_env, imports)\\n\\n-- | The error message to emit when we failed to load an interface.\\nimportDeclLoadFailure :: ImportDeclOrigin -> ModuleName -> IsBootInterface\\n -> MissingInterfaceError -> TcRnMessage\\nimportDeclLoadFailure ImplicitEssentialsImport _ _ err\\n = TcRnInterfaceError $ CantFindEssentials err LookingForEssentialsModule\\nimportDeclLoadFailure _ mod_name want_boot err\\n = TcRnInterfaceError $ Can\'tFindInterface err $ LookingForModule mod_name want_boot\\n\\n-- | Rename raw package imports\\nrenameRawPkgQual :: UnitEnv -> ModuleName -> RawPkgQual -> PkgQual\\nrenameRawPkgQual unit_env mn = \\\\case\\n NoRawPkgQual -> NoPkgQual\\n RawPkgQual _ fs -> renamePkgQual unit_env mn $ Just fs\\n\\n-- | Rename raw package imports\\nrenamePkgQual :: UnitEnv -> ModuleName -> Maybe FastString -> PkgQual\\nrenamePkgQual unit_env mn mb_pkg = case mb_pkg of\\n Nothing -> NoPkgQual\\n Just pkg_fs\\n | Just uid <- homeUnitId <$> ue_homeUnit unit_env\\n , pkg_fs == fsLit \\"this\\"\\n -> ThisPkg uid\\n\\n | Just (uid, _) <- find (fromMaybe False . fmap (== pkg_fs) . snd) home_names\\n -> ThisPkg uid\\n\\n | Just uid <- resolvePackageImport unit_state mn (PackageName pkg_fs)\\n -> OtherPkg uid\\n\\n | otherwise\\n -> OtherPkg (UnitId pkg_fs)\\n -- not really correct as pkg_fs is unlikely to be a valid unit-id but\\n -- we will report the failure later...\\n where\\n home_names =\\n [ (uid, mkFastString <$> thisPackageName (homeUnitEnv_dflags (ue_findHomeUnitEnv uid unit_env)))\\n | uid <- S.toList hpt_deps\\n ]\\n\\n unit_state = ue_homeUnitState unit_env\\n\\n hpt_deps :: S.Set UnitId\\n hpt_deps = homeUnitDepends unit_state\\n\\n\\n-- | Calculate the \'ImportAvails\' induced by an import of a particular\\n-- interface, but without \'imp_mods\'.\\ncalculateAvails :: HomeUnit\\n -> S.Set UnitId\\n -> ModIface\\n -> IsSafeImport\\n -> IsBootInterface\\n -> ImportedBy\\n -> ImportAvails\\ncalculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by =\\n let imp_mod = mi_module iface\\n imp_sem_mod= mi_semantic_module iface\\n orph_iface = mi_orphan iface\\n has_finsts = mi_finsts iface\\n deps = mi_deps iface\\n trust = getSafeMode $ mi_trust iface\\n trust_pkg = mi_trust_pkg iface\\n is_sig = mi_hsc_src iface == HsigFile\\n\\n -- If the module exports anything defined in this module, just\\n -- ignore it. Reason: otherwise it looks as if there are two\\n -- local definition sites for the thing, and an error gets\\n -- reported. Easiest thing is just to filter them out up\\n -- front. This situation only arises if a module imports\\n -- itself, or another module that imported it. (Necessarily,\\n -- this involves a loop.)\\n --\\n -- We do this *after* filterImports, so that if you say\\n -- module A where\\n -- import B( AType )\\n -- type AType = ...\\n --\\n -- module B( AType ) where\\n -- import {-# SOURCE #-} A( AType )\\n --\\n -- then you won\'t get a \'B does not export AType\' message.\\n\\n\\n -- Compute new transitive dependencies\\n --\\n -- \'dep_orphs\' and \'dep_finsts\' do NOT include the imported module\\n -- itself, but we DO need to include this module in \'imp_orphs\' and\\n -- \'imp_finsts\' if it defines an orphan or instance family; thus the\\n -- orph_iface/has_iface tests.\\n\\n deporphs = dep_orphs deps\\n depfinsts = dep_finsts deps\\n\\n orphans | orph_iface = assertPpr (not (imp_sem_mod `elem` deporphs)) (ppr imp_sem_mod <+> ppr deporphs) $\\n imp_sem_mod : deporphs\\n | otherwise = deporphs\\n\\n finsts | has_finsts = assertPpr (not (imp_sem_mod `elem` depfinsts)) (ppr imp_sem_mod <+> ppr depfinsts) $\\n imp_sem_mod : depfinsts\\n | otherwise = depfinsts\\n\\n -- Trusted packages are a lot like orphans.\\n trusted_pkgs | mod_safe\' = dep_trusted_pkgs deps\\n | otherwise = S.empty\\n\\n\\n pkg = moduleUnit (mi_module iface)\\n ipkg = toUnitId pkg\\n\\n -- Does this import mean we now require our own pkg\\n -- to be trusted? See Note [Trust Own Package]\\n ptrust = trust == Sf_Trustworthy || trust_pkg\\n pkg_trust_req\\n | isHomeUnit home_unit pkg = ptrust\\n | otherwise = False\\n\\n dependent_pkgs = if toUnitId pkg `S.member` other_home_units\\n then S.empty\\n else S.singleton (lvl, ipkg)\\n\\n lvl = case imported_by of\\n ImportedByUser imv -> imv_is_level imv\\n ImportedBySystem -> NormalLevel\\n\\n\\n direct_mods = if toUnitId pkg `S.member` other_home_units\\n then mkPlusModDeps (moduleUnitId imp_mod) lvl (GWIB (moduleName imp_mod) want_boot)\\n else emptyInstalledModuleEnv\\n\\n dep_boot_mods_map = mkModDeps (dep_boot_mods deps)\\n\\n\\n boot_mods\\n -- If we are looking for a boot module, it must be HPT\\n | IsBoot <- want_boot = extendInstalledModuleEnv dep_boot_mods_map (toUnitId <$> imp_mod) (GWIB (moduleName imp_mod) IsBoot)\\n -- Now we are importing A properly, so don\'t go looking for\\n -- A.hs-boot\\n | isHomeUnit home_unit pkg = dep_boot_mods_map\\n -- There\'s no boot files to find in external imports\\n | otherwise = emptyInstalledModuleEnv\\n\\n sig_mods =\\n if is_sig\\n then moduleName imp_mod : dep_sig_mods deps\\n else dep_sig_mods deps\\n\\n\\n in ImportAvails {\\n imp_mods = Map.singleton (mi_module iface) [imported_by],\\n imp_orphs = orphans,\\n imp_finsts = finsts,\\n imp_sig_mods = sig_mods,\\n imp_direct_dep_mods = direct_mods,\\n imp_dep_direct_pkgs = dependent_pkgs,\\n imp_boot_mods = boot_mods,\\n\\n -- Add in the imported modules trusted package\\n -- requirements. ONLY do this though if we import the\\n -- module as a safe import.\\n -- See Note [Tracking Trust Transitively]\\n -- and Note [Trust Transitive Property]\\n imp_trust_pkgs = trusted_pkgs,\\n -- Do we require our own pkg to be trusted?\\n -- See Note [Trust Own Package]\\n imp_trust_own_pkg = pkg_trust_req\\n }\\n\\nmkPlusModDeps :: UnitId -> ImportLevel -> ModuleNameWithIsBoot\\n -> InstalledModuleEnv (S.Set ImportLevel, ModuleNameWithIsBoot)\\nmkPlusModDeps uid st elt = extendInstalledModuleEnv emptyInstalledModuleEnv (mkModule uid (gwib_mod elt)) (S.singleton st, elt)\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{importsFromLocalDecls}\\n* *\\n************************************************************************\\n\\nFrom the top-level declarations of this module produce\\n * the lexical environment\\n * the ImportAvails\\ncreated by its bindings.\\n\\nNote [Top-level Names in Template Haskell decl quotes]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSee also: Note [Interactively-bound Ids in GHCi] in GHC.Driver.Env\\n Note [Looking up Exact RdrNames] in GHC.Rename.Env\\n\\nConsider a Template Haskell declaration quotation like this:\\n module M where\\n f x = h [d| f = 3 |]\\nWhen renaming the declarations inside [d| ...|], we treat the\\ntop level binders specially in two ways\\n\\n1. We give them an Internal Name, not (as usual) an External one.\\n This is done by GHC.Rename.Env.newTopSrcBinder.\\n\\n2. We make them *shadow* the outer bindings.\\n See Note [GlobalRdrEnv shadowing]\\n\\n3. We find out whether we are inside a [d| ... |] by testing the TH\\n level. This is a slight hack, because the level field was really\\n meant for the type checker, and here we are not interested in the\\n fields of Brack, hence the error thunks in thRnBrack.\\n-}\\n\\nextendGlobalRdrEnvRn :: [GlobalRdrElt]\\n -> MiniFixityEnv\\n -> RnM (TcGblEnv, TcLclEnv)\\n-- Updates both the GlobalRdrEnv and the FixityEnv\\n-- We return a new TcLclEnv only because we might have to\\n-- delete some bindings from it;\\n-- see Note [Top-level Names in Template Haskell decl quotes]\\n\\nextendGlobalRdrEnvRn new_gres new_fixities\\n = checkNoErrs $ -- See Note [Fail fast on duplicate definitions]\\n do { (gbl_env, lcl_env) <- getEnvs\\n ; level <- getThLevel\\n ; isGHCi <- getIsGHCi\\n ; let rdr_env = tcg_rdr_env gbl_env\\n fix_env = tcg_fix_env gbl_env\\n th_bndrs = getLclEnvThBndrs lcl_env\\n th_lvl = thLevelIndex level\\n\\n -- Delete new_occs from global and local envs\\n -- If we are in a TemplateHaskell decl bracket,\\n -- we are going to shadow them\\n -- See Note [GlobalRdrEnv shadowing]\\n inBracket = isBrackLevel level\\n\\n lcl_env_TH = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_rdr = minusLocalRdrEnv (tcl_rdr lcl_env) new_gres_env }) lcl_env\\n -- See Note [GlobalRdrEnv shadowing]\\n\\n lcl_env2 | inBracket = lcl_env_TH\\n | otherwise = lcl_env\\n\\n -- Deal with shadowing: see Note [GlobalRdrEnv shadowing]\\n want_shadowing = isGHCi || inBracket\\n rdr_env1 | want_shadowing = shadowNames False rdr_env new_gres_env\\n | otherwise = rdr_env\\n\\n lcl_env3 = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_th_bndrs = extendNameEnvList th_bndrs\\n [ ( n, (TopLevel, th_lvl) )\\n | n <- new_names ] }) lcl_env2\\n\\n ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres\\n\\n ; let fix_env\' = foldl\' extend_fix_env fix_env new_gres\\n gbl_env\' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env\' }\\n\\n ; traceRn \\"extendGlobalRdrEnvRn 2\\" (pprGlobalRdrEnv True rdr_env2)\\n ; return (gbl_env\', lcl_env3) }\\n where\\n new_names = map greName new_gres\\n new_gres_env = mkGlobalRdrEnv new_gres\\n\\n -- If there is a fixity decl for the gre, add it to the fixity env\\n extend_fix_env fix_env gre\\n | Just (L _ fi) <- lookupMiniFixityEnv new_fixities name\\n = extendNameEnv fix_env name (FixItem occ fi)\\n | otherwise\\n = fix_env\\n where\\n name = greName gre\\n occ = greOccName gre\\n\\n add_gre :: GlobalRdrEnv -> GlobalRdrElt -> RnM GlobalRdrEnv\\n -- Extend the GlobalRdrEnv with a LocalDef GRE\\n -- If there is already a LocalDef GRE with the same OccName,\\n -- report an error and discard the new GRE\\n -- This establishes INVARIANT 1 of GlobalRdrEnvs\\n add_gre env gre\\n | not (null dups) -- Same OccName defined twice\\n = do { addDupDeclErr (gre :| dups); return env }\\n\\n | otherwise\\n = return (extendGlobalRdrEnv env gre)\\n where\\n -- See Note [Reporting duplicate local declarations]\\n dups = filter isBadDupGRE\\n $ lookupGRE env (LookupOccName (greOccName gre) (RelevantGREsFOS WantBoth))\\n isBadDupGRE old_gre = isLocalGRE old_gre && greClashesWith gre old_gre\\n\\n{- Note [Fail fast on duplicate definitions]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIf there are duplicate bindings for the same thing, we want to fail\\nfast. Having two bindings for the same thing can cause follow-on errors.\\nExample (test T9975a):\\n data Test = Test { x :: Int }\\n pattern Test wat = Test { x = wat }\\nThis defines \'Test\' twice. The second defn has no field-names; and then\\nwe get an error from Test { x=wat }, saying \\"Test has no field \'x\'\\".\\n\\nEasiest thing is to bale out fast on duplicate definitions, which\\nwe do via `checkNoErrs` on `extendGlobalRdrEnvRn`.\\n\\nNote [Reporting duplicate local declarations]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn general, a single module may not define the same OccName multiple times. This\\nis checked in extendGlobalRdrEnvRn: when adding a new locally-defined GRE to the\\nGlobalRdrEnv we report an error if there are already duplicates in the\\nenvironment. This establishes INVARIANT 1 (see comments on GlobalRdrEnv in\\nGHC.Types.Name.Reader), which says that for a given OccName, all the\\nGlobalRdrElts to which it maps must have distinct \'greName\'s.\\n\\nFor example, the following will be rejected:\\n\\n f x = x\\n g x = x\\n f x = x -- Duplicate!\\n\\nUsers are allowed to introduce new GREs with the same OccName as an imported GRE,\\nas disambiguation is possible through the module system, e.g.:\\n\\n module M where\\n import N (f)\\n f x = x\\n g x = M.f x + N.f x\\n\\nIf both GREs are local, the general rule is that two GREs clash if they have\\nthe same OccName, i.e. they share a textual name and live in the same namespace.\\nHowever, there are additional clashes due to record fields:\\n\\n - a new variable clashes with previously defined record fields\\n which define field selectors,\\n\\n - a new record field shadows:\\n\\n - previously defined variables, if it defines a field selector,\\n - previously defined record fields, unless it is a duplicate record field.\\n\\nThis logic is implemented in the function \'GHC.Types.Name.Reader.greClashesWith\'.\\n\\nSee also Note [Skipping ambiguity errors at use sites of local declarations] in\\nGHC.Rename.Utils.\\n-}\\n\\n\\n{- *********************************************************************\\n* *\\n getLocalDeclBindersd@ returns the names for an HsDecl\\n It\'s used for source code.\\n\\n *** See Note [The Naming story] in GHC.Hs.Decls ****\\n* *\\n********************************************************************* -}\\n\\ngetLocalNonValBinders :: MiniFixityEnv -> HsGroup GhcPs\\n -> RnM ((TcGblEnv, TcLclEnv), NameSet)\\n-- Get all the top-level binders bound the group *except*\\n-- for value bindings, which are treated separately\\n-- Specifically we return AvailInfo for\\n-- * type decls (incl constructors and record selectors)\\n-- * class decls (including class ops)\\n-- * associated types\\n-- * foreign imports\\n-- * value signatures (in hs-boot files only)\\n\\ngetLocalNonValBinders fixity_env\\n (HsGroup { hs_valds = binds,\\n hs_tyclds = tycl_decls,\\n hs_fords = foreign_decls })\\n = do { -- Process all type/class decls *except* family instances\\n ; let inst_decls = tycl_decls >>= group_instds\\n ; dup_fields_ok <- xopt_DuplicateRecordFields <$> getDynFlags\\n ; has_sel <- xopt_FieldSelectors <$> getDynFlags\\n ; tc_gres\\n <- concatMapM\\n (new_tc dup_fields_ok has_sel)\\n (tyClGroupTyClDecls tycl_decls)\\n ; traceRn \\"getLocalNonValBinders 1\\" (ppr tc_gres)\\n ; envs <- extendGlobalRdrEnvRn tc_gres fixity_env\\n ; restoreEnvs envs $ do {\\n -- Bring these things into scope first\\n -- See Note [Looking up family names in family instances]\\n\\n -- Process all family instances\\n -- to bring new data constructors into scope\\n ; nti_gress <- mapM (new_assoc dup_fields_ok has_sel) inst_decls\\n\\n -- Finish off with value binders:\\n -- foreign decls and pattern synonyms for an ordinary module\\n -- type sigs in case of a hs-boot file only\\n ; is_boot <- tcIsHsBootOrSig\\n ; let val_bndrs\\n | is_boot = case binds of\\n ValBinds _ val_binds ->\\n -- In a hs-boot file, the value binders come from the\\n -- *signatures*, and there should be no foreign binders\\n [ L (l2l decl_loc) (unLoc n)\\n | L decl_loc (TypeSig _ _ ns _) <- (val_sigs val_binds), n <- ns]\\n _ -> panic \\"Non-ValBinds in hs-boot group\\"\\n | otherwise = for_hs_bndrs\\n ; val_gres <- mapM new_simple val_bndrs\\n\\n ; let avails = concat nti_gress ++ val_gres\\n new_bndrs = gresToNameSet avails `unionNameSet`\\n gresToNameSet tc_gres\\n ; traceRn \\"getLocalNonValBinders 2\\" (ppr avails)\\n ; envs <- extendGlobalRdrEnvRn avails fixity_env\\n ; return (envs, new_bndrs) } }\\n where\\n for_hs_bndrs :: [LocatedN RdrName]\\n for_hs_bndrs = hsForeignDeclsBinders foreign_decls\\n\\n -- the SrcSpan attached to the input should be the span of the\\n -- declaration, not just the name\\n new_simple :: LocatedN RdrName -> RnM GlobalRdrElt\\n new_simple rdr_name = do { nm <- newTopSrcBinder rdr_name\\n ; return (mkLocalVanillaGRE NoParent nm) }\\n\\n new_tc :: DuplicateRecordFields -> FieldSelectors -> LTyClDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_tc dup_fields_ok has_sel tc_decl -- NOT for type/data instances\\n = do { let TyDeclBinders (main_bndr, tc_flav) at_bndrs sig_bndrs\\n (LConsWithFields cons_with_flds flds) = hsLTyClDeclBinders tc_decl\\n ; tycon_name <- newTopSrcBinder $ la2la main_bndr\\n ; at_names <- mapM (newTopSrcBinder . la2la . fst) at_bndrs\\n ; sig_names <- mapM (newTopSrcBinder . la2la) sig_bndrs\\n ; con_names_with_flds <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst con_names_with_flds) flds\\n ; mapM_ (add_dup_fld_errs flds\') con_names_with_flds\\n ; let tc_gre = mkLocalTyConGRE (fmap (const tycon_name) tc_flav) tycon_name\\n fld_env = mk_fld_env con_names_with_flds flds\'\\n at_gres = zipWith (\\\\ (_, at_flav) at_nm -> mkLocalTyConGRE (fmap (const tycon_name) at_flav) at_nm)\\n at_bndrs at_names\\n sig_gres = map (mkLocalVanillaGRE (ParentIs tycon_name)) sig_names\\n con_gres = map (mkLocalConLikeGRE (ParentIs tycon_name)) fld_env\\n fld_gres = mkLocalFieldGREs (ParentIs tycon_name) fld_env\\n sub_gres = at_gres ++ sig_gres ++ con_gres ++ fld_gres\\n ; traceRn \\"getLocalNonValBinders new_tc\\" $\\n vcat [ text \\"tycon:\\" <+> ppr tycon_name\\n , text \\"tc_gre:\\" <+> ppr tc_gre\\n , text \\"sub_gres:\\" <+> ppr sub_gres ]\\n ; return $ tc_gre : sub_gres }\\n\\n -- Calculate the record field information, which feeds into the GlobalRdrElts\\n -- for DataCons and their fields. It\'s convenient to do this here where\\n -- we are working with a single datatype definition.\\n --\\n -- The information we needed was all set up for us:\\n -- see Note [Collecting record fields in data declarations] in GHC.Hs.Utils.\\n mk_fld_env :: [(Name, Either VisArity [Located Int])] -> IntMap FieldLabel\\n -> [(ConLikeName, ConInfo)]\\n mk_fld_env names flds =\\n [ (DataConName con, ConInfo (ConIsData (map fst names)) fld_info)\\n | (con, con_fl_indxs) <- names\\n , let fld_info = case fmap (map ((flds IntMap.!) . unLoc)) con_fl_indxs of\\n Left 0 -> ConIsNullary\\n Left arity -> ConHasPositionalArgs arity\\n Right [] -> ConIsNullary\\n Right (fld:flds) -> ConHasRecordFields $ fld NE.:| flds ]\\n\\n new_assoc :: DuplicateRecordFields -> FieldSelectors -> LInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_assoc _ _ (L _ (TyFamInstD {})) = return []\\n -- type instances don\'t bind new names\\n\\n new_assoc dup_fields_ok has_sel (L _ (DataFamInstD _ d))\\n = new_di dup_fields_ok has_sel Nothing d\\n new_assoc dup_fields_ok has_sel\\n (L _ (ClsInstD _ (ClsInstDecl { cid_poly_ty = inst_ty\\n , cid_decls = decls })))\\n = do -- First, attempt to grab the name of the class from the instance.\\n -- This step could fail if the instance is not headed by a class,\\n -- such as in the following examples:\\n --\\n -- (1) The class is headed by a bang pattern, such as in\\n -- `instance !Show Int` (#3811c)\\n -- (2) The class is headed by a type variable, such as in\\n -- `instance c` (#16385)\\n --\\n -- If looking up the class name fails, then mb_cls_gre will\\n -- be Nothing.\\n mb_cls_gre <- runMaybeT $ do\\n -- See (1) above\\n L loc cls_rdr <- MaybeT $ pure $ getLHsInstDeclClass_maybe inst_ty\\n -- See (2) above\\n MaybeT $ setSrcSpan (locA loc) $ lookupGlobalOccRn_maybe SameNameSpace cls_rdr\\n -- Assuming the previous step succeeded, process any associated data\\n -- family instances. If the previous step failed, bail out.\\n case mb_cls_gre of\\n Nothing\\n -> pure []\\n Just cls_gre\\n -> let cls_nm = greName cls_gre\\n in concatMapM (new_di dup_fields_ok has_sel (Just cls_nm) . unLoc) (data_fam_insts decls)\\n\\n data_fam_insts decls = concatMap get decls\\n where\\n get (L l (InstD _ (DataFamInstD { dfid_inst = d}))) = [L l d]\\n get _ = []\\n\\n new_di :: DuplicateRecordFields -> FieldSelectors\\n -> Maybe Name -- class name\\n -> DataFamInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_di dup_fields_ok has_sel mb_cls dfid@(DataFamInstDecl { dfid_eqn = ti_decl })\\n = do { main_name <- unLoc <$> lookupFamInstName mb_cls (feqn_tycon ti_decl)\\n ; let LConsWithFields cons_with_flds flds = hsDataFamInstBinders dfid\\n ; sub_names <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst sub_names) flds\\n ; mapM_ (add_dup_fld_errs flds\') sub_names\\n ; let fld_env = mk_fld_env sub_names flds\'\\n con_gres = map (mkLocalConLikeGRE (ParentIs main_name)) fld_env\\n field_gres = mkLocalFieldGREs (ParentIs main_name) fld_env\\n -- NB: the data family name is not bound here,\\n -- so we don\'t return a GlobalRdrElt for it here!\\n ; return $ con_gres ++ field_gres }\\n\\n -- Add errors if a constructor has a duplicate record field.\\n add_dup_fld_errs :: IntMap FieldLabel\\n -> (Name, Either VisArity [Located Int])\\n -> IOEnv (Env TcGblEnv TcLclEnv) ()\\n add_dup_fld_errs all_flds (con, con_flds_or_arity)\\n | Right con_flds <- con_flds_or_arity\\n , let (_, dups) = removeDups (comparing unLoc) con_flds\\n = for_ dups $ \\\\ dup_flds ->\\n -- Report the error at the location of the second occurrence\\n -- of the duplicate field.\\n let loc =\\n case dup_flds of\\n _ :| ( L loc _ : _) -> loc\\n L loc _ :| _ -> loc\\n dup_rdrs = fmap (nameRdrName . flSelector . (all_flds IntMap.!) . unLoc) dup_flds\\n in addErrAt loc $ TcRnDuplicateFieldName (RecordFieldDecl con) dup_rdrs\\n | otherwise\\n = return ()\\n\\nnewRecordFieldLabel :: DuplicateRecordFields -> FieldSelectors -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel\\nnewRecordFieldLabel _ _ [] _ = error \\"newRecordFieldLabel: datatype has no constructors!\\"\\nnewRecordFieldLabel dup_fields_ok has_sel (dc:_) (L loc (FieldOcc _ (L _ fld)))\\n = do { selName <- newTopSrcBinder $ L (l2l loc) $ field\\n ; return $ FieldLabel { flHasDuplicateRecordFields = dup_fields_ok\\n , flHasFieldSelector = has_sel\\n , flSelector = selName } }\\n where\\n fld_occ = rdrNameOcc fld\\n dc_fs = occNameFS $ nameOccName dc\\n field\\n -- Use an Exact RdrName as-is, to preserve the bindings\\n -- of an already renamer-resolved field and its use\\n -- sites. This is needed to correctly support record\\n -- selectors in Template Haskell. See Note [Binders in\\n -- Template Haskell] in \\"GHC.ThToHs\\" and Note [Looking up\\n -- Exact RdrNames] in \\"GHC.Rename.Env\\".\\n | isExact fld\\n = assertPpr (fieldOcc_maybe fld_occ == Just dc_fs)\\n (vcat [ text \\"newRecordFieldLabel: incorrect namespace for exact Name\\" <+> quotes (ppr fld)\\n , text \\"expected namespace:\\" <+> pprNameSpace (fieldName dc_fs)\\n , text \\" actual namespace:\\" <+> pprNameSpace (occNameSpace fld_occ) ])\\n fld\\n\\n -- Field names produced by the parser are namespaced with VarName.\\n -- Here we namespace them according to the first constructor.\\n -- See Note [Record field namespacing] in GHC.Types.Name.Occurrence.\\n | otherwise\\n = mkRdrUnqual $ varToRecFieldOcc dc_fs fld_occ\\n\\n{-\\nNote [Looking up family names in family instances]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider\\n\\n module M where\\n type family T a :: *\\n type instance M.T Int = Bool\\n\\nWe might think that we can simply use \'lookupOccRn\' when processing the type\\ninstance to look up \'M.T\'. Alas, we can\'t! The type family declaration is in\\nthe *same* HsGroup as the type instance declaration. Hence, as we are\\ncurrently collecting the binders declared in that HsGroup, these binders will\\nnot have been added to the global environment yet.\\n\\nSolution is simple: process the type family declarations first, extend\\nthe environment, and then process the type instances.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Filtering imports}\\n* *\\n************************************************************************\\n\\n@filterImports@ takes the @ExportEnv@ telling what the imported module makes\\navailable, and filters it through the import spec (if any).\\n\\nNote [Dealing with imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nFor import M( ies ), we take each AvailInfo from the mi_exports of M, and make\\n\\n imp_occ_env :: OccEnv (NameEnv ImpOccItem)\\n\\nThis map contains one entry for each OccName that M exports, mapping each OccName\\nto the following information:\\n\\n 1. the GlobalRdrElt corresponding to the OccName,\\n 2. whether this GlobalRdrElt was the parent in the AvailInfo we found\\n the OccName in.\\n 3. the GlobalRdrElts that were bundled together in the AvailInfo we found\\n this OccName in (not including the parent),\\n\\nWe need (2) and (3) during the construction of the OccEnv because of associated\\ntypes and bundled pattern synonyms, respectively.\\n(3) is explained in Note [Importing PatternSynonyms].\\n\\nTo explain (2), consider for example:\\n\\n module M where\\n class C a where { data T a }\\n instance C Int where { data T Int = T1 | T2 }\\n instance C Bool where { data T Int = T3 }\\n\\nHere, M\'s exports avails are (recalling the AvailTC invariant from GHC.Types.Avail)\\n\\n C(C,T), T(T,T1,T2,T3)\\n\\nNotice that T appears *twice*, once as a child and once as a parent. From\\nthese two exports, respectively, during construction of the imp_occ_env, we begin\\nby associating the following two elements with the key T:\\n\\n T -> ImpOccItem { imp_item = gre1, imp_bundled = [C,T] , imp_is_parent = False }\\n T -> ImpOccItem { imp_item = gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nwhere `gre1`, `gre2` are two GlobalRdrElts with greName T.\\nWe combine these (in function \'combine\' in \'mkImportOccEnv\') by discarding the\\nnon-parent item, thusly:\\n\\n T -> IE_ITem { imp_item = gre1 `plusGRE` gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nNote the `plusGRE`: this ensures we don\'t drop parent information;\\nsee Note [Preserve parent information when combining import OccEnvs].\\n\\nSo the overall imp_occ_env is:\\n\\n C -> ImpOccItem { imp_item = C, imp_bundled = [T ], imp_is_parent = True }\\n T -> ImpOccItem { imp_item = T , imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n T1 -> ImpOccItem { imp_item = T1, imp_bundled = [T1,T2,T3], imp_is_parent = False }\\n -- similarly for T2, T3\\n\\nNote that the imp_occ_env will have entries for data constructors too,\\nalthough we never look up data constructors.\\n\\nNote [Importing PatternSynonyms]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nAs described in Note [Dealing with imports], associated types can lead to the\\nsame Name appearing twice, both as a child and once as a parent, when\\nconstructing the imp_occ_env. The same thing can happen with pattern synonyms\\nif they are exported bundled with a type.\\n\\nA simplified example, based on #11959:\\n\\n {-# LANGUAGE PatternSynonyms #-}\\n module M (T(P), pattern P) where -- Duplicate export warning, but allowed\\n data T = MkT\\n pattern P = MkT\\n\\nHere we have T(P) and P in export_avails, and respectively construct both\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n P -> ImpOccItem { imp_item = P, imp_bundled = [] , imp_is_parent = False }\\n\\nWe combine these by dropping the one with no siblings, leaving us with:\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n\\nThat is, we simply discard the non-bundled Avail.\\n\\nNote [Importing DuplicateRecordFields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn filterImports, another complicating factor is DuplicateRecordFields.\\nSuppose we have:\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (S(foo), T(foo)) where\\n data S = MkS { foo :: Int }\\n data T = MkT { foo :: Int }\\n\\n module N where\\n import M (foo) -- this is allowed (A)\\n import M (S(foo)) -- this is allowed (B)\\n\\nHere M exports \'foo\' at two different OccNames, with different namespaces for\\nthe two construtors MkS and MkT. Then, when we look up \'foo\' in lookup_names\\nfor case (A), we have a variable foo but must look in all the record field\\nnamespaces to find the two fields (and hence two different Avails).\\nWhereas in case (B) we reach the lookup_ie case for IEThingWith,\\nwhich looks up \'S\' and then finds the unique \'foo\' amongst its children.\\n\\nSee T16745 for a test of this.\\n\\nNote [Preserve parent information when combining import OccEnvs]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen discarding one ImpOccItem in favour of another, as described in\\nNote [Dealing with imports], we must make sure to combine the GREs so that\\nwe don\'t lose information.\\n\\nConsider for example #24084:\\n\\n module M1 where { class C a where { type T a } }\\n module M2 ( module M1 ) where { import M1 }\\n module M3 where { import M2 ( C, T ); instance C () where T () = () }\\n\\nWhen processing the import list of `M3`, we will have two `Avail`s attached\\nto `T`, namely `C(C, T)` and `T(T)`. We combine them in the `combine` function\\nof `mkImportOccEnv`; as described in Note [Dealing with imports] we discard\\n`C(C, T)` in favour of `T(T)`. However, in doing so, we **must not**\\ndiscard the information want that `C` is the parent of `T`. Indeed,\\nlosing track of this information can cause errors when importing,\\nas we could get an error of the form\\n\\n \\u2018T\\u2019 is not a (visible) associated type of class \\u2018C\\u2019\\n\\nThis explains why we use `plusGRE` when combining the two ImpOccItems, even\\nthough we are discarding one in favour of the other.\\n-}\\n\\n-- | All the \'GlobalRdrElt\'s associated with an \'AvailInfo\'.\\ngresFromAvail :: HasDebugCallStack\\n => HscEnv -> Maybe ImportSpec -> AvailInfo -> [GlobalRdrElt]\\ngresFromAvail hsc_env prov avail =\\n [ mk_gre nm info\\n | nm <- availNames avail\\n , let info = lookupGREInfo hsc_env nm ]\\n where\\n\\n mk_gre n info\\n = case prov of\\n -- Nothing => bound locally\\n -- Just is => imported from \'is\'\\n Nothing -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = True, gre_imp = emptyBag\\n , gre_info = info }\\n Just is -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = False, gre_imp = unitBag is\\n , gre_info = info }\\n\\n-- | All the \'GlobalRdrElt\'s associated with a collection of \'AvailInfo\'s.\\ngresFromAvails :: HscEnv -> Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]\\ngresFromAvails hsc_env prov = concatMap (gresFromAvail hsc_env prov)\\n\\nimportsFromIface :: HscEnv -> ModIface -> ImpDeclSpec -> Maybe NameSet -> GlobalRdrEnv\\nimportsFromIface hsc_env iface decl_spec hidden = mkGlobalRdrEnv $ case hidden of\\n Nothing -> all_gres\\n Just hidden_names -> filter (not . (`elemNameSet` hidden_names) . greName) all_gres\\n where\\n all_gres = gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\nrnNamespaceSpecifier :: NamespaceSpecifier GhcPs -> NamespaceSpecifier GhcRn\\nrnNamespaceSpecifier (NoNamespaceSpecifier _) = NoNamespaceSpecifier noExtField\\nrnNamespaceSpecifier (TypeNamespaceSpecifier x) = TypeNamespaceSpecifier x\\nrnNamespaceSpecifier (DataNamespaceSpecifier x) = DataNamespaceSpecifier x\\n\\nfilterImports\\n :: HasDebugCallStack\\n => HscEnv\\n -> ModIface\\n -> ImpDeclSpec\\n -- ^ Import spec\\n -> Maybe (ImportListInterpretation, [LIE GhcPs])\\n -- ^ Whether this is a \\"hiding\\" import list\\n -> RnM (Maybe (ImportListInterpretation, [LIE GhcRn]), -- Import spec w/ Names\\n ImpUserList, -- same, but designed for storage in interfaces\\n GlobalRdrEnv) -- Same again, but in GRE form\\nfilterImports hsc_env iface decl_spec Nothing\\n = return (Nothing, ImpUserAll, importsFromIface hsc_env iface decl_spec Nothing)\\nfilterImports hsc_env iface decl_spec (Just (want_hiding, import_items))\\n = do -- check for errors, convert RdrNames to Names\\n items1 <- mapM lookup_lie import_items\\n\\n let items2 :: [(LIE GhcRn, [GlobalRdrElt])]\\n items2 = concat items1\\n -- NB we may have duplicates, and several items\\n -- for the same parent; e.g N(x) and N(y)\\n\\n (gres, imp_user_list) = case want_hiding of\\n Exactly ->\\n let gres = concatMap (gresFromIE decl_spec) items2\\n gre_env = mkGlobalRdrEnv gres\\n implicit_parents = mkNameSet $ mapMaybe parentOfImplicitlyImportedGRE gres\\n in (gre_env, ImpUserExplicit (gresToAvailInfo $ globalRdrEnvElts $ gre_env) implicit_parents)\\n EverythingBut ->\\n let hidden_names = mkNameSet $ concatMap (map greName . snd) items2\\n in (importsFromIface hsc_env iface decl_spec (Just hidden_names), ImpUserEverythingBut hidden_names)\\n\\n return (Just (want_hiding, map fst items2), imp_user_list, gres)\\n where\\n import_mod = mi_module iface\\n all_avails = mi_exports iface\\n imp_occ_env = mkImportOccEnv hsc_env decl_spec all_avails\\n\\n -- Look up a parent (type constructor, class or data constructor)\\n -- in an import.\\n lookup_parent :: IE GhcPs -> RdrName -> IELookupM ImpOccItem\\n lookup_parent ie rdr =\\n assertPpr (not $ isVarNameSpace ns)\\n (vcat [ text \\"filterImports lookup_parent: unexpected variable\\"\\n , text \\"rdr:\\" <+> ppr rdr\\n , text \\"namespace:\\" <+> pprNameSpace ns ]) $\\n do { xs <- lookup_names ie rdr\\n ; case xs of\\n cax :| [] -> return cax\\n _ -> pprPanic \\"filter_imports lookup_parent ambiguous\\" $\\n vcat [ text \\"rdr:\\" <+> ppr rdr\\n , text \\"lookups:\\" <+> ppr (fmap imp_item xs) ] }\\n -- Looking up non-variables is always unambiguous,\\n -- as there can be at most one corresponding item\\n -- in the imp_occ_env.\\n -- See item (1) of Note [Exporting duplicate declarations]\\n -- in GHC.Tc.Gen.Export.\\n where\\n occ = rdrNameOcc rdr\\n ns = occNameSpace occ\\n\\n -- Look up a RdrName used in an import, returning multiple values if there\\n -- are several fields with the same name exposed by the module\\n lookup_names :: IE GhcPs -> RdrName -> IELookupM (NonEmpty ImpOccItem)\\n lookup_names ie rdr\\n | isQual rdr\\n = failLookupWith (QualImportError rdr)\\n | otherwise\\n = case lookups of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n item:items -> return $ item :| items\\n where\\n lookups = concatMap nonDetNameEnvElts\\n $ lookupImpOccEnv (RelevantGREsFOS WantNormal) imp_occ_env (rdrNameOcc rdr)\\n\\n lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, [GlobalRdrElt])]\\n lookup_lie (L loc ieRdr)\\n = setSrcSpanA loc $\\n do (stuff, warns) <- run_lookup ([],[]) (lookup_ie ieRdr)\\n mapM_ (addTcRnDiagnostic <=< warning_msg) warns\\n return [ (L loc ie, gres) | (ie,gres) <- stuff ]\\n where\\n\\n -- Warn when importing T(..) and no children are brought in scope\\n warning_msg (DodgyImport reason) =\\n pure (TcRnDodgyImports reason)\\n warning_msg MissingImportList =\\n pure (TcRnMissingImportList ieRdr)\\n warning_msg (BadImportW ie sub) = do\\n -- \'BadImportW\' is only constructed below in \'bad_import_w\', in\\n -- the \'EverythingBut\' case, so here we assume a \'hiding\' clause.\\n (reason :| _) <- badImportItemErr iface decl_spec ie sub all_avails\\n pure (TcRnDodgyImports (DodgyImportsHiding reason))\\n warning_msg (DeprecatedExport n w) =\\n pure $ TcRnPragmaWarning\\n PragmaWarningExport\\n { pwarn_occname = occName n\\n , pwarn_impmod = moduleName import_mod }\\n w\\n\\n run_lookup :: a -> IELookupM a -> TcRn a\\n run_lookup def m = case m of\\n Failed err -> do\\n msgs <- lookup_err_msgs err\\n forM_ msgs $ \\\\msg -> addErr (TcRnImportLookup msg)\\n return def\\n Succeeded a -> return a\\n\\n lookup_err_msgs err = case err of\\n BadImport ie sub -> badImportItemErr iface decl_spec ie sub all_avails\\n IllegalImport -> pure $ NE.singleton ImportLookupIllegal\\n QualImportError rdr -> pure $ NE.singleton (ImportLookupQualified rdr)\\n\\n -- For each import item, we convert its RdrNames to Names,\\n -- and at the same time compute all the GlobalRdrElt corresponding\\n -- to what is actually imported by this item.\\n -- Returns Nothing on error.\\n --\\n -- Returns a list because, with DuplicateRecordFields, a naked\\n -- import/export of a record field can correspond to multiple\\n -- different GlobalRdrElts. See Note [Importing DuplicateRecordFields].\\n lookup_ie :: IE GhcPs\\n -> IELookupM ([(IE GhcRn, [GlobalRdrElt])], [IELookupWarning])\\n lookup_ie ie = handle_bad_import $\\n case ie of\\n IEVar _ (L l n) _ -> do\\n -- See Note [Importing DuplicateRecordFields]\\n xs <- lookup_names ie (ieWrappedName n)\\n let gres = map imp_item $ NE.toList xs\\n export_depr_warns\\n | want_hiding == Exactly\\n = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ( [ (IEVar Nothing (L l (replaceWrappedName n name)) noDocstring, [gre])\\n | gre <- gres\\n , let name = greName gre ]\\n , export_depr_warns )\\n\\n IEThingAll x ns_spec (L l tc) _ -> do\\n ImpOccItem { imp_item = gre\\n , imp_bundled = bundled_gres\\n , imp_is_parent = is_par\\n }\\n <- lookup_parent ie $ ieWrappedName tc\\n let name = greName gre\\n\\n child_gres :: [GlobalRdrElt]\\n child_gres\\n | is_par = filterByNamespaceSpecifierGREs ns_spec bundled_gres\\n | otherwise = []\\n\\n imp_list_warn\\n\\n | null child_gres\\n -- e.g. f(..) or T(..) where T is a type synonym\\n = [DodgyImport (DodgyImportsEmptyParent ie ns_spec gre)]\\n\\n -- e.g. import M( T(..) )\\n | not (is_qual decl_spec)\\n = [MissingImportList]\\n\\n | otherwise\\n = []\\n\\n renamed_ie = IEThingAll (x { ieta_warning = Nothing })\\n (rnNamespaceSpecifier ns_spec)\\n (L l (replaceWrappedName tc name))\\n noDocstring\\n export_depr_warn\\n | want_hiding == Exactly\\n = maybeToList $ mk_depr_export_warning gre\\n -- We don\'t want to warn about the children as they\\n -- are not explicitly mentioned; the warning will\\n -- be emitted later on if they are used\\n | otherwise = []\\n\\n return ( [(renamed_ie, gre:child_gres)]\\n , imp_list_warn ++ export_depr_warn)\\n\\n\\n IEThingAbs _ (L l tc\') _\\n | want_hiding == EverythingBut -- hiding ( C )\\n -- Here the \'C\' can be a data constructor\\n -- *or* a type/class, or even both\\n -> let tc = ieWrappedName tc\'\\n tc_name = lookup_parent ie tc\\n dc_name = lookup_parent ie (setRdrNameSpace tc srcDataName)\\n in\\n case catIELookupM [ tc_name, dc_name ] of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n names -> return ( [mkIEThingAbs tc\' l (imp_item name) | name <- names], [])\\n | otherwise\\n -> do ImpOccItem { imp_item = gre } <- lookup_parent ie (ieWrappedName tc\')\\n return ( [mkIEThingAbs tc\' l gre]\\n , maybeToList $ mk_depr_export_warning gre)\\n\\n IEThingWith (deprecation, ann) ltc@(L l rdr_tc) wc rdr_ns _ -> do\\n ImpOccItem { imp_item = gre, imp_bundled = subnames }\\n <- lookup_parent (IEThingAbs Nothing ltc noDocstring) (ieWrappedName rdr_tc)\\n let name = greName gre\\n\\n -- Look up the children in the sub-names of the parent\\n -- See Note [Importing DuplicateRecordFields]\\n let (children_errs, childnames) = lookupChildren subnames rdr_ns\\n\\n bad_import_warns <-\\n if null children_errs then return [] else\\n let items = map lce_wrapped_name children_errs\\n ie = IEThingWith (deprecation, ann) ltc wc items noDocstring\\n -- We are trying to import T( a,b,c,d ), and failed\\n -- to find \'b\' and \'d\'. So we make up an import item\\n -- to report as failing, namely T( b, d ).\\n -- c.f. #15413\\n subordinate_err = mkSubordinateError gre children_errs\\n in bad_import_w ie subordinate_err\\n\\n let name\' = replaceWrappedName rdr_tc name\\n childnames\' = map (to_ie_post_rn . fmap greName) childnames\\n gres = gre : map unLoc childnames\\n export_depr_warns\\n | want_hiding == Exactly = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ([ (IEThingWith (Nothing, ann) (L l name\') wc childnames\' noDocstring\\n ,gres)]\\n , bad_import_warns ++ export_depr_warns)\\n\\n IEWholeNamespace x ns_spec -> do\\n let mod_name = moduleName import_mod\\n names = map greName gres\\n renamed_ie = IEWholeNamespace x { iewn_warning = Nothing\\n , iewn_names = names }\\n (rnNamespaceSpecifier ns_spec)\\n gres = filterByNamespaceSpecifierGREs ns_spec $\\n gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n dodgy_warn\\n | null gres = [DodgyImport (DodgyImportsWildcard mod_name ns_spec)]\\n | otherwise = []\\n return ([(renamed_ie, gres)],\\n dodgy_warn)\\n\\n _other -> failLookupWith IllegalImport\\n -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed...\\n -- all of those constitute errors.\\n\\n where\\n mkIEThingAbs tc l gre\\n = (IEThingAbs Nothing (L l (replaceWrappedName tc n)) noDocstring, [gre])\\n where n = greName gre\\n\\n -- N.B. imports never have docstrings\\n noDocstring = Nothing\\n\\n handle_bad_import m = catchIELookup m $ \\\\case\\n BadImport ie sub -> do\\n ws <- bad_import_w ie sub\\n return ([], ws)\\n err -> failLookupWith err\\n\\n bad_import_w :: IE GhcPs -> IsSubordinateError -> IELookupM [IELookupWarning]\\n bad_import_w ie sub\\n | want_hiding == EverythingBut = return [BadImportW ie sub]\\n | otherwise = failLookupWith (BadImport ie sub)\\n\\n mk_depr_export_warning gre\\n = DeprecatedExport name <$> mi_export_warn_fn iface name\\n where\\n name = greName gre\\n\\n-- | Assuming a subordinate item could not be found, do another lookup for a\\n-- more specific error message.\\nmkBadExportSubordinate :: [GlobalRdrElt] -> LIEWrappedName GhcPs -> BadExportSubordinate\\nmkBadExportSubordinate child_gres n =\\n case lookupChildren child_gres [n] of\\n (LookupChildNonType {lce_nontype_item = g} : _, _) -> BadExportSubordinateNonType g\\n (LookupChildNonData {lce_nondata_item = g} : _, _) -> BadExportSubordinateNonData g\\n _ -> BadExportSubordinateNotFound n\\n\\ntype IELookupM = MaybeErr IELookupError\\n\\ndata IELookupWarning\\n = BadImportW (IE GhcPs) IsSubordinateError\\n | MissingImportList\\n | DodgyImport DodgyImportsReason\\n | DeprecatedExport Name (WarningTxt GhcRn)\\n\\n-- | Is this import/export item a subordinate or not?\\ndata IsSubordinateError\\n = IsSubordinateError { subordinate_err_parent :: !GlobalRdrElt\\n , subordinate_err_unavailable :: [FastString]\\n , subordinate_err_nontype :: [GlobalRdrElt]\\n , subordinate_err_nondata :: [GlobalRdrElt] }\\n | IsNotSubordinate\\n\\nmkSubordinateError :: GlobalRdrElt -> [LookupChildError] -> IsSubordinateError\\nmkSubordinateError gre children_errs = foldr add init_acc children_errs\\n where\\n init_acc :: IsSubordinateError\\n init_acc = IsSubordinateError gre [] [] []\\n\\n add :: LookupChildError -> IsSubordinateError -> IsSubordinateError\\n add children_err sub@IsSubordinateError{} =\\n case children_err of\\n LookupChildNonType{lce_nontype_item = g} ->\\n sub { subordinate_err_nontype = g : subordinate_err_nontype sub }\\n LookupChildNonData{lce_nondata_item = g} ->\\n sub { subordinate_err_nondata = g : subordinate_err_nondata sub }\\n LookupChildNotFound (L _ wname) ->\\n let fs = (occNameFS . rdrNameOcc . ieWrappedName) wname\\n in sub { subordinate_err_unavailable = fs : subordinate_err_unavailable sub }\\n add _ IsNotSubordinate = panic \\"mkSubordinateError: IsNotSubordinate\\"\\n\\ndata IELookupError\\n = QualImportError RdrName\\n | BadImport (IE GhcPs) IsSubordinateError\\n | IllegalImport\\n\\nfailLookupWith :: IELookupError -> IELookupM a\\nfailLookupWith err = Failed err\\n\\ncatchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a\\ncatchIELookup m h = case m of\\n Succeeded r -> return r\\n Failed err -> h err\\n\\ncatIELookupM :: [IELookupM a] -> [a]\\ncatIELookupM ms = [ a | Succeeded a <- ms ]\\n\\n-- | Information associated to an \'AvailInfo\' used in constructing\\n-- an \'OccEnv\' corresponding to imports.\\n--\\n-- See Note [Dealing with imports].\\ndata ImpOccItem\\n = ImpOccItem\\n { imp_item :: GlobalRdrElt\\n -- ^ The import item\\n , imp_bundled :: [GlobalRdrElt]\\n -- ^ Items bundled in the Avail this import item came from,\\n -- not including the import item itself if it is a parent.\\n , imp_is_parent :: Bool\\n -- ^ Is the import item a parent? See Note [Dealing with imports].\\n }\\n\\ninstance Outputable ImpOccItem where\\n ppr (ImpOccItem { imp_item = item, imp_bundled = bundled, imp_is_parent = is_par })\\n = braces $ hsep\\n [ text \\"ImpOccItem\\"\\n , if is_par then text \\"[is_par]\\" else empty\\n , ppr (greName item) <+> ppr (greParent item)\\n , braces $ text \\"bundled:\\" <+> ppr (map greName bundled) ]\\n\\n-- | Make an \'OccEnv\' of all the imports.\\n--\\n-- Complicated by the fact that associated data types and pattern synonyms\\n-- can appear twice. See Note [Dealing with imports].\\nmkImportOccEnv :: HscEnv -> ImpDeclSpec -> [IfaceExport] -> OccEnv (NameEnv ImpOccItem)\\nmkImportOccEnv hsc_env decl_spec all_avails =\\n mkOccEnv_C (plusNameEnv_C combine)\\n [ (occ, mkNameEnv [(nm, item)])\\n | avail <- all_avails\\n , let gres = gresFromAvail hsc_env (Just hiding_spec) avail\\n , gre <- gres\\n , let nm = greName gre\\n occ = greOccName gre\\n (is_parent, bundled) = case avail of\\n AvailTC c _\\n | c == nm -- (Recall the AvailTC invariant from GHC.Types.AvailInfo)\\n -> ( True, drop 1 gres ) -- \\"drop 1\\": don\'t include the parent itself.\\n | otherwise\\n -> ( False, gres )\\n _ -> ( False, [] )\\n item = ImpOccItem\\n { imp_item = gre\\n , imp_bundled = bundled\\n , imp_is_parent = is_parent }\\n ]\\n where\\n\\n hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\n -- See Note [Dealing with imports]\\n -- \'combine\' may be called for associated data types which appear\\n -- twice in the all_avails. In the example, we have two Avails for T,\\n -- namely T(T,T1,T2,T3) and C(C,T), and we combine them by dropping the\\n -- latter, in which T is not the parent.\\n combine :: ImpOccItem -> ImpOccItem -> ImpOccItem\\n combine item1@(ImpOccItem { imp_item = gre1, imp_is_parent = is_parent1 })\\n item2@(ImpOccItem { imp_item = gre2, imp_is_parent = is_parent2 })\\n | is_parent1 || is_parent2\\n , not (isRecFldGRE gre1 || isRecFldGRE gre2) -- NB: does not force GREInfo.\\n , let name1 = greName gre1\\n name2 = greName gre2\\n gre = gre1 `plusGRE` gre2\\n -- See Note [Preserve parent information when combining import OccEnvs]\\n = assertPpr (name1 == name2)\\n (ppr name1 <+> ppr name2) $\\n if is_parent1\\n then item1 { imp_item = gre }\\n else item2 { imp_item = gre }\\n -- Discard C(C,T) in favour of T(T, T1, T2, T3).\\n\\n -- \'combine\' may also be called for pattern synonyms which appear both\\n -- unassociated and associated (see Note [Importing PatternSynonyms]).\\n combine item1@(ImpOccItem { imp_item = c1, imp_bundled = kids1 })\\n item2@(ImpOccItem { imp_item = c2, imp_bundled = kids2 })\\n = assertPpr (greName c1 == greName c2\\n && (not (null kids1 && null kids2)))\\n (ppr c1 <+> ppr c2 <+> ppr kids1 <+> ppr kids2) $\\n if null kids1\\n then item2\\n else item1\\n -- Discard standalone pattern P in favour of T(P).\\n\\n-- | Essentially like @lookupGRE env (LookupOccName occ which_gres)@,\\n-- but working with \'ImpOccItem\'s instead of \'GlobalRdrElt\'s.\\nlookupImpOccEnv :: WhichGREs GREInfo\\n -> OccEnv (NameEnv ImpOccItem) -> OccName -> [NameEnv ImpOccItem]\\nlookupImpOccEnv which_gres env occ =\\n mapMaybe relevant_items $ lookupOccEnv_AllNameSpaces env occ\\n where\\n is_relevant :: ImpOccItem -> Bool\\n is_relevant (ImpOccItem { imp_item = gre }) =\\n greIsRelevant which_gres (occNameSpace occ) gre\\n relevant_items :: NameEnv ImpOccItem -> Maybe (NameEnv ImpOccItem)\\n relevant_items nms\\n | let nms\' = filterNameEnv is_relevant nms\\n = if isEmptyNameEnv nms\'\\n then Nothing\\n else Just nms\'\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{Import/Export Utils}\\n* *\\n************************************************************************\\n-}\\n\\n-- | Given an import\\\\/export spec, appropriately set the @gre_imp@ field\\n-- for the \'GlobalRdrElt\'s.\\ngresFromIE :: ImpDeclSpec -> (LIE GhcRn, [GlobalRdrElt]) -> [GlobalRdrElt]\\ngresFromIE decl_spec (L loc ie, gres)\\n = map set_gre_imp gres\\n where\\n is_explicit = case ie of\\n IEThingAll _ _ name _ -> \\\\n -> n == lieWrappedName name\\n IEWholeNamespace _ _ -> \\\\_ -> False\\n _ -> \\\\_ -> True\\n prov_fn name\\n = ImpSpec { is_decl = decl_spec, is_item = item_spec }\\n where\\n item_spec = ImpSome { is_explicit = is_explicit name\\n , is_iloc = locA loc }\\n set_gre_imp gre@( GRE { gre_name = nm } )\\n = gre { gre_imp = unitBag $ prov_fn nm }\\n\\nparentOfImplicitlyImportedGRE :: Outputable info => GlobalRdrEltX info -> Maybe Name\\nparentOfImplicitlyImportedGRE gre =\\n if any (explicit_import . is_item) $ gre_imp gre\\n then Nothing\\n else greParent_maybe gre\\n where\\n explicit_import :: ImpItemSpec -> Bool\\n explicit_import (ImpAll {}) =\\n pprPanic \\"parentOfImplicitlyImportedGRE: ImpAll\\" (ppr gre)\\n explicit_import (ImpSome { is_explicit }) = is_explicit\\n\\n{- Note [Children for duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider the module\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (F(foo, MkFInt, MkFBool)) where\\n data family F a\\n data instance F Int = MkFInt { foo :: Int }\\n data instance F Bool = MkFBool { foo :: Bool }\\n\\nThe `foo` in the export list refers to *both* selectors! For this\\nreason, lookupChildren builds an environment that maps the FastString\\nto a list of items, rather than a single item.\\n-}\\n\\nmkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]\\nmkChildEnv gres = foldr add emptyNameEnv gres\\n where\\n add gre env = case greParent gre of\\n ParentIs p -> extendNameEnv_Acc (:) Utils.singleton env p gre\\n NoParent -> env\\n\\nfindChildren :: NameEnv [a] -> Name -> [a]\\nfindChildren env n = lookupNameEnv env n `orElse` []\\n\\ndata LookupChildError\\n = LookupChildNotFound { lce_wrapped_name :: !(LIEWrappedName GhcPs) }\\n | LookupChildNonType { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nontype_item :: !GlobalRdrElt }\\n | LookupChildNonData { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nondata_item :: !GlobalRdrElt }\\n\\nlookupChildren :: [GlobalRdrElt]\\n -> [LIEWrappedName GhcPs]\\n -> ( [LookupChildError] -- The ones for which the lookup failed\\n , [LocatedA GlobalRdrElt] )\\n-- (lookupChildren all_kids rdr_items) maps each rdr_item to its\\n-- corresponding Name in all_kids, if the former exists\\n-- The matching is done by FastString, not OccName, so that\\n-- Cls( meth, AssocTy )\\n-- will correctly find AssocTy among the all_kids of Cls, even though\\n-- the RdrName for AssocTy may have a (bogus) DataName namespace\\n-- (Really the rdr_items should be FastStrings in the first place.)\\nlookupChildren all_kids rdr_items = (fails, successes)\\n where\\n mb_xs = map do_one rdr_items\\n fails = [ err | Failed err <- mb_xs ]\\n successes = [ ok | Succeeded oks <- mb_xs, ok <- NE.toList oks ]\\n\\n do_one :: LIEWrappedName GhcPs -> MaybeErr LookupChildError (NonEmpty (LocatedA GlobalRdrElt))\\n do_one item@(L l r) =\\n case r of\\n IEName{}\\n -- IEName (unadorned name) places no restriction on the namespace of\\n -- the imported entity, so we look in both `val_gres` and `typ_gres`.\\n -- In case of conflict (punning), the value namespace takes priority.\\n -- See Note [Prioritise the value namespace in subordinate import lists]\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEType{}\\n -- IEType (\'type\' namespace specifier) restricts the lookup to the\\n -- type namespace, i.e. to `typ_gres`. In case of failure, we check\\n -- `val_gres` to produce a more helpful error message.\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- val_gres -> Failed $ LookupChildNonType item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEData{}\\n -- IEData (\'data\' namespace specifier) restricts the lookup to the\\n -- data namespace, i.e. to `val_gres`. In case of failure, we check\\n -- `typ_gres` to produce a more helpful error message.\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- typ_gres -> Failed $ LookupChildNonData item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEPattern{} -> panic \\"lookupChildren: IEPattern\\" -- Never happens (invalid syntax)\\n IEDefault{} -> panic \\"lookupChildren: IEDefault\\" -- Never happens (invalid syntax)\\n where\\n fs = (occNameFS . rdrNameOcc . ieWrappedName) r\\n gres = fromMaybe [] (lookupFsEnv kid_env fs)\\n (val_gres, typ_gres) = partition (isValNameSpace . greNameSpace) gres\\n\\n -- See Note [Children for duplicate record fields]\\n kid_env :: FastStringEnv [GlobalRdrElt]\\n kid_env = extendFsEnvList_C (++) emptyFsEnv\\n [(occNameFS (occName x), [x]) | x <- all_kids]\\n\\n\\n{- Note [Prioritise the value namespace in subordinate import lists]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider this program that defines a class that has both an associated type\\nnamed (#) and a method named (#)\\n\\n module M_assoc where\\n class C a b where\\n type a # b\\n (#) :: a -> b -> ()\\n module N_assoc where\\n import M_assoc( C((#)) )\\n\\nIn the import declaration, when we see the unadorned name (#) in the subordinate\\nimport list of C, which children should we bring into scope? Our options are:\\n\\n a) only the method (#)\\n b) only the associated type (#)\\n c) both the method and the associated type\\n\\nTo follow the precedent established by top-level items, we go with option (a).\\nIndeed, consider a slightly different program\\n\\n module M_top where\\n type family a # b\\n a # b = ()\\n module N_top where\\n import M_top( (#) )\\n\\nHere the import brings only the function (#) into scope, and one has to say\\n`type (#)` to get the type family.\\n-}\\n\\n-------------------------------\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused names}\\n* *\\n*********************************************************\\n-}\\n\\nreportUnusedNames :: TcGblEnv -> HscSource -> RnM ()\\nreportUnusedNames gbl_env hsc_src\\n = do { keep <- readTcRef (tcg_keep gbl_env)\\n ; traceRn \\"RUN\\" (ppr (tcg_dus gbl_env))\\n ; warnUnusedImportDecls gbl_env hsc_src\\n ; warnUnusedTopBinds $ unused_locals keep\\n ; warnMissingSignatures gbl_env\\n ; warnMissingKindSignatures gbl_env }\\n where\\n used_names :: NameSet -> NameSet\\n used_names keep = findUses (tcg_dus gbl_env) emptyNameSet `unionNameSet` keep\\n -- NB: currently, if f x = g, we only treat \'g\' as used if \'f\' is used\\n -- Hence findUses\\n\\n -- Collect the defined names from the in-scope environment\\n defined_names :: [GlobalRdrElt]\\n defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)\\n\\n kids_env = mkChildEnv defined_names\\n -- This is done in mkExports too; duplicated work\\n\\n gre_is_used :: NameSet -> GlobalRdrElt -> Bool\\n gre_is_used used_names gre0\\n = name `elemNameSet` used_names\\n || any (\\\\ gre -> greName gre `elemNameSet` used_names) (findChildren kids_env name)\\n -- A use of C implies a use of T,\\n -- if C was brought into scope by T(..) or T(C)\\n where\\n name = greName gre0\\n\\n -- Filter out the ones that are\\n -- (a) defined in this module, and\\n -- (b) not defined by a \'deriving\' clause\\n -- The latter have an Internal Name, so we can filter them out easily\\n unused_locals :: NameSet -> [GlobalRdrElt]\\n unused_locals keep =\\n let -- Note that defined_and_used, defined_but_not_used\\n -- are both [GRE]; that\'s why we need defined_and_used\\n -- rather than just used_names\\n _defined_and_used, defined_but_not_used :: [GlobalRdrElt]\\n (_defined_and_used, defined_but_not_used)\\n = partition (gre_is_used (used_names keep)) defined_names\\n\\n in filter is_unused_local defined_but_not_used\\n is_unused_local :: GlobalRdrElt -> Bool\\n is_unused_local gre = isLocalGRE gre\\n && isExternalName (greName gre)\\n\\n{- *********************************************************************\\n* *\\n Missing signatures\\n* *\\n********************************************************************* -}\\n\\n{-\\nNote [Missing signatures]\\n~~~~~~~~~~~~~~~~~~~~~~~~~\\nThere are four warning flags in play:\\n\\n * -Wmissing-exported-signatures\\n Warn about any exported top-level function/value without a type signature.\\n Does not include pattern synonyms.\\n\\n * -Wmissing-signatures\\n Warn about any top-level function/value without a type signature. Does not\\n include pattern synonyms. Takes priority over -Wmissing-exported-signatures.\\n\\n * -Wmissing-exported-pattern-synonym-signatures\\n Warn about any exported pattern synonym without a type signature.\\n\\n * -Wmissing-pattern-synonym-signatures\\n Warn about any pattern synonym without a type signature. Takes priority over\\n -Wmissing-exported-pattern-synonym-signatures.\\n\\n-}\\n\\n-- | Warn the user about top level binders that lack type signatures.\\n-- Called /after/ type inference, so that we can report the\\n-- inferred type of the function\\nwarnMissingSignatures :: TcGblEnv -> RnM ()\\nwarnMissingSignatures gbl_env\\n = do { let exports = availsToNameSet (tcg_exports gbl_env)\\n sig_ns = tcg_sigs gbl_env\\n -- We use sig_ns to exclude top-level bindings that are generated by GHC\\n binds = collectHsBindsBinders CollNoDictBinders $ tcg_binds gbl_env\\n pat_syns = tcg_patsyns gbl_env\\n\\n not_ghc_generated :: Name -> Bool\\n not_ghc_generated name = name `elemNameSet` sig_ns\\n\\n add_binding_warn :: Id -> RnM ()\\n add_binding_warn id =\\n when (not_ghc_generated name) $\\n do { env <- liftZonkM $ tcInitTidyEnv -- Why not use emptyTidyEnv?\\n ; let ty = tidyOpenType env (idType id)\\n missing = MissingTopLevelBindingSig name ty\\n diag = TcRnMissingSignature missing exported\\n ; addDiagnosticAt (getSrcSpan name) diag }\\n where\\n name = idName id\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n add_patsyn_warn :: PatSyn -> RnM ()\\n add_patsyn_warn ps =\\n when (not_ghc_generated name) $\\n addDiagnosticAt (getSrcSpan name)\\n (TcRnMissingSignature missing exported)\\n where\\n name = patSynName ps\\n missing = MissingPatSynSig ps\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n -- Warn about missing signatures\\n -- Do this only when we have a type to offer\\n -- See Note [Missing signatures]\\n ; mapM_ add_binding_warn binds\\n ; mapM_ add_patsyn_warn pat_syns\\n }\\n\\n-- | Warn the user about tycons that lack kind signatures.\\n-- Called /after/ type (and kind) inference, so that we can report the\\n-- inferred kinds.\\nwarnMissingKindSignatures :: TcGblEnv -> RnM ()\\nwarnMissingKindSignatures gbl_env\\n = do { cusks_enabled <- xoptM LangExt.CUSKs\\n ; mapM_ (add_ty_warn cusks_enabled) tcs\\n }\\n where\\n tcs = tcg_tcs gbl_env\\n ksig_ns = tcg_ksigs gbl_env\\n exports = availsToNameSet (tcg_exports gbl_env)\\n\\n has_kind_signature :: Name -> Bool\\n has_kind_signature name = name `elemNameSet` ksig_ns\\n\\n add_ty_warn :: Bool -> TyCon -> RnM ()\\n add_ty_warn cusks_enabled tyCon =\\n when (has_kind_signature name) $\\n addDiagnosticAt (getSrcSpan name) diag\\n where\\n name = tyConName tyCon\\n diag = TcRnMissingSignature missing exported\\n missing = MissingTyConKindSig tyCon cusks_enabled\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused imports}\\n* *\\n*********************************************************\\n\\nThis code finds which import declarations are unused. The\\nspecification and implementation notes are here:\\n https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/unused-imports\\n\\nSee also Note [Choosing the best import declaration] in GHC.Types.Name.Reader\\n-}\\n\\ntype ImportDeclUsage\\n = ( LImportDecl GhcRn -- The import declaration\\n , [GlobalRdrElt] -- What *is* used (normalised)\\n , [Name] -- What is imported but *not* used\\n , [NamespaceSpecifier GhcRn] ) -- Unused wildcards\\n\\nwarnUnusedImportDecls :: TcGblEnv -> HscSource -> RnM ()\\nwarnUnusedImportDecls gbl_env hsc_src\\n = do { uses <- readMutVar (tcg_used_gres gbl_env)\\n ; let imports = tcg_rn_imports gbl_env\\n rdr_env = tcg_rdr_env gbl_env\\n\\n -- We should only warn for unnecessary *user* imports, but deciding\\n -- minimal imports should take generated imports into account\\n ; let usageUserImports = findImportUsage (excludeGenerated imports) uses\\n usageAllImports = findImportUsage imports uses\\n\\n ; traceRn \\"warnUnusedImportDecls\\" $\\n (vcat [ text \\"Uses:\\" <+> ppr uses\\n , text \\"Usage all user imports: \\" <+> ppr usageUserImports\\n , text \\"Usage all imports: \\" <+> ppr usageAllImports])\\n\\n ; mapM_ (warnUnusedImport rdr_env) usageUserImports\\n\\n ; whenGOptM Opt_D_dump_minimal_imports $\\n printMinimalImports hsc_src usageAllImports }\\n\\n-- | Exclude generated imports\\nexcludeGenerated :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\nexcludeGenerated = filterOut (isGeneratedImport . ideclOrigin . ideclExt . unLoc)\\n\\nfindImportUsage :: [LImportDecl GhcRn]\\n -> [GlobalRdrElt]\\n -> [ImportDeclUsage]\\n\\nfindImportUsage imports used_gres\\n = map unused_decl imports\\n where\\n import_usage :: ImportMap\\n import_usage = mkImportMap used_gres\\n\\n unused_decl :: LImportDecl GhcRn -> ImportDeclUsage\\n unused_decl decl@(L _ (ImportDecl { ideclImportList = imps }))\\n = -- pprTrace \\"unused_decl\\" (vcat [ ppr decl\\n -- , text \\"used\\" <+> ppr used_gres\\n -- , text \\"unused\\" <+> ppr unused_names ]) $\\n (decl, used_gres, unused_names, unused_wcs)\\n where\\n used_gres = lookupImportMap decl import_usage\\n\\n used_gre_env = mkGlobalRdrEnv used_gres\\n used_parents = mkNameSet (mapMaybe greParent_maybe used_gres)\\n\\n (unused_names, unused_wcs) -- Not trivial; see eg #7454\\n = case imps of\\n Just (Exactly, imp_ies) ->\\n let unused = foldr (add_unused . unLoc) emptyUnusedNames imp_ies\\n nms = nameSetElemsStable (collectUnusedNames unused)\\n wcs = collectUnusedWildcards unused\\n in (nms, wcs)\\n _other -> ([], []) -- No explicit import list => no unused-name list\\n\\n add_unused :: IE GhcRn -> UnusedNames -> UnusedNames\\n add_unused (IEVar _ n _) acc = add_unused_name (lieWrappedName n) True acc\\n add_unused (IEThingAbs _ n _) acc = add_unused_name (lieWrappedName n) False acc\\n add_unused (IEThingAll _ _ n _) acc = add_unused_all (lieWrappedName n) acc\\n add_unused (IEThingWith _ p wc ns _) acc = add_wc_all (add_unused_with pn xs acc)\\n where pn = lieWrappedName p\\n xs = map lieWrappedName ns\\n add_wc_all = case wc of\\n NoIEWildcard -> id\\n IEWildcard _ -> add_unused_all pn\\n add_unused (IEWholeNamespace x ns_spec) acc = add_unused_wildcard ns_spec (iewn_names x) acc\\n add_unused _ acc = acc\\n\\n add_unused_name :: Name -> Bool -> UnusedNames -> UnusedNames\\n add_unused_name n is_ie_var acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | is_ie_var\\n , isFieldName n\\n -- See Note [Reporting unused imported duplicate record fields]\\n = let\\n fs = getOccFS n\\n (flds, flds_used) = lookupFsEnv acc_fs fs `orElse` (emptyNameSet, Any False)\\n acc_fs\' = extendFsEnv acc_fs fs (extendNameSet flds n, Any used S.<> flds_used)\\n in UnusedNames acc_ns acc_wcs acc_fs\'\\n\\n | used\\n = acc\\n\\n | otherwise\\n = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n where\\n used = isJust $ lookupGRE_Name used_gre_env n\\n\\n add_unused_all :: Name -> UnusedNames -> UnusedNames\\n add_unused_all n acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | Just {} <- lookupGRE_Name used_gre_env n = acc\\n | n `elemNameSet` used_parents = acc\\n | otherwise = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n\\n add_unused_with :: Name -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_with p ns acc\\n | all (`elemNameSet` acc1_ns) ns = add_unused_name p False acc1\\n | otherwise = acc1\\n where\\n acc1@(UnusedNames acc1_ns _ _) = foldr (\\\\n acc\' -> add_unused_name n False acc\') acc ns\\n -- If you use \'signum\' from Num, then the user may well have\\n -- imported Num(signum). We don\'t want to complain that\\n -- Num is not itself mentioned. Hence the two cases in add_unused_with.\\n\\n add_unused_wildcard :: NamespaceSpecifier GhcRn -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_wildcard ns_spec names acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | any_used = acc\\n | otherwise = UnusedNames acc_ns (ns_spec : acc_wcs) acc_fs\\n where\\n -- A wildcard `type ..` or `data ..` is used if at least one of\\n -- the names it expands to is used\\n any_used = any (isJust . lookupGRE_Name used_gre_env) names\\n\\n\\n-- | An accumulator for unused names in an import list.\\n--\\n-- See Note [Reporting unused imported duplicate record fields].\\ndata UnusedNames =\\n UnusedNames\\n { unused_names :: NameSet\\n -- ^ Unused \'Name\'s in an import list, not including record fields\\n -- that are plain \'IEVar\' imports (tracked by \'rec_fld_uses\')\\n -- or wildcard imports (tracked by \'unused_wildcards\').\\n , unused_wildcards :: [NamespaceSpecifier GhcRn]\\n -- ^ Unused wildcards @type ..@ or @data ..@ in an import list.\\n , rec_fld_uses :: FastStringEnv (NameSet, Any)\\n -- ^ Record fields imported without a parent (i.e. an \'IEVar\' import).\\n --\\n -- The \'Any\' value records whether any of the record fields\\n -- sharing the same underlying \'FastString\' have been used.\\n }\\n\\nemptyUnusedNames :: UnusedNames\\nemptyUnusedNames = UnusedNames emptyNameSet [] emptyFsEnv\\n\\ninstance Outputable UnusedNames where\\n ppr (UnusedNames nms wcs flds) =\\n text \\"UnusedNames\\" <+>\\n braces (ppr nms <+> ppr wcs <+> ppr (fmap (second getAny) flds))\\n\\n-- | Collect all unused names from a \'UnusedNames\' value.\\ncollectUnusedNames :: UnusedNames -> NameSet\\ncollectUnusedNames (UnusedNames { unused_names = nms, rec_fld_uses = flds })\\n = nms S.<> unused_flds\\n where\\n unused_flds = nonDetFoldFsEnv collect_unused emptyNameSet flds\\n collect_unused :: (NameSet, Any) -> NameSet -> NameSet\\n collect_unused (nms, Any at_least_one_name_is_used) acc\\n | at_least_one_name_is_used = acc\\n | otherwise = unionNameSet nms acc\\n\\ncollectUnusedWildcards :: UnusedNames -> [NamespaceSpecifier GhcRn]\\ncollectUnusedWildcards = unused_wildcards\\n\\n{- Note [Reporting unused imported duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have (#24035):\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M1 (R1(..), R2(..)) where\\n data R1 = MkR1 { fld :: Int }\\n data R2 = MkR2 { fld :: Int }\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M2 where\\n import M1 (R1(MkR1), R2, fld)\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nIn the import of \'M1\' in \'M2\', the \'fld\' import resolves to two separate GREs,\\nnamely R1(fld) and R2(fld). From the perspective of the renamer, and in particular\\nthe \'findImportUsage\' function, it\'s as if the user had imported the two names\\nseparately (even though no source syntax allows that).\\n\\nThis means that we need to be careful when reporting unused imports: the R2(fld)\\nimport is indeed unused, but because R1(fld) is used, we should not report\\nfld as unused altogether.\\n\\nTo achieve this, we keep track of record field imports without a parent (i.e.\\nusing the IEVar constructor) separately from other import items, using the\\nUnusedNames datatype.\\nOnce we have accumulated usages, we emit warnings for unused record fields\\nwithout parents one whole group (of record fields sharing the same textual name)\\nat a time, and only if *all* of the record fields in the group are unused;\\nsee \'collectUnusedNames\'.\\n\\nNote that this only applies to record fields imported without a parent. If we\\nhad:\\n\\n import M1 (R1(MkR1, fld), R2(fld))\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nthen of course we should report the second \'fld\' as unused.\\n-}\\n\\n\\n{- Note [The ImportMap]\\n~~~~~~~~~~~~~~~~~~~~~~~\\nThe ImportMap is a short-lived intermediate data structure records, for\\neach import declaration, what stuff brought into scope by that\\ndeclaration is actually used in the module.\\n\\nThe [GlobalRdrElt] are the things imported from that decl.\\n-}\\n\\ndata ImportMap = ImportMap\\n { im_imports :: Map RealSrcSpan [GlobalRdrElt]\\n -- ^ See [The ImportMap]\\n -- If loc :-> gres, then\\n -- \'loc\' = the end loc of the bestImport of each GRE in \'gres\'\\n , im_generatedImports :: Map ModuleName [GlobalRdrElt]\\n }\\n\\nmkImportMap :: [GlobalRdrElt] -> ImportMap\\n-- For each of a list of used GREs, find all the import decls that brought\\n-- it into scope; choose one of them (bestImport), and record\\n-- the RdrName in that import decl\'s entry in the ImportMap\\nmkImportMap = foldr insertImportMap $ ImportMap Map.empty Map.empty\\n\\ninsertImportMap :: GlobalRdrElt -> ImportMap -> ImportMap\\ninsertImportMap gre@(GRE { gre_imp = imp_specs }) importMap\\n | RealSrcSpan importSpan _ <- is_dloc best_imp_spec =\\n importMap{im_imports = insertElem importSpan gre $ im_imports importMap}\\n | GeneratedSrcSpan{} <- is_dloc best_imp_spec =\\n importMap{im_generatedImports = insertElem (moduleName $ is_mod best_imp_spec) gre $ im_generatedImports importMap}\\n | otherwise = importMap\\n where\\n best_imp_spec =\\n case bagToList imp_specs of\\n [] -> pprPanic \\"mkImportMap: GRE with no ImportSpecs\\" (ppr gre)\\n is:iss -> is_decl $ bestImport (is NE.:| iss)\\n\\n -- https://github.com/haskell/containers/issues/784\\n insertElem :: Ord k => k -> v -> Map k [v] -> Map k [v]\\n insertElem k v = flip Map.alter k $ \\\\case\\n Just vs -> Just (v : vs)\\n Nothing -> Just [v]\\n\\nlookupImportMap :: LImportDecl GhcRn -> ImportMap -> [GlobalRdrElt]\\nlookupImportMap (L srcSpan ImportDecl{ideclName = L _ modName}) importMap =\\n fromMaybe [] $\\n -- should match logic in insertImportMap\\n case locA srcSpan of\\n RealSrcSpan realSrcSpan _ -> realSrcSpan `Map.lookup` im_imports importMap\\n GeneratedSrcSpan{} -> modName `Map.lookup` im_generatedImports importMap\\n _ -> Nothing\\n\\nlieNames :: LIE (GhcPass p) -> [Located (IdP (GhcPass p))]\\nlieNames = _\\n\\nwarnUnusedImport :: GlobalRdrEnv -> ImportDeclUsage -> RnM ()\\nwarnUnusedImport rdr_env (L loc decl, used, unused, unused_wcs)\\n\\n -- Do not warn for \'import M()\'\\n -- See (UI1) in Note [Unused imports]\\n | Just (Exactly, _) <- ideclImportList decl\\n , null unused && null unused_wcs\\n = return ()\\n\\n -- Note [Do not warn about Prelude hiding]\\n | Just (EverythingBut, hides) <- ideclImportList decl\\n , not (null hides)\\n , pRELUDE_NAME == unLoc (ideclName decl)\\n = return ()\\n\\n -- Do not warn about import X as Rebindable\\n -- See (UI2) in Note [Unused imports]\\n | Just (L _ mod) <- ideclAs decl\\n , mod == rEBINDABLE_MOD_NAME\\n = return ()\\n\\n -- Nothing used; drop entire declaration\\n | null used\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl UnusedImportNone)\\n\\n -- Everything imported is used; nop\\n | null unused && null unused_wcs\\n = return ()\\n\\n -- Some imports are unused: make the `SrcSpan` cover only the unused\\n -- items instead of the whole import statement\\n | Just (_, imports) <- ideclImportList decl\\n , let unused_locs = [ locA loc | L loc ie <- imports\\n , name <- ieNames ie\\n , name `elem` unused ]\\n , loc1 : locs <- unused_locs\\n , let span = foldr1 combineSrcSpans ( loc1 NE.:| locs )\\n = addDiagnosticAt span (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n -- Some imports are unused\\n | otherwise\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n where\\n -- In warning message, pretty-print identifiers unqualified unconditionally\\n -- to improve the consistent for ambiguous/unambiguous identifiers.\\n -- See #14881.\\n possible_field n =\\n case lookupGRE_Name rdr_env n of\\n Just (GRE { gre_par = par, gre_info = IAmRecField info }) ->\\n let fld_occ :: OccName\\n fld_occ = nameOccName $ flSelector $ recFieldLabel info\\n in UnusedImportNameRecField par fld_occ\\n _ -> UnusedImportNameRegular n\\n\\n -- Print unused names in a deterministic (lexicographic) order\\n sort_unused :: [UnusedImportName]\\n sort_unused =\\n [ UnusedImportWildcard wc | wc <- unused_wcs ] ++\\n [ possible_field nm | nm <- sortBy (comparing nameOccName) unused ]\\n\\ngetMinimalImports :: [ImportDeclUsage] -> RnM [LImportDecl GhcRn]\\ngetMinimalImports ie_decls\\n = do { rdr_env <- getGlobalRdrEnv\\n ; fmap combine $ mapM (mk_minimal rdr_env) ie_decls }\\n where\\n mk_minimal rdr_env (L l decl, used_gres, unused, unused_wcs)\\n | null unused && null unused_wcs\\n , Just (Exactly, _) <- ideclImportList decl\\n = return (L l decl)\\n | otherwise\\n = do { let ImportDecl { ideclName = L _ mod_name\\n , ideclSource = is_boot\\n , ideclPkgQual = pkg_qual\\n , ideclExt = XImportDeclPass { ideclOrigin = origin } } = decl\\n ; iface <- loadSrcInterface doc (importDeclLookupScope origin)\\n mod_name is_boot pkg_qual\\n ; let used_avails = gresToAvailInfo used_gres\\n ; lies <- map (L l) <$> concatMapM (to_ie rdr_env iface) used_avails\\n ; return (L l (decl { ideclImportList = Just (Exactly, lies) })) }\\n where\\n doc = text \\"Compute minimal imports for\\" <+> ppr decl\\n\\n to_ie :: GlobalRdrEnv -> ModIface -> AvailInfo -> RnM [IE GhcRn]\\n -- The main trick here is that if we\'re importing all the constructors\\n -- we want to say \\"T(..)\\", but if we\'re importing only a subset we want\\n -- to say \\"T(A,B,C)\\". So we have to find out what the module exports.\\n to_ie rdr_env _ (Avail c) -- Note [Overloaded field import]\\n = do { let\\n gre = expectJust $ lookupGRE_Name rdr_env c\\n ; return $ [IEVar Nothing (to_ie_post_rn $ noLocA $ greName gre) Nothing] }\\n to_ie _ _ avail@(AvailTC n [_]) -- Exporting the main decl and nothing else\\n | availExportsDecl avail\\n = return [IEThingAbs Nothing (to_ie_post_rn $ noLocA n) Nothing]\\n to_ie rdr_env iface (AvailTC n cs) =\\n case [ xs | avail@(AvailTC x xs) <- mi_exports iface\\n , x == n\\n , availExportsDecl avail -- Note [Partial export]\\n ] of\\n [xs]\\n | all_used xs\\n -> return [IEThingAll (IEThingAllExt Nothing noAnn noAnn noAnn)\\n (NoNamespaceSpecifier noExtField)\\n (to_ie_post_rn $ noLocA n)\\n Nothing]\\n | otherwise\\n -> do { let ns_gres = map (expectJust . lookupGRE_Name rdr_env) cs\\n ns = map greName ns_gres\\n ; return [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n -- Note [Overloaded field import]\\n _other\\n -> do { let infos = map (expectJust . lookupGRE_Name rdr_env) cs\\n (ns_gres,fs_gres) = classifyGREs infos\\n ns = map greName (ns_gres ++ fs_gres)\\n fs = map fieldGREInfo fs_gres\\n ; return $\\n if all_non_overloaded fs\\n then map (\\\\nm -> IEVar Nothing (to_ie_post_rn_var $ noLocA nm) Nothing) ns\\n else [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n where\\n\\n all_used avail_cs = all (`elem` cs) avail_cs\\n\\n all_non_overloaded = all (not . flIsOverloaded . recFieldLabel)\\n\\n combine :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\n combine = map merge . NE.groupAllWith getKey\\n\\n getKey :: LImportDecl GhcRn -> (Bool, Maybe ModuleName, ModuleName)\\n getKey decl =\\n ( isImportDeclQualified . ideclQualified $ idecl -- is this qualified? (important that this be first)\\n , unLoc <$> ideclAs idecl -- what is the qualifier (inside Maybe monad)\\n , unLoc . ideclName $ idecl -- Module Name\\n )\\n where\\n idecl :: ImportDecl GhcRn\\n idecl = unLoc decl\\n\\n merge :: NonEmpty (LImportDecl GhcRn) -> LImportDecl GhcRn\\n merge decls@((L l decl) :| _) = L l (decl { ideclImportList = Just (Exactly, lies) })\\n where lies = concatMap snd $ mapMaybe (ideclImportList . unLoc) $ NE.toList decls\\n\\nclassifyGREs :: [GlobalRdrElt] -> ([GlobalRdrElt], [FieldGlobalRdrElt])\\nclassifyGREs = partition (not . isRecFldGRE)\\n\\nprintMinimalImports :: HscSource -> [ImportDeclUsage] -> RnM ()\\n-- See Note [Printing minimal imports]\\nprintMinimalImports hsc_src imports_w_usage\\n = do { imports\' <- excludeGenerated <$> getMinimalImports imports_w_usage\\n ; this_mod <- getModule\\n ; dflags <- getDynFlags\\n ; liftIO $ withFile (mkFilename dflags this_mod) WriteMode $ \\\\h ->\\n printForUser dflags h neverQualify AllTheWay (vcat (map ppr imports\'))\\n -- The neverQualify is important. We are printing Names\\n -- but they are in the context of an \'import\' decl, and\\n -- we never qualify things inside there\\n -- E.g. import Blag( f, b )\\n -- not import Blag( Blag.f, Blag.g )!\\n }\\n where\\n mkFilename dflags this_mod\\n | Just d <- dumpDir dflags = d basefn\\n | otherwise = basefn\\n where\\n suffix = case hsc_src of\\n HsBootFile -> \\".imports-boot\\"\\n HsSrcFile -> \\".imports\\"\\n HsigFile -> \\".imports\\"\\n basefn = moduleNameString (moduleName this_mod) ++ suffix\\n\\n\\nto_ie_post_rn_var :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn_var (L l n)\\n | isDataOcc $ occName n = L l (IEPattern noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n\\n\\nto_ie_post_rn :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn (L l n)\\n | isTcOcc occ && isSymOcc occ = L l (IEType noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n where occ = occName n\\n\\n{- Note [Do not warn about Prelude hiding]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWe do not warn about\\n import Prelude hiding( x, y )\\nbecause even if nothing else from Prelude is used, it may be essential to hide\\nx,y to avoid name-shadowing warnings. Example (#9061)\\n import Prelude hiding( log )\\n f x = log where log = ()\\n\\nNote [Unused imports]\\n~~~~~~~~~~~~~~~~~~~~~\\nIn `warnUnusedImport`, if we see an import with an explicit list imports, thus\\n import M( a, b )\\nand neither `a` nor `b` is used, we report the entire import decl as unused. We\\ncheck this by looking at the names that it brings into scope scope; if there are\\nno ununused names, don\'t report.\\n\\n(UI1) We don\'t want to complain about `import M()`, because that is often used to bring\\n M\'s /instances/ into scope. That is neatly dealt with by the \\"no unused\\n names\\" (nor unused wildcard imports) criterion.\\n\\n(UI2) We don\'t report a decl as unused if it has an `as Rebindable` qualifier.\\n See (KN1) in Note [Overview of known entities] in GHC.Builtin\\n\\n\\nNote [Printing minimal imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nTo print the minimal imports we walk over all import decls (both user-supplied\\nand generated), trim their import lists, then filter out generated decls.\\n\\nNB that\\n\\n * We do *not* change the \'qualified\' or \'as\' parts!\\n\\n * We do not discard a decl altogether; we might need instances\\n from it. Instead we just trim to an empty import list\\n\\nNote [Partial export]\\n~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have\\n\\n module A( op ) where\\n class C a where\\n op :: a -> a\\n\\n module B where\\n import A\\n f = ..op...\\n\\nThen the minimal import for module B is\\n import A( op )\\nnot\\n import A( C( op ) )\\nwhich we would usually generate if C was exported from B. Hence\\nthe availExportsDecl test when deciding what to generate.\\n\\n\\nNote [Overloaded field import]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nOn the other hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n data T = MkT { foo :: Int }\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( T(foo) )\\nbecause when DuplicateRecordFields is enabled, field selectors are\\nnot in scope without their enclosing datatype.\\n\\nOn the third hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n pattern MkT { foo } = Just foo\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( foo )\\nbecause foo doesn\'t have a parent. This might actually be ambiguous if A\\nexports another field called foo, but there is no good answer to return and this\\nis a very obscure corner, so it seems to be the best we can do. See\\nDRFPatSynExport for a test of this.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Errors}\\n* *\\n************************************************************************\\n-}\\n\\nbadImportItemErr\\n :: ModIface -> ImpDeclSpec -> IE GhcPs\\n -> IsSubordinateError\\n -> [AvailInfo]\\n -> TcRn (NonEmpty ImportLookupReason)\\nbadImportItemErr iface decl_spec ie sub avails = do\\n exts <- importLookupExtensions\\n let import_lookup_bad :: BadImportKind -> ImportLookupReason\\n import_lookup_bad k = ImportLookupBad k iface decl_spec ie exts\\n dflags <- getDynFlags\\n hsc_env <- getTopEnv\\n let rdr_env = mkGlobalRdrEnv\\n $ gresFromAvails hsc_env (Just imp_spec) all_avails\\n pure $ fmap import_lookup_bad (importErrorKind dflags rdr_env)\\n where\\n importErrorKind :: DynFlags -> GlobalRdrEnv -> NonEmpty BadImportKind\\n importErrorKind dflags rdr_env\\n | any checkIfTyCon avails = case sub of\\n IsNotSubordinate -> NE.singleton BadImportAvailTyCon\\n IsSubordinateError { subordinate_err_parent = gre\\n , subordinate_err_unavailable = unavailable\\n , subordinate_err_nontype = nontype\\n , subordinate_err_nondata = nondata }\\n -> NE.fromList $ catMaybes $\\n [ fmap (BadImportNotExportedSubordinates gre) (NE.nonEmpty unavailable)\\n , fmap (BadImportNonTypeSubordinates gre) (NE.nonEmpty nontype)\\n , fmap (BadImportNonDataSubordinates gre) (NE.nonEmpty nondata) ]\\n | any checkIfVarName avails = NE.singleton BadImportAvailVar\\n | Just con <- find checkIfDataCon avails = NE.singleton (BadImportAvailDataCon (availOccName con))\\n | otherwise = NE.singleton (BadImportNotExported suggs)\\n where\\n suggs = similar_suggs ++ fieldSelectorSuggestions rdr_env rdr\\n what_look = case sub of\\n IsNotSubordinate -> WL_TyCon_or_TermVar\\n IsSubordinateError { subordinate_err_parent = gre } ->\\n case greInfo gre of\\n IAmTyCon ClassFlavour\\n -> WL_TyCon_or_TermVar\\n _ -> WL_Term\\n similar_names =\\n similarNameSuggestions (Unbound.LF what_look WL_Global)\\n dflags rdr_env emptyLocalRdrEnv rdr\\n similar_suggs =\\n case NE.nonEmpty $ mapMaybe imported_item $ similar_names of\\n Just similar -> [ SuggestSimilarNames rdr similar ]\\n Nothing -> [ ]\\n\\n -- Only keep imported items, and set the \\"HowInScope\\" to\\n -- \\"Nothing\\" to avoid printing \\"imported from...\\" in the suggestion\\n -- error message.\\n imported_item (SimilarRdrName rdr_name gre (Just (ImportedBy {})))\\n = Just (SimilarRdrName rdr_name gre Nothing)\\n imported_item _ = Nothing\\n\\n checkIfDataCon = checkIfAvailMatches isDataConName\\n checkIfTyCon = checkIfAvailMatches isTyConName\\n checkIfVarName =\\n \\\\case\\n AvailTC{} -> False\\n Avail n -> importedFS == occNameFS (occName n)\\n && (isVarOcc <||> isFieldOcc) (occName n)\\n checkIfAvailMatches namePred =\\n \\\\case\\n AvailTC _ ns ->\\n case find (\\\\n -> importedFS == occNameFS (occName n)) ns of\\n Just n -> namePred n\\n Nothing -> False\\n Avail{} -> False\\n availOccName = occName . availName\\n rdr = ieName ie\\n importedFS = occNameFS $ rdrNameOcc rdr\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n all_avails = mi_exports iface\\n\\nimportLookupExtensions :: TcRn ImportLookupExtensions\\nimportLookupExtensions = do\\n ile_pattern_synonyms <- xoptM LangExt.PatternSynonyms\\n ile_explicit_namespaces <- xoptM LangExt.ExplicitNamespaces\\n return ImportLookupExtensions{ile_pattern_synonyms, ile_explicit_namespaces}\\n\\naddDupDeclErr :: NonEmpty GlobalRdrElt -> TcRn ()\\naddDupDeclErr gres@(gre :| _)\\n -- Report the error at the later location\\n = addErrAt (getSrcSpan (NE.last sorted_names)) $ (TcRnDuplicateDecls (greOccName gre) sorted_names)\\n where\\n sorted_names =\\n NE.sortBy (SrcLoc.leftmost_smallest `on` nameSrcSpan)\\n (fmap greName gres)\\n\\n-- This data decl will parse OK\\n-- data T = a Int\\n-- treating \\"a\\" as the constructor.\\n-- It is really hard to make the parser spot this malformation.\\n-- So the renamer has to check that the constructor is legal\\n--\\n-- We can get an operator as the constructor, even in the prefix form:\\n-- data T = :% Int Int\\n-- from interface files, which always print in prefix form\\n--\\n-- We also allow type constructor names, which are defined by \\"type data\\"\\n-- declarations. See Note [Type data declarations] in GHC.Rename.Module.\\n\\ncheckConName :: RdrName -> TcRn ()\\ncheckConName name\\n = checkErr (isRdrDataCon name || isRdrTc name) (TcRnIllegalDataCon name)\\n", "filetypes": ["haskell"]}}}' 2026-10-16 14:49:01,845 - DEBUG - POST b'http://127.0.0.1:37093/receive_messages' {'content-type': 'application/json', 'x-ycm-hmac': b'Rga7Yd4l4fgfufwYw+0sxzurvznImlBO0MPmgAlS4EY='} b'{"filepath": "/home/enrico/ghc/compiler/GHC/Rename/Names.hs", "line_num": 1, "column_num": 1, "working_dir": "/home/enrico/ghc", "file_data": {"/home/enrico/ghc/compiler/GHC/Rename/Names.hs": {"contents": "{-\\n(c) The GRASP/AQUA Project, Glasgow University, 1992-1998\\n\\nExtracting imported and top-level names in scope\\n-}\\n\\n{-# LANGUAGE NondecreasingIndentation #-}\\n{-# LANGUAGE TypeFamilies #-}\\n\\nmodule GHC.Rename.Names (\\n rnImports, getLocalNonValBinders, newRecordFieldLabel,\\n importsFromIface,\\n ImportUserSpec(..),\\n extendGlobalRdrEnvRn,\\n gresFromAvails,\\n calculateAvails,\\n reportUnusedNames,\\n checkConName,\\n mkChildEnv,\\n findChildren,\\n mkBadExportSubordinate,\\n findImportUsage,\\n getMinimalImports,\\n printMinimalImports,\\n renamePkgQual, renameRawPkgQual,\\n classifyGREs,\\n ImportDeclUsage,\\n rnNamespaceSpecifier\\n ) where\\n\\nimport GHC.Prelude hiding ( head, init, last, tail )\\n\\nimport GHC.Driver.Env\\nimport GHC.Driver.Session\\nimport GHC.Driver.Ppr\\n\\nimport GHC.Rename.Env\\nimport GHC.Rename.Fixity\\nimport GHC.Rename.Utils ( warnUnusedTopBinds )\\nimport GHC.Rename.Unbound\\nimport qualified GHC.Rename.Unbound as Unbound\\n\\nimport GHC.Tc.Errors.Types\\nimport GHC.Tc.Utils.Env\\nimport GHC.Tc.Utils.Monad\\nimport GHC.Tc.Types.LclEnv\\nimport GHC.Tc.Zonk.TcType ( tcInitTidyEnv )\\n\\nimport GHC.Hs\\nimport GHC.Iface.Load ( loadSrcInterface, loadSrcInterface_maybe )\\nimport GHC.Iface.Errors.Types\\n ( IfaceMessage(..), MissingInterfaceError, InterfaceLookingFor(..)\\n , LoadEssentialsReason(..) )\\nimport GHC.Iface.Syntax ( fromIfaceWarnings )\\nimport GHC.Builtin.Modules( pRELUDE_NAME, rEBINDABLE_MOD_NAME )\\nimport GHC.Parser.PostProcess ( setRdrNameSpace )\\nimport GHC.Core.TyCo.Tidy\\nimport GHC.Core.PatSyn\\nimport GHC.Core.TyCon ( TyCon, tyConName )\\nimport qualified GHC.LanguageExtensions as LangExt\\n\\nimport GHC.Utils.Outputable as Outputable\\nimport GHC.Utils.Misc as Utils\\nimport GHC.Utils.Panic\\n\\nimport GHC.Types.Fixity.Env\\nimport GHC.Types.SafeHaskell\\nimport GHC.Types.Name\\nimport GHC.Types.Name.Env\\nimport GHC.Types.Name.Set\\nimport GHC.Types.Name.Reader\\nimport GHC.Types.Avail\\nimport GHC.Types.FieldLabel\\nimport GHC.Types.Hint\\nimport GHC.Types.SourceFile\\nimport GHC.Types.SrcLoc as SrcLoc\\nimport GHC.Types.Basic (TyConFlavour (..), convImportLevel, VisArity)\\nimport GHC.Types.UnresolvedImport\\nimport GHC.Types.Id\\nimport GHC.Types.PkgQual\\nimport GHC.Types.GREInfo (ConInfo(..), ConFieldInfo (..), ConLikeInfo (ConIsData))\\n\\nimport GHC.Unit\\nimport GHC.Unit.Module.Warnings\\nimport GHC.Unit.Module.ModIface\\nimport GHC.Unit.Module.Imported\\nimport GHC.Unit.Module.Deps\\nimport GHC.Unit.Env\\n\\nimport GHC.Data.Bag\\nimport GHC.Data.FastString\\nimport GHC.Data.FastString.Env\\nimport GHC.Data.Maybe\\nimport GHC.Data.List.SetOps ( removeDups )\\n\\nimport Control.Arrow ( second )\\nimport Control.Monad\\nimport Data.Foldable ( for_ )\\nimport Data.IntMap ( IntMap )\\nimport qualified Data.IntMap as IntMap\\nimport Data.Map ( Map )\\nimport qualified Data.Map as Map\\nimport Data.Ord ( comparing )\\nimport Data.Semigroup ( Any(..) )\\nimport qualified Data.Semigroup as S\\nimport Data.List ( partition, find, sortBy )\\nimport Data.List.NonEmpty (NonEmpty(..))\\nimport qualified Data.List.NonEmpty as NE\\nimport Data.Function ( on )\\nimport qualified Data.Set as S\\nimport System.FilePath (())\\nimport System.IO\\n\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{rnImports}\\n* *\\n************************************************************************\\n\\nNote [Tracking Trust Transitively]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen we import a package as well as checking that the direct imports are safe\\naccording to the rules outlined in the Note [Safe Haskell Trust Check] in GHC.Driver.Main\\nwe must also check that these rules hold transitively for all dependent modules\\nand packages. Doing this without caching any trust information would be very\\nslow as we would need to touch all packages and interface files a module depends\\non. To avoid this we make use of the property that if a modules Safe Haskell\\nmode changes, this triggers a recompilation from that module in the dependency\\ngraph. So we can just worry mostly about direct imports.\\n\\nThere is one trust property that can change for a package though without\\nrecompilation being triggered: package trust. So we must check that all\\npackages a module transitively depends on to be trusted are still trusted when\\nwe are compiling this module (as due to recompilation avoidance some modules\\nbelow may not be considered trusted any more without recompilation being\\ntriggered).\\n\\nWe handle this by augmenting the existing transitive list of packages a module M\\ndepends on with a bool for each package that says if it must be trusted when the\\nmodule M is being checked for trust. This list of trust required packages for a\\nsingle import is gathered in the rnImportDecl function and stored in an\\nImportAvails data structure. The union of these trust required packages for all\\nimports is done by the rnImports function using the combine function which calls\\nthe plusImportAvails function that is a union operation for the ImportAvails\\ntype. This gives us in an ImportAvails structure all packages required to be\\ntrusted for the module we are currently compiling. Checking that these packages\\nare still trusted (and that direct imports are trusted) is done in\\nGHC.Driver.Main.checkSafeImports.\\n\\nSee the note below, [Trust Own Package] for a corner case in this method and\\nhow its handled.\\n\\n\\nNote [Trust Own Package]\\n~~~~~~~~~~~~~~~~~~~~~~~~\\nThere is a corner case of package trust checking that the usual transitive check\\ndoesn\'t cover. (For how the usual check operates see the Note [Tracking Trust\\nTransitively] below). The case is when you import a -XSafe module M and M\\nimports a -XTrustworthy module N. If N resides in a different package than M,\\nthen the usual check works as M will record a package dependency on N\'s package\\nand mark it as required to be trusted. If N resides in the same package as M\\nthough, then importing M should require its own package be trusted due to N\\n(since M is -XSafe so doesn\'t create this requirement by itself). The usual\\ncheck fails as a module doesn\'t record a package dependency of its own package.\\nSo instead we now have a bool field in a modules interface file that simply\\nstates if the module requires its own package to be trusted. This field avoids\\nus having to load all interface files that the module depends on to see if one\\nis trustworthy.\\n\\n\\nNote [Trust Transitive Property]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSo there is an interesting design question in regards to transitive trust\\nchecking. Say I have a module B compiled with -XSafe. B is dependent on a bunch\\nof modules and packages, some packages it requires to be trusted as its using\\n-XTrustworthy modules from them. Now if I have a module A that doesn\'t use safe\\nhaskell at all and simply imports B, should A inherit all the trust\\nrequirements from B? Should A now also require that a package p is trusted since\\nB required it?\\n\\nWe currently say no but saying yes also makes sense. The difference is, if a\\nmodule M that doesn\'t use Safe Haskell imports a module N that does, should all\\nthe trusted package requirements be dropped since M didn\'t declare that it cares\\nabout Safe Haskell (so -XSafe is more strongly associated with the module doing\\nthe importing) or should it be done still since the author of the module N that\\nuses Safe Haskell said they cared (so -XSafe is more strongly associated with\\nthe module that was compiled that used it).\\n\\nGoing with yes is a simpler semantics we think and harder for the user to stuff\\nup but it does mean that Safe Haskell will affect users who don\'t care about\\nSafe Haskell as they might grab a package from Cabal which uses safe haskell (say\\nnetwork) and that packages imports -XTrustworthy modules from another package\\n(say bytestring), so requires that package is trusted. The user may now get\\ncompilation errors in code that doesn\'t do anything with Safe Haskell simply\\nbecause they are using the network package. They will have to call \'ghc-pkg\\ntrust network\' to get everything working. Due to this invasive nature of going\\nwith yes we have gone with no for now.\\n-}\\n\\n-- | Process Import Decls. See \'rnImportDecl\' for a description of what\\n-- the return types represent.\\n-- Note: Do the non SOURCE ones first, so that we get a helpful warning\\n-- for SOURCE ones that are unnecessary\\nrnImports :: [(LImportDecl GhcPs, SDoc)]\\n -> RnM ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\nrnImports imports = do\\n tcg_env <- getGblEnv\\n -- NB: want an identity module here, because it\'s OK for a signature\\n -- module to import from its implementor\\n let this_mod = tcg_mod tcg_env\\n let (source, ordinary) = partition (is_source_import . fst) imports\\n is_source_import (d::LImportDecl GhcPs) = ideclSource (unLoc d) == IsBoot\\n stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary\\n stuff2 <- mapAndReportM (rnImportDecl this_mod) source\\n -- Safe Haskell: See Note [Tracking Trust Transitively]\\n let (decls, imp_user_spec, rdr_env, imp_avails) = combine (stuff1 ++ stuff2)\\n -- Update imp_boot_mods if imp_direct_mods mentions any of them\\n let merged_import_avail = clobberSourceImports imp_avails\\n return (decls, imp_user_spec, rdr_env, merged_import_avail)\\n\\n where\\n clobberSourceImports imp_avails =\\n imp_avails { imp_boot_mods = imp_boot_mods\' }\\n where\\n imp_boot_mods\' = mergeInstalledModuleEnv combJ id (const emptyInstalledModuleEnv)\\n (imp_boot_mods imp_avails)\\n (imp_direct_dep_mods imp_avails)\\n\\n combJ (GWIB _ IsBoot) (_, x) = Just x\\n combJ r _ = Just r\\n -- See Note [Combining ImportAvails]\\n combine :: [(LImportDecl GhcRn, ImportUserSpec, GlobalRdrEnv, ImportAvails)]\\n -> ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\n combine ss =\\n let (decls, imp_user_spec, rdr_env, imp_avails, finsts) = foldr\\n plus\\n ([], [], emptyGlobalRdrEnv, emptyImportAvails, emptyModuleSet)\\n ss\\n in (decls, imp_user_spec, rdr_env, imp_avails { imp_finsts = moduleSetElts finsts })\\n\\n plus (decl, us, gbl_env1, imp_avails1)\\n (decls, uss, gbl_env2, imp_avails2, finsts_set)\\n = ( decl:decls,\\n us:uss,\\n gbl_env1 `plusGlobalRdrEnv` gbl_env2,\\n imp_avails1\' `plusImportAvails` imp_avails2,\\n extendModuleSetList finsts_set new_finsts )\\n where\\n imp_avails1\' = imp_avails1 { imp_finsts = [] }\\n new_finsts = imp_finsts imp_avails1\\n\\n{-\\nNote [Combining ImportAvails]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nimp_finsts in ImportAvails is a list of family instance modules\\ntransitively depended on by an import. imp_finsts for a currently\\ncompiled module is a union of all the imp_finsts of imports.\\nComputing the union of two lists of size N is O(N^2) and if we\\ndo it to M imports we end up with O(M*N^2). That can get very\\nexpensive for bigger module hierarchies.\\n\\nUnion can be optimized to O(N log N) if we use a Set.\\nimp_finsts is converted back and forth between dep_finsts, so\\nchanging a type of imp_finsts means either paying for the conversions\\nor changing the type of dep_finsts as well.\\n\\nI\'ve measured that the conversions would cost 20% of allocations on my\\ntest case, so that can be ruled out.\\n\\nChanging the type of dep_finsts forces checkFamInsts to\\nget the module lists in non-deterministic order. If we wanted to restore\\nthe deterministic order, we\'d have to sort there, which is an additional\\ncost. As far as I can tell, using a non-deterministic order is fine there,\\nbut that\'s a brittle nonlocal property which I\'d like to avoid.\\n\\nAdditionally, dep_finsts is read from an interface file, so its \\"natural\\"\\ntype is a list. Which makes it a natural type for imp_finsts.\\n\\nSince rnImports.combine is really the only place that would benefit from\\nit being a Set, it makes sense to optimize the hot loop in rnImports.combine\\nwithout changing the representation.\\n\\nSo here\'s what we do: instead of naively merging ImportAvails with\\nplusImportAvails in a loop, we make plusImportAvails merge empty imp_finsts\\nand compute the union on the side using Sets. When we\'re done, we can\\nconvert it back to a list. One nice side effect of this approach is that\\nif there\'s a lot of overlap in the imp_finsts of imports, the\\nSet doesn\'t really need to grow and we don\'t need to allocate.\\n\\nRunning generateModules from #14693 with DEPTH=16, WIDTH=30 finishes in\\n23s before, and 11s after.\\n-}\\n\\n-- | Given a located import declaration @decl@ from @this_mod@,\\n-- calculate the following pieces of information:\\n--\\n-- 1. An updated \'LImportDecl\', where all unresolved \'RdrName\' in\\n-- the entity lists have been resolved into \'Name\'s,\\n--\\n-- 2. A \'GlobalRdrEnv\' representing the new identifiers that were\\n-- brought into scope (taking into account module qualification\\n-- and hiding),\\n--\\n-- 3. \'ImportAvails\' summarizing the identifiers that were imported\\n-- by this declaration, and\\n--\\n-- 4. A boolean \'AnyHpcUsage\' which is true if the imported module\\n-- used HPC.\\nrnImportDecl :: Module -> (LImportDecl GhcPs, SDoc)\\n -> RnM (LImportDecl GhcRn, ImportUserSpec , GlobalRdrEnv, ImportAvails)\\nrnImportDecl this_mod\\n (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name\\n , ideclPkgQual = raw_pkg_qual\\n , ideclSource = want_boot\\n , ideclSafe = mod_safe\\n , ideclLevelSpec = import_level\\n , ideclQualified = qual_style\\n , ideclExt = XImportDeclPass { ideclOrigin = origin }\\n , ideclAs = as_mod, ideclImportList = imp_details }), import_reason)\\n = setSrcSpanA loc $ do\\n\\n case raw_pkg_qual of\\n NoRawPkgQual -> pure ()\\n RawPkgQual {} -> do\\n pkg_imports <- xoptM LangExt.PackageImports\\n when (not pkg_imports) $ addErr TcRnPackageImportsDisabled\\n\\n let qual_only = isImportDeclQualified qual_style\\n generated = isGeneratedImport origin\\n\\n lookup_scope = importDeclLookupScope origin\\n\\n -- If there\'s an error in loadInterface, (e.g. interface\\n -- file not found) we get lots of spurious errors from \'filterImports\'\\n let imp_mod_name = unLoc loc_imp_mod_name\\n doc = ppr imp_mod_name <+> import_reason\\n\\n hsc_env <- getTopEnv\\n unit_env <- hsc_unit_env <$> getTopEnv\\n let pkg_qual = renameRawPkgQual unit_env imp_mod_name raw_pkg_qual\\n\\n -- Check for self-import, which confuses the typechecker (#9032)\\n -- ghc --make rejects self-import cycles already, but batch-mode may not\\n -- at least not until GHC.IfaceToCore.tcHiBootIface, which is too late to avoid\\n -- typechecker crashes. (Indirect self imports are not caught until\\n -- GHC.IfaceToCore, see #10337 tracking how to make this error better.)\\n --\\n -- Originally, we also allowed \'import {-# SOURCE #-} M\', but this\\n -- caused bug #10182: in one-shot mode, we should never load an hs-boot\\n -- file for the module we are compiling into the EPS. In principle,\\n -- it should be possible to support this mode of use, but we would have to\\n -- extend Provenance to support a local definition in a qualified location.\\n -- For now, we don\'t support it, but see #10336\\n when (imp_mod_name == moduleName this_mod &&\\n (case pkg_qual of -- If we have import \\"\\" M, then we should\\n -- check that \\"\\" is \\"this\\" (which is magic)\\n -- or the name of this_mod\'s package. Yurgh!\\n -- c.f. GHC.findModule, and #9997\\n NoPkgQual -> True\\n ThisPkg uid -> uid == homeUnitId_ (hsc_dflags hsc_env)\\n OtherPkg _ -> False))\\n (addErr (TcRnSelfImport imp_mod_name))\\n\\n -- Check for a missing import list (Opt_WarnMissingImportList also\\n -- checks for T(..) items but that is done in checkDodgyImport below)\\n case imp_details of\\n Just (Exactly, _) -> return () -- Explicit import list\\n _ | generated -> return () -- Do not bleat for generated imports\\n | qual_only -> return ()\\n | otherwise -> addDiagnostic (TcRnNoExplicitImportList imp_mod_name)\\n\\n\\n mb_iface <- loadSrcInterface_maybe doc lookup_scope imp_mod_name want_boot pkg_qual\\n iface <- case mb_iface of\\n Succeeded iface -> return iface\\n Failed err -> failWithTc $\\n importDeclLoadFailure origin imp_mod_name want_boot err\\n\\n -- Compiler sanity check: if the import didn\'t say\\n -- {-# SOURCE #-} we should not get a hi-boot file\\n warnPprTrace ((want_boot == NotBoot) && (mi_boot iface == IsBoot)) \\"rnImportDecl\\" (ppr imp_mod_name) $ do\\n\\n -- Issue a user warning for a redundant {- SOURCE -} import\\n -- NB that we arrange to read all the ordinary imports before\\n -- any of the {- SOURCE -} imports.\\n --\\n -- in --make and GHCi, the compilation manager checks for this,\\n -- and indeed we shouldn\'t do it here because the existence of\\n -- the non-boot module depends on the compilation order, which\\n -- is not deterministic. The hs-boot test can show this up.\\n dflags <- getDynFlags\\n warnIf ((want_boot == IsBoot) && (mi_boot iface == NotBoot) && isOneShot (ghcMode dflags))\\n (TcRnRedundantSourceImport imp_mod_name)\\n when (mod_safe && not (safeImportsOn dflags)) $\\n addErr (TcRnSafeImportsDisabled imp_mod_name)\\n\\n let imp_mod = mi_module iface\\n qual_mod_name = fmap unLoc as_mod `orElse` imp_mod_name\\n imp_spec = ImpDeclSpec { is_mod = imp_mod, is_qual = qual_only,\\n is_dloc = locA loc, is_as = qual_mod_name,\\n is_pkg_qual = pkg_qual, is_isboot = want_boot,\\n is_level = convImportLevel import_level }\\n\\n let filter_imports = do\\n -- filter the imports according to the import declaration\\n (new_imp_details, imp_user_list, gbl_env)\\n <- filterImports hsc_env iface imp_spec imp_details\\n -- for certain error messages, we\\u2019d like to know what could be\\n -- imported here, if everything were imported\\n potential_gres <- (\\\\(_,_,x) -> x) <$> filterImports hsc_env iface imp_spec Nothing\\n return (new_imp_details, imp_user_list, gbl_env, potential_gres)\\n\\n (new_imp_details, imp_user_list, gbl_env, potential_gres) <-\\n case origin of\\n ImplicitEssentialsImport ->\\n -- The implicit GHC.Essentials import does not bring anything into scope.\\n -- See Note [Finding GHC.Essentials] in GHC.Builtin.\\n return (Nothing, ImpUserDependOnly, emptyGlobalRdrEnv, emptyGlobalRdrEnv)\\n UserWrittenImport -> filter_imports\\n ImplicitPreludeImport -> filter_imports\\n PluginImport -> filter_imports\\n\\n let is_hiding | Just (EverythingBut,_) <- imp_details = True\\n | otherwise = False\\n\\n -- should the import be safe?\\n mod_safe\' = mod_safe\\n || (not generated && safeDirectImpsReq dflags)\\n || (generated && safeImplicitImpsReq dflags)\\n\\n hsc_env <- getTopEnv\\n let home_unit = hsc_home_unit hsc_env\\n other_home_units = hsc_all_home_unit_ids hsc_env\\n\\n imported_by\\n | isDependOnlyImport imp_user_list\\n = ImportedBySystem\\n | otherwise\\n = ImportedByUser $ ImportedModsVal\\n { imv_name = is_as imp_spec\\n , imv_span = locA loc\\n , imv_is_safe = mod_safe\'\\n , imv_is_hiding = is_hiding\\n , imv_all_exports = potential_gres\\n , imv_qualified = qual_only\\n , imv_is_level = convImportLevel import_level\\n }\\n imports = calculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by\\n\\n -- Complain if we import a deprecated module\\n case fromIfaceWarnings (mi_warns iface) of\\n WarnAll txt -> addDiagnostic (TcRnDeprecatedModule imp_mod_name txt)\\n _ -> return ()\\n\\n let new_imp_decl = ImportDecl\\n { ideclExt = ideclExt decl\\n , ideclName = ideclName decl\\n , ideclPkgQual = pkg_qual\\n , ideclSource = ideclSource decl\\n , ideclSafe = mod_safe\'\\n , ideclQualified = ideclQualified decl\\n , ideclAs = ideclAs decl\\n , ideclImportList = new_imp_details\\n , ideclLevelSpec = ideclLevelSpec decl\\n }\\n\\n return (L loc new_imp_decl, ImpUserSpec imp_spec imp_user_list, gbl_env, imports)\\n\\n-- | The error message to emit when we failed to load an interface.\\nimportDeclLoadFailure :: ImportDeclOrigin -> ModuleName -> IsBootInterface\\n -> MissingInterfaceError -> TcRnMessage\\nimportDeclLoadFailure ImplicitEssentialsImport _ _ err\\n = TcRnInterfaceError $ CantFindEssentials err LookingForEssentialsModule\\nimportDeclLoadFailure _ mod_name want_boot err\\n = TcRnInterfaceError $ Can\'tFindInterface err $ LookingForModule mod_name want_boot\\n\\n-- | Rename raw package imports\\nrenameRawPkgQual :: UnitEnv -> ModuleName -> RawPkgQual -> PkgQual\\nrenameRawPkgQual unit_env mn = \\\\case\\n NoRawPkgQual -> NoPkgQual\\n RawPkgQual _ fs -> renamePkgQual unit_env mn $ Just fs\\n\\n-- | Rename raw package imports\\nrenamePkgQual :: UnitEnv -> ModuleName -> Maybe FastString -> PkgQual\\nrenamePkgQual unit_env mn mb_pkg = case mb_pkg of\\n Nothing -> NoPkgQual\\n Just pkg_fs\\n | Just uid <- homeUnitId <$> ue_homeUnit unit_env\\n , pkg_fs == fsLit \\"this\\"\\n -> ThisPkg uid\\n\\n | Just (uid, _) <- find (fromMaybe False . fmap (== pkg_fs) . snd) home_names\\n -> ThisPkg uid\\n\\n | Just uid <- resolvePackageImport unit_state mn (PackageName pkg_fs)\\n -> OtherPkg uid\\n\\n | otherwise\\n -> OtherPkg (UnitId pkg_fs)\\n -- not really correct as pkg_fs is unlikely to be a valid unit-id but\\n -- we will report the failure later...\\n where\\n home_names =\\n [ (uid, mkFastString <$> thisPackageName (homeUnitEnv_dflags (ue_findHomeUnitEnv uid unit_env)))\\n | uid <- S.toList hpt_deps\\n ]\\n\\n unit_state = ue_homeUnitState unit_env\\n\\n hpt_deps :: S.Set UnitId\\n hpt_deps = homeUnitDepends unit_state\\n\\n\\n-- | Calculate the \'ImportAvails\' induced by an import of a particular\\n-- interface, but without \'imp_mods\'.\\ncalculateAvails :: HomeUnit\\n -> S.Set UnitId\\n -> ModIface\\n -> IsSafeImport\\n -> IsBootInterface\\n -> ImportedBy\\n -> ImportAvails\\ncalculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by =\\n let imp_mod = mi_module iface\\n imp_sem_mod= mi_semantic_module iface\\n orph_iface = mi_orphan iface\\n has_finsts = mi_finsts iface\\n deps = mi_deps iface\\n trust = getSafeMode $ mi_trust iface\\n trust_pkg = mi_trust_pkg iface\\n is_sig = mi_hsc_src iface == HsigFile\\n\\n -- If the module exports anything defined in this module, just\\n -- ignore it. Reason: otherwise it looks as if there are two\\n -- local definition sites for the thing, and an error gets\\n -- reported. Easiest thing is just to filter them out up\\n -- front. This situation only arises if a module imports\\n -- itself, or another module that imported it. (Necessarily,\\n -- this involves a loop.)\\n --\\n -- We do this *after* filterImports, so that if you say\\n -- module A where\\n -- import B( AType )\\n -- type AType = ...\\n --\\n -- module B( AType ) where\\n -- import {-# SOURCE #-} A( AType )\\n --\\n -- then you won\'t get a \'B does not export AType\' message.\\n\\n\\n -- Compute new transitive dependencies\\n --\\n -- \'dep_orphs\' and \'dep_finsts\' do NOT include the imported module\\n -- itself, but we DO need to include this module in \'imp_orphs\' and\\n -- \'imp_finsts\' if it defines an orphan or instance family; thus the\\n -- orph_iface/has_iface tests.\\n\\n deporphs = dep_orphs deps\\n depfinsts = dep_finsts deps\\n\\n orphans | orph_iface = assertPpr (not (imp_sem_mod `elem` deporphs)) (ppr imp_sem_mod <+> ppr deporphs) $\\n imp_sem_mod : deporphs\\n | otherwise = deporphs\\n\\n finsts | has_finsts = assertPpr (not (imp_sem_mod `elem` depfinsts)) (ppr imp_sem_mod <+> ppr depfinsts) $\\n imp_sem_mod : depfinsts\\n | otherwise = depfinsts\\n\\n -- Trusted packages are a lot like orphans.\\n trusted_pkgs | mod_safe\' = dep_trusted_pkgs deps\\n | otherwise = S.empty\\n\\n\\n pkg = moduleUnit (mi_module iface)\\n ipkg = toUnitId pkg\\n\\n -- Does this import mean we now require our own pkg\\n -- to be trusted? See Note [Trust Own Package]\\n ptrust = trust == Sf_Trustworthy || trust_pkg\\n pkg_trust_req\\n | isHomeUnit home_unit pkg = ptrust\\n | otherwise = False\\n\\n dependent_pkgs = if toUnitId pkg `S.member` other_home_units\\n then S.empty\\n else S.singleton (lvl, ipkg)\\n\\n lvl = case imported_by of\\n ImportedByUser imv -> imv_is_level imv\\n ImportedBySystem -> NormalLevel\\n\\n\\n direct_mods = if toUnitId pkg `S.member` other_home_units\\n then mkPlusModDeps (moduleUnitId imp_mod) lvl (GWIB (moduleName imp_mod) want_boot)\\n else emptyInstalledModuleEnv\\n\\n dep_boot_mods_map = mkModDeps (dep_boot_mods deps)\\n\\n\\n boot_mods\\n -- If we are looking for a boot module, it must be HPT\\n | IsBoot <- want_boot = extendInstalledModuleEnv dep_boot_mods_map (toUnitId <$> imp_mod) (GWIB (moduleName imp_mod) IsBoot)\\n -- Now we are importing A properly, so don\'t go looking for\\n -- A.hs-boot\\n | isHomeUnit home_unit pkg = dep_boot_mods_map\\n -- There\'s no boot files to find in external imports\\n | otherwise = emptyInstalledModuleEnv\\n\\n sig_mods =\\n if is_sig\\n then moduleName imp_mod : dep_sig_mods deps\\n else dep_sig_mods deps\\n\\n\\n in ImportAvails {\\n imp_mods = Map.singleton (mi_module iface) [imported_by],\\n imp_orphs = orphans,\\n imp_finsts = finsts,\\n imp_sig_mods = sig_mods,\\n imp_direct_dep_mods = direct_mods,\\n imp_dep_direct_pkgs = dependent_pkgs,\\n imp_boot_mods = boot_mods,\\n\\n -- Add in the imported modules trusted package\\n -- requirements. ONLY do this though if we import the\\n -- module as a safe import.\\n -- See Note [Tracking Trust Transitively]\\n -- and Note [Trust Transitive Property]\\n imp_trust_pkgs = trusted_pkgs,\\n -- Do we require our own pkg to be trusted?\\n -- See Note [Trust Own Package]\\n imp_trust_own_pkg = pkg_trust_req\\n }\\n\\nmkPlusModDeps :: UnitId -> ImportLevel -> ModuleNameWithIsBoot\\n -> InstalledModuleEnv (S.Set ImportLevel, ModuleNameWithIsBoot)\\nmkPlusModDeps uid st elt = extendInstalledModuleEnv emptyInstalledModuleEnv (mkModule uid (gwib_mod elt)) (S.singleton st, elt)\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{importsFromLocalDecls}\\n* *\\n************************************************************************\\n\\nFrom the top-level declarations of this module produce\\n * the lexical environment\\n * the ImportAvails\\ncreated by its bindings.\\n\\nNote [Top-level Names in Template Haskell decl quotes]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSee also: Note [Interactively-bound Ids in GHCi] in GHC.Driver.Env\\n Note [Looking up Exact RdrNames] in GHC.Rename.Env\\n\\nConsider a Template Haskell declaration quotation like this:\\n module M where\\n f x = h [d| f = 3 |]\\nWhen renaming the declarations inside [d| ...|], we treat the\\ntop level binders specially in two ways\\n\\n1. We give them an Internal Name, not (as usual) an External one.\\n This is done by GHC.Rename.Env.newTopSrcBinder.\\n\\n2. We make them *shadow* the outer bindings.\\n See Note [GlobalRdrEnv shadowing]\\n\\n3. We find out whether we are inside a [d| ... |] by testing the TH\\n level. This is a slight hack, because the level field was really\\n meant for the type checker, and here we are not interested in the\\n fields of Brack, hence the error thunks in thRnBrack.\\n-}\\n\\nextendGlobalRdrEnvRn :: [GlobalRdrElt]\\n -> MiniFixityEnv\\n -> RnM (TcGblEnv, TcLclEnv)\\n-- Updates both the GlobalRdrEnv and the FixityEnv\\n-- We return a new TcLclEnv only because we might have to\\n-- delete some bindings from it;\\n-- see Note [Top-level Names in Template Haskell decl quotes]\\n\\nextendGlobalRdrEnvRn new_gres new_fixities\\n = checkNoErrs $ -- See Note [Fail fast on duplicate definitions]\\n do { (gbl_env, lcl_env) <- getEnvs\\n ; level <- getThLevel\\n ; isGHCi <- getIsGHCi\\n ; let rdr_env = tcg_rdr_env gbl_env\\n fix_env = tcg_fix_env gbl_env\\n th_bndrs = getLclEnvThBndrs lcl_env\\n th_lvl = thLevelIndex level\\n\\n -- Delete new_occs from global and local envs\\n -- If we are in a TemplateHaskell decl bracket,\\n -- we are going to shadow them\\n -- See Note [GlobalRdrEnv shadowing]\\n inBracket = isBrackLevel level\\n\\n lcl_env_TH = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_rdr = minusLocalRdrEnv (tcl_rdr lcl_env) new_gres_env }) lcl_env\\n -- See Note [GlobalRdrEnv shadowing]\\n\\n lcl_env2 | inBracket = lcl_env_TH\\n | otherwise = lcl_env\\n\\n -- Deal with shadowing: see Note [GlobalRdrEnv shadowing]\\n want_shadowing = isGHCi || inBracket\\n rdr_env1 | want_shadowing = shadowNames False rdr_env new_gres_env\\n | otherwise = rdr_env\\n\\n lcl_env3 = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_th_bndrs = extendNameEnvList th_bndrs\\n [ ( n, (TopLevel, th_lvl) )\\n | n <- new_names ] }) lcl_env2\\n\\n ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres\\n\\n ; let fix_env\' = foldl\' extend_fix_env fix_env new_gres\\n gbl_env\' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env\' }\\n\\n ; traceRn \\"extendGlobalRdrEnvRn 2\\" (pprGlobalRdrEnv True rdr_env2)\\n ; return (gbl_env\', lcl_env3) }\\n where\\n new_names = map greName new_gres\\n new_gres_env = mkGlobalRdrEnv new_gres\\n\\n -- If there is a fixity decl for the gre, add it to the fixity env\\n extend_fix_env fix_env gre\\n | Just (L _ fi) <- lookupMiniFixityEnv new_fixities name\\n = extendNameEnv fix_env name (FixItem occ fi)\\n | otherwise\\n = fix_env\\n where\\n name = greName gre\\n occ = greOccName gre\\n\\n add_gre :: GlobalRdrEnv -> GlobalRdrElt -> RnM GlobalRdrEnv\\n -- Extend the GlobalRdrEnv with a LocalDef GRE\\n -- If there is already a LocalDef GRE with the same OccName,\\n -- report an error and discard the new GRE\\n -- This establishes INVARIANT 1 of GlobalRdrEnvs\\n add_gre env gre\\n | not (null dups) -- Same OccName defined twice\\n = do { addDupDeclErr (gre :| dups); return env }\\n\\n | otherwise\\n = return (extendGlobalRdrEnv env gre)\\n where\\n -- See Note [Reporting duplicate local declarations]\\n dups = filter isBadDupGRE\\n $ lookupGRE env (LookupOccName (greOccName gre) (RelevantGREsFOS WantBoth))\\n isBadDupGRE old_gre = isLocalGRE old_gre && greClashesWith gre old_gre\\n\\n{- Note [Fail fast on duplicate definitions]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIf there are duplicate bindings for the same thing, we want to fail\\nfast. Having two bindings for the same thing can cause follow-on errors.\\nExample (test T9975a):\\n data Test = Test { x :: Int }\\n pattern Test wat = Test { x = wat }\\nThis defines \'Test\' twice. The second defn has no field-names; and then\\nwe get an error from Test { x=wat }, saying \\"Test has no field \'x\'\\".\\n\\nEasiest thing is to bale out fast on duplicate definitions, which\\nwe do via `checkNoErrs` on `extendGlobalRdrEnvRn`.\\n\\nNote [Reporting duplicate local declarations]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn general, a single module may not define the same OccName multiple times. This\\nis checked in extendGlobalRdrEnvRn: when adding a new locally-defined GRE to the\\nGlobalRdrEnv we report an error if there are already duplicates in the\\nenvironment. This establishes INVARIANT 1 (see comments on GlobalRdrEnv in\\nGHC.Types.Name.Reader), which says that for a given OccName, all the\\nGlobalRdrElts to which it maps must have distinct \'greName\'s.\\n\\nFor example, the following will be rejected:\\n\\n f x = x\\n g x = x\\n f x = x -- Duplicate!\\n\\nUsers are allowed to introduce new GREs with the same OccName as an imported GRE,\\nas disambiguation is possible through the module system, e.g.:\\n\\n module M where\\n import N (f)\\n f x = x\\n g x = M.f x + N.f x\\n\\nIf both GREs are local, the general rule is that two GREs clash if they have\\nthe same OccName, i.e. they share a textual name and live in the same namespace.\\nHowever, there are additional clashes due to record fields:\\n\\n - a new variable clashes with previously defined record fields\\n which define field selectors,\\n\\n - a new record field shadows:\\n\\n - previously defined variables, if it defines a field selector,\\n - previously defined record fields, unless it is a duplicate record field.\\n\\nThis logic is implemented in the function \'GHC.Types.Name.Reader.greClashesWith\'.\\n\\nSee also Note [Skipping ambiguity errors at use sites of local declarations] in\\nGHC.Rename.Utils.\\n-}\\n\\n\\n{- *********************************************************************\\n* *\\n getLocalDeclBindersd@ returns the names for an HsDecl\\n It\'s used for source code.\\n\\n *** See Note [The Naming story] in GHC.Hs.Decls ****\\n* *\\n********************************************************************* -}\\n\\ngetLocalNonValBinders :: MiniFixityEnv -> HsGroup GhcPs\\n -> RnM ((TcGblEnv, TcLclEnv), NameSet)\\n-- Get all the top-level binders bound the group *except*\\n-- for value bindings, which are treated separately\\n-- Specifically we return AvailInfo for\\n-- * type decls (incl constructors and record selectors)\\n-- * class decls (including class ops)\\n-- * associated types\\n-- * foreign imports\\n-- * value signatures (in hs-boot files only)\\n\\ngetLocalNonValBinders fixity_env\\n (HsGroup { hs_valds = binds,\\n hs_tyclds = tycl_decls,\\n hs_fords = foreign_decls })\\n = do { -- Process all type/class decls *except* family instances\\n ; let inst_decls = tycl_decls >>= group_instds\\n ; dup_fields_ok <- xopt_DuplicateRecordFields <$> getDynFlags\\n ; has_sel <- xopt_FieldSelectors <$> getDynFlags\\n ; tc_gres\\n <- concatMapM\\n (new_tc dup_fields_ok has_sel)\\n (tyClGroupTyClDecls tycl_decls)\\n ; traceRn \\"getLocalNonValBinders 1\\" (ppr tc_gres)\\n ; envs <- extendGlobalRdrEnvRn tc_gres fixity_env\\n ; restoreEnvs envs $ do {\\n -- Bring these things into scope first\\n -- See Note [Looking up family names in family instances]\\n\\n -- Process all family instances\\n -- to bring new data constructors into scope\\n ; nti_gress <- mapM (new_assoc dup_fields_ok has_sel) inst_decls\\n\\n -- Finish off with value binders:\\n -- foreign decls and pattern synonyms for an ordinary module\\n -- type sigs in case of a hs-boot file only\\n ; is_boot <- tcIsHsBootOrSig\\n ; let val_bndrs\\n | is_boot = case binds of\\n ValBinds _ val_binds ->\\n -- In a hs-boot file, the value binders come from the\\n -- *signatures*, and there should be no foreign binders\\n [ L (l2l decl_loc) (unLoc n)\\n | L decl_loc (TypeSig _ _ ns _) <- (val_sigs val_binds), n <- ns]\\n _ -> panic \\"Non-ValBinds in hs-boot group\\"\\n | otherwise = for_hs_bndrs\\n ; val_gres <- mapM new_simple val_bndrs\\n\\n ; let avails = concat nti_gress ++ val_gres\\n new_bndrs = gresToNameSet avails `unionNameSet`\\n gresToNameSet tc_gres\\n ; traceRn \\"getLocalNonValBinders 2\\" (ppr avails)\\n ; envs <- extendGlobalRdrEnvRn avails fixity_env\\n ; return (envs, new_bndrs) } }\\n where\\n for_hs_bndrs :: [LocatedN RdrName]\\n for_hs_bndrs = hsForeignDeclsBinders foreign_decls\\n\\n -- the SrcSpan attached to the input should be the span of the\\n -- declaration, not just the name\\n new_simple :: LocatedN RdrName -> RnM GlobalRdrElt\\n new_simple rdr_name = do { nm <- newTopSrcBinder rdr_name\\n ; return (mkLocalVanillaGRE NoParent nm) }\\n\\n new_tc :: DuplicateRecordFields -> FieldSelectors -> LTyClDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_tc dup_fields_ok has_sel tc_decl -- NOT for type/data instances\\n = do { let TyDeclBinders (main_bndr, tc_flav) at_bndrs sig_bndrs\\n (LConsWithFields cons_with_flds flds) = hsLTyClDeclBinders tc_decl\\n ; tycon_name <- newTopSrcBinder $ la2la main_bndr\\n ; at_names <- mapM (newTopSrcBinder . la2la . fst) at_bndrs\\n ; sig_names <- mapM (newTopSrcBinder . la2la) sig_bndrs\\n ; con_names_with_flds <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst con_names_with_flds) flds\\n ; mapM_ (add_dup_fld_errs flds\') con_names_with_flds\\n ; let tc_gre = mkLocalTyConGRE (fmap (const tycon_name) tc_flav) tycon_name\\n fld_env = mk_fld_env con_names_with_flds flds\'\\n at_gres = zipWith (\\\\ (_, at_flav) at_nm -> mkLocalTyConGRE (fmap (const tycon_name) at_flav) at_nm)\\n at_bndrs at_names\\n sig_gres = map (mkLocalVanillaGRE (ParentIs tycon_name)) sig_names\\n con_gres = map (mkLocalConLikeGRE (ParentIs tycon_name)) fld_env\\n fld_gres = mkLocalFieldGREs (ParentIs tycon_name) fld_env\\n sub_gres = at_gres ++ sig_gres ++ con_gres ++ fld_gres\\n ; traceRn \\"getLocalNonValBinders new_tc\\" $\\n vcat [ text \\"tycon:\\" <+> ppr tycon_name\\n , text \\"tc_gre:\\" <+> ppr tc_gre\\n , text \\"sub_gres:\\" <+> ppr sub_gres ]\\n ; return $ tc_gre : sub_gres }\\n\\n -- Calculate the record field information, which feeds into the GlobalRdrElts\\n -- for DataCons and their fields. It\'s convenient to do this here where\\n -- we are working with a single datatype definition.\\n --\\n -- The information we needed was all set up for us:\\n -- see Note [Collecting record fields in data declarations] in GHC.Hs.Utils.\\n mk_fld_env :: [(Name, Either VisArity [Located Int])] -> IntMap FieldLabel\\n -> [(ConLikeName, ConInfo)]\\n mk_fld_env names flds =\\n [ (DataConName con, ConInfo (ConIsData (map fst names)) fld_info)\\n | (con, con_fl_indxs) <- names\\n , let fld_info = case fmap (map ((flds IntMap.!) . unLoc)) con_fl_indxs of\\n Left 0 -> ConIsNullary\\n Left arity -> ConHasPositionalArgs arity\\n Right [] -> ConIsNullary\\n Right (fld:flds) -> ConHasRecordFields $ fld NE.:| flds ]\\n\\n new_assoc :: DuplicateRecordFields -> FieldSelectors -> LInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_assoc _ _ (L _ (TyFamInstD {})) = return []\\n -- type instances don\'t bind new names\\n\\n new_assoc dup_fields_ok has_sel (L _ (DataFamInstD _ d))\\n = new_di dup_fields_ok has_sel Nothing d\\n new_assoc dup_fields_ok has_sel\\n (L _ (ClsInstD _ (ClsInstDecl { cid_poly_ty = inst_ty\\n , cid_decls = decls })))\\n = do -- First, attempt to grab the name of the class from the instance.\\n -- This step could fail if the instance is not headed by a class,\\n -- such as in the following examples:\\n --\\n -- (1) The class is headed by a bang pattern, such as in\\n -- `instance !Show Int` (#3811c)\\n -- (2) The class is headed by a type variable, such as in\\n -- `instance c` (#16385)\\n --\\n -- If looking up the class name fails, then mb_cls_gre will\\n -- be Nothing.\\n mb_cls_gre <- runMaybeT $ do\\n -- See (1) above\\n L loc cls_rdr <- MaybeT $ pure $ getLHsInstDeclClass_maybe inst_ty\\n -- See (2) above\\n MaybeT $ setSrcSpan (locA loc) $ lookupGlobalOccRn_maybe SameNameSpace cls_rdr\\n -- Assuming the previous step succeeded, process any associated data\\n -- family instances. If the previous step failed, bail out.\\n case mb_cls_gre of\\n Nothing\\n -> pure []\\n Just cls_gre\\n -> let cls_nm = greName cls_gre\\n in concatMapM (new_di dup_fields_ok has_sel (Just cls_nm) . unLoc) (data_fam_insts decls)\\n\\n data_fam_insts decls = concatMap get decls\\n where\\n get (L l (InstD _ (DataFamInstD { dfid_inst = d}))) = [L l d]\\n get _ = []\\n\\n new_di :: DuplicateRecordFields -> FieldSelectors\\n -> Maybe Name -- class name\\n -> DataFamInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_di dup_fields_ok has_sel mb_cls dfid@(DataFamInstDecl { dfid_eqn = ti_decl })\\n = do { main_name <- unLoc <$> lookupFamInstName mb_cls (feqn_tycon ti_decl)\\n ; let LConsWithFields cons_with_flds flds = hsDataFamInstBinders dfid\\n ; sub_names <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst sub_names) flds\\n ; mapM_ (add_dup_fld_errs flds\') sub_names\\n ; let fld_env = mk_fld_env sub_names flds\'\\n con_gres = map (mkLocalConLikeGRE (ParentIs main_name)) fld_env\\n field_gres = mkLocalFieldGREs (ParentIs main_name) fld_env\\n -- NB: the data family name is not bound here,\\n -- so we don\'t return a GlobalRdrElt for it here!\\n ; return $ con_gres ++ field_gres }\\n\\n -- Add errors if a constructor has a duplicate record field.\\n add_dup_fld_errs :: IntMap FieldLabel\\n -> (Name, Either VisArity [Located Int])\\n -> IOEnv (Env TcGblEnv TcLclEnv) ()\\n add_dup_fld_errs all_flds (con, con_flds_or_arity)\\n | Right con_flds <- con_flds_or_arity\\n , let (_, dups) = removeDups (comparing unLoc) con_flds\\n = for_ dups $ \\\\ dup_flds ->\\n -- Report the error at the location of the second occurrence\\n -- of the duplicate field.\\n let loc =\\n case dup_flds of\\n _ :| ( L loc _ : _) -> loc\\n L loc _ :| _ -> loc\\n dup_rdrs = fmap (nameRdrName . flSelector . (all_flds IntMap.!) . unLoc) dup_flds\\n in addErrAt loc $ TcRnDuplicateFieldName (RecordFieldDecl con) dup_rdrs\\n | otherwise\\n = return ()\\n\\nnewRecordFieldLabel :: DuplicateRecordFields -> FieldSelectors -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel\\nnewRecordFieldLabel _ _ [] _ = error \\"newRecordFieldLabel: datatype has no constructors!\\"\\nnewRecordFieldLabel dup_fields_ok has_sel (dc:_) (L loc (FieldOcc _ (L _ fld)))\\n = do { selName <- newTopSrcBinder $ L (l2l loc) $ field\\n ; return $ FieldLabel { flHasDuplicateRecordFields = dup_fields_ok\\n , flHasFieldSelector = has_sel\\n , flSelector = selName } }\\n where\\n fld_occ = rdrNameOcc fld\\n dc_fs = occNameFS $ nameOccName dc\\n field\\n -- Use an Exact RdrName as-is, to preserve the bindings\\n -- of an already renamer-resolved field and its use\\n -- sites. This is needed to correctly support record\\n -- selectors in Template Haskell. See Note [Binders in\\n -- Template Haskell] in \\"GHC.ThToHs\\" and Note [Looking up\\n -- Exact RdrNames] in \\"GHC.Rename.Env\\".\\n | isExact fld\\n = assertPpr (fieldOcc_maybe fld_occ == Just dc_fs)\\n (vcat [ text \\"newRecordFieldLabel: incorrect namespace for exact Name\\" <+> quotes (ppr fld)\\n , text \\"expected namespace:\\" <+> pprNameSpace (fieldName dc_fs)\\n , text \\" actual namespace:\\" <+> pprNameSpace (occNameSpace fld_occ) ])\\n fld\\n\\n -- Field names produced by the parser are namespaced with VarName.\\n -- Here we namespace them according to the first constructor.\\n -- See Note [Record field namespacing] in GHC.Types.Name.Occurrence.\\n | otherwise\\n = mkRdrUnqual $ varToRecFieldOcc dc_fs fld_occ\\n\\n{-\\nNote [Looking up family names in family instances]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider\\n\\n module M where\\n type family T a :: *\\n type instance M.T Int = Bool\\n\\nWe might think that we can simply use \'lookupOccRn\' when processing the type\\ninstance to look up \'M.T\'. Alas, we can\'t! The type family declaration is in\\nthe *same* HsGroup as the type instance declaration. Hence, as we are\\ncurrently collecting the binders declared in that HsGroup, these binders will\\nnot have been added to the global environment yet.\\n\\nSolution is simple: process the type family declarations first, extend\\nthe environment, and then process the type instances.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Filtering imports}\\n* *\\n************************************************************************\\n\\n@filterImports@ takes the @ExportEnv@ telling what the imported module makes\\navailable, and filters it through the import spec (if any).\\n\\nNote [Dealing with imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nFor import M( ies ), we take each AvailInfo from the mi_exports of M, and make\\n\\n imp_occ_env :: OccEnv (NameEnv ImpOccItem)\\n\\nThis map contains one entry for each OccName that M exports, mapping each OccName\\nto the following information:\\n\\n 1. the GlobalRdrElt corresponding to the OccName,\\n 2. whether this GlobalRdrElt was the parent in the AvailInfo we found\\n the OccName in.\\n 3. the GlobalRdrElts that were bundled together in the AvailInfo we found\\n this OccName in (not including the parent),\\n\\nWe need (2) and (3) during the construction of the OccEnv because of associated\\ntypes and bundled pattern synonyms, respectively.\\n(3) is explained in Note [Importing PatternSynonyms].\\n\\nTo explain (2), consider for example:\\n\\n module M where\\n class C a where { data T a }\\n instance C Int where { data T Int = T1 | T2 }\\n instance C Bool where { data T Int = T3 }\\n\\nHere, M\'s exports avails are (recalling the AvailTC invariant from GHC.Types.Avail)\\n\\n C(C,T), T(T,T1,T2,T3)\\n\\nNotice that T appears *twice*, once as a child and once as a parent. From\\nthese two exports, respectively, during construction of the imp_occ_env, we begin\\nby associating the following two elements with the key T:\\n\\n T -> ImpOccItem { imp_item = gre1, imp_bundled = [C,T] , imp_is_parent = False }\\n T -> ImpOccItem { imp_item = gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nwhere `gre1`, `gre2` are two GlobalRdrElts with greName T.\\nWe combine these (in function \'combine\' in \'mkImportOccEnv\') by discarding the\\nnon-parent item, thusly:\\n\\n T -> IE_ITem { imp_item = gre1 `plusGRE` gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nNote the `plusGRE`: this ensures we don\'t drop parent information;\\nsee Note [Preserve parent information when combining import OccEnvs].\\n\\nSo the overall imp_occ_env is:\\n\\n C -> ImpOccItem { imp_item = C, imp_bundled = [T ], imp_is_parent = True }\\n T -> ImpOccItem { imp_item = T , imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n T1 -> ImpOccItem { imp_item = T1, imp_bundled = [T1,T2,T3], imp_is_parent = False }\\n -- similarly for T2, T3\\n\\nNote that the imp_occ_env will have entries for data constructors too,\\nalthough we never look up data constructors.\\n\\nNote [Importing PatternSynonyms]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nAs described in Note [Dealing with imports], associated types can lead to the\\nsame Name appearing twice, both as a child and once as a parent, when\\nconstructing the imp_occ_env. The same thing can happen with pattern synonyms\\nif they are exported bundled with a type.\\n\\nA simplified example, based on #11959:\\n\\n {-# LANGUAGE PatternSynonyms #-}\\n module M (T(P), pattern P) where -- Duplicate export warning, but allowed\\n data T = MkT\\n pattern P = MkT\\n\\nHere we have T(P) and P in export_avails, and respectively construct both\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n P -> ImpOccItem { imp_item = P, imp_bundled = [] , imp_is_parent = False }\\n\\nWe combine these by dropping the one with no siblings, leaving us with:\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n\\nThat is, we simply discard the non-bundled Avail.\\n\\nNote [Importing DuplicateRecordFields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn filterImports, another complicating factor is DuplicateRecordFields.\\nSuppose we have:\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (S(foo), T(foo)) where\\n data S = MkS { foo :: Int }\\n data T = MkT { foo :: Int }\\n\\n module N where\\n import M (foo) -- this is allowed (A)\\n import M (S(foo)) -- this is allowed (B)\\n\\nHere M exports \'foo\' at two different OccNames, with different namespaces for\\nthe two construtors MkS and MkT. Then, when we look up \'foo\' in lookup_names\\nfor case (A), we have a variable foo but must look in all the record field\\nnamespaces to find the two fields (and hence two different Avails).\\nWhereas in case (B) we reach the lookup_ie case for IEThingWith,\\nwhich looks up \'S\' and then finds the unique \'foo\' amongst its children.\\n\\nSee T16745 for a test of this.\\n\\nNote [Preserve parent information when combining import OccEnvs]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen discarding one ImpOccItem in favour of another, as described in\\nNote [Dealing with imports], we must make sure to combine the GREs so that\\nwe don\'t lose information.\\n\\nConsider for example #24084:\\n\\n module M1 where { class C a where { type T a } }\\n module M2 ( module M1 ) where { import M1 }\\n module M3 where { import M2 ( C, T ); instance C () where T () = () }\\n\\nWhen processing the import list of `M3`, we will have two `Avail`s attached\\nto `T`, namely `C(C, T)` and `T(T)`. We combine them in the `combine` function\\nof `mkImportOccEnv`; as described in Note [Dealing with imports] we discard\\n`C(C, T)` in favour of `T(T)`. However, in doing so, we **must not**\\ndiscard the information want that `C` is the parent of `T`. Indeed,\\nlosing track of this information can cause errors when importing,\\nas we could get an error of the form\\n\\n \\u2018T\\u2019 is not a (visible) associated type of class \\u2018C\\u2019\\n\\nThis explains why we use `plusGRE` when combining the two ImpOccItems, even\\nthough we are discarding one in favour of the other.\\n-}\\n\\n-- | All the \'GlobalRdrElt\'s associated with an \'AvailInfo\'.\\ngresFromAvail :: HasDebugCallStack\\n => HscEnv -> Maybe ImportSpec -> AvailInfo -> [GlobalRdrElt]\\ngresFromAvail hsc_env prov avail =\\n [ mk_gre nm info\\n | nm <- availNames avail\\n , let info = lookupGREInfo hsc_env nm ]\\n where\\n\\n mk_gre n info\\n = case prov of\\n -- Nothing => bound locally\\n -- Just is => imported from \'is\'\\n Nothing -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = True, gre_imp = emptyBag\\n , gre_info = info }\\n Just is -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = False, gre_imp = unitBag is\\n , gre_info = info }\\n\\n-- | All the \'GlobalRdrElt\'s associated with a collection of \'AvailInfo\'s.\\ngresFromAvails :: HscEnv -> Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]\\ngresFromAvails hsc_env prov = concatMap (gresFromAvail hsc_env prov)\\n\\nimportsFromIface :: HscEnv -> ModIface -> ImpDeclSpec -> Maybe NameSet -> GlobalRdrEnv\\nimportsFromIface hsc_env iface decl_spec hidden = mkGlobalRdrEnv $ case hidden of\\n Nothing -> all_gres\\n Just hidden_names -> filter (not . (`elemNameSet` hidden_names) . greName) all_gres\\n where\\n all_gres = gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\nrnNamespaceSpecifier :: NamespaceSpecifier GhcPs -> NamespaceSpecifier GhcRn\\nrnNamespaceSpecifier (NoNamespaceSpecifier _) = NoNamespaceSpecifier noExtField\\nrnNamespaceSpecifier (TypeNamespaceSpecifier x) = TypeNamespaceSpecifier x\\nrnNamespaceSpecifier (DataNamespaceSpecifier x) = DataNamespaceSpecifier x\\n\\nfilterImports\\n :: HasDebugCallStack\\n => HscEnv\\n -> ModIface\\n -> ImpDeclSpec\\n -- ^ Import spec\\n -> Maybe (ImportListInterpretation, [LIE GhcPs])\\n -- ^ Whether this is a \\"hiding\\" import list\\n -> RnM (Maybe (ImportListInterpretation, [LIE GhcRn]), -- Import spec w/ Names\\n ImpUserList, -- same, but designed for storage in interfaces\\n GlobalRdrEnv) -- Same again, but in GRE form\\nfilterImports hsc_env iface decl_spec Nothing\\n = return (Nothing, ImpUserAll, importsFromIface hsc_env iface decl_spec Nothing)\\nfilterImports hsc_env iface decl_spec (Just (want_hiding, import_items))\\n = do -- check for errors, convert RdrNames to Names\\n items1 <- mapM lookup_lie import_items\\n\\n let items2 :: [(LIE GhcRn, [GlobalRdrElt])]\\n items2 = concat items1\\n -- NB we may have duplicates, and several items\\n -- for the same parent; e.g N(x) and N(y)\\n\\n (gres, imp_user_list) = case want_hiding of\\n Exactly ->\\n let gres = concatMap (gresFromIE decl_spec) items2\\n gre_env = mkGlobalRdrEnv gres\\n implicit_parents = mkNameSet $ mapMaybe parentOfImplicitlyImportedGRE gres\\n in (gre_env, ImpUserExplicit (gresToAvailInfo $ globalRdrEnvElts $ gre_env) implicit_parents)\\n EverythingBut ->\\n let hidden_names = mkNameSet $ concatMap (map greName . snd) items2\\n in (importsFromIface hsc_env iface decl_spec (Just hidden_names), ImpUserEverythingBut hidden_names)\\n\\n return (Just (want_hiding, map fst items2), imp_user_list, gres)\\n where\\n import_mod = mi_module iface\\n all_avails = mi_exports iface\\n imp_occ_env = mkImportOccEnv hsc_env decl_spec all_avails\\n\\n -- Look up a parent (type constructor, class or data constructor)\\n -- in an import.\\n lookup_parent :: IE GhcPs -> RdrName -> IELookupM ImpOccItem\\n lookup_parent ie rdr =\\n assertPpr (not $ isVarNameSpace ns)\\n (vcat [ text \\"filterImports lookup_parent: unexpected variable\\"\\n , text \\"rdr:\\" <+> ppr rdr\\n , text \\"namespace:\\" <+> pprNameSpace ns ]) $\\n do { xs <- lookup_names ie rdr\\n ; case xs of\\n cax :| [] -> return cax\\n _ -> pprPanic \\"filter_imports lookup_parent ambiguous\\" $\\n vcat [ text \\"rdr:\\" <+> ppr rdr\\n , text \\"lookups:\\" <+> ppr (fmap imp_item xs) ] }\\n -- Looking up non-variables is always unambiguous,\\n -- as there can be at most one corresponding item\\n -- in the imp_occ_env.\\n -- See item (1) of Note [Exporting duplicate declarations]\\n -- in GHC.Tc.Gen.Export.\\n where\\n occ = rdrNameOcc rdr\\n ns = occNameSpace occ\\n\\n -- Look up a RdrName used in an import, returning multiple values if there\\n -- are several fields with the same name exposed by the module\\n lookup_names :: IE GhcPs -> RdrName -> IELookupM (NonEmpty ImpOccItem)\\n lookup_names ie rdr\\n | isQual rdr\\n = failLookupWith (QualImportError rdr)\\n | otherwise\\n = case lookups of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n item:items -> return $ item :| items\\n where\\n lookups = concatMap nonDetNameEnvElts\\n $ lookupImpOccEnv (RelevantGREsFOS WantNormal) imp_occ_env (rdrNameOcc rdr)\\n\\n lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, [GlobalRdrElt])]\\n lookup_lie (L loc ieRdr)\\n = setSrcSpanA loc $\\n do (stuff, warns) <- run_lookup ([],[]) (lookup_ie ieRdr)\\n mapM_ (addTcRnDiagnostic <=< warning_msg) warns\\n return [ (L loc ie, gres) | (ie,gres) <- stuff ]\\n where\\n\\n -- Warn when importing T(..) and no children are brought in scope\\n warning_msg (DodgyImport reason) =\\n pure (TcRnDodgyImports reason)\\n warning_msg MissingImportList =\\n pure (TcRnMissingImportList ieRdr)\\n warning_msg (BadImportW ie sub) = do\\n -- \'BadImportW\' is only constructed below in \'bad_import_w\', in\\n -- the \'EverythingBut\' case, so here we assume a \'hiding\' clause.\\n (reason :| _) <- badImportItemErr iface decl_spec ie sub all_avails\\n pure (TcRnDodgyImports (DodgyImportsHiding reason))\\n warning_msg (DeprecatedExport n w) =\\n pure $ TcRnPragmaWarning\\n PragmaWarningExport\\n { pwarn_occname = occName n\\n , pwarn_impmod = moduleName import_mod }\\n w\\n\\n run_lookup :: a -> IELookupM a -> TcRn a\\n run_lookup def m = case m of\\n Failed err -> do\\n msgs <- lookup_err_msgs err\\n forM_ msgs $ \\\\msg -> addErr (TcRnImportLookup msg)\\n return def\\n Succeeded a -> return a\\n\\n lookup_err_msgs err = case err of\\n BadImport ie sub -> badImportItemErr iface decl_spec ie sub all_avails\\n IllegalImport -> pure $ NE.singleton ImportLookupIllegal\\n QualImportError rdr -> pure $ NE.singleton (ImportLookupQualified rdr)\\n\\n -- For each import item, we convert its RdrNames to Names,\\n -- and at the same time compute all the GlobalRdrElt corresponding\\n -- to what is actually imported by this item.\\n -- Returns Nothing on error.\\n --\\n -- Returns a list because, with DuplicateRecordFields, a naked\\n -- import/export of a record field can correspond to multiple\\n -- different GlobalRdrElts. See Note [Importing DuplicateRecordFields].\\n lookup_ie :: IE GhcPs\\n -> IELookupM ([(IE GhcRn, [GlobalRdrElt])], [IELookupWarning])\\n lookup_ie ie = handle_bad_import $\\n case ie of\\n IEVar _ (L l n) _ -> do\\n -- See Note [Importing DuplicateRecordFields]\\n xs <- lookup_names ie (ieWrappedName n)\\n let gres = map imp_item $ NE.toList xs\\n export_depr_warns\\n | want_hiding == Exactly\\n = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ( [ (IEVar Nothing (L l (replaceWrappedName n name)) noDocstring, [gre])\\n | gre <- gres\\n , let name = greName gre ]\\n , export_depr_warns )\\n\\n IEThingAll x ns_spec (L l tc) _ -> do\\n ImpOccItem { imp_item = gre\\n , imp_bundled = bundled_gres\\n , imp_is_parent = is_par\\n }\\n <- lookup_parent ie $ ieWrappedName tc\\n let name = greName gre\\n\\n child_gres :: [GlobalRdrElt]\\n child_gres\\n | is_par = filterByNamespaceSpecifierGREs ns_spec bundled_gres\\n | otherwise = []\\n\\n imp_list_warn\\n\\n | null child_gres\\n -- e.g. f(..) or T(..) where T is a type synonym\\n = [DodgyImport (DodgyImportsEmptyParent ie ns_spec gre)]\\n\\n -- e.g. import M( T(..) )\\n | not (is_qual decl_spec)\\n = [MissingImportList]\\n\\n | otherwise\\n = []\\n\\n renamed_ie = IEThingAll (x { ieta_warning = Nothing })\\n (rnNamespaceSpecifier ns_spec)\\n (L l (replaceWrappedName tc name))\\n noDocstring\\n export_depr_warn\\n | want_hiding == Exactly\\n = maybeToList $ mk_depr_export_warning gre\\n -- We don\'t want to warn about the children as they\\n -- are not explicitly mentioned; the warning will\\n -- be emitted later on if they are used\\n | otherwise = []\\n\\n return ( [(renamed_ie, gre:child_gres)]\\n , imp_list_warn ++ export_depr_warn)\\n\\n\\n IEThingAbs _ (L l tc\') _\\n | want_hiding == EverythingBut -- hiding ( C )\\n -- Here the \'C\' can be a data constructor\\n -- *or* a type/class, or even both\\n -> let tc = ieWrappedName tc\'\\n tc_name = lookup_parent ie tc\\n dc_name = lookup_parent ie (setRdrNameSpace tc srcDataName)\\n in\\n case catIELookupM [ tc_name, dc_name ] of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n names -> return ( [mkIEThingAbs tc\' l (imp_item name) | name <- names], [])\\n | otherwise\\n -> do ImpOccItem { imp_item = gre } <- lookup_parent ie (ieWrappedName tc\')\\n return ( [mkIEThingAbs tc\' l gre]\\n , maybeToList $ mk_depr_export_warning gre)\\n\\n IEThingWith (deprecation, ann) ltc@(L l rdr_tc) wc rdr_ns _ -> do\\n ImpOccItem { imp_item = gre, imp_bundled = subnames }\\n <- lookup_parent (IEThingAbs Nothing ltc noDocstring) (ieWrappedName rdr_tc)\\n let name = greName gre\\n\\n -- Look up the children in the sub-names of the parent\\n -- See Note [Importing DuplicateRecordFields]\\n let (children_errs, childnames) = lookupChildren subnames rdr_ns\\n\\n bad_import_warns <-\\n if null children_errs then return [] else\\n let items = map lce_wrapped_name children_errs\\n ie = IEThingWith (deprecation, ann) ltc wc items noDocstring\\n -- We are trying to import T( a,b,c,d ), and failed\\n -- to find \'b\' and \'d\'. So we make up an import item\\n -- to report as failing, namely T( b, d ).\\n -- c.f. #15413\\n subordinate_err = mkSubordinateError gre children_errs\\n in bad_import_w ie subordinate_err\\n\\n let name\' = replaceWrappedName rdr_tc name\\n childnames\' = map (to_ie_post_rn . fmap greName) childnames\\n gres = gre : map unLoc childnames\\n export_depr_warns\\n | want_hiding == Exactly = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ([ (IEThingWith (Nothing, ann) (L l name\') wc childnames\' noDocstring\\n ,gres)]\\n , bad_import_warns ++ export_depr_warns)\\n\\n IEWholeNamespace x ns_spec -> do\\n let mod_name = moduleName import_mod\\n names = map greName gres\\n renamed_ie = IEWholeNamespace x { iewn_warning = Nothing\\n , iewn_names = names }\\n (rnNamespaceSpecifier ns_spec)\\n gres = filterByNamespaceSpecifierGREs ns_spec $\\n gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n dodgy_warn\\n | null gres = [DodgyImport (DodgyImportsWildcard mod_name ns_spec)]\\n | otherwise = []\\n return ([(renamed_ie, gres)],\\n dodgy_warn)\\n\\n _other -> failLookupWith IllegalImport\\n -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed...\\n -- all of those constitute errors.\\n\\n where\\n mkIEThingAbs tc l gre\\n = (IEThingAbs Nothing (L l (replaceWrappedName tc n)) noDocstring, [gre])\\n where n = greName gre\\n\\n -- N.B. imports never have docstrings\\n noDocstring = Nothing\\n\\n handle_bad_import m = catchIELookup m $ \\\\case\\n BadImport ie sub -> do\\n ws <- bad_import_w ie sub\\n return ([], ws)\\n err -> failLookupWith err\\n\\n bad_import_w :: IE GhcPs -> IsSubordinateError -> IELookupM [IELookupWarning]\\n bad_import_w ie sub\\n | want_hiding == EverythingBut = return [BadImportW ie sub]\\n | otherwise = failLookupWith (BadImport ie sub)\\n\\n mk_depr_export_warning gre\\n = DeprecatedExport name <$> mi_export_warn_fn iface name\\n where\\n name = greName gre\\n\\n-- | Assuming a subordinate item could not be found, do another lookup for a\\n-- more specific error message.\\nmkBadExportSubordinate :: [GlobalRdrElt] -> LIEWrappedName GhcPs -> BadExportSubordinate\\nmkBadExportSubordinate child_gres n =\\n case lookupChildren child_gres [n] of\\n (LookupChildNonType {lce_nontype_item = g} : _, _) -> BadExportSubordinateNonType g\\n (LookupChildNonData {lce_nondata_item = g} : _, _) -> BadExportSubordinateNonData g\\n _ -> BadExportSubordinateNotFound n\\n\\ntype IELookupM = MaybeErr IELookupError\\n\\ndata IELookupWarning\\n = BadImportW (IE GhcPs) IsSubordinateError\\n | MissingImportList\\n | DodgyImport DodgyImportsReason\\n | DeprecatedExport Name (WarningTxt GhcRn)\\n\\n-- | Is this import/export item a subordinate or not?\\ndata IsSubordinateError\\n = IsSubordinateError { subordinate_err_parent :: !GlobalRdrElt\\n , subordinate_err_unavailable :: [FastString]\\n , subordinate_err_nontype :: [GlobalRdrElt]\\n , subordinate_err_nondata :: [GlobalRdrElt] }\\n | IsNotSubordinate\\n\\nmkSubordinateError :: GlobalRdrElt -> [LookupChildError] -> IsSubordinateError\\nmkSubordinateError gre children_errs = foldr add init_acc children_errs\\n where\\n init_acc :: IsSubordinateError\\n init_acc = IsSubordinateError gre [] [] []\\n\\n add :: LookupChildError -> IsSubordinateError -> IsSubordinateError\\n add children_err sub@IsSubordinateError{} =\\n case children_err of\\n LookupChildNonType{lce_nontype_item = g} ->\\n sub { subordinate_err_nontype = g : subordinate_err_nontype sub }\\n LookupChildNonData{lce_nondata_item = g} ->\\n sub { subordinate_err_nondata = g : subordinate_err_nondata sub }\\n LookupChildNotFound (L _ wname) ->\\n let fs = (occNameFS . rdrNameOcc . ieWrappedName) wname\\n in sub { subordinate_err_unavailable = fs : subordinate_err_unavailable sub }\\n add _ IsNotSubordinate = panic \\"mkSubordinateError: IsNotSubordinate\\"\\n\\ndata IELookupError\\n = QualImportError RdrName\\n | BadImport (IE GhcPs) IsSubordinateError\\n | IllegalImport\\n\\nfailLookupWith :: IELookupError -> IELookupM a\\nfailLookupWith err = Failed err\\n\\ncatchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a\\ncatchIELookup m h = case m of\\n Succeeded r -> return r\\n Failed err -> h err\\n\\ncatIELookupM :: [IELookupM a] -> [a]\\ncatIELookupM ms = [ a | Succeeded a <- ms ]\\n\\n-- | Information associated to an \'AvailInfo\' used in constructing\\n-- an \'OccEnv\' corresponding to imports.\\n--\\n-- See Note [Dealing with imports].\\ndata ImpOccItem\\n = ImpOccItem\\n { imp_item :: GlobalRdrElt\\n -- ^ The import item\\n , imp_bundled :: [GlobalRdrElt]\\n -- ^ Items bundled in the Avail this import item came from,\\n -- not including the import item itself if it is a parent.\\n , imp_is_parent :: Bool\\n -- ^ Is the import item a parent? See Note [Dealing with imports].\\n }\\n\\ninstance Outputable ImpOccItem where\\n ppr (ImpOccItem { imp_item = item, imp_bundled = bundled, imp_is_parent = is_par })\\n = braces $ hsep\\n [ text \\"ImpOccItem\\"\\n , if is_par then text \\"[is_par]\\" else empty\\n , ppr (greName item) <+> ppr (greParent item)\\n , braces $ text \\"bundled:\\" <+> ppr (map greName bundled) ]\\n\\n-- | Make an \'OccEnv\' of all the imports.\\n--\\n-- Complicated by the fact that associated data types and pattern synonyms\\n-- can appear twice. See Note [Dealing with imports].\\nmkImportOccEnv :: HscEnv -> ImpDeclSpec -> [IfaceExport] -> OccEnv (NameEnv ImpOccItem)\\nmkImportOccEnv hsc_env decl_spec all_avails =\\n mkOccEnv_C (plusNameEnv_C combine)\\n [ (occ, mkNameEnv [(nm, item)])\\n | avail <- all_avails\\n , let gres = gresFromAvail hsc_env (Just hiding_spec) avail\\n , gre <- gres\\n , let nm = greName gre\\n occ = greOccName gre\\n (is_parent, bundled) = case avail of\\n AvailTC c _\\n | c == nm -- (Recall the AvailTC invariant from GHC.Types.AvailInfo)\\n -> ( True, drop 1 gres ) -- \\"drop 1\\": don\'t include the parent itself.\\n | otherwise\\n -> ( False, gres )\\n _ -> ( False, [] )\\n item = ImpOccItem\\n { imp_item = gre\\n , imp_bundled = bundled\\n , imp_is_parent = is_parent }\\n ]\\n where\\n\\n hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\n -- See Note [Dealing with imports]\\n -- \'combine\' may be called for associated data types which appear\\n -- twice in the all_avails. In the example, we have two Avails for T,\\n -- namely T(T,T1,T2,T3) and C(C,T), and we combine them by dropping the\\n -- latter, in which T is not the parent.\\n combine :: ImpOccItem -> ImpOccItem -> ImpOccItem\\n combine item1@(ImpOccItem { imp_item = gre1, imp_is_parent = is_parent1 })\\n item2@(ImpOccItem { imp_item = gre2, imp_is_parent = is_parent2 })\\n | is_parent1 || is_parent2\\n , not (isRecFldGRE gre1 || isRecFldGRE gre2) -- NB: does not force GREInfo.\\n , let name1 = greName gre1\\n name2 = greName gre2\\n gre = gre1 `plusGRE` gre2\\n -- See Note [Preserve parent information when combining import OccEnvs]\\n = assertPpr (name1 == name2)\\n (ppr name1 <+> ppr name2) $\\n if is_parent1\\n then item1 { imp_item = gre }\\n else item2 { imp_item = gre }\\n -- Discard C(C,T) in favour of T(T, T1, T2, T3).\\n\\n -- \'combine\' may also be called for pattern synonyms which appear both\\n -- unassociated and associated (see Note [Importing PatternSynonyms]).\\n combine item1@(ImpOccItem { imp_item = c1, imp_bundled = kids1 })\\n item2@(ImpOccItem { imp_item = c2, imp_bundled = kids2 })\\n = assertPpr (greName c1 == greName c2\\n && (not (null kids1 && null kids2)))\\n (ppr c1 <+> ppr c2 <+> ppr kids1 <+> ppr kids2) $\\n if null kids1\\n then item2\\n else item1\\n -- Discard standalone pattern P in favour of T(P).\\n\\n-- | Essentially like @lookupGRE env (LookupOccName occ which_gres)@,\\n-- but working with \'ImpOccItem\'s instead of \'GlobalRdrElt\'s.\\nlookupImpOccEnv :: WhichGREs GREInfo\\n -> OccEnv (NameEnv ImpOccItem) -> OccName -> [NameEnv ImpOccItem]\\nlookupImpOccEnv which_gres env occ =\\n mapMaybe relevant_items $ lookupOccEnv_AllNameSpaces env occ\\n where\\n is_relevant :: ImpOccItem -> Bool\\n is_relevant (ImpOccItem { imp_item = gre }) =\\n greIsRelevant which_gres (occNameSpace occ) gre\\n relevant_items :: NameEnv ImpOccItem -> Maybe (NameEnv ImpOccItem)\\n relevant_items nms\\n | let nms\' = filterNameEnv is_relevant nms\\n = if isEmptyNameEnv nms\'\\n then Nothing\\n else Just nms\'\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{Import/Export Utils}\\n* *\\n************************************************************************\\n-}\\n\\n-- | Given an import\\\\/export spec, appropriately set the @gre_imp@ field\\n-- for the \'GlobalRdrElt\'s.\\ngresFromIE :: ImpDeclSpec -> (LIE GhcRn, [GlobalRdrElt]) -> [GlobalRdrElt]\\ngresFromIE decl_spec (L loc ie, gres)\\n = map set_gre_imp gres\\n where\\n is_explicit = case ie of\\n IEThingAll _ _ name _ -> \\\\n -> n == lieWrappedName name\\n IEWholeNamespace _ _ -> \\\\_ -> False\\n _ -> \\\\_ -> True\\n prov_fn name\\n = ImpSpec { is_decl = decl_spec, is_item = item_spec }\\n where\\n item_spec = ImpSome { is_explicit = is_explicit name\\n , is_iloc = locA loc }\\n set_gre_imp gre@( GRE { gre_name = nm } )\\n = gre { gre_imp = unitBag $ prov_fn nm }\\n\\nparentOfImplicitlyImportedGRE :: Outputable info => GlobalRdrEltX info -> Maybe Name\\nparentOfImplicitlyImportedGRE gre =\\n if any (explicit_import . is_item) $ gre_imp gre\\n then Nothing\\n else greParent_maybe gre\\n where\\n explicit_import :: ImpItemSpec -> Bool\\n explicit_import (ImpAll {}) =\\n pprPanic \\"parentOfImplicitlyImportedGRE: ImpAll\\" (ppr gre)\\n explicit_import (ImpSome { is_explicit }) = is_explicit\\n\\n{- Note [Children for duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider the module\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (F(foo, MkFInt, MkFBool)) where\\n data family F a\\n data instance F Int = MkFInt { foo :: Int }\\n data instance F Bool = MkFBool { foo :: Bool }\\n\\nThe `foo` in the export list refers to *both* selectors! For this\\nreason, lookupChildren builds an environment that maps the FastString\\nto a list of items, rather than a single item.\\n-}\\n\\nmkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]\\nmkChildEnv gres = foldr add emptyNameEnv gres\\n where\\n add gre env = case greParent gre of\\n ParentIs p -> extendNameEnv_Acc (:) Utils.singleton env p gre\\n NoParent -> env\\n\\nfindChildren :: NameEnv [a] -> Name -> [a]\\nfindChildren env n = lookupNameEnv env n `orElse` []\\n\\ndata LookupChildError\\n = LookupChildNotFound { lce_wrapped_name :: !(LIEWrappedName GhcPs) }\\n | LookupChildNonType { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nontype_item :: !GlobalRdrElt }\\n | LookupChildNonData { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nondata_item :: !GlobalRdrElt }\\n\\nlookupChildren :: [GlobalRdrElt]\\n -> [LIEWrappedName GhcPs]\\n -> ( [LookupChildError] -- The ones for which the lookup failed\\n , [LocatedA GlobalRdrElt] )\\n-- (lookupChildren all_kids rdr_items) maps each rdr_item to its\\n-- corresponding Name in all_kids, if the former exists\\n-- The matching is done by FastString, not OccName, so that\\n-- Cls( meth, AssocTy )\\n-- will correctly find AssocTy among the all_kids of Cls, even though\\n-- the RdrName for AssocTy may have a (bogus) DataName namespace\\n-- (Really the rdr_items should be FastStrings in the first place.)\\nlookupChildren all_kids rdr_items = (fails, successes)\\n where\\n mb_xs = map do_one rdr_items\\n fails = [ err | Failed err <- mb_xs ]\\n successes = [ ok | Succeeded oks <- mb_xs, ok <- NE.toList oks ]\\n\\n do_one :: LIEWrappedName GhcPs -> MaybeErr LookupChildError (NonEmpty (LocatedA GlobalRdrElt))\\n do_one item@(L l r) =\\n case r of\\n IEName{}\\n -- IEName (unadorned name) places no restriction on the namespace of\\n -- the imported entity, so we look in both `val_gres` and `typ_gres`.\\n -- In case of conflict (punning), the value namespace takes priority.\\n -- See Note [Prioritise the value namespace in subordinate import lists]\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEType{}\\n -- IEType (\'type\' namespace specifier) restricts the lookup to the\\n -- type namespace, i.e. to `typ_gres`. In case of failure, we check\\n -- `val_gres` to produce a more helpful error message.\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- val_gres -> Failed $ LookupChildNonType item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEData{}\\n -- IEData (\'data\' namespace specifier) restricts the lookup to the\\n -- data namespace, i.e. to `val_gres`. In case of failure, we check\\n -- `typ_gres` to produce a more helpful error message.\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- typ_gres -> Failed $ LookupChildNonData item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEPattern{} -> panic \\"lookupChildren: IEPattern\\" -- Never happens (invalid syntax)\\n IEDefault{} -> panic \\"lookupChildren: IEDefault\\" -- Never happens (invalid syntax)\\n where\\n fs = (occNameFS . rdrNameOcc . ieWrappedName) r\\n gres = fromMaybe [] (lookupFsEnv kid_env fs)\\n (val_gres, typ_gres) = partition (isValNameSpace . greNameSpace) gres\\n\\n -- See Note [Children for duplicate record fields]\\n kid_env :: FastStringEnv [GlobalRdrElt]\\n kid_env = extendFsEnvList_C (++) emptyFsEnv\\n [(occNameFS (occName x), [x]) | x <- all_kids]\\n\\n\\n{- Note [Prioritise the value namespace in subordinate import lists]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider this program that defines a class that has both an associated type\\nnamed (#) and a method named (#)\\n\\n module M_assoc where\\n class C a b where\\n type a # b\\n (#) :: a -> b -> ()\\n module N_assoc where\\n import M_assoc( C((#)) )\\n\\nIn the import declaration, when we see the unadorned name (#) in the subordinate\\nimport list of C, which children should we bring into scope? Our options are:\\n\\n a) only the method (#)\\n b) only the associated type (#)\\n c) both the method and the associated type\\n\\nTo follow the precedent established by top-level items, we go with option (a).\\nIndeed, consider a slightly different program\\n\\n module M_top where\\n type family a # b\\n a # b = ()\\n module N_top where\\n import M_top( (#) )\\n\\nHere the import brings only the function (#) into scope, and one has to say\\n`type (#)` to get the type family.\\n-}\\n\\n-------------------------------\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused names}\\n* *\\n*********************************************************\\n-}\\n\\nreportUnusedNames :: TcGblEnv -> HscSource -> RnM ()\\nreportUnusedNames gbl_env hsc_src\\n = do { keep <- readTcRef (tcg_keep gbl_env)\\n ; traceRn \\"RUN\\" (ppr (tcg_dus gbl_env))\\n ; warnUnusedImportDecls gbl_env hsc_src\\n ; warnUnusedTopBinds $ unused_locals keep\\n ; warnMissingSignatures gbl_env\\n ; warnMissingKindSignatures gbl_env }\\n where\\n used_names :: NameSet -> NameSet\\n used_names keep = findUses (tcg_dus gbl_env) emptyNameSet `unionNameSet` keep\\n -- NB: currently, if f x = g, we only treat \'g\' as used if \'f\' is used\\n -- Hence findUses\\n\\n -- Collect the defined names from the in-scope environment\\n defined_names :: [GlobalRdrElt]\\n defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)\\n\\n kids_env = mkChildEnv defined_names\\n -- This is done in mkExports too; duplicated work\\n\\n gre_is_used :: NameSet -> GlobalRdrElt -> Bool\\n gre_is_used used_names gre0\\n = name `elemNameSet` used_names\\n || any (\\\\ gre -> greName gre `elemNameSet` used_names) (findChildren kids_env name)\\n -- A use of C implies a use of T,\\n -- if C was brought into scope by T(..) or T(C)\\n where\\n name = greName gre0\\n\\n -- Filter out the ones that are\\n -- (a) defined in this module, and\\n -- (b) not defined by a \'deriving\' clause\\n -- The latter have an Internal Name, so we can filter them out easily\\n unused_locals :: NameSet -> [GlobalRdrElt]\\n unused_locals keep =\\n let -- Note that defined_and_used, defined_but_not_used\\n -- are both [GRE]; that\'s why we need defined_and_used\\n -- rather than just used_names\\n _defined_and_used, defined_but_not_used :: [GlobalRdrElt]\\n (_defined_and_used, defined_but_not_used)\\n = partition (gre_is_used (used_names keep)) defined_names\\n\\n in filter is_unused_local defined_but_not_used\\n is_unused_local :: GlobalRdrElt -> Bool\\n is_unused_local gre = isLocalGRE gre\\n && isExternalName (greName gre)\\n\\n{- *********************************************************************\\n* *\\n Missing signatures\\n* *\\n********************************************************************* -}\\n\\n{-\\nNote [Missing signatures]\\n~~~~~~~~~~~~~~~~~~~~~~~~~\\nThere are four warning flags in play:\\n\\n * -Wmissing-exported-signatures\\n Warn about any exported top-level function/value without a type signature.\\n Does not include pattern synonyms.\\n\\n * -Wmissing-signatures\\n Warn about any top-level function/value without a type signature. Does not\\n include pattern synonyms. Takes priority over -Wmissing-exported-signatures.\\n\\n * -Wmissing-exported-pattern-synonym-signatures\\n Warn about any exported pattern synonym without a type signature.\\n\\n * -Wmissing-pattern-synonym-signatures\\n Warn about any pattern synonym without a type signature. Takes priority over\\n -Wmissing-exported-pattern-synonym-signatures.\\n\\n-}\\n\\n-- | Warn the user about top level binders that lack type signatures.\\n-- Called /after/ type inference, so that we can report the\\n-- inferred type of the function\\nwarnMissingSignatures :: TcGblEnv -> RnM ()\\nwarnMissingSignatures gbl_env\\n = do { let exports = availsToNameSet (tcg_exports gbl_env)\\n sig_ns = tcg_sigs gbl_env\\n -- We use sig_ns to exclude top-level bindings that are generated by GHC\\n binds = collectHsBindsBinders CollNoDictBinders $ tcg_binds gbl_env\\n pat_syns = tcg_patsyns gbl_env\\n\\n not_ghc_generated :: Name -> Bool\\n not_ghc_generated name = name `elemNameSet` sig_ns\\n\\n add_binding_warn :: Id -> RnM ()\\n add_binding_warn id =\\n when (not_ghc_generated name) $\\n do { env <- liftZonkM $ tcInitTidyEnv -- Why not use emptyTidyEnv?\\n ; let ty = tidyOpenType env (idType id)\\n missing = MissingTopLevelBindingSig name ty\\n diag = TcRnMissingSignature missing exported\\n ; addDiagnosticAt (getSrcSpan name) diag }\\n where\\n name = idName id\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n add_patsyn_warn :: PatSyn -> RnM ()\\n add_patsyn_warn ps =\\n when (not_ghc_generated name) $\\n addDiagnosticAt (getSrcSpan name)\\n (TcRnMissingSignature missing exported)\\n where\\n name = patSynName ps\\n missing = MissingPatSynSig ps\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n -- Warn about missing signatures\\n -- Do this only when we have a type to offer\\n -- See Note [Missing signatures]\\n ; mapM_ add_binding_warn binds\\n ; mapM_ add_patsyn_warn pat_syns\\n }\\n\\n-- | Warn the user about tycons that lack kind signatures.\\n-- Called /after/ type (and kind) inference, so that we can report the\\n-- inferred kinds.\\nwarnMissingKindSignatures :: TcGblEnv -> RnM ()\\nwarnMissingKindSignatures gbl_env\\n = do { cusks_enabled <- xoptM LangExt.CUSKs\\n ; mapM_ (add_ty_warn cusks_enabled) tcs\\n }\\n where\\n tcs = tcg_tcs gbl_env\\n ksig_ns = tcg_ksigs gbl_env\\n exports = availsToNameSet (tcg_exports gbl_env)\\n\\n has_kind_signature :: Name -> Bool\\n has_kind_signature name = name `elemNameSet` ksig_ns\\n\\n add_ty_warn :: Bool -> TyCon -> RnM ()\\n add_ty_warn cusks_enabled tyCon =\\n when (has_kind_signature name) $\\n addDiagnosticAt (getSrcSpan name) diag\\n where\\n name = tyConName tyCon\\n diag = TcRnMissingSignature missing exported\\n missing = MissingTyConKindSig tyCon cusks_enabled\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused imports}\\n* *\\n*********************************************************\\n\\nThis code finds which import declarations are unused. The\\nspecification and implementation notes are here:\\n https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/unused-imports\\n\\nSee also Note [Choosing the best import declaration] in GHC.Types.Name.Reader\\n-}\\n\\ntype ImportDeclUsage\\n = ( LImportDecl GhcRn -- The import declaration\\n , [GlobalRdrElt] -- What *is* used (normalised)\\n , [Name] -- What is imported but *not* used\\n , [NamespaceSpecifier GhcRn] ) -- Unused wildcards\\n\\nwarnUnusedImportDecls :: TcGblEnv -> HscSource -> RnM ()\\nwarnUnusedImportDecls gbl_env hsc_src\\n = do { uses <- readMutVar (tcg_used_gres gbl_env)\\n ; let imports = tcg_rn_imports gbl_env\\n rdr_env = tcg_rdr_env gbl_env\\n\\n -- We should only warn for unnecessary *user* imports, but deciding\\n -- minimal imports should take generated imports into account\\n ; let usageUserImports = findImportUsage (excludeGenerated imports) uses\\n usageAllImports = findImportUsage imports uses\\n\\n ; traceRn \\"warnUnusedImportDecls\\" $\\n (vcat [ text \\"Uses:\\" <+> ppr uses\\n , text \\"Usage all user imports: \\" <+> ppr usageUserImports\\n , text \\"Usage all imports: \\" <+> ppr usageAllImports])\\n\\n ; mapM_ (warnUnusedImport rdr_env) usageUserImports\\n\\n ; whenGOptM Opt_D_dump_minimal_imports $\\n printMinimalImports hsc_src usageAllImports }\\n\\n-- | Exclude generated imports\\nexcludeGenerated :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\nexcludeGenerated = filterOut (isGeneratedImport . ideclOrigin . ideclExt . unLoc)\\n\\nfindImportUsage :: [LImportDecl GhcRn]\\n -> [GlobalRdrElt]\\n -> [ImportDeclUsage]\\n\\nfindImportUsage imports used_gres\\n = map unused_decl imports\\n where\\n import_usage :: ImportMap\\n import_usage = mkImportMap used_gres\\n\\n unused_decl :: LImportDecl GhcRn -> ImportDeclUsage\\n unused_decl decl@(L _ (ImportDecl { ideclImportList = imps }))\\n = -- pprTrace \\"unused_decl\\" (vcat [ ppr decl\\n -- , text \\"used\\" <+> ppr used_gres\\n -- , text \\"unused\\" <+> ppr unused_names ]) $\\n (decl, used_gres, unused_names, unused_wcs)\\n where\\n used_gres = lookupImportMap decl import_usage\\n\\n used_gre_env = mkGlobalRdrEnv used_gres\\n used_parents = mkNameSet (mapMaybe greParent_maybe used_gres)\\n\\n (unused_names, unused_wcs) -- Not trivial; see eg #7454\\n = case imps of\\n Just (Exactly, imp_ies) ->\\n let unused = foldr (add_unused . unLoc) emptyUnusedNames imp_ies\\n nms = nameSetElemsStable (collectUnusedNames unused)\\n wcs = collectUnusedWildcards unused\\n in (nms, wcs)\\n _other -> ([], []) -- No explicit import list => no unused-name list\\n\\n add_unused :: IE GhcRn -> UnusedNames -> UnusedNames\\n add_unused (IEVar _ n _) acc = add_unused_name (lieWrappedName n) True acc\\n add_unused (IEThingAbs _ n _) acc = add_unused_name (lieWrappedName n) False acc\\n add_unused (IEThingAll _ _ n _) acc = add_unused_all (lieWrappedName n) acc\\n add_unused (IEThingWith _ p wc ns _) acc = add_wc_all (add_unused_with pn xs acc)\\n where pn = lieWrappedName p\\n xs = map lieWrappedName ns\\n add_wc_all = case wc of\\n NoIEWildcard -> id\\n IEWildcard _ -> add_unused_all pn\\n add_unused (IEWholeNamespace x ns_spec) acc = add_unused_wildcard ns_spec (iewn_names x) acc\\n add_unused _ acc = acc\\n\\n add_unused_name :: Name -> Bool -> UnusedNames -> UnusedNames\\n add_unused_name n is_ie_var acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | is_ie_var\\n , isFieldName n\\n -- See Note [Reporting unused imported duplicate record fields]\\n = let\\n fs = getOccFS n\\n (flds, flds_used) = lookupFsEnv acc_fs fs `orElse` (emptyNameSet, Any False)\\n acc_fs\' = extendFsEnv acc_fs fs (extendNameSet flds n, Any used S.<> flds_used)\\n in UnusedNames acc_ns acc_wcs acc_fs\'\\n\\n | used\\n = acc\\n\\n | otherwise\\n = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n where\\n used = isJust $ lookupGRE_Name used_gre_env n\\n\\n add_unused_all :: Name -> UnusedNames -> UnusedNames\\n add_unused_all n acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | Just {} <- lookupGRE_Name used_gre_env n = acc\\n | n `elemNameSet` used_parents = acc\\n | otherwise = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n\\n add_unused_with :: Name -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_with p ns acc\\n | all (`elemNameSet` acc1_ns) ns = add_unused_name p False acc1\\n | otherwise = acc1\\n where\\n acc1@(UnusedNames acc1_ns _ _) = foldr (\\\\n acc\' -> add_unused_name n False acc\') acc ns\\n -- If you use \'signum\' from Num, then the user may well have\\n -- imported Num(signum). We don\'t want to complain that\\n -- Num is not itself mentioned. Hence the two cases in add_unused_with.\\n\\n add_unused_wildcard :: NamespaceSpecifier GhcRn -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_wildcard ns_spec names acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | any_used = acc\\n | otherwise = UnusedNames acc_ns (ns_spec : acc_wcs) acc_fs\\n where\\n -- A wildcard `type ..` or `data ..` is used if at least one of\\n -- the names it expands to is used\\n any_used = any (isJust . lookupGRE_Name used_gre_env) names\\n\\n\\n-- | An accumulator for unused names in an import list.\\n--\\n-- See Note [Reporting unused imported duplicate record fields].\\ndata UnusedNames =\\n UnusedNames\\n { unused_names :: NameSet\\n -- ^ Unused \'Name\'s in an import list, not including record fields\\n -- that are plain \'IEVar\' imports (tracked by \'rec_fld_uses\')\\n -- or wildcard imports (tracked by \'unused_wildcards\').\\n , unused_wildcards :: [NamespaceSpecifier GhcRn]\\n -- ^ Unused wildcards @type ..@ or @data ..@ in an import list.\\n , rec_fld_uses :: FastStringEnv (NameSet, Any)\\n -- ^ Record fields imported without a parent (i.e. an \'IEVar\' import).\\n --\\n -- The \'Any\' value records whether any of the record fields\\n -- sharing the same underlying \'FastString\' have been used.\\n }\\n\\nemptyUnusedNames :: UnusedNames\\nemptyUnusedNames = UnusedNames emptyNameSet [] emptyFsEnv\\n\\ninstance Outputable UnusedNames where\\n ppr (UnusedNames nms wcs flds) =\\n text \\"UnusedNames\\" <+>\\n braces (ppr nms <+> ppr wcs <+> ppr (fmap (second getAny) flds))\\n\\n-- | Collect all unused names from a \'UnusedNames\' value.\\ncollectUnusedNames :: UnusedNames -> NameSet\\ncollectUnusedNames (UnusedNames { unused_names = nms, rec_fld_uses = flds })\\n = nms S.<> unused_flds\\n where\\n unused_flds = nonDetFoldFsEnv collect_unused emptyNameSet flds\\n collect_unused :: (NameSet, Any) -> NameSet -> NameSet\\n collect_unused (nms, Any at_least_one_name_is_used) acc\\n | at_least_one_name_is_used = acc\\n | otherwise = unionNameSet nms acc\\n\\ncollectUnusedWildcards :: UnusedNames -> [NamespaceSpecifier GhcRn]\\ncollectUnusedWildcards = unused_wildcards\\n\\n{- Note [Reporting unused imported duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have (#24035):\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M1 (R1(..), R2(..)) where\\n data R1 = MkR1 { fld :: Int }\\n data R2 = MkR2 { fld :: Int }\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M2 where\\n import M1 (R1(MkR1), R2, fld)\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nIn the import of \'M1\' in \'M2\', the \'fld\' import resolves to two separate GREs,\\nnamely R1(fld) and R2(fld). From the perspective of the renamer, and in particular\\nthe \'findImportUsage\' function, it\'s as if the user had imported the two names\\nseparately (even though no source syntax allows that).\\n\\nThis means that we need to be careful when reporting unused imports: the R2(fld)\\nimport is indeed unused, but because R1(fld) is used, we should not report\\nfld as unused altogether.\\n\\nTo achieve this, we keep track of record field imports without a parent (i.e.\\nusing the IEVar constructor) separately from other import items, using the\\nUnusedNames datatype.\\nOnce we have accumulated usages, we emit warnings for unused record fields\\nwithout parents one whole group (of record fields sharing the same textual name)\\nat a time, and only if *all* of the record fields in the group are unused;\\nsee \'collectUnusedNames\'.\\n\\nNote that this only applies to record fields imported without a parent. If we\\nhad:\\n\\n import M1 (R1(MkR1, fld), R2(fld))\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nthen of course we should report the second \'fld\' as unused.\\n-}\\n\\n\\n{- Note [The ImportMap]\\n~~~~~~~~~~~~~~~~~~~~~~~\\nThe ImportMap is a short-lived intermediate data structure records, for\\neach import declaration, what stuff brought into scope by that\\ndeclaration is actually used in the module.\\n\\nThe [GlobalRdrElt] are the things imported from that decl.\\n-}\\n\\ndata ImportMap = ImportMap\\n { im_imports :: Map RealSrcSpan [GlobalRdrElt]\\n -- ^ See [The ImportMap]\\n -- If loc :-> gres, then\\n -- \'loc\' = the end loc of the bestImport of each GRE in \'gres\'\\n , im_generatedImports :: Map ModuleName [GlobalRdrElt]\\n }\\n\\nmkImportMap :: [GlobalRdrElt] -> ImportMap\\n-- For each of a list of used GREs, find all the import decls that brought\\n-- it into scope; choose one of them (bestImport), and record\\n-- the RdrName in that import decl\'s entry in the ImportMap\\nmkImportMap = foldr insertImportMap $ ImportMap Map.empty Map.empty\\n\\ninsertImportMap :: GlobalRdrElt -> ImportMap -> ImportMap\\ninsertImportMap gre@(GRE { gre_imp = imp_specs }) importMap\\n | RealSrcSpan importSpan _ <- is_dloc best_imp_spec =\\n importMap{im_imports = insertElem importSpan gre $ im_imports importMap}\\n | GeneratedSrcSpan{} <- is_dloc best_imp_spec =\\n importMap{im_generatedImports = insertElem (moduleName $ is_mod best_imp_spec) gre $ im_generatedImports importMap}\\n | otherwise = importMap\\n where\\n best_imp_spec =\\n case bagToList imp_specs of\\n [] -> pprPanic \\"mkImportMap: GRE with no ImportSpecs\\" (ppr gre)\\n is:iss -> is_decl $ bestImport (is NE.:| iss)\\n\\n -- https://github.com/haskell/containers/issues/784\\n insertElem :: Ord k => k -> v -> Map k [v] -> Map k [v]\\n insertElem k v = flip Map.alter k $ \\\\case\\n Just vs -> Just (v : vs)\\n Nothing -> Just [v]\\n\\nlookupImportMap :: LImportDecl GhcRn -> ImportMap -> [GlobalRdrElt]\\nlookupImportMap (L srcSpan ImportDecl{ideclName = L _ modName}) importMap =\\n fromMaybe [] $\\n -- should match logic in insertImportMap\\n case locA srcSpan of\\n RealSrcSpan realSrcSpan _ -> realSrcSpan `Map.lookup` im_imports importMap\\n GeneratedSrcSpan{} -> modName `Map.lookup` im_generatedImports importMap\\n _ -> Nothing\\n\\nlieNames :: LIE (GhcPass p) -> [Located (IdP (GhcPass p))]\\nlieNames = _\\n\\nwarnUnusedImport :: GlobalRdrEnv -> ImportDeclUsage -> RnM ()\\nwarnUnusedImport rdr_env (L loc decl, used, unused, unused_wcs)\\n\\n -- Do not warn for \'import M()\'\\n -- See (UI1) in Note [Unused imports]\\n | Just (Exactly, _) <- ideclImportList decl\\n , null unused && null unused_wcs\\n = return ()\\n\\n -- Note [Do not warn about Prelude hiding]\\n | Just (EverythingBut, hides) <- ideclImportList decl\\n , not (null hides)\\n , pRELUDE_NAME == unLoc (ideclName decl)\\n = return ()\\n\\n -- Do not warn about import X as Rebindable\\n -- See (UI2) in Note [Unused imports]\\n | Just (L _ mod) <- ideclAs decl\\n , mod == rEBINDABLE_MOD_NAME\\n = return ()\\n\\n -- Nothing used; drop entire declaration\\n | null used\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl UnusedImportNone)\\n\\n -- Everything imported is used; nop\\n | null unused && null unused_wcs\\n = return ()\\n\\n -- Some imports are unused: make the `SrcSpan` cover only the unused\\n -- items instead of the whole import statement\\n | Just (_, imports) <- ideclImportList decl\\n , let unused_locs = [ locA loc | L loc ie <- imports\\n , name <- ieNames ie\\n , name `elem` unused ]\\n , loc1 : locs <- unused_locs\\n , let span = foldr1 combineSrcSpans ( loc1 NE.:| locs )\\n = addDiagnosticAt span (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n -- Some imports are unused\\n | otherwise\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n where\\n -- In warning message, pretty-print identifiers unqualified unconditionally\\n -- to improve the consistent for ambiguous/unambiguous identifiers.\\n -- See #14881.\\n possible_field n =\\n case lookupGRE_Name rdr_env n of\\n Just (GRE { gre_par = par, gre_info = IAmRecField info }) ->\\n let fld_occ :: OccName\\n fld_occ = nameOccName $ flSelector $ recFieldLabel info\\n in UnusedImportNameRecField par fld_occ\\n _ -> UnusedImportNameRegular n\\n\\n -- Print unused names in a deterministic (lexicographic) order\\n sort_unused :: [UnusedImportName]\\n sort_unused =\\n [ UnusedImportWildcard wc | wc <- unused_wcs ] ++\\n [ possible_field nm | nm <- sortBy (comparing nameOccName) unused ]\\n\\ngetMinimalImports :: [ImportDeclUsage] -> RnM [LImportDecl GhcRn]\\ngetMinimalImports ie_decls\\n = do { rdr_env <- getGlobalRdrEnv\\n ; fmap combine $ mapM (mk_minimal rdr_env) ie_decls }\\n where\\n mk_minimal rdr_env (L l decl, used_gres, unused, unused_wcs)\\n | null unused && null unused_wcs\\n , Just (Exactly, _) <- ideclImportList decl\\n = return (L l decl)\\n | otherwise\\n = do { let ImportDecl { ideclName = L _ mod_name\\n , ideclSource = is_boot\\n , ideclPkgQual = pkg_qual\\n , ideclExt = XImportDeclPass { ideclOrigin = origin } } = decl\\n ; iface <- loadSrcInterface doc (importDeclLookupScope origin)\\n mod_name is_boot pkg_qual\\n ; let used_avails = gresToAvailInfo used_gres\\n ; lies <- map (L l) <$> concatMapM (to_ie rdr_env iface) used_avails\\n ; return (L l (decl { ideclImportList = Just (Exactly, lies) })) }\\n where\\n doc = text \\"Compute minimal imports for\\" <+> ppr decl\\n\\n to_ie :: GlobalRdrEnv -> ModIface -> AvailInfo -> RnM [IE GhcRn]\\n -- The main trick here is that if we\'re importing all the constructors\\n -- we want to say \\"T(..)\\", but if we\'re importing only a subset we want\\n -- to say \\"T(A,B,C)\\". So we have to find out what the module exports.\\n to_ie rdr_env _ (Avail c) -- Note [Overloaded field import]\\n = do { let\\n gre = expectJust $ lookupGRE_Name rdr_env c\\n ; return $ [IEVar Nothing (to_ie_post_rn $ noLocA $ greName gre) Nothing] }\\n to_ie _ _ avail@(AvailTC n [_]) -- Exporting the main decl and nothing else\\n | availExportsDecl avail\\n = return [IEThingAbs Nothing (to_ie_post_rn $ noLocA n) Nothing]\\n to_ie rdr_env iface (AvailTC n cs) =\\n case [ xs | avail@(AvailTC x xs) <- mi_exports iface\\n , x == n\\n , availExportsDecl avail -- Note [Partial export]\\n ] of\\n [xs]\\n | all_used xs\\n -> return [IEThingAll (IEThingAllExt Nothing noAnn noAnn noAnn)\\n (NoNamespaceSpecifier noExtField)\\n (to_ie_post_rn $ noLocA n)\\n Nothing]\\n | otherwise\\n -> do { let ns_gres = map (expectJust . lookupGRE_Name rdr_env) cs\\n ns = map greName ns_gres\\n ; return [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n -- Note [Overloaded field import]\\n _other\\n -> do { let infos = map (expectJust . lookupGRE_Name rdr_env) cs\\n (ns_gres,fs_gres) = classifyGREs infos\\n ns = map greName (ns_gres ++ fs_gres)\\n fs = map fieldGREInfo fs_gres\\n ; return $\\n if all_non_overloaded fs\\n then map (\\\\nm -> IEVar Nothing (to_ie_post_rn_var $ noLocA nm) Nothing) ns\\n else [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n where\\n\\n all_used avail_cs = all (`elem` cs) avail_cs\\n\\n all_non_overloaded = all (not . flIsOverloaded . recFieldLabel)\\n\\n combine :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\n combine = map merge . NE.groupAllWith getKey\\n\\n getKey :: LImportDecl GhcRn -> (Bool, Maybe ModuleName, ModuleName)\\n getKey decl =\\n ( isImportDeclQualified . ideclQualified $ idecl -- is this qualified? (important that this be first)\\n , unLoc <$> ideclAs idecl -- what is the qualifier (inside Maybe monad)\\n , unLoc . ideclName $ idecl -- Module Name\\n )\\n where\\n idecl :: ImportDecl GhcRn\\n idecl = unLoc decl\\n\\n merge :: NonEmpty (LImportDecl GhcRn) -> LImportDecl GhcRn\\n merge decls@((L l decl) :| _) = L l (decl { ideclImportList = Just (Exactly, lies) })\\n where lies = concatMap snd $ mapMaybe (ideclImportList . unLoc) $ NE.toList decls\\n\\nclassifyGREs :: [GlobalRdrElt] -> ([GlobalRdrElt], [FieldGlobalRdrElt])\\nclassifyGREs = partition (not . isRecFldGRE)\\n\\nprintMinimalImports :: HscSource -> [ImportDeclUsage] -> RnM ()\\n-- See Note [Printing minimal imports]\\nprintMinimalImports hsc_src imports_w_usage\\n = do { imports\' <- excludeGenerated <$> getMinimalImports imports_w_usage\\n ; this_mod <- getModule\\n ; dflags <- getDynFlags\\n ; liftIO $ withFile (mkFilename dflags this_mod) WriteMode $ \\\\h ->\\n printForUser dflags h neverQualify AllTheWay (vcat (map ppr imports\'))\\n -- The neverQualify is important. We are printing Names\\n -- but they are in the context of an \'import\' decl, and\\n -- we never qualify things inside there\\n -- E.g. import Blag( f, b )\\n -- not import Blag( Blag.f, Blag.g )!\\n }\\n where\\n mkFilename dflags this_mod\\n | Just d <- dumpDir dflags = d basefn\\n | otherwise = basefn\\n where\\n suffix = case hsc_src of\\n HsBootFile -> \\".imports-boot\\"\\n HsSrcFile -> \\".imports\\"\\n HsigFile -> \\".imports\\"\\n basefn = moduleNameString (moduleName this_mod) ++ suffix\\n\\n\\nto_ie_post_rn_var :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn_var (L l n)\\n | isDataOcc $ occName n = L l (IEPattern noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n\\n\\nto_ie_post_rn :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn (L l n)\\n | isTcOcc occ && isSymOcc occ = L l (IEType noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n where occ = occName n\\n\\n{- Note [Do not warn about Prelude hiding]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWe do not warn about\\n import Prelude hiding( x, y )\\nbecause even if nothing else from Prelude is used, it may be essential to hide\\nx,y to avoid name-shadowing warnings. Example (#9061)\\n import Prelude hiding( log )\\n f x = log where log = ()\\n\\nNote [Unused imports]\\n~~~~~~~~~~~~~~~~~~~~~\\nIn `warnUnusedImport`, if we see an import with an explicit list imports, thus\\n import M( a, b )\\nand neither `a` nor `b` is used, we report the entire import decl as unused. We\\ncheck this by looking at the names that it brings into scope scope; if there are\\nno ununused names, don\'t report.\\n\\n(UI1) We don\'t want to complain about `import M()`, because that is often used to bring\\n M\'s /instances/ into scope. That is neatly dealt with by the \\"no unused\\n names\\" (nor unused wildcard imports) criterion.\\n\\n(UI2) We don\'t report a decl as unused if it has an `as Rebindable` qualifier.\\n See (KN1) in Note [Overview of known entities] in GHC.Builtin\\n\\n\\nNote [Printing minimal imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nTo print the minimal imports we walk over all import decls (both user-supplied\\nand generated), trim their import lists, then filter out generated decls.\\n\\nNB that\\n\\n * We do *not* change the \'qualified\' or \'as\' parts!\\n\\n * We do not discard a decl altogether; we might need instances\\n from it. Instead we just trim to an empty import list\\n\\nNote [Partial export]\\n~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have\\n\\n module A( op ) where\\n class C a where\\n op :: a -> a\\n\\n module B where\\n import A\\n f = ..op...\\n\\nThen the minimal import for module B is\\n import A( op )\\nnot\\n import A( C( op ) )\\nwhich we would usually generate if C was exported from B. Hence\\nthe availExportsDecl test when deciding what to generate.\\n\\n\\nNote [Overloaded field import]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nOn the other hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n data T = MkT { foo :: Int }\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( T(foo) )\\nbecause when DuplicateRecordFields is enabled, field selectors are\\nnot in scope without their enclosing datatype.\\n\\nOn the third hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n pattern MkT { foo } = Just foo\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( foo )\\nbecause foo doesn\'t have a parent. This might actually be ambiguous if A\\nexports another field called foo, but there is no good answer to return and this\\nis a very obscure corner, so it seems to be the best we can do. See\\nDRFPatSynExport for a test of this.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Errors}\\n* *\\n************************************************************************\\n-}\\n\\nbadImportItemErr\\n :: ModIface -> ImpDeclSpec -> IE GhcPs\\n -> IsSubordinateError\\n -> [AvailInfo]\\n -> TcRn (NonEmpty ImportLookupReason)\\nbadImportItemErr iface decl_spec ie sub avails = do\\n exts <- importLookupExtensions\\n let import_lookup_bad :: BadImportKind -> ImportLookupReason\\n import_lookup_bad k = ImportLookupBad k iface decl_spec ie exts\\n dflags <- getDynFlags\\n hsc_env <- getTopEnv\\n let rdr_env = mkGlobalRdrEnv\\n $ gresFromAvails hsc_env (Just imp_spec) all_avails\\n pure $ fmap import_lookup_bad (importErrorKind dflags rdr_env)\\n where\\n importErrorKind :: DynFlags -> GlobalRdrEnv -> NonEmpty BadImportKind\\n importErrorKind dflags rdr_env\\n | any checkIfTyCon avails = case sub of\\n IsNotSubordinate -> NE.singleton BadImportAvailTyCon\\n IsSubordinateError { subordinate_err_parent = gre\\n , subordinate_err_unavailable = unavailable\\n , subordinate_err_nontype = nontype\\n , subordinate_err_nondata = nondata }\\n -> NE.fromList $ catMaybes $\\n [ fmap (BadImportNotExportedSubordinates gre) (NE.nonEmpty unavailable)\\n , fmap (BadImportNonTypeSubordinates gre) (NE.nonEmpty nontype)\\n , fmap (BadImportNonDataSubordinates gre) (NE.nonEmpty nondata) ]\\n | any checkIfVarName avails = NE.singleton BadImportAvailVar\\n | Just con <- find checkIfDataCon avails = NE.singleton (BadImportAvailDataCon (availOccName con))\\n | otherwise = NE.singleton (BadImportNotExported suggs)\\n where\\n suggs = similar_suggs ++ fieldSelectorSuggestions rdr_env rdr\\n what_look = case sub of\\n IsNotSubordinate -> WL_TyCon_or_TermVar\\n IsSubordinateError { subordinate_err_parent = gre } ->\\n case greInfo gre of\\n IAmTyCon ClassFlavour\\n -> WL_TyCon_or_TermVar\\n _ -> WL_Term\\n similar_names =\\n similarNameSuggestions (Unbound.LF what_look WL_Global)\\n dflags rdr_env emptyLocalRdrEnv rdr\\n similar_suggs =\\n case NE.nonEmpty $ mapMaybe imported_item $ similar_names of\\n Just similar -> [ SuggestSimilarNames rdr similar ]\\n Nothing -> [ ]\\n\\n -- Only keep imported items, and set the \\"HowInScope\\" to\\n -- \\"Nothing\\" to avoid printing \\"imported from...\\" in the suggestion\\n -- error message.\\n imported_item (SimilarRdrName rdr_name gre (Just (ImportedBy {})))\\n = Just (SimilarRdrName rdr_name gre Nothing)\\n imported_item _ = Nothing\\n\\n checkIfDataCon = checkIfAvailMatches isDataConName\\n checkIfTyCon = checkIfAvailMatches isTyConName\\n checkIfVarName =\\n \\\\case\\n AvailTC{} -> False\\n Avail n -> importedFS == occNameFS (occName n)\\n && (isVarOcc <||> isFieldOcc) (occName n)\\n checkIfAvailMatches namePred =\\n \\\\case\\n AvailTC _ ns ->\\n case find (\\\\n -> importedFS == occNameFS (occName n)) ns of\\n Just n -> namePred n\\n Nothing -> False\\n Avail{} -> False\\n availOccName = occName . availName\\n rdr = ieName ie\\n importedFS = occNameFS $ rdrNameOcc rdr\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n all_avails = mi_exports iface\\n\\nimportLookupExtensions :: TcRn ImportLookupExtensions\\nimportLookupExtensions = do\\n ile_pattern_synonyms <- xoptM LangExt.PatternSynonyms\\n ile_explicit_namespaces <- xoptM LangExt.ExplicitNamespaces\\n return ImportLookupExtensions{ile_pattern_synonyms, ile_explicit_namespaces}\\n\\naddDupDeclErr :: NonEmpty GlobalRdrElt -> TcRn ()\\naddDupDeclErr gres@(gre :| _)\\n -- Report the error at the later location\\n = addErrAt (getSrcSpan (NE.last sorted_names)) $ (TcRnDuplicateDecls (greOccName gre) sorted_names)\\n where\\n sorted_names =\\n NE.sortBy (SrcLoc.leftmost_smallest `on` nameSrcSpan)\\n (fmap greName gres)\\n\\n-- This data decl will parse OK\\n-- data T = a Int\\n-- treating \\"a\\" as the constructor.\\n-- It is really hard to make the parser spot this malformation.\\n-- So the renamer has to check that the constructor is legal\\n--\\n-- We can get an operator as the constructor, even in the prefix form:\\n-- data T = :% Int Int\\n-- from interface files, which always print in prefix form\\n--\\n-- We also allow type constructor names, which are defined by \\"type data\\"\\n-- declarations. See Note [Type data declarations] in GHC.Rename.Module.\\n\\ncheckConName :: RdrName -> TcRn ()\\ncheckConName name\\n = checkErr (isRdrDataCon name || isRdrTc name) (TcRnIllegalDataCon name)\\n", "filetypes": ["haskell"]}}}' 2026-10-16 14:49:11,912 - DEBUG - POST b'http://127.0.0.1:37093/receive_messages' {'content-type': 'application/json', 'x-ycm-hmac': b'Rga7Yd4l4fgfufwYw+0sxzurvznImlBO0MPmgAlS4EY='} b'{"filepath": "/home/enrico/ghc/compiler/GHC/Rename/Names.hs", "line_num": 1, "column_num": 1, "working_dir": "/home/enrico/ghc", "file_data": {"/home/enrico/ghc/compiler/GHC/Rename/Names.hs": {"contents": "{-\\n(c) The GRASP/AQUA Project, Glasgow University, 1992-1998\\n\\nExtracting imported and top-level names in scope\\n-}\\n\\n{-# LANGUAGE NondecreasingIndentation #-}\\n{-# LANGUAGE TypeFamilies #-}\\n\\nmodule GHC.Rename.Names (\\n rnImports, getLocalNonValBinders, newRecordFieldLabel,\\n importsFromIface,\\n ImportUserSpec(..),\\n extendGlobalRdrEnvRn,\\n gresFromAvails,\\n calculateAvails,\\n reportUnusedNames,\\n checkConName,\\n mkChildEnv,\\n findChildren,\\n mkBadExportSubordinate,\\n findImportUsage,\\n getMinimalImports,\\n printMinimalImports,\\n renamePkgQual, renameRawPkgQual,\\n classifyGREs,\\n ImportDeclUsage,\\n rnNamespaceSpecifier\\n ) where\\n\\nimport GHC.Prelude hiding ( head, init, last, tail )\\n\\nimport GHC.Driver.Env\\nimport GHC.Driver.Session\\nimport GHC.Driver.Ppr\\n\\nimport GHC.Rename.Env\\nimport GHC.Rename.Fixity\\nimport GHC.Rename.Utils ( warnUnusedTopBinds )\\nimport GHC.Rename.Unbound\\nimport qualified GHC.Rename.Unbound as Unbound\\n\\nimport GHC.Tc.Errors.Types\\nimport GHC.Tc.Utils.Env\\nimport GHC.Tc.Utils.Monad\\nimport GHC.Tc.Types.LclEnv\\nimport GHC.Tc.Zonk.TcType ( tcInitTidyEnv )\\n\\nimport GHC.Hs\\nimport GHC.Iface.Load ( loadSrcInterface, loadSrcInterface_maybe )\\nimport GHC.Iface.Errors.Types\\n ( IfaceMessage(..), MissingInterfaceError, InterfaceLookingFor(..)\\n , LoadEssentialsReason(..) )\\nimport GHC.Iface.Syntax ( fromIfaceWarnings )\\nimport GHC.Builtin.Modules( pRELUDE_NAME, rEBINDABLE_MOD_NAME )\\nimport GHC.Parser.PostProcess ( setRdrNameSpace )\\nimport GHC.Core.TyCo.Tidy\\nimport GHC.Core.PatSyn\\nimport GHC.Core.TyCon ( TyCon, tyConName )\\nimport qualified GHC.LanguageExtensions as LangExt\\n\\nimport GHC.Utils.Outputable as Outputable\\nimport GHC.Utils.Misc as Utils\\nimport GHC.Utils.Panic\\n\\nimport GHC.Types.Fixity.Env\\nimport GHC.Types.SafeHaskell\\nimport GHC.Types.Name\\nimport GHC.Types.Name.Env\\nimport GHC.Types.Name.Set\\nimport GHC.Types.Name.Reader\\nimport GHC.Types.Avail\\nimport GHC.Types.FieldLabel\\nimport GHC.Types.Hint\\nimport GHC.Types.SourceFile\\nimport GHC.Types.SrcLoc as SrcLoc\\nimport GHC.Types.Basic (TyConFlavour (..), convImportLevel, VisArity)\\nimport GHC.Types.UnresolvedImport\\nimport GHC.Types.Id\\nimport GHC.Types.PkgQual\\nimport GHC.Types.GREInfo (ConInfo(..), ConFieldInfo (..), ConLikeInfo (ConIsData))\\n\\nimport GHC.Unit\\nimport GHC.Unit.Module.Warnings\\nimport GHC.Unit.Module.ModIface\\nimport GHC.Unit.Module.Imported\\nimport GHC.Unit.Module.Deps\\nimport GHC.Unit.Env\\n\\nimport GHC.Data.Bag\\nimport GHC.Data.FastString\\nimport GHC.Data.FastString.Env\\nimport GHC.Data.Maybe\\nimport GHC.Data.List.SetOps ( removeDups )\\n\\nimport Control.Arrow ( second )\\nimport Control.Monad\\nimport Data.Foldable ( for_ )\\nimport Data.IntMap ( IntMap )\\nimport qualified Data.IntMap as IntMap\\nimport Data.Map ( Map )\\nimport qualified Data.Map as Map\\nimport Data.Ord ( comparing )\\nimport Data.Semigroup ( Any(..) )\\nimport qualified Data.Semigroup as S\\nimport Data.List ( partition, find, sortBy )\\nimport Data.List.NonEmpty (NonEmpty(..))\\nimport qualified Data.List.NonEmpty as NE\\nimport Data.Function ( on )\\nimport qualified Data.Set as S\\nimport System.FilePath (())\\nimport System.IO\\n\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{rnImports}\\n* *\\n************************************************************************\\n\\nNote [Tracking Trust Transitively]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen we import a package as well as checking that the direct imports are safe\\naccording to the rules outlined in the Note [Safe Haskell Trust Check] in GHC.Driver.Main\\nwe must also check that these rules hold transitively for all dependent modules\\nand packages. Doing this without caching any trust information would be very\\nslow as we would need to touch all packages and interface files a module depends\\non. To avoid this we make use of the property that if a modules Safe Haskell\\nmode changes, this triggers a recompilation from that module in the dependency\\ngraph. So we can just worry mostly about direct imports.\\n\\nThere is one trust property that can change for a package though without\\nrecompilation being triggered: package trust. So we must check that all\\npackages a module transitively depends on to be trusted are still trusted when\\nwe are compiling this module (as due to recompilation avoidance some modules\\nbelow may not be considered trusted any more without recompilation being\\ntriggered).\\n\\nWe handle this by augmenting the existing transitive list of packages a module M\\ndepends on with a bool for each package that says if it must be trusted when the\\nmodule M is being checked for trust. This list of trust required packages for a\\nsingle import is gathered in the rnImportDecl function and stored in an\\nImportAvails data structure. The union of these trust required packages for all\\nimports is done by the rnImports function using the combine function which calls\\nthe plusImportAvails function that is a union operation for the ImportAvails\\ntype. This gives us in an ImportAvails structure all packages required to be\\ntrusted for the module we are currently compiling. Checking that these packages\\nare still trusted (and that direct imports are trusted) is done in\\nGHC.Driver.Main.checkSafeImports.\\n\\nSee the note below, [Trust Own Package] for a corner case in this method and\\nhow its handled.\\n\\n\\nNote [Trust Own Package]\\n~~~~~~~~~~~~~~~~~~~~~~~~\\nThere is a corner case of package trust checking that the usual transitive check\\ndoesn\'t cover. (For how the usual check operates see the Note [Tracking Trust\\nTransitively] below). The case is when you import a -XSafe module M and M\\nimports a -XTrustworthy module N. If N resides in a different package than M,\\nthen the usual check works as M will record a package dependency on N\'s package\\nand mark it as required to be trusted. If N resides in the same package as M\\nthough, then importing M should require its own package be trusted due to N\\n(since M is -XSafe so doesn\'t create this requirement by itself). The usual\\ncheck fails as a module doesn\'t record a package dependency of its own package.\\nSo instead we now have a bool field in a modules interface file that simply\\nstates if the module requires its own package to be trusted. This field avoids\\nus having to load all interface files that the module depends on to see if one\\nis trustworthy.\\n\\n\\nNote [Trust Transitive Property]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSo there is an interesting design question in regards to transitive trust\\nchecking. Say I have a module B compiled with -XSafe. B is dependent on a bunch\\nof modules and packages, some packages it requires to be trusted as its using\\n-XTrustworthy modules from them. Now if I have a module A that doesn\'t use safe\\nhaskell at all and simply imports B, should A inherit all the trust\\nrequirements from B? Should A now also require that a package p is trusted since\\nB required it?\\n\\nWe currently say no but saying yes also makes sense. The difference is, if a\\nmodule M that doesn\'t use Safe Haskell imports a module N that does, should all\\nthe trusted package requirements be dropped since M didn\'t declare that it cares\\nabout Safe Haskell (so -XSafe is more strongly associated with the module doing\\nthe importing) or should it be done still since the author of the module N that\\nuses Safe Haskell said they cared (so -XSafe is more strongly associated with\\nthe module that was compiled that used it).\\n\\nGoing with yes is a simpler semantics we think and harder for the user to stuff\\nup but it does mean that Safe Haskell will affect users who don\'t care about\\nSafe Haskell as they might grab a package from Cabal which uses safe haskell (say\\nnetwork) and that packages imports -XTrustworthy modules from another package\\n(say bytestring), so requires that package is trusted. The user may now get\\ncompilation errors in code that doesn\'t do anything with Safe Haskell simply\\nbecause they are using the network package. They will have to call \'ghc-pkg\\ntrust network\' to get everything working. Due to this invasive nature of going\\nwith yes we have gone with no for now.\\n-}\\n\\n-- | Process Import Decls. See \'rnImportDecl\' for a description of what\\n-- the return types represent.\\n-- Note: Do the non SOURCE ones first, so that we get a helpful warning\\n-- for SOURCE ones that are unnecessary\\nrnImports :: [(LImportDecl GhcPs, SDoc)]\\n -> RnM ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\nrnImports imports = do\\n tcg_env <- getGblEnv\\n -- NB: want an identity module here, because it\'s OK for a signature\\n -- module to import from its implementor\\n let this_mod = tcg_mod tcg_env\\n let (source, ordinary) = partition (is_source_import . fst) imports\\n is_source_import (d::LImportDecl GhcPs) = ideclSource (unLoc d) == IsBoot\\n stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary\\n stuff2 <- mapAndReportM (rnImportDecl this_mod) source\\n -- Safe Haskell: See Note [Tracking Trust Transitively]\\n let (decls, imp_user_spec, rdr_env, imp_avails) = combine (stuff1 ++ stuff2)\\n -- Update imp_boot_mods if imp_direct_mods mentions any of them\\n let merged_import_avail = clobberSourceImports imp_avails\\n return (decls, imp_user_spec, rdr_env, merged_import_avail)\\n\\n where\\n clobberSourceImports imp_avails =\\n imp_avails { imp_boot_mods = imp_boot_mods\' }\\n where\\n imp_boot_mods\' = mergeInstalledModuleEnv combJ id (const emptyInstalledModuleEnv)\\n (imp_boot_mods imp_avails)\\n (imp_direct_dep_mods imp_avails)\\n\\n combJ (GWIB _ IsBoot) (_, x) = Just x\\n combJ r _ = Just r\\n -- See Note [Combining ImportAvails]\\n combine :: [(LImportDecl GhcRn, ImportUserSpec, GlobalRdrEnv, ImportAvails)]\\n -> ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\n combine ss =\\n let (decls, imp_user_spec, rdr_env, imp_avails, finsts) = foldr\\n plus\\n ([], [], emptyGlobalRdrEnv, emptyImportAvails, emptyModuleSet)\\n ss\\n in (decls, imp_user_spec, rdr_env, imp_avails { imp_finsts = moduleSetElts finsts })\\n\\n plus (decl, us, gbl_env1, imp_avails1)\\n (decls, uss, gbl_env2, imp_avails2, finsts_set)\\n = ( decl:decls,\\n us:uss,\\n gbl_env1 `plusGlobalRdrEnv` gbl_env2,\\n imp_avails1\' `plusImportAvails` imp_avails2,\\n extendModuleSetList finsts_set new_finsts )\\n where\\n imp_avails1\' = imp_avails1 { imp_finsts = [] }\\n new_finsts = imp_finsts imp_avails1\\n\\n{-\\nNote [Combining ImportAvails]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nimp_finsts in ImportAvails is a list of family instance modules\\ntransitively depended on by an import. imp_finsts for a currently\\ncompiled module is a union of all the imp_finsts of imports.\\nComputing the union of two lists of size N is O(N^2) and if we\\ndo it to M imports we end up with O(M*N^2). That can get very\\nexpensive for bigger module hierarchies.\\n\\nUnion can be optimized to O(N log N) if we use a Set.\\nimp_finsts is converted back and forth between dep_finsts, so\\nchanging a type of imp_finsts means either paying for the conversions\\nor changing the type of dep_finsts as well.\\n\\nI\'ve measured that the conversions would cost 20% of allocations on my\\ntest case, so that can be ruled out.\\n\\nChanging the type of dep_finsts forces checkFamInsts to\\nget the module lists in non-deterministic order. If we wanted to restore\\nthe deterministic order, we\'d have to sort there, which is an additional\\ncost. As far as I can tell, using a non-deterministic order is fine there,\\nbut that\'s a brittle nonlocal property which I\'d like to avoid.\\n\\nAdditionally, dep_finsts is read from an interface file, so its \\"natural\\"\\ntype is a list. Which makes it a natural type for imp_finsts.\\n\\nSince rnImports.combine is really the only place that would benefit from\\nit being a Set, it makes sense to optimize the hot loop in rnImports.combine\\nwithout changing the representation.\\n\\nSo here\'s what we do: instead of naively merging ImportAvails with\\nplusImportAvails in a loop, we make plusImportAvails merge empty imp_finsts\\nand compute the union on the side using Sets. When we\'re done, we can\\nconvert it back to a list. One nice side effect of this approach is that\\nif there\'s a lot of overlap in the imp_finsts of imports, the\\nSet doesn\'t really need to grow and we don\'t need to allocate.\\n\\nRunning generateModules from #14693 with DEPTH=16, WIDTH=30 finishes in\\n23s before, and 11s after.\\n-}\\n\\n-- | Given a located import declaration @decl@ from @this_mod@,\\n-- calculate the following pieces of information:\\n--\\n-- 1. An updated \'LImportDecl\', where all unresolved \'RdrName\' in\\n-- the entity lists have been resolved into \'Name\'s,\\n--\\n-- 2. A \'GlobalRdrEnv\' representing the new identifiers that were\\n-- brought into scope (taking into account module qualification\\n-- and hiding),\\n--\\n-- 3. \'ImportAvails\' summarizing the identifiers that were imported\\n-- by this declaration, and\\n--\\n-- 4. A boolean \'AnyHpcUsage\' which is true if the imported module\\n-- used HPC.\\nrnImportDecl :: Module -> (LImportDecl GhcPs, SDoc)\\n -> RnM (LImportDecl GhcRn, ImportUserSpec , GlobalRdrEnv, ImportAvails)\\nrnImportDecl this_mod\\n (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name\\n , ideclPkgQual = raw_pkg_qual\\n , ideclSource = want_boot\\n , ideclSafe = mod_safe\\n , ideclLevelSpec = import_level\\n , ideclQualified = qual_style\\n , ideclExt = XImportDeclPass { ideclOrigin = origin }\\n , ideclAs = as_mod, ideclImportList = imp_details }), import_reason)\\n = setSrcSpanA loc $ do\\n\\n case raw_pkg_qual of\\n NoRawPkgQual -> pure ()\\n RawPkgQual {} -> do\\n pkg_imports <- xoptM LangExt.PackageImports\\n when (not pkg_imports) $ addErr TcRnPackageImportsDisabled\\n\\n let qual_only = isImportDeclQualified qual_style\\n generated = isGeneratedImport origin\\n\\n lookup_scope = importDeclLookupScope origin\\n\\n -- If there\'s an error in loadInterface, (e.g. interface\\n -- file not found) we get lots of spurious errors from \'filterImports\'\\n let imp_mod_name = unLoc loc_imp_mod_name\\n doc = ppr imp_mod_name <+> import_reason\\n\\n hsc_env <- getTopEnv\\n unit_env <- hsc_unit_env <$> getTopEnv\\n let pkg_qual = renameRawPkgQual unit_env imp_mod_name raw_pkg_qual\\n\\n -- Check for self-import, which confuses the typechecker (#9032)\\n -- ghc --make rejects self-import cycles already, but batch-mode may not\\n -- at least not until GHC.IfaceToCore.tcHiBootIface, which is too late to avoid\\n -- typechecker crashes. (Indirect self imports are not caught until\\n -- GHC.IfaceToCore, see #10337 tracking how to make this error better.)\\n --\\n -- Originally, we also allowed \'import {-# SOURCE #-} M\', but this\\n -- caused bug #10182: in one-shot mode, we should never load an hs-boot\\n -- file for the module we are compiling into the EPS. In principle,\\n -- it should be possible to support this mode of use, but we would have to\\n -- extend Provenance to support a local definition in a qualified location.\\n -- For now, we don\'t support it, but see #10336\\n when (imp_mod_name == moduleName this_mod &&\\n (case pkg_qual of -- If we have import \\"\\" M, then we should\\n -- check that \\"\\" is \\"this\\" (which is magic)\\n -- or the name of this_mod\'s package. Yurgh!\\n -- c.f. GHC.findModule, and #9997\\n NoPkgQual -> True\\n ThisPkg uid -> uid == homeUnitId_ (hsc_dflags hsc_env)\\n OtherPkg _ -> False))\\n (addErr (TcRnSelfImport imp_mod_name))\\n\\n -- Check for a missing import list (Opt_WarnMissingImportList also\\n -- checks for T(..) items but that is done in checkDodgyImport below)\\n case imp_details of\\n Just (Exactly, _) -> return () -- Explicit import list\\n _ | generated -> return () -- Do not bleat for generated imports\\n | qual_only -> return ()\\n | otherwise -> addDiagnostic (TcRnNoExplicitImportList imp_mod_name)\\n\\n\\n mb_iface <- loadSrcInterface_maybe doc lookup_scope imp_mod_name want_boot pkg_qual\\n iface <- case mb_iface of\\n Succeeded iface -> return iface\\n Failed err -> failWithTc $\\n importDeclLoadFailure origin imp_mod_name want_boot err\\n\\n -- Compiler sanity check: if the import didn\'t say\\n -- {-# SOURCE #-} we should not get a hi-boot file\\n warnPprTrace ((want_boot == NotBoot) && (mi_boot iface == IsBoot)) \\"rnImportDecl\\" (ppr imp_mod_name) $ do\\n\\n -- Issue a user warning for a redundant {- SOURCE -} import\\n -- NB that we arrange to read all the ordinary imports before\\n -- any of the {- SOURCE -} imports.\\n --\\n -- in --make and GHCi, the compilation manager checks for this,\\n -- and indeed we shouldn\'t do it here because the existence of\\n -- the non-boot module depends on the compilation order, which\\n -- is not deterministic. The hs-boot test can show this up.\\n dflags <- getDynFlags\\n warnIf ((want_boot == IsBoot) && (mi_boot iface == NotBoot) && isOneShot (ghcMode dflags))\\n (TcRnRedundantSourceImport imp_mod_name)\\n when (mod_safe && not (safeImportsOn dflags)) $\\n addErr (TcRnSafeImportsDisabled imp_mod_name)\\n\\n let imp_mod = mi_module iface\\n qual_mod_name = fmap unLoc as_mod `orElse` imp_mod_name\\n imp_spec = ImpDeclSpec { is_mod = imp_mod, is_qual = qual_only,\\n is_dloc = locA loc, is_as = qual_mod_name,\\n is_pkg_qual = pkg_qual, is_isboot = want_boot,\\n is_level = convImportLevel import_level }\\n\\n let filter_imports = do\\n -- filter the imports according to the import declaration\\n (new_imp_details, imp_user_list, gbl_env)\\n <- filterImports hsc_env iface imp_spec imp_details\\n -- for certain error messages, we\\u2019d like to know what could be\\n -- imported here, if everything were imported\\n potential_gres <- (\\\\(_,_,x) -> x) <$> filterImports hsc_env iface imp_spec Nothing\\n return (new_imp_details, imp_user_list, gbl_env, potential_gres)\\n\\n (new_imp_details, imp_user_list, gbl_env, potential_gres) <-\\n case origin of\\n ImplicitEssentialsImport ->\\n -- The implicit GHC.Essentials import does not bring anything into scope.\\n -- See Note [Finding GHC.Essentials] in GHC.Builtin.\\n return (Nothing, ImpUserDependOnly, emptyGlobalRdrEnv, emptyGlobalRdrEnv)\\n UserWrittenImport -> filter_imports\\n ImplicitPreludeImport -> filter_imports\\n PluginImport -> filter_imports\\n\\n let is_hiding | Just (EverythingBut,_) <- imp_details = True\\n | otherwise = False\\n\\n -- should the import be safe?\\n mod_safe\' = mod_safe\\n || (not generated && safeDirectImpsReq dflags)\\n || (generated && safeImplicitImpsReq dflags)\\n\\n hsc_env <- getTopEnv\\n let home_unit = hsc_home_unit hsc_env\\n other_home_units = hsc_all_home_unit_ids hsc_env\\n\\n imported_by\\n | isDependOnlyImport imp_user_list\\n = ImportedBySystem\\n | otherwise\\n = ImportedByUser $ ImportedModsVal\\n { imv_name = is_as imp_spec\\n , imv_span = locA loc\\n , imv_is_safe = mod_safe\'\\n , imv_is_hiding = is_hiding\\n , imv_all_exports = potential_gres\\n , imv_qualified = qual_only\\n , imv_is_level = convImportLevel import_level\\n }\\n imports = calculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by\\n\\n -- Complain if we import a deprecated module\\n case fromIfaceWarnings (mi_warns iface) of\\n WarnAll txt -> addDiagnostic (TcRnDeprecatedModule imp_mod_name txt)\\n _ -> return ()\\n\\n let new_imp_decl = ImportDecl\\n { ideclExt = ideclExt decl\\n , ideclName = ideclName decl\\n , ideclPkgQual = pkg_qual\\n , ideclSource = ideclSource decl\\n , ideclSafe = mod_safe\'\\n , ideclQualified = ideclQualified decl\\n , ideclAs = ideclAs decl\\n , ideclImportList = new_imp_details\\n , ideclLevelSpec = ideclLevelSpec decl\\n }\\n\\n return (L loc new_imp_decl, ImpUserSpec imp_spec imp_user_list, gbl_env, imports)\\n\\n-- | The error message to emit when we failed to load an interface.\\nimportDeclLoadFailure :: ImportDeclOrigin -> ModuleName -> IsBootInterface\\n -> MissingInterfaceError -> TcRnMessage\\nimportDeclLoadFailure ImplicitEssentialsImport _ _ err\\n = TcRnInterfaceError $ CantFindEssentials err LookingForEssentialsModule\\nimportDeclLoadFailure _ mod_name want_boot err\\n = TcRnInterfaceError $ Can\'tFindInterface err $ LookingForModule mod_name want_boot\\n\\n-- | Rename raw package imports\\nrenameRawPkgQual :: UnitEnv -> ModuleName -> RawPkgQual -> PkgQual\\nrenameRawPkgQual unit_env mn = \\\\case\\n NoRawPkgQual -> NoPkgQual\\n RawPkgQual _ fs -> renamePkgQual unit_env mn $ Just fs\\n\\n-- | Rename raw package imports\\nrenamePkgQual :: UnitEnv -> ModuleName -> Maybe FastString -> PkgQual\\nrenamePkgQual unit_env mn mb_pkg = case mb_pkg of\\n Nothing -> NoPkgQual\\n Just pkg_fs\\n | Just uid <- homeUnitId <$> ue_homeUnit unit_env\\n , pkg_fs == fsLit \\"this\\"\\n -> ThisPkg uid\\n\\n | Just (uid, _) <- find (fromMaybe False . fmap (== pkg_fs) . snd) home_names\\n -> ThisPkg uid\\n\\n | Just uid <- resolvePackageImport unit_state mn (PackageName pkg_fs)\\n -> OtherPkg uid\\n\\n | otherwise\\n -> OtherPkg (UnitId pkg_fs)\\n -- not really correct as pkg_fs is unlikely to be a valid unit-id but\\n -- we will report the failure later...\\n where\\n home_names =\\n [ (uid, mkFastString <$> thisPackageName (homeUnitEnv_dflags (ue_findHomeUnitEnv uid unit_env)))\\n | uid <- S.toList hpt_deps\\n ]\\n\\n unit_state = ue_homeUnitState unit_env\\n\\n hpt_deps :: S.Set UnitId\\n hpt_deps = homeUnitDepends unit_state\\n\\n\\n-- | Calculate the \'ImportAvails\' induced by an import of a particular\\n-- interface, but without \'imp_mods\'.\\ncalculateAvails :: HomeUnit\\n -> S.Set UnitId\\n -> ModIface\\n -> IsSafeImport\\n -> IsBootInterface\\n -> ImportedBy\\n -> ImportAvails\\ncalculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by =\\n let imp_mod = mi_module iface\\n imp_sem_mod= mi_semantic_module iface\\n orph_iface = mi_orphan iface\\n has_finsts = mi_finsts iface\\n deps = mi_deps iface\\n trust = getSafeMode $ mi_trust iface\\n trust_pkg = mi_trust_pkg iface\\n is_sig = mi_hsc_src iface == HsigFile\\n\\n -- If the module exports anything defined in this module, just\\n -- ignore it. Reason: otherwise it looks as if there are two\\n -- local definition sites for the thing, and an error gets\\n -- reported. Easiest thing is just to filter them out up\\n -- front. This situation only arises if a module imports\\n -- itself, or another module that imported it. (Necessarily,\\n -- this involves a loop.)\\n --\\n -- We do this *after* filterImports, so that if you say\\n -- module A where\\n -- import B( AType )\\n -- type AType = ...\\n --\\n -- module B( AType ) where\\n -- import {-# SOURCE #-} A( AType )\\n --\\n -- then you won\'t get a \'B does not export AType\' message.\\n\\n\\n -- Compute new transitive dependencies\\n --\\n -- \'dep_orphs\' and \'dep_finsts\' do NOT include the imported module\\n -- itself, but we DO need to include this module in \'imp_orphs\' and\\n -- \'imp_finsts\' if it defines an orphan or instance family; thus the\\n -- orph_iface/has_iface tests.\\n\\n deporphs = dep_orphs deps\\n depfinsts = dep_finsts deps\\n\\n orphans | orph_iface = assertPpr (not (imp_sem_mod `elem` deporphs)) (ppr imp_sem_mod <+> ppr deporphs) $\\n imp_sem_mod : deporphs\\n | otherwise = deporphs\\n\\n finsts | has_finsts = assertPpr (not (imp_sem_mod `elem` depfinsts)) (ppr imp_sem_mod <+> ppr depfinsts) $\\n imp_sem_mod : depfinsts\\n | otherwise = depfinsts\\n\\n -- Trusted packages are a lot like orphans.\\n trusted_pkgs | mod_safe\' = dep_trusted_pkgs deps\\n | otherwise = S.empty\\n\\n\\n pkg = moduleUnit (mi_module iface)\\n ipkg = toUnitId pkg\\n\\n -- Does this import mean we now require our own pkg\\n -- to be trusted? See Note [Trust Own Package]\\n ptrust = trust == Sf_Trustworthy || trust_pkg\\n pkg_trust_req\\n | isHomeUnit home_unit pkg = ptrust\\n | otherwise = False\\n\\n dependent_pkgs = if toUnitId pkg `S.member` other_home_units\\n then S.empty\\n else S.singleton (lvl, ipkg)\\n\\n lvl = case imported_by of\\n ImportedByUser imv -> imv_is_level imv\\n ImportedBySystem -> NormalLevel\\n\\n\\n direct_mods = if toUnitId pkg `S.member` other_home_units\\n then mkPlusModDeps (moduleUnitId imp_mod) lvl (GWIB (moduleName imp_mod) want_boot)\\n else emptyInstalledModuleEnv\\n\\n dep_boot_mods_map = mkModDeps (dep_boot_mods deps)\\n\\n\\n boot_mods\\n -- If we are looking for a boot module, it must be HPT\\n | IsBoot <- want_boot = extendInstalledModuleEnv dep_boot_mods_map (toUnitId <$> imp_mod) (GWIB (moduleName imp_mod) IsBoot)\\n -- Now we are importing A properly, so don\'t go looking for\\n -- A.hs-boot\\n | isHomeUnit home_unit pkg = dep_boot_mods_map\\n -- There\'s no boot files to find in external imports\\n | otherwise = emptyInstalledModuleEnv\\n\\n sig_mods =\\n if is_sig\\n then moduleName imp_mod : dep_sig_mods deps\\n else dep_sig_mods deps\\n\\n\\n in ImportAvails {\\n imp_mods = Map.singleton (mi_module iface) [imported_by],\\n imp_orphs = orphans,\\n imp_finsts = finsts,\\n imp_sig_mods = sig_mods,\\n imp_direct_dep_mods = direct_mods,\\n imp_dep_direct_pkgs = dependent_pkgs,\\n imp_boot_mods = boot_mods,\\n\\n -- Add in the imported modules trusted package\\n -- requirements. ONLY do this though if we import the\\n -- module as a safe import.\\n -- See Note [Tracking Trust Transitively]\\n -- and Note [Trust Transitive Property]\\n imp_trust_pkgs = trusted_pkgs,\\n -- Do we require our own pkg to be trusted?\\n -- See Note [Trust Own Package]\\n imp_trust_own_pkg = pkg_trust_req\\n }\\n\\nmkPlusModDeps :: UnitId -> ImportLevel -> ModuleNameWithIsBoot\\n -> InstalledModuleEnv (S.Set ImportLevel, ModuleNameWithIsBoot)\\nmkPlusModDeps uid st elt = extendInstalledModuleEnv emptyInstalledModuleEnv (mkModule uid (gwib_mod elt)) (S.singleton st, elt)\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{importsFromLocalDecls}\\n* *\\n************************************************************************\\n\\nFrom the top-level declarations of this module produce\\n * the lexical environment\\n * the ImportAvails\\ncreated by its bindings.\\n\\nNote [Top-level Names in Template Haskell decl quotes]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSee also: Note [Interactively-bound Ids in GHCi] in GHC.Driver.Env\\n Note [Looking up Exact RdrNames] in GHC.Rename.Env\\n\\nConsider a Template Haskell declaration quotation like this:\\n module M where\\n f x = h [d| f = 3 |]\\nWhen renaming the declarations inside [d| ...|], we treat the\\ntop level binders specially in two ways\\n\\n1. We give them an Internal Name, not (as usual) an External one.\\n This is done by GHC.Rename.Env.newTopSrcBinder.\\n\\n2. We make them *shadow* the outer bindings.\\n See Note [GlobalRdrEnv shadowing]\\n\\n3. We find out whether we are inside a [d| ... |] by testing the TH\\n level. This is a slight hack, because the level field was really\\n meant for the type checker, and here we are not interested in the\\n fields of Brack, hence the error thunks in thRnBrack.\\n-}\\n\\nextendGlobalRdrEnvRn :: [GlobalRdrElt]\\n -> MiniFixityEnv\\n -> RnM (TcGblEnv, TcLclEnv)\\n-- Updates both the GlobalRdrEnv and the FixityEnv\\n-- We return a new TcLclEnv only because we might have to\\n-- delete some bindings from it;\\n-- see Note [Top-level Names in Template Haskell decl quotes]\\n\\nextendGlobalRdrEnvRn new_gres new_fixities\\n = checkNoErrs $ -- See Note [Fail fast on duplicate definitions]\\n do { (gbl_env, lcl_env) <- getEnvs\\n ; level <- getThLevel\\n ; isGHCi <- getIsGHCi\\n ; let rdr_env = tcg_rdr_env gbl_env\\n fix_env = tcg_fix_env gbl_env\\n th_bndrs = getLclEnvThBndrs lcl_env\\n th_lvl = thLevelIndex level\\n\\n -- Delete new_occs from global and local envs\\n -- If we are in a TemplateHaskell decl bracket,\\n -- we are going to shadow them\\n -- See Note [GlobalRdrEnv shadowing]\\n inBracket = isBrackLevel level\\n\\n lcl_env_TH = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_rdr = minusLocalRdrEnv (tcl_rdr lcl_env) new_gres_env }) lcl_env\\n -- See Note [GlobalRdrEnv shadowing]\\n\\n lcl_env2 | inBracket = lcl_env_TH\\n | otherwise = lcl_env\\n\\n -- Deal with shadowing: see Note [GlobalRdrEnv shadowing]\\n want_shadowing = isGHCi || inBracket\\n rdr_env1 | want_shadowing = shadowNames False rdr_env new_gres_env\\n | otherwise = rdr_env\\n\\n lcl_env3 = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_th_bndrs = extendNameEnvList th_bndrs\\n [ ( n, (TopLevel, th_lvl) )\\n | n <- new_names ] }) lcl_env2\\n\\n ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres\\n\\n ; let fix_env\' = foldl\' extend_fix_env fix_env new_gres\\n gbl_env\' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env\' }\\n\\n ; traceRn \\"extendGlobalRdrEnvRn 2\\" (pprGlobalRdrEnv True rdr_env2)\\n ; return (gbl_env\', lcl_env3) }\\n where\\n new_names = map greName new_gres\\n new_gres_env = mkGlobalRdrEnv new_gres\\n\\n -- If there is a fixity decl for the gre, add it to the fixity env\\n extend_fix_env fix_env gre\\n | Just (L _ fi) <- lookupMiniFixityEnv new_fixities name\\n = extendNameEnv fix_env name (FixItem occ fi)\\n | otherwise\\n = fix_env\\n where\\n name = greName gre\\n occ = greOccName gre\\n\\n add_gre :: GlobalRdrEnv -> GlobalRdrElt -> RnM GlobalRdrEnv\\n -- Extend the GlobalRdrEnv with a LocalDef GRE\\n -- If there is already a LocalDef GRE with the same OccName,\\n -- report an error and discard the new GRE\\n -- This establishes INVARIANT 1 of GlobalRdrEnvs\\n add_gre env gre\\n | not (null dups) -- Same OccName defined twice\\n = do { addDupDeclErr (gre :| dups); return env }\\n\\n | otherwise\\n = return (extendGlobalRdrEnv env gre)\\n where\\n -- See Note [Reporting duplicate local declarations]\\n dups = filter isBadDupGRE\\n $ lookupGRE env (LookupOccName (greOccName gre) (RelevantGREsFOS WantBoth))\\n isBadDupGRE old_gre = isLocalGRE old_gre && greClashesWith gre old_gre\\n\\n{- Note [Fail fast on duplicate definitions]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIf there are duplicate bindings for the same thing, we want to fail\\nfast. Having two bindings for the same thing can cause follow-on errors.\\nExample (test T9975a):\\n data Test = Test { x :: Int }\\n pattern Test wat = Test { x = wat }\\nThis defines \'Test\' twice. The second defn has no field-names; and then\\nwe get an error from Test { x=wat }, saying \\"Test has no field \'x\'\\".\\n\\nEasiest thing is to bale out fast on duplicate definitions, which\\nwe do via `checkNoErrs` on `extendGlobalRdrEnvRn`.\\n\\nNote [Reporting duplicate local declarations]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn general, a single module may not define the same OccName multiple times. This\\nis checked in extendGlobalRdrEnvRn: when adding a new locally-defined GRE to the\\nGlobalRdrEnv we report an error if there are already duplicates in the\\nenvironment. This establishes INVARIANT 1 (see comments on GlobalRdrEnv in\\nGHC.Types.Name.Reader), which says that for a given OccName, all the\\nGlobalRdrElts to which it maps must have distinct \'greName\'s.\\n\\nFor example, the following will be rejected:\\n\\n f x = x\\n g x = x\\n f x = x -- Duplicate!\\n\\nUsers are allowed to introduce new GREs with the same OccName as an imported GRE,\\nas disambiguation is possible through the module system, e.g.:\\n\\n module M where\\n import N (f)\\n f x = x\\n g x = M.f x + N.f x\\n\\nIf both GREs are local, the general rule is that two GREs clash if they have\\nthe same OccName, i.e. they share a textual name and live in the same namespace.\\nHowever, there are additional clashes due to record fields:\\n\\n - a new variable clashes with previously defined record fields\\n which define field selectors,\\n\\n - a new record field shadows:\\n\\n - previously defined variables, if it defines a field selector,\\n - previously defined record fields, unless it is a duplicate record field.\\n\\nThis logic is implemented in the function \'GHC.Types.Name.Reader.greClashesWith\'.\\n\\nSee also Note [Skipping ambiguity errors at use sites of local declarations] in\\nGHC.Rename.Utils.\\n-}\\n\\n\\n{- *********************************************************************\\n* *\\n getLocalDeclBindersd@ returns the names for an HsDecl\\n It\'s used for source code.\\n\\n *** See Note [The Naming story] in GHC.Hs.Decls ****\\n* *\\n********************************************************************* -}\\n\\ngetLocalNonValBinders :: MiniFixityEnv -> HsGroup GhcPs\\n -> RnM ((TcGblEnv, TcLclEnv), NameSet)\\n-- Get all the top-level binders bound the group *except*\\n-- for value bindings, which are treated separately\\n-- Specifically we return AvailInfo for\\n-- * type decls (incl constructors and record selectors)\\n-- * class decls (including class ops)\\n-- * associated types\\n-- * foreign imports\\n-- * value signatures (in hs-boot files only)\\n\\ngetLocalNonValBinders fixity_env\\n (HsGroup { hs_valds = binds,\\n hs_tyclds = tycl_decls,\\n hs_fords = foreign_decls })\\n = do { -- Process all type/class decls *except* family instances\\n ; let inst_decls = tycl_decls >>= group_instds\\n ; dup_fields_ok <- xopt_DuplicateRecordFields <$> getDynFlags\\n ; has_sel <- xopt_FieldSelectors <$> getDynFlags\\n ; tc_gres\\n <- concatMapM\\n (new_tc dup_fields_ok has_sel)\\n (tyClGroupTyClDecls tycl_decls)\\n ; traceRn \\"getLocalNonValBinders 1\\" (ppr tc_gres)\\n ; envs <- extendGlobalRdrEnvRn tc_gres fixity_env\\n ; restoreEnvs envs $ do {\\n -- Bring these things into scope first\\n -- See Note [Looking up family names in family instances]\\n\\n -- Process all family instances\\n -- to bring new data constructors into scope\\n ; nti_gress <- mapM (new_assoc dup_fields_ok has_sel) inst_decls\\n\\n -- Finish off with value binders:\\n -- foreign decls and pattern synonyms for an ordinary module\\n -- type sigs in case of a hs-boot file only\\n ; is_boot <- tcIsHsBootOrSig\\n ; let val_bndrs\\n | is_boot = case binds of\\n ValBinds _ val_binds ->\\n -- In a hs-boot file, the value binders come from the\\n -- *signatures*, and there should be no foreign binders\\n [ L (l2l decl_loc) (unLoc n)\\n | L decl_loc (TypeSig _ _ ns _) <- (val_sigs val_binds), n <- ns]\\n _ -> panic \\"Non-ValBinds in hs-boot group\\"\\n | otherwise = for_hs_bndrs\\n ; val_gres <- mapM new_simple val_bndrs\\n\\n ; let avails = concat nti_gress ++ val_gres\\n new_bndrs = gresToNameSet avails `unionNameSet`\\n gresToNameSet tc_gres\\n ; traceRn \\"getLocalNonValBinders 2\\" (ppr avails)\\n ; envs <- extendGlobalRdrEnvRn avails fixity_env\\n ; return (envs, new_bndrs) } }\\n where\\n for_hs_bndrs :: [LocatedN RdrName]\\n for_hs_bndrs = hsForeignDeclsBinders foreign_decls\\n\\n -- the SrcSpan attached to the input should be the span of the\\n -- declaration, not just the name\\n new_simple :: LocatedN RdrName -> RnM GlobalRdrElt\\n new_simple rdr_name = do { nm <- newTopSrcBinder rdr_name\\n ; return (mkLocalVanillaGRE NoParent nm) }\\n\\n new_tc :: DuplicateRecordFields -> FieldSelectors -> LTyClDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_tc dup_fields_ok has_sel tc_decl -- NOT for type/data instances\\n = do { let TyDeclBinders (main_bndr, tc_flav) at_bndrs sig_bndrs\\n (LConsWithFields cons_with_flds flds) = hsLTyClDeclBinders tc_decl\\n ; tycon_name <- newTopSrcBinder $ la2la main_bndr\\n ; at_names <- mapM (newTopSrcBinder . la2la . fst) at_bndrs\\n ; sig_names <- mapM (newTopSrcBinder . la2la) sig_bndrs\\n ; con_names_with_flds <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst con_names_with_flds) flds\\n ; mapM_ (add_dup_fld_errs flds\') con_names_with_flds\\n ; let tc_gre = mkLocalTyConGRE (fmap (const tycon_name) tc_flav) tycon_name\\n fld_env = mk_fld_env con_names_with_flds flds\'\\n at_gres = zipWith (\\\\ (_, at_flav) at_nm -> mkLocalTyConGRE (fmap (const tycon_name) at_flav) at_nm)\\n at_bndrs at_names\\n sig_gres = map (mkLocalVanillaGRE (ParentIs tycon_name)) sig_names\\n con_gres = map (mkLocalConLikeGRE (ParentIs tycon_name)) fld_env\\n fld_gres = mkLocalFieldGREs (ParentIs tycon_name) fld_env\\n sub_gres = at_gres ++ sig_gres ++ con_gres ++ fld_gres\\n ; traceRn \\"getLocalNonValBinders new_tc\\" $\\n vcat [ text \\"tycon:\\" <+> ppr tycon_name\\n , text \\"tc_gre:\\" <+> ppr tc_gre\\n , text \\"sub_gres:\\" <+> ppr sub_gres ]\\n ; return $ tc_gre : sub_gres }\\n\\n -- Calculate the record field information, which feeds into the GlobalRdrElts\\n -- for DataCons and their fields. It\'s convenient to do this here where\\n -- we are working with a single datatype definition.\\n --\\n -- The information we needed was all set up for us:\\n -- see Note [Collecting record fields in data declarations] in GHC.Hs.Utils.\\n mk_fld_env :: [(Name, Either VisArity [Located Int])] -> IntMap FieldLabel\\n -> [(ConLikeName, ConInfo)]\\n mk_fld_env names flds =\\n [ (DataConName con, ConInfo (ConIsData (map fst names)) fld_info)\\n | (con, con_fl_indxs) <- names\\n , let fld_info = case fmap (map ((flds IntMap.!) . unLoc)) con_fl_indxs of\\n Left 0 -> ConIsNullary\\n Left arity -> ConHasPositionalArgs arity\\n Right [] -> ConIsNullary\\n Right (fld:flds) -> ConHasRecordFields $ fld NE.:| flds ]\\n\\n new_assoc :: DuplicateRecordFields -> FieldSelectors -> LInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_assoc _ _ (L _ (TyFamInstD {})) = return []\\n -- type instances don\'t bind new names\\n\\n new_assoc dup_fields_ok has_sel (L _ (DataFamInstD _ d))\\n = new_di dup_fields_ok has_sel Nothing d\\n new_assoc dup_fields_ok has_sel\\n (L _ (ClsInstD _ (ClsInstDecl { cid_poly_ty = inst_ty\\n , cid_decls = decls })))\\n = do -- First, attempt to grab the name of the class from the instance.\\n -- This step could fail if the instance is not headed by a class,\\n -- such as in the following examples:\\n --\\n -- (1) The class is headed by a bang pattern, such as in\\n -- `instance !Show Int` (#3811c)\\n -- (2) The class is headed by a type variable, such as in\\n -- `instance c` (#16385)\\n --\\n -- If looking up the class name fails, then mb_cls_gre will\\n -- be Nothing.\\n mb_cls_gre <- runMaybeT $ do\\n -- See (1) above\\n L loc cls_rdr <- MaybeT $ pure $ getLHsInstDeclClass_maybe inst_ty\\n -- See (2) above\\n MaybeT $ setSrcSpan (locA loc) $ lookupGlobalOccRn_maybe SameNameSpace cls_rdr\\n -- Assuming the previous step succeeded, process any associated data\\n -- family instances. If the previous step failed, bail out.\\n case mb_cls_gre of\\n Nothing\\n -> pure []\\n Just cls_gre\\n -> let cls_nm = greName cls_gre\\n in concatMapM (new_di dup_fields_ok has_sel (Just cls_nm) . unLoc) (data_fam_insts decls)\\n\\n data_fam_insts decls = concatMap get decls\\n where\\n get (L l (InstD _ (DataFamInstD { dfid_inst = d}))) = [L l d]\\n get _ = []\\n\\n new_di :: DuplicateRecordFields -> FieldSelectors\\n -> Maybe Name -- class name\\n -> DataFamInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_di dup_fields_ok has_sel mb_cls dfid@(DataFamInstDecl { dfid_eqn = ti_decl })\\n = do { main_name <- unLoc <$> lookupFamInstName mb_cls (feqn_tycon ti_decl)\\n ; let LConsWithFields cons_with_flds flds = hsDataFamInstBinders dfid\\n ; sub_names <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst sub_names) flds\\n ; mapM_ (add_dup_fld_errs flds\') sub_names\\n ; let fld_env = mk_fld_env sub_names flds\'\\n con_gres = map (mkLocalConLikeGRE (ParentIs main_name)) fld_env\\n field_gres = mkLocalFieldGREs (ParentIs main_name) fld_env\\n -- NB: the data family name is not bound here,\\n -- so we don\'t return a GlobalRdrElt for it here!\\n ; return $ con_gres ++ field_gres }\\n\\n -- Add errors if a constructor has a duplicate record field.\\n add_dup_fld_errs :: IntMap FieldLabel\\n -> (Name, Either VisArity [Located Int])\\n -> IOEnv (Env TcGblEnv TcLclEnv) ()\\n add_dup_fld_errs all_flds (con, con_flds_or_arity)\\n | Right con_flds <- con_flds_or_arity\\n , let (_, dups) = removeDups (comparing unLoc) con_flds\\n = for_ dups $ \\\\ dup_flds ->\\n -- Report the error at the location of the second occurrence\\n -- of the duplicate field.\\n let loc =\\n case dup_flds of\\n _ :| ( L loc _ : _) -> loc\\n L loc _ :| _ -> loc\\n dup_rdrs = fmap (nameRdrName . flSelector . (all_flds IntMap.!) . unLoc) dup_flds\\n in addErrAt loc $ TcRnDuplicateFieldName (RecordFieldDecl con) dup_rdrs\\n | otherwise\\n = return ()\\n\\nnewRecordFieldLabel :: DuplicateRecordFields -> FieldSelectors -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel\\nnewRecordFieldLabel _ _ [] _ = error \\"newRecordFieldLabel: datatype has no constructors!\\"\\nnewRecordFieldLabel dup_fields_ok has_sel (dc:_) (L loc (FieldOcc _ (L _ fld)))\\n = do { selName <- newTopSrcBinder $ L (l2l loc) $ field\\n ; return $ FieldLabel { flHasDuplicateRecordFields = dup_fields_ok\\n , flHasFieldSelector = has_sel\\n , flSelector = selName } }\\n where\\n fld_occ = rdrNameOcc fld\\n dc_fs = occNameFS $ nameOccName dc\\n field\\n -- Use an Exact RdrName as-is, to preserve the bindings\\n -- of an already renamer-resolved field and its use\\n -- sites. This is needed to correctly support record\\n -- selectors in Template Haskell. See Note [Binders in\\n -- Template Haskell] in \\"GHC.ThToHs\\" and Note [Looking up\\n -- Exact RdrNames] in \\"GHC.Rename.Env\\".\\n | isExact fld\\n = assertPpr (fieldOcc_maybe fld_occ == Just dc_fs)\\n (vcat [ text \\"newRecordFieldLabel: incorrect namespace for exact Name\\" <+> quotes (ppr fld)\\n , text \\"expected namespace:\\" <+> pprNameSpace (fieldName dc_fs)\\n , text \\" actual namespace:\\" <+> pprNameSpace (occNameSpace fld_occ) ])\\n fld\\n\\n -- Field names produced by the parser are namespaced with VarName.\\n -- Here we namespace them according to the first constructor.\\n -- See Note [Record field namespacing] in GHC.Types.Name.Occurrence.\\n | otherwise\\n = mkRdrUnqual $ varToRecFieldOcc dc_fs fld_occ\\n\\n{-\\nNote [Looking up family names in family instances]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider\\n\\n module M where\\n type family T a :: *\\n type instance M.T Int = Bool\\n\\nWe might think that we can simply use \'lookupOccRn\' when processing the type\\ninstance to look up \'M.T\'. Alas, we can\'t! The type family declaration is in\\nthe *same* HsGroup as the type instance declaration. Hence, as we are\\ncurrently collecting the binders declared in that HsGroup, these binders will\\nnot have been added to the global environment yet.\\n\\nSolution is simple: process the type family declarations first, extend\\nthe environment, and then process the type instances.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Filtering imports}\\n* *\\n************************************************************************\\n\\n@filterImports@ takes the @ExportEnv@ telling what the imported module makes\\navailable, and filters it through the import spec (if any).\\n\\nNote [Dealing with imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nFor import M( ies ), we take each AvailInfo from the mi_exports of M, and make\\n\\n imp_occ_env :: OccEnv (NameEnv ImpOccItem)\\n\\nThis map contains one entry for each OccName that M exports, mapping each OccName\\nto the following information:\\n\\n 1. the GlobalRdrElt corresponding to the OccName,\\n 2. whether this GlobalRdrElt was the parent in the AvailInfo we found\\n the OccName in.\\n 3. the GlobalRdrElts that were bundled together in the AvailInfo we found\\n this OccName in (not including the parent),\\n\\nWe need (2) and (3) during the construction of the OccEnv because of associated\\ntypes and bundled pattern synonyms, respectively.\\n(3) is explained in Note [Importing PatternSynonyms].\\n\\nTo explain (2), consider for example:\\n\\n module M where\\n class C a where { data T a }\\n instance C Int where { data T Int = T1 | T2 }\\n instance C Bool where { data T Int = T3 }\\n\\nHere, M\'s exports avails are (recalling the AvailTC invariant from GHC.Types.Avail)\\n\\n C(C,T), T(T,T1,T2,T3)\\n\\nNotice that T appears *twice*, once as a child and once as a parent. From\\nthese two exports, respectively, during construction of the imp_occ_env, we begin\\nby associating the following two elements with the key T:\\n\\n T -> ImpOccItem { imp_item = gre1, imp_bundled = [C,T] , imp_is_parent = False }\\n T -> ImpOccItem { imp_item = gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nwhere `gre1`, `gre2` are two GlobalRdrElts with greName T.\\nWe combine these (in function \'combine\' in \'mkImportOccEnv\') by discarding the\\nnon-parent item, thusly:\\n\\n T -> IE_ITem { imp_item = gre1 `plusGRE` gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nNote the `plusGRE`: this ensures we don\'t drop parent information;\\nsee Note [Preserve parent information when combining import OccEnvs].\\n\\nSo the overall imp_occ_env is:\\n\\n C -> ImpOccItem { imp_item = C, imp_bundled = [T ], imp_is_parent = True }\\n T -> ImpOccItem { imp_item = T , imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n T1 -> ImpOccItem { imp_item = T1, imp_bundled = [T1,T2,T3], imp_is_parent = False }\\n -- similarly for T2, T3\\n\\nNote that the imp_occ_env will have entries for data constructors too,\\nalthough we never look up data constructors.\\n\\nNote [Importing PatternSynonyms]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nAs described in Note [Dealing with imports], associated types can lead to the\\nsame Name appearing twice, both as a child and once as a parent, when\\nconstructing the imp_occ_env. The same thing can happen with pattern synonyms\\nif they are exported bundled with a type.\\n\\nA simplified example, based on #11959:\\n\\n {-# LANGUAGE PatternSynonyms #-}\\n module M (T(P), pattern P) where -- Duplicate export warning, but allowed\\n data T = MkT\\n pattern P = MkT\\n\\nHere we have T(P) and P in export_avails, and respectively construct both\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n P -> ImpOccItem { imp_item = P, imp_bundled = [] , imp_is_parent = False }\\n\\nWe combine these by dropping the one with no siblings, leaving us with:\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n\\nThat is, we simply discard the non-bundled Avail.\\n\\nNote [Importing DuplicateRecordFields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn filterImports, another complicating factor is DuplicateRecordFields.\\nSuppose we have:\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (S(foo), T(foo)) where\\n data S = MkS { foo :: Int }\\n data T = MkT { foo :: Int }\\n\\n module N where\\n import M (foo) -- this is allowed (A)\\n import M (S(foo)) -- this is allowed (B)\\n\\nHere M exports \'foo\' at two different OccNames, with different namespaces for\\nthe two construtors MkS and MkT. Then, when we look up \'foo\' in lookup_names\\nfor case (A), we have a variable foo but must look in all the record field\\nnamespaces to find the two fields (and hence two different Avails).\\nWhereas in case (B) we reach the lookup_ie case for IEThingWith,\\nwhich looks up \'S\' and then finds the unique \'foo\' amongst its children.\\n\\nSee T16745 for a test of this.\\n\\nNote [Preserve parent information when combining import OccEnvs]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen discarding one ImpOccItem in favour of another, as described in\\nNote [Dealing with imports], we must make sure to combine the GREs so that\\nwe don\'t lose information.\\n\\nConsider for example #24084:\\n\\n module M1 where { class C a where { type T a } }\\n module M2 ( module M1 ) where { import M1 }\\n module M3 where { import M2 ( C, T ); instance C () where T () = () }\\n\\nWhen processing the import list of `M3`, we will have two `Avail`s attached\\nto `T`, namely `C(C, T)` and `T(T)`. We combine them in the `combine` function\\nof `mkImportOccEnv`; as described in Note [Dealing with imports] we discard\\n`C(C, T)` in favour of `T(T)`. However, in doing so, we **must not**\\ndiscard the information want that `C` is the parent of `T`. Indeed,\\nlosing track of this information can cause errors when importing,\\nas we could get an error of the form\\n\\n \\u2018T\\u2019 is not a (visible) associated type of class \\u2018C\\u2019\\n\\nThis explains why we use `plusGRE` when combining the two ImpOccItems, even\\nthough we are discarding one in favour of the other.\\n-}\\n\\n-- | All the \'GlobalRdrElt\'s associated with an \'AvailInfo\'.\\ngresFromAvail :: HasDebugCallStack\\n => HscEnv -> Maybe ImportSpec -> AvailInfo -> [GlobalRdrElt]\\ngresFromAvail hsc_env prov avail =\\n [ mk_gre nm info\\n | nm <- availNames avail\\n , let info = lookupGREInfo hsc_env nm ]\\n where\\n\\n mk_gre n info\\n = case prov of\\n -- Nothing => bound locally\\n -- Just is => imported from \'is\'\\n Nothing -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = True, gre_imp = emptyBag\\n , gre_info = info }\\n Just is -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = False, gre_imp = unitBag is\\n , gre_info = info }\\n\\n-- | All the \'GlobalRdrElt\'s associated with a collection of \'AvailInfo\'s.\\ngresFromAvails :: HscEnv -> Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]\\ngresFromAvails hsc_env prov = concatMap (gresFromAvail hsc_env prov)\\n\\nimportsFromIface :: HscEnv -> ModIface -> ImpDeclSpec -> Maybe NameSet -> GlobalRdrEnv\\nimportsFromIface hsc_env iface decl_spec hidden = mkGlobalRdrEnv $ case hidden of\\n Nothing -> all_gres\\n Just hidden_names -> filter (not . (`elemNameSet` hidden_names) . greName) all_gres\\n where\\n all_gres = gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\nrnNamespaceSpecifier :: NamespaceSpecifier GhcPs -> NamespaceSpecifier GhcRn\\nrnNamespaceSpecifier (NoNamespaceSpecifier _) = NoNamespaceSpecifier noExtField\\nrnNamespaceSpecifier (TypeNamespaceSpecifier x) = TypeNamespaceSpecifier x\\nrnNamespaceSpecifier (DataNamespaceSpecifier x) = DataNamespaceSpecifier x\\n\\nfilterImports\\n :: HasDebugCallStack\\n => HscEnv\\n -> ModIface\\n -> ImpDeclSpec\\n -- ^ Import spec\\n -> Maybe (ImportListInterpretation, [LIE GhcPs])\\n -- ^ Whether this is a \\"hiding\\" import list\\n -> RnM (Maybe (ImportListInterpretation, [LIE GhcRn]), -- Import spec w/ Names\\n ImpUserList, -- same, but designed for storage in interfaces\\n GlobalRdrEnv) -- Same again, but in GRE form\\nfilterImports hsc_env iface decl_spec Nothing\\n = return (Nothing, ImpUserAll, importsFromIface hsc_env iface decl_spec Nothing)\\nfilterImports hsc_env iface decl_spec (Just (want_hiding, import_items))\\n = do -- check for errors, convert RdrNames to Names\\n items1 <- mapM lookup_lie import_items\\n\\n let items2 :: [(LIE GhcRn, [GlobalRdrElt])]\\n items2 = concat items1\\n -- NB we may have duplicates, and several items\\n -- for the same parent; e.g N(x) and N(y)\\n\\n (gres, imp_user_list) = case want_hiding of\\n Exactly ->\\n let gres = concatMap (gresFromIE decl_spec) items2\\n gre_env = mkGlobalRdrEnv gres\\n implicit_parents = mkNameSet $ mapMaybe parentOfImplicitlyImportedGRE gres\\n in (gre_env, ImpUserExplicit (gresToAvailInfo $ globalRdrEnvElts $ gre_env) implicit_parents)\\n EverythingBut ->\\n let hidden_names = mkNameSet $ concatMap (map greName . snd) items2\\n in (importsFromIface hsc_env iface decl_spec (Just hidden_names), ImpUserEverythingBut hidden_names)\\n\\n return (Just (want_hiding, map fst items2), imp_user_list, gres)\\n where\\n import_mod = mi_module iface\\n all_avails = mi_exports iface\\n imp_occ_env = mkImportOccEnv hsc_env decl_spec all_avails\\n\\n -- Look up a parent (type constructor, class or data constructor)\\n -- in an import.\\n lookup_parent :: IE GhcPs -> RdrName -> IELookupM ImpOccItem\\n lookup_parent ie rdr =\\n assertPpr (not $ isVarNameSpace ns)\\n (vcat [ text \\"filterImports lookup_parent: unexpected variable\\"\\n , text \\"rdr:\\" <+> ppr rdr\\n , text \\"namespace:\\" <+> pprNameSpace ns ]) $\\n do { xs <- lookup_names ie rdr\\n ; case xs of\\n cax :| [] -> return cax\\n _ -> pprPanic \\"filter_imports lookup_parent ambiguous\\" $\\n vcat [ text \\"rdr:\\" <+> ppr rdr\\n , text \\"lookups:\\" <+> ppr (fmap imp_item xs) ] }\\n -- Looking up non-variables is always unambiguous,\\n -- as there can be at most one corresponding item\\n -- in the imp_occ_env.\\n -- See item (1) of Note [Exporting duplicate declarations]\\n -- in GHC.Tc.Gen.Export.\\n where\\n occ = rdrNameOcc rdr\\n ns = occNameSpace occ\\n\\n -- Look up a RdrName used in an import, returning multiple values if there\\n -- are several fields with the same name exposed by the module\\n lookup_names :: IE GhcPs -> RdrName -> IELookupM (NonEmpty ImpOccItem)\\n lookup_names ie rdr\\n | isQual rdr\\n = failLookupWith (QualImportError rdr)\\n | otherwise\\n = case lookups of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n item:items -> return $ item :| items\\n where\\n lookups = concatMap nonDetNameEnvElts\\n $ lookupImpOccEnv (RelevantGREsFOS WantNormal) imp_occ_env (rdrNameOcc rdr)\\n\\n lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, [GlobalRdrElt])]\\n lookup_lie (L loc ieRdr)\\n = setSrcSpanA loc $\\n do (stuff, warns) <- run_lookup ([],[]) (lookup_ie ieRdr)\\n mapM_ (addTcRnDiagnostic <=< warning_msg) warns\\n return [ (L loc ie, gres) | (ie,gres) <- stuff ]\\n where\\n\\n -- Warn when importing T(..) and no children are brought in scope\\n warning_msg (DodgyImport reason) =\\n pure (TcRnDodgyImports reason)\\n warning_msg MissingImportList =\\n pure (TcRnMissingImportList ieRdr)\\n warning_msg (BadImportW ie sub) = do\\n -- \'BadImportW\' is only constructed below in \'bad_import_w\', in\\n -- the \'EverythingBut\' case, so here we assume a \'hiding\' clause.\\n (reason :| _) <- badImportItemErr iface decl_spec ie sub all_avails\\n pure (TcRnDodgyImports (DodgyImportsHiding reason))\\n warning_msg (DeprecatedExport n w) =\\n pure $ TcRnPragmaWarning\\n PragmaWarningExport\\n { pwarn_occname = occName n\\n , pwarn_impmod = moduleName import_mod }\\n w\\n\\n run_lookup :: a -> IELookupM a -> TcRn a\\n run_lookup def m = case m of\\n Failed err -> do\\n msgs <- lookup_err_msgs err\\n forM_ msgs $ \\\\msg -> addErr (TcRnImportLookup msg)\\n return def\\n Succeeded a -> return a\\n\\n lookup_err_msgs err = case err of\\n BadImport ie sub -> badImportItemErr iface decl_spec ie sub all_avails\\n IllegalImport -> pure $ NE.singleton ImportLookupIllegal\\n QualImportError rdr -> pure $ NE.singleton (ImportLookupQualified rdr)\\n\\n -- For each import item, we convert its RdrNames to Names,\\n -- and at the same time compute all the GlobalRdrElt corresponding\\n -- to what is actually imported by this item.\\n -- Returns Nothing on error.\\n --\\n -- Returns a list because, with DuplicateRecordFields, a naked\\n -- import/export of a record field can correspond to multiple\\n -- different GlobalRdrElts. See Note [Importing DuplicateRecordFields].\\n lookup_ie :: IE GhcPs\\n -> IELookupM ([(IE GhcRn, [GlobalRdrElt])], [IELookupWarning])\\n lookup_ie ie = handle_bad_import $\\n case ie of\\n IEVar _ (L l n) _ -> do\\n -- See Note [Importing DuplicateRecordFields]\\n xs <- lookup_names ie (ieWrappedName n)\\n let gres = map imp_item $ NE.toList xs\\n export_depr_warns\\n | want_hiding == Exactly\\n = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ( [ (IEVar Nothing (L l (replaceWrappedName n name)) noDocstring, [gre])\\n | gre <- gres\\n , let name = greName gre ]\\n , export_depr_warns )\\n\\n IEThingAll x ns_spec (L l tc) _ -> do\\n ImpOccItem { imp_item = gre\\n , imp_bundled = bundled_gres\\n , imp_is_parent = is_par\\n }\\n <- lookup_parent ie $ ieWrappedName tc\\n let name = greName gre\\n\\n child_gres :: [GlobalRdrElt]\\n child_gres\\n | is_par = filterByNamespaceSpecifierGREs ns_spec bundled_gres\\n | otherwise = []\\n\\n imp_list_warn\\n\\n | null child_gres\\n -- e.g. f(..) or T(..) where T is a type synonym\\n = [DodgyImport (DodgyImportsEmptyParent ie ns_spec gre)]\\n\\n -- e.g. import M( T(..) )\\n | not (is_qual decl_spec)\\n = [MissingImportList]\\n\\n | otherwise\\n = []\\n\\n renamed_ie = IEThingAll (x { ieta_warning = Nothing })\\n (rnNamespaceSpecifier ns_spec)\\n (L l (replaceWrappedName tc name))\\n noDocstring\\n export_depr_warn\\n | want_hiding == Exactly\\n = maybeToList $ mk_depr_export_warning gre\\n -- We don\'t want to warn about the children as they\\n -- are not explicitly mentioned; the warning will\\n -- be emitted later on if they are used\\n | otherwise = []\\n\\n return ( [(renamed_ie, gre:child_gres)]\\n , imp_list_warn ++ export_depr_warn)\\n\\n\\n IEThingAbs _ (L l tc\') _\\n | want_hiding == EverythingBut -- hiding ( C )\\n -- Here the \'C\' can be a data constructor\\n -- *or* a type/class, or even both\\n -> let tc = ieWrappedName tc\'\\n tc_name = lookup_parent ie tc\\n dc_name = lookup_parent ie (setRdrNameSpace tc srcDataName)\\n in\\n case catIELookupM [ tc_name, dc_name ] of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n names -> return ( [mkIEThingAbs tc\' l (imp_item name) | name <- names], [])\\n | otherwise\\n -> do ImpOccItem { imp_item = gre } <- lookup_parent ie (ieWrappedName tc\')\\n return ( [mkIEThingAbs tc\' l gre]\\n , maybeToList $ mk_depr_export_warning gre)\\n\\n IEThingWith (deprecation, ann) ltc@(L l rdr_tc) wc rdr_ns _ -> do\\n ImpOccItem { imp_item = gre, imp_bundled = subnames }\\n <- lookup_parent (IEThingAbs Nothing ltc noDocstring) (ieWrappedName rdr_tc)\\n let name = greName gre\\n\\n -- Look up the children in the sub-names of the parent\\n -- See Note [Importing DuplicateRecordFields]\\n let (children_errs, childnames) = lookupChildren subnames rdr_ns\\n\\n bad_import_warns <-\\n if null children_errs then return [] else\\n let items = map lce_wrapped_name children_errs\\n ie = IEThingWith (deprecation, ann) ltc wc items noDocstring\\n -- We are trying to import T( a,b,c,d ), and failed\\n -- to find \'b\' and \'d\'. So we make up an import item\\n -- to report as failing, namely T( b, d ).\\n -- c.f. #15413\\n subordinate_err = mkSubordinateError gre children_errs\\n in bad_import_w ie subordinate_err\\n\\n let name\' = replaceWrappedName rdr_tc name\\n childnames\' = map (to_ie_post_rn . fmap greName) childnames\\n gres = gre : map unLoc childnames\\n export_depr_warns\\n | want_hiding == Exactly = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ([ (IEThingWith (Nothing, ann) (L l name\') wc childnames\' noDocstring\\n ,gres)]\\n , bad_import_warns ++ export_depr_warns)\\n\\n IEWholeNamespace x ns_spec -> do\\n let mod_name = moduleName import_mod\\n names = map greName gres\\n renamed_ie = IEWholeNamespace x { iewn_warning = Nothing\\n , iewn_names = names }\\n (rnNamespaceSpecifier ns_spec)\\n gres = filterByNamespaceSpecifierGREs ns_spec $\\n gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n dodgy_warn\\n | null gres = [DodgyImport (DodgyImportsWildcard mod_name ns_spec)]\\n | otherwise = []\\n return ([(renamed_ie, gres)],\\n dodgy_warn)\\n\\n _other -> failLookupWith IllegalImport\\n -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed...\\n -- all of those constitute errors.\\n\\n where\\n mkIEThingAbs tc l gre\\n = (IEThingAbs Nothing (L l (replaceWrappedName tc n)) noDocstring, [gre])\\n where n = greName gre\\n\\n -- N.B. imports never have docstrings\\n noDocstring = Nothing\\n\\n handle_bad_import m = catchIELookup m $ \\\\case\\n BadImport ie sub -> do\\n ws <- bad_import_w ie sub\\n return ([], ws)\\n err -> failLookupWith err\\n\\n bad_import_w :: IE GhcPs -> IsSubordinateError -> IELookupM [IELookupWarning]\\n bad_import_w ie sub\\n | want_hiding == EverythingBut = return [BadImportW ie sub]\\n | otherwise = failLookupWith (BadImport ie sub)\\n\\n mk_depr_export_warning gre\\n = DeprecatedExport name <$> mi_export_warn_fn iface name\\n where\\n name = greName gre\\n\\n-- | Assuming a subordinate item could not be found, do another lookup for a\\n-- more specific error message.\\nmkBadExportSubordinate :: [GlobalRdrElt] -> LIEWrappedName GhcPs -> BadExportSubordinate\\nmkBadExportSubordinate child_gres n =\\n case lookupChildren child_gres [n] of\\n (LookupChildNonType {lce_nontype_item = g} : _, _) -> BadExportSubordinateNonType g\\n (LookupChildNonData {lce_nondata_item = g} : _, _) -> BadExportSubordinateNonData g\\n _ -> BadExportSubordinateNotFound n\\n\\ntype IELookupM = MaybeErr IELookupError\\n\\ndata IELookupWarning\\n = BadImportW (IE GhcPs) IsSubordinateError\\n | MissingImportList\\n | DodgyImport DodgyImportsReason\\n | DeprecatedExport Name (WarningTxt GhcRn)\\n\\n-- | Is this import/export item a subordinate or not?\\ndata IsSubordinateError\\n = IsSubordinateError { subordinate_err_parent :: !GlobalRdrElt\\n , subordinate_err_unavailable :: [FastString]\\n , subordinate_err_nontype :: [GlobalRdrElt]\\n , subordinate_err_nondata :: [GlobalRdrElt] }\\n | IsNotSubordinate\\n\\nmkSubordinateError :: GlobalRdrElt -> [LookupChildError] -> IsSubordinateError\\nmkSubordinateError gre children_errs = foldr add init_acc children_errs\\n where\\n init_acc :: IsSubordinateError\\n init_acc = IsSubordinateError gre [] [] []\\n\\n add :: LookupChildError -> IsSubordinateError -> IsSubordinateError\\n add children_err sub@IsSubordinateError{} =\\n case children_err of\\n LookupChildNonType{lce_nontype_item = g} ->\\n sub { subordinate_err_nontype = g : subordinate_err_nontype sub }\\n LookupChildNonData{lce_nondata_item = g} ->\\n sub { subordinate_err_nondata = g : subordinate_err_nondata sub }\\n LookupChildNotFound (L _ wname) ->\\n let fs = (occNameFS . rdrNameOcc . ieWrappedName) wname\\n in sub { subordinate_err_unavailable = fs : subordinate_err_unavailable sub }\\n add _ IsNotSubordinate = panic \\"mkSubordinateError: IsNotSubordinate\\"\\n\\ndata IELookupError\\n = QualImportError RdrName\\n | BadImport (IE GhcPs) IsSubordinateError\\n | IllegalImport\\n\\nfailLookupWith :: IELookupError -> IELookupM a\\nfailLookupWith err = Failed err\\n\\ncatchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a\\ncatchIELookup m h = case m of\\n Succeeded r -> return r\\n Failed err -> h err\\n\\ncatIELookupM :: [IELookupM a] -> [a]\\ncatIELookupM ms = [ a | Succeeded a <- ms ]\\n\\n-- | Information associated to an \'AvailInfo\' used in constructing\\n-- an \'OccEnv\' corresponding to imports.\\n--\\n-- See Note [Dealing with imports].\\ndata ImpOccItem\\n = ImpOccItem\\n { imp_item :: GlobalRdrElt\\n -- ^ The import item\\n , imp_bundled :: [GlobalRdrElt]\\n -- ^ Items bundled in the Avail this import item came from,\\n -- not including the import item itself if it is a parent.\\n , imp_is_parent :: Bool\\n -- ^ Is the import item a parent? See Note [Dealing with imports].\\n }\\n\\ninstance Outputable ImpOccItem where\\n ppr (ImpOccItem { imp_item = item, imp_bundled = bundled, imp_is_parent = is_par })\\n = braces $ hsep\\n [ text \\"ImpOccItem\\"\\n , if is_par then text \\"[is_par]\\" else empty\\n , ppr (greName item) <+> ppr (greParent item)\\n , braces $ text \\"bundled:\\" <+> ppr (map greName bundled) ]\\n\\n-- | Make an \'OccEnv\' of all the imports.\\n--\\n-- Complicated by the fact that associated data types and pattern synonyms\\n-- can appear twice. See Note [Dealing with imports].\\nmkImportOccEnv :: HscEnv -> ImpDeclSpec -> [IfaceExport] -> OccEnv (NameEnv ImpOccItem)\\nmkImportOccEnv hsc_env decl_spec all_avails =\\n mkOccEnv_C (plusNameEnv_C combine)\\n [ (occ, mkNameEnv [(nm, item)])\\n | avail <- all_avails\\n , let gres = gresFromAvail hsc_env (Just hiding_spec) avail\\n , gre <- gres\\n , let nm = greName gre\\n occ = greOccName gre\\n (is_parent, bundled) = case avail of\\n AvailTC c _\\n | c == nm -- (Recall the AvailTC invariant from GHC.Types.AvailInfo)\\n -> ( True, drop 1 gres ) -- \\"drop 1\\": don\'t include the parent itself.\\n | otherwise\\n -> ( False, gres )\\n _ -> ( False, [] )\\n item = ImpOccItem\\n { imp_item = gre\\n , imp_bundled = bundled\\n , imp_is_parent = is_parent }\\n ]\\n where\\n\\n hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\n -- See Note [Dealing with imports]\\n -- \'combine\' may be called for associated data types which appear\\n -- twice in the all_avails. In the example, we have two Avails for T,\\n -- namely T(T,T1,T2,T3) and C(C,T), and we combine them by dropping the\\n -- latter, in which T is not the parent.\\n combine :: ImpOccItem -> ImpOccItem -> ImpOccItem\\n combine item1@(ImpOccItem { imp_item = gre1, imp_is_parent = is_parent1 })\\n item2@(ImpOccItem { imp_item = gre2, imp_is_parent = is_parent2 })\\n | is_parent1 || is_parent2\\n , not (isRecFldGRE gre1 || isRecFldGRE gre2) -- NB: does not force GREInfo.\\n , let name1 = greName gre1\\n name2 = greName gre2\\n gre = gre1 `plusGRE` gre2\\n -- See Note [Preserve parent information when combining import OccEnvs]\\n = assertPpr (name1 == name2)\\n (ppr name1 <+> ppr name2) $\\n if is_parent1\\n then item1 { imp_item = gre }\\n else item2 { imp_item = gre }\\n -- Discard C(C,T) in favour of T(T, T1, T2, T3).\\n\\n -- \'combine\' may also be called for pattern synonyms which appear both\\n -- unassociated and associated (see Note [Importing PatternSynonyms]).\\n combine item1@(ImpOccItem { imp_item = c1, imp_bundled = kids1 })\\n item2@(ImpOccItem { imp_item = c2, imp_bundled = kids2 })\\n = assertPpr (greName c1 == greName c2\\n && (not (null kids1 && null kids2)))\\n (ppr c1 <+> ppr c2 <+> ppr kids1 <+> ppr kids2) $\\n if null kids1\\n then item2\\n else item1\\n -- Discard standalone pattern P in favour of T(P).\\n\\n-- | Essentially like @lookupGRE env (LookupOccName occ which_gres)@,\\n-- but working with \'ImpOccItem\'s instead of \'GlobalRdrElt\'s.\\nlookupImpOccEnv :: WhichGREs GREInfo\\n -> OccEnv (NameEnv ImpOccItem) -> OccName -> [NameEnv ImpOccItem]\\nlookupImpOccEnv which_gres env occ =\\n mapMaybe relevant_items $ lookupOccEnv_AllNameSpaces env occ\\n where\\n is_relevant :: ImpOccItem -> Bool\\n is_relevant (ImpOccItem { imp_item = gre }) =\\n greIsRelevant which_gres (occNameSpace occ) gre\\n relevant_items :: NameEnv ImpOccItem -> Maybe (NameEnv ImpOccItem)\\n relevant_items nms\\n | let nms\' = filterNameEnv is_relevant nms\\n = if isEmptyNameEnv nms\'\\n then Nothing\\n else Just nms\'\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{Import/Export Utils}\\n* *\\n************************************************************************\\n-}\\n\\n-- | Given an import\\\\/export spec, appropriately set the @gre_imp@ field\\n-- for the \'GlobalRdrElt\'s.\\ngresFromIE :: ImpDeclSpec -> (LIE GhcRn, [GlobalRdrElt]) -> [GlobalRdrElt]\\ngresFromIE decl_spec (L loc ie, gres)\\n = map set_gre_imp gres\\n where\\n is_explicit = case ie of\\n IEThingAll _ _ name _ -> \\\\n -> n == lieWrappedName name\\n IEWholeNamespace _ _ -> \\\\_ -> False\\n _ -> \\\\_ -> True\\n prov_fn name\\n = ImpSpec { is_decl = decl_spec, is_item = item_spec }\\n where\\n item_spec = ImpSome { is_explicit = is_explicit name\\n , is_iloc = locA loc }\\n set_gre_imp gre@( GRE { gre_name = nm } )\\n = gre { gre_imp = unitBag $ prov_fn nm }\\n\\nparentOfImplicitlyImportedGRE :: Outputable info => GlobalRdrEltX info -> Maybe Name\\nparentOfImplicitlyImportedGRE gre =\\n if any (explicit_import . is_item) $ gre_imp gre\\n then Nothing\\n else greParent_maybe gre\\n where\\n explicit_import :: ImpItemSpec -> Bool\\n explicit_import (ImpAll {}) =\\n pprPanic \\"parentOfImplicitlyImportedGRE: ImpAll\\" (ppr gre)\\n explicit_import (ImpSome { is_explicit }) = is_explicit\\n\\n{- Note [Children for duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider the module\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (F(foo, MkFInt, MkFBool)) where\\n data family F a\\n data instance F Int = MkFInt { foo :: Int }\\n data instance F Bool = MkFBool { foo :: Bool }\\n\\nThe `foo` in the export list refers to *both* selectors! For this\\nreason, lookupChildren builds an environment that maps the FastString\\nto a list of items, rather than a single item.\\n-}\\n\\nmkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]\\nmkChildEnv gres = foldr add emptyNameEnv gres\\n where\\n add gre env = case greParent gre of\\n ParentIs p -> extendNameEnv_Acc (:) Utils.singleton env p gre\\n NoParent -> env\\n\\nfindChildren :: NameEnv [a] -> Name -> [a]\\nfindChildren env n = lookupNameEnv env n `orElse` []\\n\\ndata LookupChildError\\n = LookupChildNotFound { lce_wrapped_name :: !(LIEWrappedName GhcPs) }\\n | LookupChildNonType { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nontype_item :: !GlobalRdrElt }\\n | LookupChildNonData { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nondata_item :: !GlobalRdrElt }\\n\\nlookupChildren :: [GlobalRdrElt]\\n -> [LIEWrappedName GhcPs]\\n -> ( [LookupChildError] -- The ones for which the lookup failed\\n , [LocatedA GlobalRdrElt] )\\n-- (lookupChildren all_kids rdr_items) maps each rdr_item to its\\n-- corresponding Name in all_kids, if the former exists\\n-- The matching is done by FastString, not OccName, so that\\n-- Cls( meth, AssocTy )\\n-- will correctly find AssocTy among the all_kids of Cls, even though\\n-- the RdrName for AssocTy may have a (bogus) DataName namespace\\n-- (Really the rdr_items should be FastStrings in the first place.)\\nlookupChildren all_kids rdr_items = (fails, successes)\\n where\\n mb_xs = map do_one rdr_items\\n fails = [ err | Failed err <- mb_xs ]\\n successes = [ ok | Succeeded oks <- mb_xs, ok <- NE.toList oks ]\\n\\n do_one :: LIEWrappedName GhcPs -> MaybeErr LookupChildError (NonEmpty (LocatedA GlobalRdrElt))\\n do_one item@(L l r) =\\n case r of\\n IEName{}\\n -- IEName (unadorned name) places no restriction on the namespace of\\n -- the imported entity, so we look in both `val_gres` and `typ_gres`.\\n -- In case of conflict (punning), the value namespace takes priority.\\n -- See Note [Prioritise the value namespace in subordinate import lists]\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEType{}\\n -- IEType (\'type\' namespace specifier) restricts the lookup to the\\n -- type namespace, i.e. to `typ_gres`. In case of failure, we check\\n -- `val_gres` to produce a more helpful error message.\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- val_gres -> Failed $ LookupChildNonType item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEData{}\\n -- IEData (\'data\' namespace specifier) restricts the lookup to the\\n -- data namespace, i.e. to `val_gres`. In case of failure, we check\\n -- `typ_gres` to produce a more helpful error message.\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- typ_gres -> Failed $ LookupChildNonData item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEPattern{} -> panic \\"lookupChildren: IEPattern\\" -- Never happens (invalid syntax)\\n IEDefault{} -> panic \\"lookupChildren: IEDefault\\" -- Never happens (invalid syntax)\\n where\\n fs = (occNameFS . rdrNameOcc . ieWrappedName) r\\n gres = fromMaybe [] (lookupFsEnv kid_env fs)\\n (val_gres, typ_gres) = partition (isValNameSpace . greNameSpace) gres\\n\\n -- See Note [Children for duplicate record fields]\\n kid_env :: FastStringEnv [GlobalRdrElt]\\n kid_env = extendFsEnvList_C (++) emptyFsEnv\\n [(occNameFS (occName x), [x]) | x <- all_kids]\\n\\n\\n{- Note [Prioritise the value namespace in subordinate import lists]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider this program that defines a class that has both an associated type\\nnamed (#) and a method named (#)\\n\\n module M_assoc where\\n class C a b where\\n type a # b\\n (#) :: a -> b -> ()\\n module N_assoc where\\n import M_assoc( C((#)) )\\n\\nIn the import declaration, when we see the unadorned name (#) in the subordinate\\nimport list of C, which children should we bring into scope? Our options are:\\n\\n a) only the method (#)\\n b) only the associated type (#)\\n c) both the method and the associated type\\n\\nTo follow the precedent established by top-level items, we go with option (a).\\nIndeed, consider a slightly different program\\n\\n module M_top where\\n type family a # b\\n a # b = ()\\n module N_top where\\n import M_top( (#) )\\n\\nHere the import brings only the function (#) into scope, and one has to say\\n`type (#)` to get the type family.\\n-}\\n\\n-------------------------------\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused names}\\n* *\\n*********************************************************\\n-}\\n\\nreportUnusedNames :: TcGblEnv -> HscSource -> RnM ()\\nreportUnusedNames gbl_env hsc_src\\n = do { keep <- readTcRef (tcg_keep gbl_env)\\n ; traceRn \\"RUN\\" (ppr (tcg_dus gbl_env))\\n ; warnUnusedImportDecls gbl_env hsc_src\\n ; warnUnusedTopBinds $ unused_locals keep\\n ; warnMissingSignatures gbl_env\\n ; warnMissingKindSignatures gbl_env }\\n where\\n used_names :: NameSet -> NameSet\\n used_names keep = findUses (tcg_dus gbl_env) emptyNameSet `unionNameSet` keep\\n -- NB: currently, if f x = g, we only treat \'g\' as used if \'f\' is used\\n -- Hence findUses\\n\\n -- Collect the defined names from the in-scope environment\\n defined_names :: [GlobalRdrElt]\\n defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)\\n\\n kids_env = mkChildEnv defined_names\\n -- This is done in mkExports too; duplicated work\\n\\n gre_is_used :: NameSet -> GlobalRdrElt -> Bool\\n gre_is_used used_names gre0\\n = name `elemNameSet` used_names\\n || any (\\\\ gre -> greName gre `elemNameSet` used_names) (findChildren kids_env name)\\n -- A use of C implies a use of T,\\n -- if C was brought into scope by T(..) or T(C)\\n where\\n name = greName gre0\\n\\n -- Filter out the ones that are\\n -- (a) defined in this module, and\\n -- (b) not defined by a \'deriving\' clause\\n -- The latter have an Internal Name, so we can filter them out easily\\n unused_locals :: NameSet -> [GlobalRdrElt]\\n unused_locals keep =\\n let -- Note that defined_and_used, defined_but_not_used\\n -- are both [GRE]; that\'s why we need defined_and_used\\n -- rather than just used_names\\n _defined_and_used, defined_but_not_used :: [GlobalRdrElt]\\n (_defined_and_used, defined_but_not_used)\\n = partition (gre_is_used (used_names keep)) defined_names\\n\\n in filter is_unused_local defined_but_not_used\\n is_unused_local :: GlobalRdrElt -> Bool\\n is_unused_local gre = isLocalGRE gre\\n && isExternalName (greName gre)\\n\\n{- *********************************************************************\\n* *\\n Missing signatures\\n* *\\n********************************************************************* -}\\n\\n{-\\nNote [Missing signatures]\\n~~~~~~~~~~~~~~~~~~~~~~~~~\\nThere are four warning flags in play:\\n\\n * -Wmissing-exported-signatures\\n Warn about any exported top-level function/value without a type signature.\\n Does not include pattern synonyms.\\n\\n * -Wmissing-signatures\\n Warn about any top-level function/value without a type signature. Does not\\n include pattern synonyms. Takes priority over -Wmissing-exported-signatures.\\n\\n * -Wmissing-exported-pattern-synonym-signatures\\n Warn about any exported pattern synonym without a type signature.\\n\\n * -Wmissing-pattern-synonym-signatures\\n Warn about any pattern synonym without a type signature. Takes priority over\\n -Wmissing-exported-pattern-synonym-signatures.\\n\\n-}\\n\\n-- | Warn the user about top level binders that lack type signatures.\\n-- Called /after/ type inference, so that we can report the\\n-- inferred type of the function\\nwarnMissingSignatures :: TcGblEnv -> RnM ()\\nwarnMissingSignatures gbl_env\\n = do { let exports = availsToNameSet (tcg_exports gbl_env)\\n sig_ns = tcg_sigs gbl_env\\n -- We use sig_ns to exclude top-level bindings that are generated by GHC\\n binds = collectHsBindsBinders CollNoDictBinders $ tcg_binds gbl_env\\n pat_syns = tcg_patsyns gbl_env\\n\\n not_ghc_generated :: Name -> Bool\\n not_ghc_generated name = name `elemNameSet` sig_ns\\n\\n add_binding_warn :: Id -> RnM ()\\n add_binding_warn id =\\n when (not_ghc_generated name) $\\n do { env <- liftZonkM $ tcInitTidyEnv -- Why not use emptyTidyEnv?\\n ; let ty = tidyOpenType env (idType id)\\n missing = MissingTopLevelBindingSig name ty\\n diag = TcRnMissingSignature missing exported\\n ; addDiagnosticAt (getSrcSpan name) diag }\\n where\\n name = idName id\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n add_patsyn_warn :: PatSyn -> RnM ()\\n add_patsyn_warn ps =\\n when (not_ghc_generated name) $\\n addDiagnosticAt (getSrcSpan name)\\n (TcRnMissingSignature missing exported)\\n where\\n name = patSynName ps\\n missing = MissingPatSynSig ps\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n -- Warn about missing signatures\\n -- Do this only when we have a type to offer\\n -- See Note [Missing signatures]\\n ; mapM_ add_binding_warn binds\\n ; mapM_ add_patsyn_warn pat_syns\\n }\\n\\n-- | Warn the user about tycons that lack kind signatures.\\n-- Called /after/ type (and kind) inference, so that we can report the\\n-- inferred kinds.\\nwarnMissingKindSignatures :: TcGblEnv -> RnM ()\\nwarnMissingKindSignatures gbl_env\\n = do { cusks_enabled <- xoptM LangExt.CUSKs\\n ; mapM_ (add_ty_warn cusks_enabled) tcs\\n }\\n where\\n tcs = tcg_tcs gbl_env\\n ksig_ns = tcg_ksigs gbl_env\\n exports = availsToNameSet (tcg_exports gbl_env)\\n\\n has_kind_signature :: Name -> Bool\\n has_kind_signature name = name `elemNameSet` ksig_ns\\n\\n add_ty_warn :: Bool -> TyCon -> RnM ()\\n add_ty_warn cusks_enabled tyCon =\\n when (has_kind_signature name) $\\n addDiagnosticAt (getSrcSpan name) diag\\n where\\n name = tyConName tyCon\\n diag = TcRnMissingSignature missing exported\\n missing = MissingTyConKindSig tyCon cusks_enabled\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused imports}\\n* *\\n*********************************************************\\n\\nThis code finds which import declarations are unused. The\\nspecification and implementation notes are here:\\n https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/unused-imports\\n\\nSee also Note [Choosing the best import declaration] in GHC.Types.Name.Reader\\n-}\\n\\ntype ImportDeclUsage\\n = ( LImportDecl GhcRn -- The import declaration\\n , [GlobalRdrElt] -- What *is* used (normalised)\\n , [Name] -- What is imported but *not* used\\n , [NamespaceSpecifier GhcRn] ) -- Unused wildcards\\n\\nwarnUnusedImportDecls :: TcGblEnv -> HscSource -> RnM ()\\nwarnUnusedImportDecls gbl_env hsc_src\\n = do { uses <- readMutVar (tcg_used_gres gbl_env)\\n ; let imports = tcg_rn_imports gbl_env\\n rdr_env = tcg_rdr_env gbl_env\\n\\n -- We should only warn for unnecessary *user* imports, but deciding\\n -- minimal imports should take generated imports into account\\n ; let usageUserImports = findImportUsage (excludeGenerated imports) uses\\n usageAllImports = findImportUsage imports uses\\n\\n ; traceRn \\"warnUnusedImportDecls\\" $\\n (vcat [ text \\"Uses:\\" <+> ppr uses\\n , text \\"Usage all user imports: \\" <+> ppr usageUserImports\\n , text \\"Usage all imports: \\" <+> ppr usageAllImports])\\n\\n ; mapM_ (warnUnusedImport rdr_env) usageUserImports\\n\\n ; whenGOptM Opt_D_dump_minimal_imports $\\n printMinimalImports hsc_src usageAllImports }\\n\\n-- | Exclude generated imports\\nexcludeGenerated :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\nexcludeGenerated = filterOut (isGeneratedImport . ideclOrigin . ideclExt . unLoc)\\n\\nfindImportUsage :: [LImportDecl GhcRn]\\n -> [GlobalRdrElt]\\n -> [ImportDeclUsage]\\n\\nfindImportUsage imports used_gres\\n = map unused_decl imports\\n where\\n import_usage :: ImportMap\\n import_usage = mkImportMap used_gres\\n\\n unused_decl :: LImportDecl GhcRn -> ImportDeclUsage\\n unused_decl decl@(L _ (ImportDecl { ideclImportList = imps }))\\n = -- pprTrace \\"unused_decl\\" (vcat [ ppr decl\\n -- , text \\"used\\" <+> ppr used_gres\\n -- , text \\"unused\\" <+> ppr unused_names ]) $\\n (decl, used_gres, unused_names, unused_wcs)\\n where\\n used_gres = lookupImportMap decl import_usage\\n\\n used_gre_env = mkGlobalRdrEnv used_gres\\n used_parents = mkNameSet (mapMaybe greParent_maybe used_gres)\\n\\n (unused_names, unused_wcs) -- Not trivial; see eg #7454\\n = case imps of\\n Just (Exactly, imp_ies) ->\\n let unused = foldr (add_unused . unLoc) emptyUnusedNames imp_ies\\n nms = nameSetElemsStable (collectUnusedNames unused)\\n wcs = collectUnusedWildcards unused\\n in (nms, wcs)\\n _other -> ([], []) -- No explicit import list => no unused-name list\\n\\n add_unused :: IE GhcRn -> UnusedNames -> UnusedNames\\n add_unused (IEVar _ n _) acc = add_unused_name (lieWrappedName n) True acc\\n add_unused (IEThingAbs _ n _) acc = add_unused_name (lieWrappedName n) False acc\\n add_unused (IEThingAll _ _ n _) acc = add_unused_all (lieWrappedName n) acc\\n add_unused (IEThingWith _ p wc ns _) acc = add_wc_all (add_unused_with pn xs acc)\\n where pn = lieWrappedName p\\n xs = map lieWrappedName ns\\n add_wc_all = case wc of\\n NoIEWildcard -> id\\n IEWildcard _ -> add_unused_all pn\\n add_unused (IEWholeNamespace x ns_spec) acc = add_unused_wildcard ns_spec (iewn_names x) acc\\n add_unused _ acc = acc\\n\\n add_unused_name :: Name -> Bool -> UnusedNames -> UnusedNames\\n add_unused_name n is_ie_var acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | is_ie_var\\n , isFieldName n\\n -- See Note [Reporting unused imported duplicate record fields]\\n = let\\n fs = getOccFS n\\n (flds, flds_used) = lookupFsEnv acc_fs fs `orElse` (emptyNameSet, Any False)\\n acc_fs\' = extendFsEnv acc_fs fs (extendNameSet flds n, Any used S.<> flds_used)\\n in UnusedNames acc_ns acc_wcs acc_fs\'\\n\\n | used\\n = acc\\n\\n | otherwise\\n = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n where\\n used = isJust $ lookupGRE_Name used_gre_env n\\n\\n add_unused_all :: Name -> UnusedNames -> UnusedNames\\n add_unused_all n acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | Just {} <- lookupGRE_Name used_gre_env n = acc\\n | n `elemNameSet` used_parents = acc\\n | otherwise = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n\\n add_unused_with :: Name -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_with p ns acc\\n | all (`elemNameSet` acc1_ns) ns = add_unused_name p False acc1\\n | otherwise = acc1\\n where\\n acc1@(UnusedNames acc1_ns _ _) = foldr (\\\\n acc\' -> add_unused_name n False acc\') acc ns\\n -- If you use \'signum\' from Num, then the user may well have\\n -- imported Num(signum). We don\'t want to complain that\\n -- Num is not itself mentioned. Hence the two cases in add_unused_with.\\n\\n add_unused_wildcard :: NamespaceSpecifier GhcRn -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_wildcard ns_spec names acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | any_used = acc\\n | otherwise = UnusedNames acc_ns (ns_spec : acc_wcs) acc_fs\\n where\\n -- A wildcard `type ..` or `data ..` is used if at least one of\\n -- the names it expands to is used\\n any_used = any (isJust . lookupGRE_Name used_gre_env) names\\n\\n\\n-- | An accumulator for unused names in an import list.\\n--\\n-- See Note [Reporting unused imported duplicate record fields].\\ndata UnusedNames =\\n UnusedNames\\n { unused_names :: NameSet\\n -- ^ Unused \'Name\'s in an import list, not including record fields\\n -- that are plain \'IEVar\' imports (tracked by \'rec_fld_uses\')\\n -- or wildcard imports (tracked by \'unused_wildcards\').\\n , unused_wildcards :: [NamespaceSpecifier GhcRn]\\n -- ^ Unused wildcards @type ..@ or @data ..@ in an import list.\\n , rec_fld_uses :: FastStringEnv (NameSet, Any)\\n -- ^ Record fields imported without a parent (i.e. an \'IEVar\' import).\\n --\\n -- The \'Any\' value records whether any of the record fields\\n -- sharing the same underlying \'FastString\' have been used.\\n }\\n\\nemptyUnusedNames :: UnusedNames\\nemptyUnusedNames = UnusedNames emptyNameSet [] emptyFsEnv\\n\\ninstance Outputable UnusedNames where\\n ppr (UnusedNames nms wcs flds) =\\n text \\"UnusedNames\\" <+>\\n braces (ppr nms <+> ppr wcs <+> ppr (fmap (second getAny) flds))\\n\\n-- | Collect all unused names from a \'UnusedNames\' value.\\ncollectUnusedNames :: UnusedNames -> NameSet\\ncollectUnusedNames (UnusedNames { unused_names = nms, rec_fld_uses = flds })\\n = nms S.<> unused_flds\\n where\\n unused_flds = nonDetFoldFsEnv collect_unused emptyNameSet flds\\n collect_unused :: (NameSet, Any) -> NameSet -> NameSet\\n collect_unused (nms, Any at_least_one_name_is_used) acc\\n | at_least_one_name_is_used = acc\\n | otherwise = unionNameSet nms acc\\n\\ncollectUnusedWildcards :: UnusedNames -> [NamespaceSpecifier GhcRn]\\ncollectUnusedWildcards = unused_wildcards\\n\\n{- Note [Reporting unused imported duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have (#24035):\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M1 (R1(..), R2(..)) where\\n data R1 = MkR1 { fld :: Int }\\n data R2 = MkR2 { fld :: Int }\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M2 where\\n import M1 (R1(MkR1), R2, fld)\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nIn the import of \'M1\' in \'M2\', the \'fld\' import resolves to two separate GREs,\\nnamely R1(fld) and R2(fld). From the perspective of the renamer, and in particular\\nthe \'findImportUsage\' function, it\'s as if the user had imported the two names\\nseparately (even though no source syntax allows that).\\n\\nThis means that we need to be careful when reporting unused imports: the R2(fld)\\nimport is indeed unused, but because R1(fld) is used, we should not report\\nfld as unused altogether.\\n\\nTo achieve this, we keep track of record field imports without a parent (i.e.\\nusing the IEVar constructor) separately from other import items, using the\\nUnusedNames datatype.\\nOnce we have accumulated usages, we emit warnings for unused record fields\\nwithout parents one whole group (of record fields sharing the same textual name)\\nat a time, and only if *all* of the record fields in the group are unused;\\nsee \'collectUnusedNames\'.\\n\\nNote that this only applies to record fields imported without a parent. If we\\nhad:\\n\\n import M1 (R1(MkR1, fld), R2(fld))\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nthen of course we should report the second \'fld\' as unused.\\n-}\\n\\n\\n{- Note [The ImportMap]\\n~~~~~~~~~~~~~~~~~~~~~~~\\nThe ImportMap is a short-lived intermediate data structure records, for\\neach import declaration, what stuff brought into scope by that\\ndeclaration is actually used in the module.\\n\\nThe [GlobalRdrElt] are the things imported from that decl.\\n-}\\n\\ndata ImportMap = ImportMap\\n { im_imports :: Map RealSrcSpan [GlobalRdrElt]\\n -- ^ See [The ImportMap]\\n -- If loc :-> gres, then\\n -- \'loc\' = the end loc of the bestImport of each GRE in \'gres\'\\n , im_generatedImports :: Map ModuleName [GlobalRdrElt]\\n }\\n\\nmkImportMap :: [GlobalRdrElt] -> ImportMap\\n-- For each of a list of used GREs, find all the import decls that brought\\n-- it into scope; choose one of them (bestImport), and record\\n-- the RdrName in that import decl\'s entry in the ImportMap\\nmkImportMap = foldr insertImportMap $ ImportMap Map.empty Map.empty\\n\\ninsertImportMap :: GlobalRdrElt -> ImportMap -> ImportMap\\ninsertImportMap gre@(GRE { gre_imp = imp_specs }) importMap\\n | RealSrcSpan importSpan _ <- is_dloc best_imp_spec =\\n importMap{im_imports = insertElem importSpan gre $ im_imports importMap}\\n | GeneratedSrcSpan{} <- is_dloc best_imp_spec =\\n importMap{im_generatedImports = insertElem (moduleName $ is_mod best_imp_spec) gre $ im_generatedImports importMap}\\n | otherwise = importMap\\n where\\n best_imp_spec =\\n case bagToList imp_specs of\\n [] -> pprPanic \\"mkImportMap: GRE with no ImportSpecs\\" (ppr gre)\\n is:iss -> is_decl $ bestImport (is NE.:| iss)\\n\\n -- https://github.com/haskell/containers/issues/784\\n insertElem :: Ord k => k -> v -> Map k [v] -> Map k [v]\\n insertElem k v = flip Map.alter k $ \\\\case\\n Just vs -> Just (v : vs)\\n Nothing -> Just [v]\\n\\nlookupImportMap :: LImportDecl GhcRn -> ImportMap -> [GlobalRdrElt]\\nlookupImportMap (L srcSpan ImportDecl{ideclName = L _ modName}) importMap =\\n fromMaybe [] $\\n -- should match logic in insertImportMap\\n case locA srcSpan of\\n RealSrcSpan realSrcSpan _ -> realSrcSpan `Map.lookup` im_imports importMap\\n GeneratedSrcSpan{} -> modName `Map.lookup` im_generatedImports importMap\\n _ -> Nothing\\n\\nlieNames :: LIE (GhcPass p) -> [Located (IdP (GhcPass p))]\\nlieNames = _\\n\\nwarnUnusedImport :: GlobalRdrEnv -> ImportDeclUsage -> RnM ()\\nwarnUnusedImport rdr_env (L loc decl, used, unused, unused_wcs)\\n\\n -- Do not warn for \'import M()\'\\n -- See (UI1) in Note [Unused imports]\\n | Just (Exactly, _) <- ideclImportList decl\\n , null unused && null unused_wcs\\n = return ()\\n\\n -- Note [Do not warn about Prelude hiding]\\n | Just (EverythingBut, hides) <- ideclImportList decl\\n , not (null hides)\\n , pRELUDE_NAME == unLoc (ideclName decl)\\n = return ()\\n\\n -- Do not warn about import X as Rebindable\\n -- See (UI2) in Note [Unused imports]\\n | Just (L _ mod) <- ideclAs decl\\n , mod == rEBINDABLE_MOD_NAME\\n = return ()\\n\\n -- Nothing used; drop entire declaration\\n | null used\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl UnusedImportNone)\\n\\n -- Everything imported is used; nop\\n | null unused && null unused_wcs\\n = return ()\\n\\n -- Some imports are unused: make the `SrcSpan` cover only the unused\\n -- items instead of the whole import statement\\n | Just (_, imports) <- ideclImportList decl\\n , let unused_locs = [ locA loc | L loc ie <- imports\\n , name <- ieNames ie\\n , name `elem` unused ]\\n , loc1 : locs <- unused_locs\\n , let span = foldr1 combineSrcSpans ( loc1 NE.:| locs )\\n = addDiagnosticAt span (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n -- Some imports are unused\\n | otherwise\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n where\\n -- In warning message, pretty-print identifiers unqualified unconditionally\\n -- to improve the consistent for ambiguous/unambiguous identifiers.\\n -- See #14881.\\n possible_field n =\\n case lookupGRE_Name rdr_env n of\\n Just (GRE { gre_par = par, gre_info = IAmRecField info }) ->\\n let fld_occ :: OccName\\n fld_occ = nameOccName $ flSelector $ recFieldLabel info\\n in UnusedImportNameRecField par fld_occ\\n _ -> UnusedImportNameRegular n\\n\\n -- Print unused names in a deterministic (lexicographic) order\\n sort_unused :: [UnusedImportName]\\n sort_unused =\\n [ UnusedImportWildcard wc | wc <- unused_wcs ] ++\\n [ possible_field nm | nm <- sortBy (comparing nameOccName) unused ]\\n\\ngetMinimalImports :: [ImportDeclUsage] -> RnM [LImportDecl GhcRn]\\ngetMinimalImports ie_decls\\n = do { rdr_env <- getGlobalRdrEnv\\n ; fmap combine $ mapM (mk_minimal rdr_env) ie_decls }\\n where\\n mk_minimal rdr_env (L l decl, used_gres, unused, unused_wcs)\\n | null unused && null unused_wcs\\n , Just (Exactly, _) <- ideclImportList decl\\n = return (L l decl)\\n | otherwise\\n = do { let ImportDecl { ideclName = L _ mod_name\\n , ideclSource = is_boot\\n , ideclPkgQual = pkg_qual\\n , ideclExt = XImportDeclPass { ideclOrigin = origin } } = decl\\n ; iface <- loadSrcInterface doc (importDeclLookupScope origin)\\n mod_name is_boot pkg_qual\\n ; let used_avails = gresToAvailInfo used_gres\\n ; lies <- map (L l) <$> concatMapM (to_ie rdr_env iface) used_avails\\n ; return (L l (decl { ideclImportList = Just (Exactly, lies) })) }\\n where\\n doc = text \\"Compute minimal imports for\\" <+> ppr decl\\n\\n to_ie :: GlobalRdrEnv -> ModIface -> AvailInfo -> RnM [IE GhcRn]\\n -- The main trick here is that if we\'re importing all the constructors\\n -- we want to say \\"T(..)\\", but if we\'re importing only a subset we want\\n -- to say \\"T(A,B,C)\\". So we have to find out what the module exports.\\n to_ie rdr_env _ (Avail c) -- Note [Overloaded field import]\\n = do { let\\n gre = expectJust $ lookupGRE_Name rdr_env c\\n ; return $ [IEVar Nothing (to_ie_post_rn $ noLocA $ greName gre) Nothing] }\\n to_ie _ _ avail@(AvailTC n [_]) -- Exporting the main decl and nothing else\\n | availExportsDecl avail\\n = return [IEThingAbs Nothing (to_ie_post_rn $ noLocA n) Nothing]\\n to_ie rdr_env iface (AvailTC n cs) =\\n case [ xs | avail@(AvailTC x xs) <- mi_exports iface\\n , x == n\\n , availExportsDecl avail -- Note [Partial export]\\n ] of\\n [xs]\\n | all_used xs\\n -> return [IEThingAll (IEThingAllExt Nothing noAnn noAnn noAnn)\\n (NoNamespaceSpecifier noExtField)\\n (to_ie_post_rn $ noLocA n)\\n Nothing]\\n | otherwise\\n -> do { let ns_gres = map (expectJust . lookupGRE_Name rdr_env) cs\\n ns = map greName ns_gres\\n ; return [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n -- Note [Overloaded field import]\\n _other\\n -> do { let infos = map (expectJust . lookupGRE_Name rdr_env) cs\\n (ns_gres,fs_gres) = classifyGREs infos\\n ns = map greName (ns_gres ++ fs_gres)\\n fs = map fieldGREInfo fs_gres\\n ; return $\\n if all_non_overloaded fs\\n then map (\\\\nm -> IEVar Nothing (to_ie_post_rn_var $ noLocA nm) Nothing) ns\\n else [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n where\\n\\n all_used avail_cs = all (`elem` cs) avail_cs\\n\\n all_non_overloaded = all (not . flIsOverloaded . recFieldLabel)\\n\\n combine :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\n combine = map merge . NE.groupAllWith getKey\\n\\n getKey :: LImportDecl GhcRn -> (Bool, Maybe ModuleName, ModuleName)\\n getKey decl =\\n ( isImportDeclQualified . ideclQualified $ idecl -- is this qualified? (important that this be first)\\n , unLoc <$> ideclAs idecl -- what is the qualifier (inside Maybe monad)\\n , unLoc . ideclName $ idecl -- Module Name\\n )\\n where\\n idecl :: ImportDecl GhcRn\\n idecl = unLoc decl\\n\\n merge :: NonEmpty (LImportDecl GhcRn) -> LImportDecl GhcRn\\n merge decls@((L l decl) :| _) = L l (decl { ideclImportList = Just (Exactly, lies) })\\n where lies = concatMap snd $ mapMaybe (ideclImportList . unLoc) $ NE.toList decls\\n\\nclassifyGREs :: [GlobalRdrElt] -> ([GlobalRdrElt], [FieldGlobalRdrElt])\\nclassifyGREs = partition (not . isRecFldGRE)\\n\\nprintMinimalImports :: HscSource -> [ImportDeclUsage] -> RnM ()\\n-- See Note [Printing minimal imports]\\nprintMinimalImports hsc_src imports_w_usage\\n = do { imports\' <- excludeGenerated <$> getMinimalImports imports_w_usage\\n ; this_mod <- getModule\\n ; dflags <- getDynFlags\\n ; liftIO $ withFile (mkFilename dflags this_mod) WriteMode $ \\\\h ->\\n printForUser dflags h neverQualify AllTheWay (vcat (map ppr imports\'))\\n -- The neverQualify is important. We are printing Names\\n -- but they are in the context of an \'import\' decl, and\\n -- we never qualify things inside there\\n -- E.g. import Blag( f, b )\\n -- not import Blag( Blag.f, Blag.g )!\\n }\\n where\\n mkFilename dflags this_mod\\n | Just d <- dumpDir dflags = d basefn\\n | otherwise = basefn\\n where\\n suffix = case hsc_src of\\n HsBootFile -> \\".imports-boot\\"\\n HsSrcFile -> \\".imports\\"\\n HsigFile -> \\".imports\\"\\n basefn = moduleNameString (moduleName this_mod) ++ suffix\\n\\n\\nto_ie_post_rn_var :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn_var (L l n)\\n | isDataOcc $ occName n = L l (IEPattern noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n\\n\\nto_ie_post_rn :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn (L l n)\\n | isTcOcc occ && isSymOcc occ = L l (IEType noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n where occ = occName n\\n\\n{- Note [Do not warn about Prelude hiding]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWe do not warn about\\n import Prelude hiding( x, y )\\nbecause even if nothing else from Prelude is used, it may be essential to hide\\nx,y to avoid name-shadowing warnings. Example (#9061)\\n import Prelude hiding( log )\\n f x = log where log = ()\\n\\nNote [Unused imports]\\n~~~~~~~~~~~~~~~~~~~~~\\nIn `warnUnusedImport`, if we see an import with an explicit list imports, thus\\n import M( a, b )\\nand neither `a` nor `b` is used, we report the entire import decl as unused. We\\ncheck this by looking at the names that it brings into scope scope; if there are\\nno ununused names, don\'t report.\\n\\n(UI1) We don\'t want to complain about `import M()`, because that is often used to bring\\n M\'s /instances/ into scope. That is neatly dealt with by the \\"no unused\\n names\\" (nor unused wildcard imports) criterion.\\n\\n(UI2) We don\'t report a decl as unused if it has an `as Rebindable` qualifier.\\n See (KN1) in Note [Overview of known entities] in GHC.Builtin\\n\\n\\nNote [Printing minimal imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nTo print the minimal imports we walk over all import decls (both user-supplied\\nand generated), trim their import lists, then filter out generated decls.\\n\\nNB that\\n\\n * We do *not* change the \'qualified\' or \'as\' parts!\\n\\n * We do not discard a decl altogether; we might need instances\\n from it. Instead we just trim to an empty import list\\n\\nNote [Partial export]\\n~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have\\n\\n module A( op ) where\\n class C a where\\n op :: a -> a\\n\\n module B where\\n import A\\n f = ..op...\\n\\nThen the minimal import for module B is\\n import A( op )\\nnot\\n import A( C( op ) )\\nwhich we would usually generate if C was exported from B. Hence\\nthe availExportsDecl test when deciding what to generate.\\n\\n\\nNote [Overloaded field import]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nOn the other hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n data T = MkT { foo :: Int }\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( T(foo) )\\nbecause when DuplicateRecordFields is enabled, field selectors are\\nnot in scope without their enclosing datatype.\\n\\nOn the third hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n pattern MkT { foo } = Just foo\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( foo )\\nbecause foo doesn\'t have a parent. This might actually be ambiguous if A\\nexports another field called foo, but there is no good answer to return and this\\nis a very obscure corner, so it seems to be the best we can do. See\\nDRFPatSynExport for a test of this.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Errors}\\n* *\\n************************************************************************\\n-}\\n\\nbadImportItemErr\\n :: ModIface -> ImpDeclSpec -> IE GhcPs\\n -> IsSubordinateError\\n -> [AvailInfo]\\n -> TcRn (NonEmpty ImportLookupReason)\\nbadImportItemErr iface decl_spec ie sub avails = do\\n exts <- importLookupExtensions\\n let import_lookup_bad :: BadImportKind -> ImportLookupReason\\n import_lookup_bad k = ImportLookupBad k iface decl_spec ie exts\\n dflags <- getDynFlags\\n hsc_env <- getTopEnv\\n let rdr_env = mkGlobalRdrEnv\\n $ gresFromAvails hsc_env (Just imp_spec) all_avails\\n pure $ fmap import_lookup_bad (importErrorKind dflags rdr_env)\\n where\\n importErrorKind :: DynFlags -> GlobalRdrEnv -> NonEmpty BadImportKind\\n importErrorKind dflags rdr_env\\n | any checkIfTyCon avails = case sub of\\n IsNotSubordinate -> NE.singleton BadImportAvailTyCon\\n IsSubordinateError { subordinate_err_parent = gre\\n , subordinate_err_unavailable = unavailable\\n , subordinate_err_nontype = nontype\\n , subordinate_err_nondata = nondata }\\n -> NE.fromList $ catMaybes $\\n [ fmap (BadImportNotExportedSubordinates gre) (NE.nonEmpty unavailable)\\n , fmap (BadImportNonTypeSubordinates gre) (NE.nonEmpty nontype)\\n , fmap (BadImportNonDataSubordinates gre) (NE.nonEmpty nondata) ]\\n | any checkIfVarName avails = NE.singleton BadImportAvailVar\\n | Just con <- find checkIfDataCon avails = NE.singleton (BadImportAvailDataCon (availOccName con))\\n | otherwise = NE.singleton (BadImportNotExported suggs)\\n where\\n suggs = similar_suggs ++ fieldSelectorSuggestions rdr_env rdr\\n what_look = case sub of\\n IsNotSubordinate -> WL_TyCon_or_TermVar\\n IsSubordinateError { subordinate_err_parent = gre } ->\\n case greInfo gre of\\n IAmTyCon ClassFlavour\\n -> WL_TyCon_or_TermVar\\n _ -> WL_Term\\n similar_names =\\n similarNameSuggestions (Unbound.LF what_look WL_Global)\\n dflags rdr_env emptyLocalRdrEnv rdr\\n similar_suggs =\\n case NE.nonEmpty $ mapMaybe imported_item $ similar_names of\\n Just similar -> [ SuggestSimilarNames rdr similar ]\\n Nothing -> [ ]\\n\\n -- Only keep imported items, and set the \\"HowInScope\\" to\\n -- \\"Nothing\\" to avoid printing \\"imported from...\\" in the suggestion\\n -- error message.\\n imported_item (SimilarRdrName rdr_name gre (Just (ImportedBy {})))\\n = Just (SimilarRdrName rdr_name gre Nothing)\\n imported_item _ = Nothing\\n\\n checkIfDataCon = checkIfAvailMatches isDataConName\\n checkIfTyCon = checkIfAvailMatches isTyConName\\n checkIfVarName =\\n \\\\case\\n AvailTC{} -> False\\n Avail n -> importedFS == occNameFS (occName n)\\n && (isVarOcc <||> isFieldOcc) (occName n)\\n checkIfAvailMatches namePred =\\n \\\\case\\n AvailTC _ ns ->\\n case find (\\\\n -> importedFS == occNameFS (occName n)) ns of\\n Just n -> namePred n\\n Nothing -> False\\n Avail{} -> False\\n availOccName = occName . availName\\n rdr = ieName ie\\n importedFS = occNameFS $ rdrNameOcc rdr\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n all_avails = mi_exports iface\\n\\nimportLookupExtensions :: TcRn ImportLookupExtensions\\nimportLookupExtensions = do\\n ile_pattern_synonyms <- xoptM LangExt.PatternSynonyms\\n ile_explicit_namespaces <- xoptM LangExt.ExplicitNamespaces\\n return ImportLookupExtensions{ile_pattern_synonyms, ile_explicit_namespaces}\\n\\naddDupDeclErr :: NonEmpty GlobalRdrElt -> TcRn ()\\naddDupDeclErr gres@(gre :| _)\\n -- Report the error at the later location\\n = addErrAt (getSrcSpan (NE.last sorted_names)) $ (TcRnDuplicateDecls (greOccName gre) sorted_names)\\n where\\n sorted_names =\\n NE.sortBy (SrcLoc.leftmost_smallest `on` nameSrcSpan)\\n (fmap greName gres)\\n\\n-- This data decl will parse OK\\n-- data T = a Int\\n-- treating \\"a\\" as the constructor.\\n-- It is really hard to make the parser spot this malformation.\\n-- So the renamer has to check that the constructor is legal\\n--\\n-- We can get an operator as the constructor, even in the prefix form:\\n-- data T = :% Int Int\\n-- from interface files, which always print in prefix form\\n--\\n-- We also allow type constructor names, which are defined by \\"type data\\"\\n-- declarations. See Note [Type data declarations] in GHC.Rename.Module.\\n\\ncheckConName :: RdrName -> TcRn ()\\ncheckConName name\\n = checkErr (isRdrDataCon name || isRdrTc name) (TcRnIllegalDataCon name)\\n", "filetypes": ["haskell"]}}}' 2026-10-16 14:49:21,981 - DEBUG - POST b'http://127.0.0.1:37093/receive_messages' {'content-type': 'application/json', 'x-ycm-hmac': b'Rga7Yd4l4fgfufwYw+0sxzurvznImlBO0MPmgAlS4EY='} b'{"filepath": "/home/enrico/ghc/compiler/GHC/Rename/Names.hs", "line_num": 1, "column_num": 1, "working_dir": "/home/enrico/ghc", "file_data": {"/home/enrico/ghc/compiler/GHC/Rename/Names.hs": {"contents": "{-\\n(c) The GRASP/AQUA Project, Glasgow University, 1992-1998\\n\\nExtracting imported and top-level names in scope\\n-}\\n\\n{-# LANGUAGE NondecreasingIndentation #-}\\n{-# LANGUAGE TypeFamilies #-}\\n\\nmodule GHC.Rename.Names (\\n rnImports, getLocalNonValBinders, newRecordFieldLabel,\\n importsFromIface,\\n ImportUserSpec(..),\\n extendGlobalRdrEnvRn,\\n gresFromAvails,\\n calculateAvails,\\n reportUnusedNames,\\n checkConName,\\n mkChildEnv,\\n findChildren,\\n mkBadExportSubordinate,\\n findImportUsage,\\n getMinimalImports,\\n printMinimalImports,\\n renamePkgQual, renameRawPkgQual,\\n classifyGREs,\\n ImportDeclUsage,\\n rnNamespaceSpecifier\\n ) where\\n\\nimport GHC.Prelude hiding ( head, init, last, tail )\\n\\nimport GHC.Driver.Env\\nimport GHC.Driver.Session\\nimport GHC.Driver.Ppr\\n\\nimport GHC.Rename.Env\\nimport GHC.Rename.Fixity\\nimport GHC.Rename.Utils ( warnUnusedTopBinds )\\nimport GHC.Rename.Unbound\\nimport qualified GHC.Rename.Unbound as Unbound\\n\\nimport GHC.Tc.Errors.Types\\nimport GHC.Tc.Utils.Env\\nimport GHC.Tc.Utils.Monad\\nimport GHC.Tc.Types.LclEnv\\nimport GHC.Tc.Zonk.TcType ( tcInitTidyEnv )\\n\\nimport GHC.Hs\\nimport GHC.Iface.Load ( loadSrcInterface, loadSrcInterface_maybe )\\nimport GHC.Iface.Errors.Types\\n ( IfaceMessage(..), MissingInterfaceError, InterfaceLookingFor(..)\\n , LoadEssentialsReason(..) )\\nimport GHC.Iface.Syntax ( fromIfaceWarnings )\\nimport GHC.Builtin.Modules( pRELUDE_NAME, rEBINDABLE_MOD_NAME )\\nimport GHC.Parser.PostProcess ( setRdrNameSpace )\\nimport GHC.Core.TyCo.Tidy\\nimport GHC.Core.PatSyn\\nimport GHC.Core.TyCon ( TyCon, tyConName )\\nimport qualified GHC.LanguageExtensions as LangExt\\n\\nimport GHC.Utils.Outputable as Outputable\\nimport GHC.Utils.Misc as Utils\\nimport GHC.Utils.Panic\\n\\nimport GHC.Types.Fixity.Env\\nimport GHC.Types.SafeHaskell\\nimport GHC.Types.Name\\nimport GHC.Types.Name.Env\\nimport GHC.Types.Name.Set\\nimport GHC.Types.Name.Reader\\nimport GHC.Types.Avail\\nimport GHC.Types.FieldLabel\\nimport GHC.Types.Hint\\nimport GHC.Types.SourceFile\\nimport GHC.Types.SrcLoc as SrcLoc\\nimport GHC.Types.Basic (TyConFlavour (..), convImportLevel, VisArity)\\nimport GHC.Types.UnresolvedImport\\nimport GHC.Types.Id\\nimport GHC.Types.PkgQual\\nimport GHC.Types.GREInfo (ConInfo(..), ConFieldInfo (..), ConLikeInfo (ConIsData))\\n\\nimport GHC.Unit\\nimport GHC.Unit.Module.Warnings\\nimport GHC.Unit.Module.ModIface\\nimport GHC.Unit.Module.Imported\\nimport GHC.Unit.Module.Deps\\nimport GHC.Unit.Env\\n\\nimport GHC.Data.Bag\\nimport GHC.Data.FastString\\nimport GHC.Data.FastString.Env\\nimport GHC.Data.Maybe\\nimport GHC.Data.List.SetOps ( removeDups )\\n\\nimport Control.Arrow ( second )\\nimport Control.Monad\\nimport Data.Foldable ( for_ )\\nimport Data.IntMap ( IntMap )\\nimport qualified Data.IntMap as IntMap\\nimport Data.Map ( Map )\\nimport qualified Data.Map as Map\\nimport Data.Ord ( comparing )\\nimport Data.Semigroup ( Any(..) )\\nimport qualified Data.Semigroup as S\\nimport Data.List ( partition, find, sortBy )\\nimport Data.List.NonEmpty (NonEmpty(..))\\nimport qualified Data.List.NonEmpty as NE\\nimport Data.Function ( on )\\nimport qualified Data.Set as S\\nimport System.FilePath (())\\nimport System.IO\\n\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{rnImports}\\n* *\\n************************************************************************\\n\\nNote [Tracking Trust Transitively]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen we import a package as well as checking that the direct imports are safe\\naccording to the rules outlined in the Note [Safe Haskell Trust Check] in GHC.Driver.Main\\nwe must also check that these rules hold transitively for all dependent modules\\nand packages. Doing this without caching any trust information would be very\\nslow as we would need to touch all packages and interface files a module depends\\non. To avoid this we make use of the property that if a modules Safe Haskell\\nmode changes, this triggers a recompilation from that module in the dependency\\ngraph. So we can just worry mostly about direct imports.\\n\\nThere is one trust property that can change for a package though without\\nrecompilation being triggered: package trust. So we must check that all\\npackages a module transitively depends on to be trusted are still trusted when\\nwe are compiling this module (as due to recompilation avoidance some modules\\nbelow may not be considered trusted any more without recompilation being\\ntriggered).\\n\\nWe handle this by augmenting the existing transitive list of packages a module M\\ndepends on with a bool for each package that says if it must be trusted when the\\nmodule M is being checked for trust. This list of trust required packages for a\\nsingle import is gathered in the rnImportDecl function and stored in an\\nImportAvails data structure. The union of these trust required packages for all\\nimports is done by the rnImports function using the combine function which calls\\nthe plusImportAvails function that is a union operation for the ImportAvails\\ntype. This gives us in an ImportAvails structure all packages required to be\\ntrusted for the module we are currently compiling. Checking that these packages\\nare still trusted (and that direct imports are trusted) is done in\\nGHC.Driver.Main.checkSafeImports.\\n\\nSee the note below, [Trust Own Package] for a corner case in this method and\\nhow its handled.\\n\\n\\nNote [Trust Own Package]\\n~~~~~~~~~~~~~~~~~~~~~~~~\\nThere is a corner case of package trust checking that the usual transitive check\\ndoesn\'t cover. (For how the usual check operates see the Note [Tracking Trust\\nTransitively] below). The case is when you import a -XSafe module M and M\\nimports a -XTrustworthy module N. If N resides in a different package than M,\\nthen the usual check works as M will record a package dependency on N\'s package\\nand mark it as required to be trusted. If N resides in the same package as M\\nthough, then importing M should require its own package be trusted due to N\\n(since M is -XSafe so doesn\'t create this requirement by itself). The usual\\ncheck fails as a module doesn\'t record a package dependency of its own package.\\nSo instead we now have a bool field in a modules interface file that simply\\nstates if the module requires its own package to be trusted. This field avoids\\nus having to load all interface files that the module depends on to see if one\\nis trustworthy.\\n\\n\\nNote [Trust Transitive Property]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSo there is an interesting design question in regards to transitive trust\\nchecking. Say I have a module B compiled with -XSafe. B is dependent on a bunch\\nof modules and packages, some packages it requires to be trusted as its using\\n-XTrustworthy modules from them. Now if I have a module A that doesn\'t use safe\\nhaskell at all and simply imports B, should A inherit all the trust\\nrequirements from B? Should A now also require that a package p is trusted since\\nB required it?\\n\\nWe currently say no but saying yes also makes sense. The difference is, if a\\nmodule M that doesn\'t use Safe Haskell imports a module N that does, should all\\nthe trusted package requirements be dropped since M didn\'t declare that it cares\\nabout Safe Haskell (so -XSafe is more strongly associated with the module doing\\nthe importing) or should it be done still since the author of the module N that\\nuses Safe Haskell said they cared (so -XSafe is more strongly associated with\\nthe module that was compiled that used it).\\n\\nGoing with yes is a simpler semantics we think and harder for the user to stuff\\nup but it does mean that Safe Haskell will affect users who don\'t care about\\nSafe Haskell as they might grab a package from Cabal which uses safe haskell (say\\nnetwork) and that packages imports -XTrustworthy modules from another package\\n(say bytestring), so requires that package is trusted. The user may now get\\ncompilation errors in code that doesn\'t do anything with Safe Haskell simply\\nbecause they are using the network package. They will have to call \'ghc-pkg\\ntrust network\' to get everything working. Due to this invasive nature of going\\nwith yes we have gone with no for now.\\n-}\\n\\n-- | Process Import Decls. See \'rnImportDecl\' for a description of what\\n-- the return types represent.\\n-- Note: Do the non SOURCE ones first, so that we get a helpful warning\\n-- for SOURCE ones that are unnecessary\\nrnImports :: [(LImportDecl GhcPs, SDoc)]\\n -> RnM ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\nrnImports imports = do\\n tcg_env <- getGblEnv\\n -- NB: want an identity module here, because it\'s OK for a signature\\n -- module to import from its implementor\\n let this_mod = tcg_mod tcg_env\\n let (source, ordinary) = partition (is_source_import . fst) imports\\n is_source_import (d::LImportDecl GhcPs) = ideclSource (unLoc d) == IsBoot\\n stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary\\n stuff2 <- mapAndReportM (rnImportDecl this_mod) source\\n -- Safe Haskell: See Note [Tracking Trust Transitively]\\n let (decls, imp_user_spec, rdr_env, imp_avails) = combine (stuff1 ++ stuff2)\\n -- Update imp_boot_mods if imp_direct_mods mentions any of them\\n let merged_import_avail = clobberSourceImports imp_avails\\n return (decls, imp_user_spec, rdr_env, merged_import_avail)\\n\\n where\\n clobberSourceImports imp_avails =\\n imp_avails { imp_boot_mods = imp_boot_mods\' }\\n where\\n imp_boot_mods\' = mergeInstalledModuleEnv combJ id (const emptyInstalledModuleEnv)\\n (imp_boot_mods imp_avails)\\n (imp_direct_dep_mods imp_avails)\\n\\n combJ (GWIB _ IsBoot) (_, x) = Just x\\n combJ r _ = Just r\\n -- See Note [Combining ImportAvails]\\n combine :: [(LImportDecl GhcRn, ImportUserSpec, GlobalRdrEnv, ImportAvails)]\\n -> ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\n combine ss =\\n let (decls, imp_user_spec, rdr_env, imp_avails, finsts) = foldr\\n plus\\n ([], [], emptyGlobalRdrEnv, emptyImportAvails, emptyModuleSet)\\n ss\\n in (decls, imp_user_spec, rdr_env, imp_avails { imp_finsts = moduleSetElts finsts })\\n\\n plus (decl, us, gbl_env1, imp_avails1)\\n (decls, uss, gbl_env2, imp_avails2, finsts_set)\\n = ( decl:decls,\\n us:uss,\\n gbl_env1 `plusGlobalRdrEnv` gbl_env2,\\n imp_avails1\' `plusImportAvails` imp_avails2,\\n extendModuleSetList finsts_set new_finsts )\\n where\\n imp_avails1\' = imp_avails1 { imp_finsts = [] }\\n new_finsts = imp_finsts imp_avails1\\n\\n{-\\nNote [Combining ImportAvails]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nimp_finsts in ImportAvails is a list of family instance modules\\ntransitively depended on by an import. imp_finsts for a currently\\ncompiled module is a union of all the imp_finsts of imports.\\nComputing the union of two lists of size N is O(N^2) and if we\\ndo it to M imports we end up with O(M*N^2). That can get very\\nexpensive for bigger module hierarchies.\\n\\nUnion can be optimized to O(N log N) if we use a Set.\\nimp_finsts is converted back and forth between dep_finsts, so\\nchanging a type of imp_finsts means either paying for the conversions\\nor changing the type of dep_finsts as well.\\n\\nI\'ve measured that the conversions would cost 20% of allocations on my\\ntest case, so that can be ruled out.\\n\\nChanging the type of dep_finsts forces checkFamInsts to\\nget the module lists in non-deterministic order. If we wanted to restore\\nthe deterministic order, we\'d have to sort there, which is an additional\\ncost. As far as I can tell, using a non-deterministic order is fine there,\\nbut that\'s a brittle nonlocal property which I\'d like to avoid.\\n\\nAdditionally, dep_finsts is read from an interface file, so its \\"natural\\"\\ntype is a list. Which makes it a natural type for imp_finsts.\\n\\nSince rnImports.combine is really the only place that would benefit from\\nit being a Set, it makes sense to optimize the hot loop in rnImports.combine\\nwithout changing the representation.\\n\\nSo here\'s what we do: instead of naively merging ImportAvails with\\nplusImportAvails in a loop, we make plusImportAvails merge empty imp_finsts\\nand compute the union on the side using Sets. When we\'re done, we can\\nconvert it back to a list. One nice side effect of this approach is that\\nif there\'s a lot of overlap in the imp_finsts of imports, the\\nSet doesn\'t really need to grow and we don\'t need to allocate.\\n\\nRunning generateModules from #14693 with DEPTH=16, WIDTH=30 finishes in\\n23s before, and 11s after.\\n-}\\n\\n-- | Given a located import declaration @decl@ from @this_mod@,\\n-- calculate the following pieces of information:\\n--\\n-- 1. An updated \'LImportDecl\', where all unresolved \'RdrName\' in\\n-- the entity lists have been resolved into \'Name\'s,\\n--\\n-- 2. A \'GlobalRdrEnv\' representing the new identifiers that were\\n-- brought into scope (taking into account module qualification\\n-- and hiding),\\n--\\n-- 3. \'ImportAvails\' summarizing the identifiers that were imported\\n-- by this declaration, and\\n--\\n-- 4. A boolean \'AnyHpcUsage\' which is true if the imported module\\n-- used HPC.\\nrnImportDecl :: Module -> (LImportDecl GhcPs, SDoc)\\n -> RnM (LImportDecl GhcRn, ImportUserSpec , GlobalRdrEnv, ImportAvails)\\nrnImportDecl this_mod\\n (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name\\n , ideclPkgQual = raw_pkg_qual\\n , ideclSource = want_boot\\n , ideclSafe = mod_safe\\n , ideclLevelSpec = import_level\\n , ideclQualified = qual_style\\n , ideclExt = XImportDeclPass { ideclOrigin = origin }\\n , ideclAs = as_mod, ideclImportList = imp_details }), import_reason)\\n = setSrcSpanA loc $ do\\n\\n case raw_pkg_qual of\\n NoRawPkgQual -> pure ()\\n RawPkgQual {} -> do\\n pkg_imports <- xoptM LangExt.PackageImports\\n when (not pkg_imports) $ addErr TcRnPackageImportsDisabled\\n\\n let qual_only = isImportDeclQualified qual_style\\n generated = isGeneratedImport origin\\n\\n lookup_scope = importDeclLookupScope origin\\n\\n -- If there\'s an error in loadInterface, (e.g. interface\\n -- file not found) we get lots of spurious errors from \'filterImports\'\\n let imp_mod_name = unLoc loc_imp_mod_name\\n doc = ppr imp_mod_name <+> import_reason\\n\\n hsc_env <- getTopEnv\\n unit_env <- hsc_unit_env <$> getTopEnv\\n let pkg_qual = renameRawPkgQual unit_env imp_mod_name raw_pkg_qual\\n\\n -- Check for self-import, which confuses the typechecker (#9032)\\n -- ghc --make rejects self-import cycles already, but batch-mode may not\\n -- at least not until GHC.IfaceToCore.tcHiBootIface, which is too late to avoid\\n -- typechecker crashes. (Indirect self imports are not caught until\\n -- GHC.IfaceToCore, see #10337 tracking how to make this error better.)\\n --\\n -- Originally, we also allowed \'import {-# SOURCE #-} M\', but this\\n -- caused bug #10182: in one-shot mode, we should never load an hs-boot\\n -- file for the module we are compiling into the EPS. In principle,\\n -- it should be possible to support this mode of use, but we would have to\\n -- extend Provenance to support a local definition in a qualified location.\\n -- For now, we don\'t support it, but see #10336\\n when (imp_mod_name == moduleName this_mod &&\\n (case pkg_qual of -- If we have import \\"\\" M, then we should\\n -- check that \\"\\" is \\"this\\" (which is magic)\\n -- or the name of this_mod\'s package. Yurgh!\\n -- c.f. GHC.findModule, and #9997\\n NoPkgQual -> True\\n ThisPkg uid -> uid == homeUnitId_ (hsc_dflags hsc_env)\\n OtherPkg _ -> False))\\n (addErr (TcRnSelfImport imp_mod_name))\\n\\n -- Check for a missing import list (Opt_WarnMissingImportList also\\n -- checks for T(..) items but that is done in checkDodgyImport below)\\n case imp_details of\\n Just (Exactly, _) -> return () -- Explicit import list\\n _ | generated -> return () -- Do not bleat for generated imports\\n | qual_only -> return ()\\n | otherwise -> addDiagnostic (TcRnNoExplicitImportList imp_mod_name)\\n\\n\\n mb_iface <- loadSrcInterface_maybe doc lookup_scope imp_mod_name want_boot pkg_qual\\n iface <- case mb_iface of\\n Succeeded iface -> return iface\\n Failed err -> failWithTc $\\n importDeclLoadFailure origin imp_mod_name want_boot err\\n\\n -- Compiler sanity check: if the import didn\'t say\\n -- {-# SOURCE #-} we should not get a hi-boot file\\n warnPprTrace ((want_boot == NotBoot) && (mi_boot iface == IsBoot)) \\"rnImportDecl\\" (ppr imp_mod_name) $ do\\n\\n -- Issue a user warning for a redundant {- SOURCE -} import\\n -- NB that we arrange to read all the ordinary imports before\\n -- any of the {- SOURCE -} imports.\\n --\\n -- in --make and GHCi, the compilation manager checks for this,\\n -- and indeed we shouldn\'t do it here because the existence of\\n -- the non-boot module depends on the compilation order, which\\n -- is not deterministic. The hs-boot test can show this up.\\n dflags <- getDynFlags\\n warnIf ((want_boot == IsBoot) && (mi_boot iface == NotBoot) && isOneShot (ghcMode dflags))\\n (TcRnRedundantSourceImport imp_mod_name)\\n when (mod_safe && not (safeImportsOn dflags)) $\\n addErr (TcRnSafeImportsDisabled imp_mod_name)\\n\\n let imp_mod = mi_module iface\\n qual_mod_name = fmap unLoc as_mod `orElse` imp_mod_name\\n imp_spec = ImpDeclSpec { is_mod = imp_mod, is_qual = qual_only,\\n is_dloc = locA loc, is_as = qual_mod_name,\\n is_pkg_qual = pkg_qual, is_isboot = want_boot,\\n is_level = convImportLevel import_level }\\n\\n let filter_imports = do\\n -- filter the imports according to the import declaration\\n (new_imp_details, imp_user_list, gbl_env)\\n <- filterImports hsc_env iface imp_spec imp_details\\n -- for certain error messages, we\\u2019d like to know what could be\\n -- imported here, if everything were imported\\n potential_gres <- (\\\\(_,_,x) -> x) <$> filterImports hsc_env iface imp_spec Nothing\\n return (new_imp_details, imp_user_list, gbl_env, potential_gres)\\n\\n (new_imp_details, imp_user_list, gbl_env, potential_gres) <-\\n case origin of\\n ImplicitEssentialsImport ->\\n -- The implicit GHC.Essentials import does not bring anything into scope.\\n -- See Note [Finding GHC.Essentials] in GHC.Builtin.\\n return (Nothing, ImpUserDependOnly, emptyGlobalRdrEnv, emptyGlobalRdrEnv)\\n UserWrittenImport -> filter_imports\\n ImplicitPreludeImport -> filter_imports\\n PluginImport -> filter_imports\\n\\n let is_hiding | Just (EverythingBut,_) <- imp_details = True\\n | otherwise = False\\n\\n -- should the import be safe?\\n mod_safe\' = mod_safe\\n || (not generated && safeDirectImpsReq dflags)\\n || (generated && safeImplicitImpsReq dflags)\\n\\n hsc_env <- getTopEnv\\n let home_unit = hsc_home_unit hsc_env\\n other_home_units = hsc_all_home_unit_ids hsc_env\\n\\n imported_by\\n | isDependOnlyImport imp_user_list\\n = ImportedBySystem\\n | otherwise\\n = ImportedByUser $ ImportedModsVal\\n { imv_name = is_as imp_spec\\n , imv_span = locA loc\\n , imv_is_safe = mod_safe\'\\n , imv_is_hiding = is_hiding\\n , imv_all_exports = potential_gres\\n , imv_qualified = qual_only\\n , imv_is_level = convImportLevel import_level\\n }\\n imports = calculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by\\n\\n -- Complain if we import a deprecated module\\n case fromIfaceWarnings (mi_warns iface) of\\n WarnAll txt -> addDiagnostic (TcRnDeprecatedModule imp_mod_name txt)\\n _ -> return ()\\n\\n let new_imp_decl = ImportDecl\\n { ideclExt = ideclExt decl\\n , ideclName = ideclName decl\\n , ideclPkgQual = pkg_qual\\n , ideclSource = ideclSource decl\\n , ideclSafe = mod_safe\'\\n , ideclQualified = ideclQualified decl\\n , ideclAs = ideclAs decl\\n , ideclImportList = new_imp_details\\n , ideclLevelSpec = ideclLevelSpec decl\\n }\\n\\n return (L loc new_imp_decl, ImpUserSpec imp_spec imp_user_list, gbl_env, imports)\\n\\n-- | The error message to emit when we failed to load an interface.\\nimportDeclLoadFailure :: ImportDeclOrigin -> ModuleName -> IsBootInterface\\n -> MissingInterfaceError -> TcRnMessage\\nimportDeclLoadFailure ImplicitEssentialsImport _ _ err\\n = TcRnInterfaceError $ CantFindEssentials err LookingForEssentialsModule\\nimportDeclLoadFailure _ mod_name want_boot err\\n = TcRnInterfaceError $ Can\'tFindInterface err $ LookingForModule mod_name want_boot\\n\\n-- | Rename raw package imports\\nrenameRawPkgQual :: UnitEnv -> ModuleName -> RawPkgQual -> PkgQual\\nrenameRawPkgQual unit_env mn = \\\\case\\n NoRawPkgQual -> NoPkgQual\\n RawPkgQual _ fs -> renamePkgQual unit_env mn $ Just fs\\n\\n-- | Rename raw package imports\\nrenamePkgQual :: UnitEnv -> ModuleName -> Maybe FastString -> PkgQual\\nrenamePkgQual unit_env mn mb_pkg = case mb_pkg of\\n Nothing -> NoPkgQual\\n Just pkg_fs\\n | Just uid <- homeUnitId <$> ue_homeUnit unit_env\\n , pkg_fs == fsLit \\"this\\"\\n -> ThisPkg uid\\n\\n | Just (uid, _) <- find (fromMaybe False . fmap (== pkg_fs) . snd) home_names\\n -> ThisPkg uid\\n\\n | Just uid <- resolvePackageImport unit_state mn (PackageName pkg_fs)\\n -> OtherPkg uid\\n\\n | otherwise\\n -> OtherPkg (UnitId pkg_fs)\\n -- not really correct as pkg_fs is unlikely to be a valid unit-id but\\n -- we will report the failure later...\\n where\\n home_names =\\n [ (uid, mkFastString <$> thisPackageName (homeUnitEnv_dflags (ue_findHomeUnitEnv uid unit_env)))\\n | uid <- S.toList hpt_deps\\n ]\\n\\n unit_state = ue_homeUnitState unit_env\\n\\n hpt_deps :: S.Set UnitId\\n hpt_deps = homeUnitDepends unit_state\\n\\n\\n-- | Calculate the \'ImportAvails\' induced by an import of a particular\\n-- interface, but without \'imp_mods\'.\\ncalculateAvails :: HomeUnit\\n -> S.Set UnitId\\n -> ModIface\\n -> IsSafeImport\\n -> IsBootInterface\\n -> ImportedBy\\n -> ImportAvails\\ncalculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by =\\n let imp_mod = mi_module iface\\n imp_sem_mod= mi_semantic_module iface\\n orph_iface = mi_orphan iface\\n has_finsts = mi_finsts iface\\n deps = mi_deps iface\\n trust = getSafeMode $ mi_trust iface\\n trust_pkg = mi_trust_pkg iface\\n is_sig = mi_hsc_src iface == HsigFile\\n\\n -- If the module exports anything defined in this module, just\\n -- ignore it. Reason: otherwise it looks as if there are two\\n -- local definition sites for the thing, and an error gets\\n -- reported. Easiest thing is just to filter them out up\\n -- front. This situation only arises if a module imports\\n -- itself, or another module that imported it. (Necessarily,\\n -- this involves a loop.)\\n --\\n -- We do this *after* filterImports, so that if you say\\n -- module A where\\n -- import B( AType )\\n -- type AType = ...\\n --\\n -- module B( AType ) where\\n -- import {-# SOURCE #-} A( AType )\\n --\\n -- then you won\'t get a \'B does not export AType\' message.\\n\\n\\n -- Compute new transitive dependencies\\n --\\n -- \'dep_orphs\' and \'dep_finsts\' do NOT include the imported module\\n -- itself, but we DO need to include this module in \'imp_orphs\' and\\n -- \'imp_finsts\' if it defines an orphan or instance family; thus the\\n -- orph_iface/has_iface tests.\\n\\n deporphs = dep_orphs deps\\n depfinsts = dep_finsts deps\\n\\n orphans | orph_iface = assertPpr (not (imp_sem_mod `elem` deporphs)) (ppr imp_sem_mod <+> ppr deporphs) $\\n imp_sem_mod : deporphs\\n | otherwise = deporphs\\n\\n finsts | has_finsts = assertPpr (not (imp_sem_mod `elem` depfinsts)) (ppr imp_sem_mod <+> ppr depfinsts) $\\n imp_sem_mod : depfinsts\\n | otherwise = depfinsts\\n\\n -- Trusted packages are a lot like orphans.\\n trusted_pkgs | mod_safe\' = dep_trusted_pkgs deps\\n | otherwise = S.empty\\n\\n\\n pkg = moduleUnit (mi_module iface)\\n ipkg = toUnitId pkg\\n\\n -- Does this import mean we now require our own pkg\\n -- to be trusted? See Note [Trust Own Package]\\n ptrust = trust == Sf_Trustworthy || trust_pkg\\n pkg_trust_req\\n | isHomeUnit home_unit pkg = ptrust\\n | otherwise = False\\n\\n dependent_pkgs = if toUnitId pkg `S.member` other_home_units\\n then S.empty\\n else S.singleton (lvl, ipkg)\\n\\n lvl = case imported_by of\\n ImportedByUser imv -> imv_is_level imv\\n ImportedBySystem -> NormalLevel\\n\\n\\n direct_mods = if toUnitId pkg `S.member` other_home_units\\n then mkPlusModDeps (moduleUnitId imp_mod) lvl (GWIB (moduleName imp_mod) want_boot)\\n else emptyInstalledModuleEnv\\n\\n dep_boot_mods_map = mkModDeps (dep_boot_mods deps)\\n\\n\\n boot_mods\\n -- If we are looking for a boot module, it must be HPT\\n | IsBoot <- want_boot = extendInstalledModuleEnv dep_boot_mods_map (toUnitId <$> imp_mod) (GWIB (moduleName imp_mod) IsBoot)\\n -- Now we are importing A properly, so don\'t go looking for\\n -- A.hs-boot\\n | isHomeUnit home_unit pkg = dep_boot_mods_map\\n -- There\'s no boot files to find in external imports\\n | otherwise = emptyInstalledModuleEnv\\n\\n sig_mods =\\n if is_sig\\n then moduleName imp_mod : dep_sig_mods deps\\n else dep_sig_mods deps\\n\\n\\n in ImportAvails {\\n imp_mods = Map.singleton (mi_module iface) [imported_by],\\n imp_orphs = orphans,\\n imp_finsts = finsts,\\n imp_sig_mods = sig_mods,\\n imp_direct_dep_mods = direct_mods,\\n imp_dep_direct_pkgs = dependent_pkgs,\\n imp_boot_mods = boot_mods,\\n\\n -- Add in the imported modules trusted package\\n -- requirements. ONLY do this though if we import the\\n -- module as a safe import.\\n -- See Note [Tracking Trust Transitively]\\n -- and Note [Trust Transitive Property]\\n imp_trust_pkgs = trusted_pkgs,\\n -- Do we require our own pkg to be trusted?\\n -- See Note [Trust Own Package]\\n imp_trust_own_pkg = pkg_trust_req\\n }\\n\\nmkPlusModDeps :: UnitId -> ImportLevel -> ModuleNameWithIsBoot\\n -> InstalledModuleEnv (S.Set ImportLevel, ModuleNameWithIsBoot)\\nmkPlusModDeps uid st elt = extendInstalledModuleEnv emptyInstalledModuleEnv (mkModule uid (gwib_mod elt)) (S.singleton st, elt)\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{importsFromLocalDecls}\\n* *\\n************************************************************************\\n\\nFrom the top-level declarations of this module produce\\n * the lexical environment\\n * the ImportAvails\\ncreated by its bindings.\\n\\nNote [Top-level Names in Template Haskell decl quotes]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSee also: Note [Interactively-bound Ids in GHCi] in GHC.Driver.Env\\n Note [Looking up Exact RdrNames] in GHC.Rename.Env\\n\\nConsider a Template Haskell declaration quotation like this:\\n module M where\\n f x = h [d| f = 3 |]\\nWhen renaming the declarations inside [d| ...|], we treat the\\ntop level binders specially in two ways\\n\\n1. We give them an Internal Name, not (as usual) an External one.\\n This is done by GHC.Rename.Env.newTopSrcBinder.\\n\\n2. We make them *shadow* the outer bindings.\\n See Note [GlobalRdrEnv shadowing]\\n\\n3. We find out whether we are inside a [d| ... |] by testing the TH\\n level. This is a slight hack, because the level field was really\\n meant for the type checker, and here we are not interested in the\\n fields of Brack, hence the error thunks in thRnBrack.\\n-}\\n\\nextendGlobalRdrEnvRn :: [GlobalRdrElt]\\n -> MiniFixityEnv\\n -> RnM (TcGblEnv, TcLclEnv)\\n-- Updates both the GlobalRdrEnv and the FixityEnv\\n-- We return a new TcLclEnv only because we might have to\\n-- delete some bindings from it;\\n-- see Note [Top-level Names in Template Haskell decl quotes]\\n\\nextendGlobalRdrEnvRn new_gres new_fixities\\n = checkNoErrs $ -- See Note [Fail fast on duplicate definitions]\\n do { (gbl_env, lcl_env) <- getEnvs\\n ; level <- getThLevel\\n ; isGHCi <- getIsGHCi\\n ; let rdr_env = tcg_rdr_env gbl_env\\n fix_env = tcg_fix_env gbl_env\\n th_bndrs = getLclEnvThBndrs lcl_env\\n th_lvl = thLevelIndex level\\n\\n -- Delete new_occs from global and local envs\\n -- If we are in a TemplateHaskell decl bracket,\\n -- we are going to shadow them\\n -- See Note [GlobalRdrEnv shadowing]\\n inBracket = isBrackLevel level\\n\\n lcl_env_TH = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_rdr = minusLocalRdrEnv (tcl_rdr lcl_env) new_gres_env }) lcl_env\\n -- See Note [GlobalRdrEnv shadowing]\\n\\n lcl_env2 | inBracket = lcl_env_TH\\n | otherwise = lcl_env\\n\\n -- Deal with shadowing: see Note [GlobalRdrEnv shadowing]\\n want_shadowing = isGHCi || inBracket\\n rdr_env1 | want_shadowing = shadowNames False rdr_env new_gres_env\\n | otherwise = rdr_env\\n\\n lcl_env3 = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_th_bndrs = extendNameEnvList th_bndrs\\n [ ( n, (TopLevel, th_lvl) )\\n | n <- new_names ] }) lcl_env2\\n\\n ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres\\n\\n ; let fix_env\' = foldl\' extend_fix_env fix_env new_gres\\n gbl_env\' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env\' }\\n\\n ; traceRn \\"extendGlobalRdrEnvRn 2\\" (pprGlobalRdrEnv True rdr_env2)\\n ; return (gbl_env\', lcl_env3) }\\n where\\n new_names = map greName new_gres\\n new_gres_env = mkGlobalRdrEnv new_gres\\n\\n -- If there is a fixity decl for the gre, add it to the fixity env\\n extend_fix_env fix_env gre\\n | Just (L _ fi) <- lookupMiniFixityEnv new_fixities name\\n = extendNameEnv fix_env name (FixItem occ fi)\\n | otherwise\\n = fix_env\\n where\\n name = greName gre\\n occ = greOccName gre\\n\\n add_gre :: GlobalRdrEnv -> GlobalRdrElt -> RnM GlobalRdrEnv\\n -- Extend the GlobalRdrEnv with a LocalDef GRE\\n -- If there is already a LocalDef GRE with the same OccName,\\n -- report an error and discard the new GRE\\n -- This establishes INVARIANT 1 of GlobalRdrEnvs\\n add_gre env gre\\n | not (null dups) -- Same OccName defined twice\\n = do { addDupDeclErr (gre :| dups); return env }\\n\\n | otherwise\\n = return (extendGlobalRdrEnv env gre)\\n where\\n -- See Note [Reporting duplicate local declarations]\\n dups = filter isBadDupGRE\\n $ lookupGRE env (LookupOccName (greOccName gre) (RelevantGREsFOS WantBoth))\\n isBadDupGRE old_gre = isLocalGRE old_gre && greClashesWith gre old_gre\\n\\n{- Note [Fail fast on duplicate definitions]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIf there are duplicate bindings for the same thing, we want to fail\\nfast. Having two bindings for the same thing can cause follow-on errors.\\nExample (test T9975a):\\n data Test = Test { x :: Int }\\n pattern Test wat = Test { x = wat }\\nThis defines \'Test\' twice. The second defn has no field-names; and then\\nwe get an error from Test { x=wat }, saying \\"Test has no field \'x\'\\".\\n\\nEasiest thing is to bale out fast on duplicate definitions, which\\nwe do via `checkNoErrs` on `extendGlobalRdrEnvRn`.\\n\\nNote [Reporting duplicate local declarations]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn general, a single module may not define the same OccName multiple times. This\\nis checked in extendGlobalRdrEnvRn: when adding a new locally-defined GRE to the\\nGlobalRdrEnv we report an error if there are already duplicates in the\\nenvironment. This establishes INVARIANT 1 (see comments on GlobalRdrEnv in\\nGHC.Types.Name.Reader), which says that for a given OccName, all the\\nGlobalRdrElts to which it maps must have distinct \'greName\'s.\\n\\nFor example, the following will be rejected:\\n\\n f x = x\\n g x = x\\n f x = x -- Duplicate!\\n\\nUsers are allowed to introduce new GREs with the same OccName as an imported GRE,\\nas disambiguation is possible through the module system, e.g.:\\n\\n module M where\\n import N (f)\\n f x = x\\n g x = M.f x + N.f x\\n\\nIf both GREs are local, the general rule is that two GREs clash if they have\\nthe same OccName, i.e. they share a textual name and live in the same namespace.\\nHowever, there are additional clashes due to record fields:\\n\\n - a new variable clashes with previously defined record fields\\n which define field selectors,\\n\\n - a new record field shadows:\\n\\n - previously defined variables, if it defines a field selector,\\n - previously defined record fields, unless it is a duplicate record field.\\n\\nThis logic is implemented in the function \'GHC.Types.Name.Reader.greClashesWith\'.\\n\\nSee also Note [Skipping ambiguity errors at use sites of local declarations] in\\nGHC.Rename.Utils.\\n-}\\n\\n\\n{- *********************************************************************\\n* *\\n getLocalDeclBindersd@ returns the names for an HsDecl\\n It\'s used for source code.\\n\\n *** See Note [The Naming story] in GHC.Hs.Decls ****\\n* *\\n********************************************************************* -}\\n\\ngetLocalNonValBinders :: MiniFixityEnv -> HsGroup GhcPs\\n -> RnM ((TcGblEnv, TcLclEnv), NameSet)\\n-- Get all the top-level binders bound the group *except*\\n-- for value bindings, which are treated separately\\n-- Specifically we return AvailInfo for\\n-- * type decls (incl constructors and record selectors)\\n-- * class decls (including class ops)\\n-- * associated types\\n-- * foreign imports\\n-- * value signatures (in hs-boot files only)\\n\\ngetLocalNonValBinders fixity_env\\n (HsGroup { hs_valds = binds,\\n hs_tyclds = tycl_decls,\\n hs_fords = foreign_decls })\\n = do { -- Process all type/class decls *except* family instances\\n ; let inst_decls = tycl_decls >>= group_instds\\n ; dup_fields_ok <- xopt_DuplicateRecordFields <$> getDynFlags\\n ; has_sel <- xopt_FieldSelectors <$> getDynFlags\\n ; tc_gres\\n <- concatMapM\\n (new_tc dup_fields_ok has_sel)\\n (tyClGroupTyClDecls tycl_decls)\\n ; traceRn \\"getLocalNonValBinders 1\\" (ppr tc_gres)\\n ; envs <- extendGlobalRdrEnvRn tc_gres fixity_env\\n ; restoreEnvs envs $ do {\\n -- Bring these things into scope first\\n -- See Note [Looking up family names in family instances]\\n\\n -- Process all family instances\\n -- to bring new data constructors into scope\\n ; nti_gress <- mapM (new_assoc dup_fields_ok has_sel) inst_decls\\n\\n -- Finish off with value binders:\\n -- foreign decls and pattern synonyms for an ordinary module\\n -- type sigs in case of a hs-boot file only\\n ; is_boot <- tcIsHsBootOrSig\\n ; let val_bndrs\\n | is_boot = case binds of\\n ValBinds _ val_binds ->\\n -- In a hs-boot file, the value binders come from the\\n -- *signatures*, and there should be no foreign binders\\n [ L (l2l decl_loc) (unLoc n)\\n | L decl_loc (TypeSig _ _ ns _) <- (val_sigs val_binds), n <- ns]\\n _ -> panic \\"Non-ValBinds in hs-boot group\\"\\n | otherwise = for_hs_bndrs\\n ; val_gres <- mapM new_simple val_bndrs\\n\\n ; let avails = concat nti_gress ++ val_gres\\n new_bndrs = gresToNameSet avails `unionNameSet`\\n gresToNameSet tc_gres\\n ; traceRn \\"getLocalNonValBinders 2\\" (ppr avails)\\n ; envs <- extendGlobalRdrEnvRn avails fixity_env\\n ; return (envs, new_bndrs) } }\\n where\\n for_hs_bndrs :: [LocatedN RdrName]\\n for_hs_bndrs = hsForeignDeclsBinders foreign_decls\\n\\n -- the SrcSpan attached to the input should be the span of the\\n -- declaration, not just the name\\n new_simple :: LocatedN RdrName -> RnM GlobalRdrElt\\n new_simple rdr_name = do { nm <- newTopSrcBinder rdr_name\\n ; return (mkLocalVanillaGRE NoParent nm) }\\n\\n new_tc :: DuplicateRecordFields -> FieldSelectors -> LTyClDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_tc dup_fields_ok has_sel tc_decl -- NOT for type/data instances\\n = do { let TyDeclBinders (main_bndr, tc_flav) at_bndrs sig_bndrs\\n (LConsWithFields cons_with_flds flds) = hsLTyClDeclBinders tc_decl\\n ; tycon_name <- newTopSrcBinder $ la2la main_bndr\\n ; at_names <- mapM (newTopSrcBinder . la2la . fst) at_bndrs\\n ; sig_names <- mapM (newTopSrcBinder . la2la) sig_bndrs\\n ; con_names_with_flds <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst con_names_with_flds) flds\\n ; mapM_ (add_dup_fld_errs flds\') con_names_with_flds\\n ; let tc_gre = mkLocalTyConGRE (fmap (const tycon_name) tc_flav) tycon_name\\n fld_env = mk_fld_env con_names_with_flds flds\'\\n at_gres = zipWith (\\\\ (_, at_flav) at_nm -> mkLocalTyConGRE (fmap (const tycon_name) at_flav) at_nm)\\n at_bndrs at_names\\n sig_gres = map (mkLocalVanillaGRE (ParentIs tycon_name)) sig_names\\n con_gres = map (mkLocalConLikeGRE (ParentIs tycon_name)) fld_env\\n fld_gres = mkLocalFieldGREs (ParentIs tycon_name) fld_env\\n sub_gres = at_gres ++ sig_gres ++ con_gres ++ fld_gres\\n ; traceRn \\"getLocalNonValBinders new_tc\\" $\\n vcat [ text \\"tycon:\\" <+> ppr tycon_name\\n , text \\"tc_gre:\\" <+> ppr tc_gre\\n , text \\"sub_gres:\\" <+> ppr sub_gres ]\\n ; return $ tc_gre : sub_gres }\\n\\n -- Calculate the record field information, which feeds into the GlobalRdrElts\\n -- for DataCons and their fields. It\'s convenient to do this here where\\n -- we are working with a single datatype definition.\\n --\\n -- The information we needed was all set up for us:\\n -- see Note [Collecting record fields in data declarations] in GHC.Hs.Utils.\\n mk_fld_env :: [(Name, Either VisArity [Located Int])] -> IntMap FieldLabel\\n -> [(ConLikeName, ConInfo)]\\n mk_fld_env names flds =\\n [ (DataConName con, ConInfo (ConIsData (map fst names)) fld_info)\\n | (con, con_fl_indxs) <- names\\n , let fld_info = case fmap (map ((flds IntMap.!) . unLoc)) con_fl_indxs of\\n Left 0 -> ConIsNullary\\n Left arity -> ConHasPositionalArgs arity\\n Right [] -> ConIsNullary\\n Right (fld:flds) -> ConHasRecordFields $ fld NE.:| flds ]\\n\\n new_assoc :: DuplicateRecordFields -> FieldSelectors -> LInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_assoc _ _ (L _ (TyFamInstD {})) = return []\\n -- type instances don\'t bind new names\\n\\n new_assoc dup_fields_ok has_sel (L _ (DataFamInstD _ d))\\n = new_di dup_fields_ok has_sel Nothing d\\n new_assoc dup_fields_ok has_sel\\n (L _ (ClsInstD _ (ClsInstDecl { cid_poly_ty = inst_ty\\n , cid_decls = decls })))\\n = do -- First, attempt to grab the name of the class from the instance.\\n -- This step could fail if the instance is not headed by a class,\\n -- such as in the following examples:\\n --\\n -- (1) The class is headed by a bang pattern, such as in\\n -- `instance !Show Int` (#3811c)\\n -- (2) The class is headed by a type variable, such as in\\n -- `instance c` (#16385)\\n --\\n -- If looking up the class name fails, then mb_cls_gre will\\n -- be Nothing.\\n mb_cls_gre <- runMaybeT $ do\\n -- See (1) above\\n L loc cls_rdr <- MaybeT $ pure $ getLHsInstDeclClass_maybe inst_ty\\n -- See (2) above\\n MaybeT $ setSrcSpan (locA loc) $ lookupGlobalOccRn_maybe SameNameSpace cls_rdr\\n -- Assuming the previous step succeeded, process any associated data\\n -- family instances. If the previous step failed, bail out.\\n case mb_cls_gre of\\n Nothing\\n -> pure []\\n Just cls_gre\\n -> let cls_nm = greName cls_gre\\n in concatMapM (new_di dup_fields_ok has_sel (Just cls_nm) . unLoc) (data_fam_insts decls)\\n\\n data_fam_insts decls = concatMap get decls\\n where\\n get (L l (InstD _ (DataFamInstD { dfid_inst = d}))) = [L l d]\\n get _ = []\\n\\n new_di :: DuplicateRecordFields -> FieldSelectors\\n -> Maybe Name -- class name\\n -> DataFamInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_di dup_fields_ok has_sel mb_cls dfid@(DataFamInstDecl { dfid_eqn = ti_decl })\\n = do { main_name <- unLoc <$> lookupFamInstName mb_cls (feqn_tycon ti_decl)\\n ; let LConsWithFields cons_with_flds flds = hsDataFamInstBinders dfid\\n ; sub_names <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst sub_names) flds\\n ; mapM_ (add_dup_fld_errs flds\') sub_names\\n ; let fld_env = mk_fld_env sub_names flds\'\\n con_gres = map (mkLocalConLikeGRE (ParentIs main_name)) fld_env\\n field_gres = mkLocalFieldGREs (ParentIs main_name) fld_env\\n -- NB: the data family name is not bound here,\\n -- so we don\'t return a GlobalRdrElt for it here!\\n ; return $ con_gres ++ field_gres }\\n\\n -- Add errors if a constructor has a duplicate record field.\\n add_dup_fld_errs :: IntMap FieldLabel\\n -> (Name, Either VisArity [Located Int])\\n -> IOEnv (Env TcGblEnv TcLclEnv) ()\\n add_dup_fld_errs all_flds (con, con_flds_or_arity)\\n | Right con_flds <- con_flds_or_arity\\n , let (_, dups) = removeDups (comparing unLoc) con_flds\\n = for_ dups $ \\\\ dup_flds ->\\n -- Report the error at the location of the second occurrence\\n -- of the duplicate field.\\n let loc =\\n case dup_flds of\\n _ :| ( L loc _ : _) -> loc\\n L loc _ :| _ -> loc\\n dup_rdrs = fmap (nameRdrName . flSelector . (all_flds IntMap.!) . unLoc) dup_flds\\n in addErrAt loc $ TcRnDuplicateFieldName (RecordFieldDecl con) dup_rdrs\\n | otherwise\\n = return ()\\n\\nnewRecordFieldLabel :: DuplicateRecordFields -> FieldSelectors -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel\\nnewRecordFieldLabel _ _ [] _ = error \\"newRecordFieldLabel: datatype has no constructors!\\"\\nnewRecordFieldLabel dup_fields_ok has_sel (dc:_) (L loc (FieldOcc _ (L _ fld)))\\n = do { selName <- newTopSrcBinder $ L (l2l loc) $ field\\n ; return $ FieldLabel { flHasDuplicateRecordFields = dup_fields_ok\\n , flHasFieldSelector = has_sel\\n , flSelector = selName } }\\n where\\n fld_occ = rdrNameOcc fld\\n dc_fs = occNameFS $ nameOccName dc\\n field\\n -- Use an Exact RdrName as-is, to preserve the bindings\\n -- of an already renamer-resolved field and its use\\n -- sites. This is needed to correctly support record\\n -- selectors in Template Haskell. See Note [Binders in\\n -- Template Haskell] in \\"GHC.ThToHs\\" and Note [Looking up\\n -- Exact RdrNames] in \\"GHC.Rename.Env\\".\\n | isExact fld\\n = assertPpr (fieldOcc_maybe fld_occ == Just dc_fs)\\n (vcat [ text \\"newRecordFieldLabel: incorrect namespace for exact Name\\" <+> quotes (ppr fld)\\n , text \\"expected namespace:\\" <+> pprNameSpace (fieldName dc_fs)\\n , text \\" actual namespace:\\" <+> pprNameSpace (occNameSpace fld_occ) ])\\n fld\\n\\n -- Field names produced by the parser are namespaced with VarName.\\n -- Here we namespace them according to the first constructor.\\n -- See Note [Record field namespacing] in GHC.Types.Name.Occurrence.\\n | otherwise\\n = mkRdrUnqual $ varToRecFieldOcc dc_fs fld_occ\\n\\n{-\\nNote [Looking up family names in family instances]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider\\n\\n module M where\\n type family T a :: *\\n type instance M.T Int = Bool\\n\\nWe might think that we can simply use \'lookupOccRn\' when processing the type\\ninstance to look up \'M.T\'. Alas, we can\'t! The type family declaration is in\\nthe *same* HsGroup as the type instance declaration. Hence, as we are\\ncurrently collecting the binders declared in that HsGroup, these binders will\\nnot have been added to the global environment yet.\\n\\nSolution is simple: process the type family declarations first, extend\\nthe environment, and then process the type instances.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Filtering imports}\\n* *\\n************************************************************************\\n\\n@filterImports@ takes the @ExportEnv@ telling what the imported module makes\\navailable, and filters it through the import spec (if any).\\n\\nNote [Dealing with imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nFor import M( ies ), we take each AvailInfo from the mi_exports of M, and make\\n\\n imp_occ_env :: OccEnv (NameEnv ImpOccItem)\\n\\nThis map contains one entry for each OccName that M exports, mapping each OccName\\nto the following information:\\n\\n 1. the GlobalRdrElt corresponding to the OccName,\\n 2. whether this GlobalRdrElt was the parent in the AvailInfo we found\\n the OccName in.\\n 3. the GlobalRdrElts that were bundled together in the AvailInfo we found\\n this OccName in (not including the parent),\\n\\nWe need (2) and (3) during the construction of the OccEnv because of associated\\ntypes and bundled pattern synonyms, respectively.\\n(3) is explained in Note [Importing PatternSynonyms].\\n\\nTo explain (2), consider for example:\\n\\n module M where\\n class C a where { data T a }\\n instance C Int where { data T Int = T1 | T2 }\\n instance C Bool where { data T Int = T3 }\\n\\nHere, M\'s exports avails are (recalling the AvailTC invariant from GHC.Types.Avail)\\n\\n C(C,T), T(T,T1,T2,T3)\\n\\nNotice that T appears *twice*, once as a child and once as a parent. From\\nthese two exports, respectively, during construction of the imp_occ_env, we begin\\nby associating the following two elements with the key T:\\n\\n T -> ImpOccItem { imp_item = gre1, imp_bundled = [C,T] , imp_is_parent = False }\\n T -> ImpOccItem { imp_item = gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nwhere `gre1`, `gre2` are two GlobalRdrElts with greName T.\\nWe combine these (in function \'combine\' in \'mkImportOccEnv\') by discarding the\\nnon-parent item, thusly:\\n\\n T -> IE_ITem { imp_item = gre1 `plusGRE` gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nNote the `plusGRE`: this ensures we don\'t drop parent information;\\nsee Note [Preserve parent information when combining import OccEnvs].\\n\\nSo the overall imp_occ_env is:\\n\\n C -> ImpOccItem { imp_item = C, imp_bundled = [T ], imp_is_parent = True }\\n T -> ImpOccItem { imp_item = T , imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n T1 -> ImpOccItem { imp_item = T1, imp_bundled = [T1,T2,T3], imp_is_parent = False }\\n -- similarly for T2, T3\\n\\nNote that the imp_occ_env will have entries for data constructors too,\\nalthough we never look up data constructors.\\n\\nNote [Importing PatternSynonyms]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nAs described in Note [Dealing with imports], associated types can lead to the\\nsame Name appearing twice, both as a child and once as a parent, when\\nconstructing the imp_occ_env. The same thing can happen with pattern synonyms\\nif they are exported bundled with a type.\\n\\nA simplified example, based on #11959:\\n\\n {-# LANGUAGE PatternSynonyms #-}\\n module M (T(P), pattern P) where -- Duplicate export warning, but allowed\\n data T = MkT\\n pattern P = MkT\\n\\nHere we have T(P) and P in export_avails, and respectively construct both\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n P -> ImpOccItem { imp_item = P, imp_bundled = [] , imp_is_parent = False }\\n\\nWe combine these by dropping the one with no siblings, leaving us with:\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n\\nThat is, we simply discard the non-bundled Avail.\\n\\nNote [Importing DuplicateRecordFields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn filterImports, another complicating factor is DuplicateRecordFields.\\nSuppose we have:\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (S(foo), T(foo)) where\\n data S = MkS { foo :: Int }\\n data T = MkT { foo :: Int }\\n\\n module N where\\n import M (foo) -- this is allowed (A)\\n import M (S(foo)) -- this is allowed (B)\\n\\nHere M exports \'foo\' at two different OccNames, with different namespaces for\\nthe two construtors MkS and MkT. Then, when we look up \'foo\' in lookup_names\\nfor case (A), we have a variable foo but must look in all the record field\\nnamespaces to find the two fields (and hence two different Avails).\\nWhereas in case (B) we reach the lookup_ie case for IEThingWith,\\nwhich looks up \'S\' and then finds the unique \'foo\' amongst its children.\\n\\nSee T16745 for a test of this.\\n\\nNote [Preserve parent information when combining import OccEnvs]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen discarding one ImpOccItem in favour of another, as described in\\nNote [Dealing with imports], we must make sure to combine the GREs so that\\nwe don\'t lose information.\\n\\nConsider for example #24084:\\n\\n module M1 where { class C a where { type T a } }\\n module M2 ( module M1 ) where { import M1 }\\n module M3 where { import M2 ( C, T ); instance C () where T () = () }\\n\\nWhen processing the import list of `M3`, we will have two `Avail`s attached\\nto `T`, namely `C(C, T)` and `T(T)`. We combine them in the `combine` function\\nof `mkImportOccEnv`; as described in Note [Dealing with imports] we discard\\n`C(C, T)` in favour of `T(T)`. However, in doing so, we **must not**\\ndiscard the information want that `C` is the parent of `T`. Indeed,\\nlosing track of this information can cause errors when importing,\\nas we could get an error of the form\\n\\n \\u2018T\\u2019 is not a (visible) associated type of class \\u2018C\\u2019\\n\\nThis explains why we use `plusGRE` when combining the two ImpOccItems, even\\nthough we are discarding one in favour of the other.\\n-}\\n\\n-- | All the \'GlobalRdrElt\'s associated with an \'AvailInfo\'.\\ngresFromAvail :: HasDebugCallStack\\n => HscEnv -> Maybe ImportSpec -> AvailInfo -> [GlobalRdrElt]\\ngresFromAvail hsc_env prov avail =\\n [ mk_gre nm info\\n | nm <- availNames avail\\n , let info = lookupGREInfo hsc_env nm ]\\n where\\n\\n mk_gre n info\\n = case prov of\\n -- Nothing => bound locally\\n -- Just is => imported from \'is\'\\n Nothing -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = True, gre_imp = emptyBag\\n , gre_info = info }\\n Just is -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = False, gre_imp = unitBag is\\n , gre_info = info }\\n\\n-- | All the \'GlobalRdrElt\'s associated with a collection of \'AvailInfo\'s.\\ngresFromAvails :: HscEnv -> Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]\\ngresFromAvails hsc_env prov = concatMap (gresFromAvail hsc_env prov)\\n\\nimportsFromIface :: HscEnv -> ModIface -> ImpDeclSpec -> Maybe NameSet -> GlobalRdrEnv\\nimportsFromIface hsc_env iface decl_spec hidden = mkGlobalRdrEnv $ case hidden of\\n Nothing -> all_gres\\n Just hidden_names -> filter (not . (`elemNameSet` hidden_names) . greName) all_gres\\n where\\n all_gres = gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\nrnNamespaceSpecifier :: NamespaceSpecifier GhcPs -> NamespaceSpecifier GhcRn\\nrnNamespaceSpecifier (NoNamespaceSpecifier _) = NoNamespaceSpecifier noExtField\\nrnNamespaceSpecifier (TypeNamespaceSpecifier x) = TypeNamespaceSpecifier x\\nrnNamespaceSpecifier (DataNamespaceSpecifier x) = DataNamespaceSpecifier x\\n\\nfilterImports\\n :: HasDebugCallStack\\n => HscEnv\\n -> ModIface\\n -> ImpDeclSpec\\n -- ^ Import spec\\n -> Maybe (ImportListInterpretation, [LIE GhcPs])\\n -- ^ Whether this is a \\"hiding\\" import list\\n -> RnM (Maybe (ImportListInterpretation, [LIE GhcRn]), -- Import spec w/ Names\\n ImpUserList, -- same, but designed for storage in interfaces\\n GlobalRdrEnv) -- Same again, but in GRE form\\nfilterImports hsc_env iface decl_spec Nothing\\n = return (Nothing, ImpUserAll, importsFromIface hsc_env iface decl_spec Nothing)\\nfilterImports hsc_env iface decl_spec (Just (want_hiding, import_items))\\n = do -- check for errors, convert RdrNames to Names\\n items1 <- mapM lookup_lie import_items\\n\\n let items2 :: [(LIE GhcRn, [GlobalRdrElt])]\\n items2 = concat items1\\n -- NB we may have duplicates, and several items\\n -- for the same parent; e.g N(x) and N(y)\\n\\n (gres, imp_user_list) = case want_hiding of\\n Exactly ->\\n let gres = concatMap (gresFromIE decl_spec) items2\\n gre_env = mkGlobalRdrEnv gres\\n implicit_parents = mkNameSet $ mapMaybe parentOfImplicitlyImportedGRE gres\\n in (gre_env, ImpUserExplicit (gresToAvailInfo $ globalRdrEnvElts $ gre_env) implicit_parents)\\n EverythingBut ->\\n let hidden_names = mkNameSet $ concatMap (map greName . snd) items2\\n in (importsFromIface hsc_env iface decl_spec (Just hidden_names), ImpUserEverythingBut hidden_names)\\n\\n return (Just (want_hiding, map fst items2), imp_user_list, gres)\\n where\\n import_mod = mi_module iface\\n all_avails = mi_exports iface\\n imp_occ_env = mkImportOccEnv hsc_env decl_spec all_avails\\n\\n -- Look up a parent (type constructor, class or data constructor)\\n -- in an import.\\n lookup_parent :: IE GhcPs -> RdrName -> IELookupM ImpOccItem\\n lookup_parent ie rdr =\\n assertPpr (not $ isVarNameSpace ns)\\n (vcat [ text \\"filterImports lookup_parent: unexpected variable\\"\\n , text \\"rdr:\\" <+> ppr rdr\\n , text \\"namespace:\\" <+> pprNameSpace ns ]) $\\n do { xs <- lookup_names ie rdr\\n ; case xs of\\n cax :| [] -> return cax\\n _ -> pprPanic \\"filter_imports lookup_parent ambiguous\\" $\\n vcat [ text \\"rdr:\\" <+> ppr rdr\\n , text \\"lookups:\\" <+> ppr (fmap imp_item xs) ] }\\n -- Looking up non-variables is always unambiguous,\\n -- as there can be at most one corresponding item\\n -- in the imp_occ_env.\\n -- See item (1) of Note [Exporting duplicate declarations]\\n -- in GHC.Tc.Gen.Export.\\n where\\n occ = rdrNameOcc rdr\\n ns = occNameSpace occ\\n\\n -- Look up a RdrName used in an import, returning multiple values if there\\n -- are several fields with the same name exposed by the module\\n lookup_names :: IE GhcPs -> RdrName -> IELookupM (NonEmpty ImpOccItem)\\n lookup_names ie rdr\\n | isQual rdr\\n = failLookupWith (QualImportError rdr)\\n | otherwise\\n = case lookups of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n item:items -> return $ item :| items\\n where\\n lookups = concatMap nonDetNameEnvElts\\n $ lookupImpOccEnv (RelevantGREsFOS WantNormal) imp_occ_env (rdrNameOcc rdr)\\n\\n lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, [GlobalRdrElt])]\\n lookup_lie (L loc ieRdr)\\n = setSrcSpanA loc $\\n do (stuff, warns) <- run_lookup ([],[]) (lookup_ie ieRdr)\\n mapM_ (addTcRnDiagnostic <=< warning_msg) warns\\n return [ (L loc ie, gres) | (ie,gres) <- stuff ]\\n where\\n\\n -- Warn when importing T(..) and no children are brought in scope\\n warning_msg (DodgyImport reason) =\\n pure (TcRnDodgyImports reason)\\n warning_msg MissingImportList =\\n pure (TcRnMissingImportList ieRdr)\\n warning_msg (BadImportW ie sub) = do\\n -- \'BadImportW\' is only constructed below in \'bad_import_w\', in\\n -- the \'EverythingBut\' case, so here we assume a \'hiding\' clause.\\n (reason :| _) <- badImportItemErr iface decl_spec ie sub all_avails\\n pure (TcRnDodgyImports (DodgyImportsHiding reason))\\n warning_msg (DeprecatedExport n w) =\\n pure $ TcRnPragmaWarning\\n PragmaWarningExport\\n { pwarn_occname = occName n\\n , pwarn_impmod = moduleName import_mod }\\n w\\n\\n run_lookup :: a -> IELookupM a -> TcRn a\\n run_lookup def m = case m of\\n Failed err -> do\\n msgs <- lookup_err_msgs err\\n forM_ msgs $ \\\\msg -> addErr (TcRnImportLookup msg)\\n return def\\n Succeeded a -> return a\\n\\n lookup_err_msgs err = case err of\\n BadImport ie sub -> badImportItemErr iface decl_spec ie sub all_avails\\n IllegalImport -> pure $ NE.singleton ImportLookupIllegal\\n QualImportError rdr -> pure $ NE.singleton (ImportLookupQualified rdr)\\n\\n -- For each import item, we convert its RdrNames to Names,\\n -- and at the same time compute all the GlobalRdrElt corresponding\\n -- to what is actually imported by this item.\\n -- Returns Nothing on error.\\n --\\n -- Returns a list because, with DuplicateRecordFields, a naked\\n -- import/export of a record field can correspond to multiple\\n -- different GlobalRdrElts. See Note [Importing DuplicateRecordFields].\\n lookup_ie :: IE GhcPs\\n -> IELookupM ([(IE GhcRn, [GlobalRdrElt])], [IELookupWarning])\\n lookup_ie ie = handle_bad_import $\\n case ie of\\n IEVar _ (L l n) _ -> do\\n -- See Note [Importing DuplicateRecordFields]\\n xs <- lookup_names ie (ieWrappedName n)\\n let gres = map imp_item $ NE.toList xs\\n export_depr_warns\\n | want_hiding == Exactly\\n = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ( [ (IEVar Nothing (L l (replaceWrappedName n name)) noDocstring, [gre])\\n | gre <- gres\\n , let name = greName gre ]\\n , export_depr_warns )\\n\\n IEThingAll x ns_spec (L l tc) _ -> do\\n ImpOccItem { imp_item = gre\\n , imp_bundled = bundled_gres\\n , imp_is_parent = is_par\\n }\\n <- lookup_parent ie $ ieWrappedName tc\\n let name = greName gre\\n\\n child_gres :: [GlobalRdrElt]\\n child_gres\\n | is_par = filterByNamespaceSpecifierGREs ns_spec bundled_gres\\n | otherwise = []\\n\\n imp_list_warn\\n\\n | null child_gres\\n -- e.g. f(..) or T(..) where T is a type synonym\\n = [DodgyImport (DodgyImportsEmptyParent ie ns_spec gre)]\\n\\n -- e.g. import M( T(..) )\\n | not (is_qual decl_spec)\\n = [MissingImportList]\\n\\n | otherwise\\n = []\\n\\n renamed_ie = IEThingAll (x { ieta_warning = Nothing })\\n (rnNamespaceSpecifier ns_spec)\\n (L l (replaceWrappedName tc name))\\n noDocstring\\n export_depr_warn\\n | want_hiding == Exactly\\n = maybeToList $ mk_depr_export_warning gre\\n -- We don\'t want to warn about the children as they\\n -- are not explicitly mentioned; the warning will\\n -- be emitted later on if they are used\\n | otherwise = []\\n\\n return ( [(renamed_ie, gre:child_gres)]\\n , imp_list_warn ++ export_depr_warn)\\n\\n\\n IEThingAbs _ (L l tc\') _\\n | want_hiding == EverythingBut -- hiding ( C )\\n -- Here the \'C\' can be a data constructor\\n -- *or* a type/class, or even both\\n -> let tc = ieWrappedName tc\'\\n tc_name = lookup_parent ie tc\\n dc_name = lookup_parent ie (setRdrNameSpace tc srcDataName)\\n in\\n case catIELookupM [ tc_name, dc_name ] of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n names -> return ( [mkIEThingAbs tc\' l (imp_item name) | name <- names], [])\\n | otherwise\\n -> do ImpOccItem { imp_item = gre } <- lookup_parent ie (ieWrappedName tc\')\\n return ( [mkIEThingAbs tc\' l gre]\\n , maybeToList $ mk_depr_export_warning gre)\\n\\n IEThingWith (deprecation, ann) ltc@(L l rdr_tc) wc rdr_ns _ -> do\\n ImpOccItem { imp_item = gre, imp_bundled = subnames }\\n <- lookup_parent (IEThingAbs Nothing ltc noDocstring) (ieWrappedName rdr_tc)\\n let name = greName gre\\n\\n -- Look up the children in the sub-names of the parent\\n -- See Note [Importing DuplicateRecordFields]\\n let (children_errs, childnames) = lookupChildren subnames rdr_ns\\n\\n bad_import_warns <-\\n if null children_errs then return [] else\\n let items = map lce_wrapped_name children_errs\\n ie = IEThingWith (deprecation, ann) ltc wc items noDocstring\\n -- We are trying to import T( a,b,c,d ), and failed\\n -- to find \'b\' and \'d\'. So we make up an import item\\n -- to report as failing, namely T( b, d ).\\n -- c.f. #15413\\n subordinate_err = mkSubordinateError gre children_errs\\n in bad_import_w ie subordinate_err\\n\\n let name\' = replaceWrappedName rdr_tc name\\n childnames\' = map (to_ie_post_rn . fmap greName) childnames\\n gres = gre : map unLoc childnames\\n export_depr_warns\\n | want_hiding == Exactly = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ([ (IEThingWith (Nothing, ann) (L l name\') wc childnames\' noDocstring\\n ,gres)]\\n , bad_import_warns ++ export_depr_warns)\\n\\n IEWholeNamespace x ns_spec -> do\\n let mod_name = moduleName import_mod\\n names = map greName gres\\n renamed_ie = IEWholeNamespace x { iewn_warning = Nothing\\n , iewn_names = names }\\n (rnNamespaceSpecifier ns_spec)\\n gres = filterByNamespaceSpecifierGREs ns_spec $\\n gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n dodgy_warn\\n | null gres = [DodgyImport (DodgyImportsWildcard mod_name ns_spec)]\\n | otherwise = []\\n return ([(renamed_ie, gres)],\\n dodgy_warn)\\n\\n _other -> failLookupWith IllegalImport\\n -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed...\\n -- all of those constitute errors.\\n\\n where\\n mkIEThingAbs tc l gre\\n = (IEThingAbs Nothing (L l (replaceWrappedName tc n)) noDocstring, [gre])\\n where n = greName gre\\n\\n -- N.B. imports never have docstrings\\n noDocstring = Nothing\\n\\n handle_bad_import m = catchIELookup m $ \\\\case\\n BadImport ie sub -> do\\n ws <- bad_import_w ie sub\\n return ([], ws)\\n err -> failLookupWith err\\n\\n bad_import_w :: IE GhcPs -> IsSubordinateError -> IELookupM [IELookupWarning]\\n bad_import_w ie sub\\n | want_hiding == EverythingBut = return [BadImportW ie sub]\\n | otherwise = failLookupWith (BadImport ie sub)\\n\\n mk_depr_export_warning gre\\n = DeprecatedExport name <$> mi_export_warn_fn iface name\\n where\\n name = greName gre\\n\\n-- | Assuming a subordinate item could not be found, do another lookup for a\\n-- more specific error message.\\nmkBadExportSubordinate :: [GlobalRdrElt] -> LIEWrappedName GhcPs -> BadExportSubordinate\\nmkBadExportSubordinate child_gres n =\\n case lookupChildren child_gres [n] of\\n (LookupChildNonType {lce_nontype_item = g} : _, _) -> BadExportSubordinateNonType g\\n (LookupChildNonData {lce_nondata_item = g} : _, _) -> BadExportSubordinateNonData g\\n _ -> BadExportSubordinateNotFound n\\n\\ntype IELookupM = MaybeErr IELookupError\\n\\ndata IELookupWarning\\n = BadImportW (IE GhcPs) IsSubordinateError\\n | MissingImportList\\n | DodgyImport DodgyImportsReason\\n | DeprecatedExport Name (WarningTxt GhcRn)\\n\\n-- | Is this import/export item a subordinate or not?\\ndata IsSubordinateError\\n = IsSubordinateError { subordinate_err_parent :: !GlobalRdrElt\\n , subordinate_err_unavailable :: [FastString]\\n , subordinate_err_nontype :: [GlobalRdrElt]\\n , subordinate_err_nondata :: [GlobalRdrElt] }\\n | IsNotSubordinate\\n\\nmkSubordinateError :: GlobalRdrElt -> [LookupChildError] -> IsSubordinateError\\nmkSubordinateError gre children_errs = foldr add init_acc children_errs\\n where\\n init_acc :: IsSubordinateError\\n init_acc = IsSubordinateError gre [] [] []\\n\\n add :: LookupChildError -> IsSubordinateError -> IsSubordinateError\\n add children_err sub@IsSubordinateError{} =\\n case children_err of\\n LookupChildNonType{lce_nontype_item = g} ->\\n sub { subordinate_err_nontype = g : subordinate_err_nontype sub }\\n LookupChildNonData{lce_nondata_item = g} ->\\n sub { subordinate_err_nondata = g : subordinate_err_nondata sub }\\n LookupChildNotFound (L _ wname) ->\\n let fs = (occNameFS . rdrNameOcc . ieWrappedName) wname\\n in sub { subordinate_err_unavailable = fs : subordinate_err_unavailable sub }\\n add _ IsNotSubordinate = panic \\"mkSubordinateError: IsNotSubordinate\\"\\n\\ndata IELookupError\\n = QualImportError RdrName\\n | BadImport (IE GhcPs) IsSubordinateError\\n | IllegalImport\\n\\nfailLookupWith :: IELookupError -> IELookupM a\\nfailLookupWith err = Failed err\\n\\ncatchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a\\ncatchIELookup m h = case m of\\n Succeeded r -> return r\\n Failed err -> h err\\n\\ncatIELookupM :: [IELookupM a] -> [a]\\ncatIELookupM ms = [ a | Succeeded a <- ms ]\\n\\n-- | Information associated to an \'AvailInfo\' used in constructing\\n-- an \'OccEnv\' corresponding to imports.\\n--\\n-- See Note [Dealing with imports].\\ndata ImpOccItem\\n = ImpOccItem\\n { imp_item :: GlobalRdrElt\\n -- ^ The import item\\n , imp_bundled :: [GlobalRdrElt]\\n -- ^ Items bundled in the Avail this import item came from,\\n -- not including the import item itself if it is a parent.\\n , imp_is_parent :: Bool\\n -- ^ Is the import item a parent? See Note [Dealing with imports].\\n }\\n\\ninstance Outputable ImpOccItem where\\n ppr (ImpOccItem { imp_item = item, imp_bundled = bundled, imp_is_parent = is_par })\\n = braces $ hsep\\n [ text \\"ImpOccItem\\"\\n , if is_par then text \\"[is_par]\\" else empty\\n , ppr (greName item) <+> ppr (greParent item)\\n , braces $ text \\"bundled:\\" <+> ppr (map greName bundled) ]\\n\\n-- | Make an \'OccEnv\' of all the imports.\\n--\\n-- Complicated by the fact that associated data types and pattern synonyms\\n-- can appear twice. See Note [Dealing with imports].\\nmkImportOccEnv :: HscEnv -> ImpDeclSpec -> [IfaceExport] -> OccEnv (NameEnv ImpOccItem)\\nmkImportOccEnv hsc_env decl_spec all_avails =\\n mkOccEnv_C (plusNameEnv_C combine)\\n [ (occ, mkNameEnv [(nm, item)])\\n | avail <- all_avails\\n , let gres = gresFromAvail hsc_env (Just hiding_spec) avail\\n , gre <- gres\\n , let nm = greName gre\\n occ = greOccName gre\\n (is_parent, bundled) = case avail of\\n AvailTC c _\\n | c == nm -- (Recall the AvailTC invariant from GHC.Types.AvailInfo)\\n -> ( True, drop 1 gres ) -- \\"drop 1\\": don\'t include the parent itself.\\n | otherwise\\n -> ( False, gres )\\n _ -> ( False, [] )\\n item = ImpOccItem\\n { imp_item = gre\\n , imp_bundled = bundled\\n , imp_is_parent = is_parent }\\n ]\\n where\\n\\n hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\n -- See Note [Dealing with imports]\\n -- \'combine\' may be called for associated data types which appear\\n -- twice in the all_avails. In the example, we have two Avails for T,\\n -- namely T(T,T1,T2,T3) and C(C,T), and we combine them by dropping the\\n -- latter, in which T is not the parent.\\n combine :: ImpOccItem -> ImpOccItem -> ImpOccItem\\n combine item1@(ImpOccItem { imp_item = gre1, imp_is_parent = is_parent1 })\\n item2@(ImpOccItem { imp_item = gre2, imp_is_parent = is_parent2 })\\n | is_parent1 || is_parent2\\n , not (isRecFldGRE gre1 || isRecFldGRE gre2) -- NB: does not force GREInfo.\\n , let name1 = greName gre1\\n name2 = greName gre2\\n gre = gre1 `plusGRE` gre2\\n -- See Note [Preserve parent information when combining import OccEnvs]\\n = assertPpr (name1 == name2)\\n (ppr name1 <+> ppr name2) $\\n if is_parent1\\n then item1 { imp_item = gre }\\n else item2 { imp_item = gre }\\n -- Discard C(C,T) in favour of T(T, T1, T2, T3).\\n\\n -- \'combine\' may also be called for pattern synonyms which appear both\\n -- unassociated and associated (see Note [Importing PatternSynonyms]).\\n combine item1@(ImpOccItem { imp_item = c1, imp_bundled = kids1 })\\n item2@(ImpOccItem { imp_item = c2, imp_bundled = kids2 })\\n = assertPpr (greName c1 == greName c2\\n && (not (null kids1 && null kids2)))\\n (ppr c1 <+> ppr c2 <+> ppr kids1 <+> ppr kids2) $\\n if null kids1\\n then item2\\n else item1\\n -- Discard standalone pattern P in favour of T(P).\\n\\n-- | Essentially like @lookupGRE env (LookupOccName occ which_gres)@,\\n-- but working with \'ImpOccItem\'s instead of \'GlobalRdrElt\'s.\\nlookupImpOccEnv :: WhichGREs GREInfo\\n -> OccEnv (NameEnv ImpOccItem) -> OccName -> [NameEnv ImpOccItem]\\nlookupImpOccEnv which_gres env occ =\\n mapMaybe relevant_items $ lookupOccEnv_AllNameSpaces env occ\\n where\\n is_relevant :: ImpOccItem -> Bool\\n is_relevant (ImpOccItem { imp_item = gre }) =\\n greIsRelevant which_gres (occNameSpace occ) gre\\n relevant_items :: NameEnv ImpOccItem -> Maybe (NameEnv ImpOccItem)\\n relevant_items nms\\n | let nms\' = filterNameEnv is_relevant nms\\n = if isEmptyNameEnv nms\'\\n then Nothing\\n else Just nms\'\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{Import/Export Utils}\\n* *\\n************************************************************************\\n-}\\n\\n-- | Given an import\\\\/export spec, appropriately set the @gre_imp@ field\\n-- for the \'GlobalRdrElt\'s.\\ngresFromIE :: ImpDeclSpec -> (LIE GhcRn, [GlobalRdrElt]) -> [GlobalRdrElt]\\ngresFromIE decl_spec (L loc ie, gres)\\n = map set_gre_imp gres\\n where\\n is_explicit = case ie of\\n IEThingAll _ _ name _ -> \\\\n -> n == lieWrappedName name\\n IEWholeNamespace _ _ -> \\\\_ -> False\\n _ -> \\\\_ -> True\\n prov_fn name\\n = ImpSpec { is_decl = decl_spec, is_item = item_spec }\\n where\\n item_spec = ImpSome { is_explicit = is_explicit name\\n , is_iloc = locA loc }\\n set_gre_imp gre@( GRE { gre_name = nm } )\\n = gre { gre_imp = unitBag $ prov_fn nm }\\n\\nparentOfImplicitlyImportedGRE :: Outputable info => GlobalRdrEltX info -> Maybe Name\\nparentOfImplicitlyImportedGRE gre =\\n if any (explicit_import . is_item) $ gre_imp gre\\n then Nothing\\n else greParent_maybe gre\\n where\\n explicit_import :: ImpItemSpec -> Bool\\n explicit_import (ImpAll {}) =\\n pprPanic \\"parentOfImplicitlyImportedGRE: ImpAll\\" (ppr gre)\\n explicit_import (ImpSome { is_explicit }) = is_explicit\\n\\n{- Note [Children for duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider the module\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (F(foo, MkFInt, MkFBool)) where\\n data family F a\\n data instance F Int = MkFInt { foo :: Int }\\n data instance F Bool = MkFBool { foo :: Bool }\\n\\nThe `foo` in the export list refers to *both* selectors! For this\\nreason, lookupChildren builds an environment that maps the FastString\\nto a list of items, rather than a single item.\\n-}\\n\\nmkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]\\nmkChildEnv gres = foldr add emptyNameEnv gres\\n where\\n add gre env = case greParent gre of\\n ParentIs p -> extendNameEnv_Acc (:) Utils.singleton env p gre\\n NoParent -> env\\n\\nfindChildren :: NameEnv [a] -> Name -> [a]\\nfindChildren env n = lookupNameEnv env n `orElse` []\\n\\ndata LookupChildError\\n = LookupChildNotFound { lce_wrapped_name :: !(LIEWrappedName GhcPs) }\\n | LookupChildNonType { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nontype_item :: !GlobalRdrElt }\\n | LookupChildNonData { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nondata_item :: !GlobalRdrElt }\\n\\nlookupChildren :: [GlobalRdrElt]\\n -> [LIEWrappedName GhcPs]\\n -> ( [LookupChildError] -- The ones for which the lookup failed\\n , [LocatedA GlobalRdrElt] )\\n-- (lookupChildren all_kids rdr_items) maps each rdr_item to its\\n-- corresponding Name in all_kids, if the former exists\\n-- The matching is done by FastString, not OccName, so that\\n-- Cls( meth, AssocTy )\\n-- will correctly find AssocTy among the all_kids of Cls, even though\\n-- the RdrName for AssocTy may have a (bogus) DataName namespace\\n-- (Really the rdr_items should be FastStrings in the first place.)\\nlookupChildren all_kids rdr_items = (fails, successes)\\n where\\n mb_xs = map do_one rdr_items\\n fails = [ err | Failed err <- mb_xs ]\\n successes = [ ok | Succeeded oks <- mb_xs, ok <- NE.toList oks ]\\n\\n do_one :: LIEWrappedName GhcPs -> MaybeErr LookupChildError (NonEmpty (LocatedA GlobalRdrElt))\\n do_one item@(L l r) =\\n case r of\\n IEName{}\\n -- IEName (unadorned name) places no restriction on the namespace of\\n -- the imported entity, so we look in both `val_gres` and `typ_gres`.\\n -- In case of conflict (punning), the value namespace takes priority.\\n -- See Note [Prioritise the value namespace in subordinate import lists]\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEType{}\\n -- IEType (\'type\' namespace specifier) restricts the lookup to the\\n -- type namespace, i.e. to `typ_gres`. In case of failure, we check\\n -- `val_gres` to produce a more helpful error message.\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- val_gres -> Failed $ LookupChildNonType item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEData{}\\n -- IEData (\'data\' namespace specifier) restricts the lookup to the\\n -- data namespace, i.e. to `val_gres`. In case of failure, we check\\n -- `typ_gres` to produce a more helpful error message.\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- typ_gres -> Failed $ LookupChildNonData item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEPattern{} -> panic \\"lookupChildren: IEPattern\\" -- Never happens (invalid syntax)\\n IEDefault{} -> panic \\"lookupChildren: IEDefault\\" -- Never happens (invalid syntax)\\n where\\n fs = (occNameFS . rdrNameOcc . ieWrappedName) r\\n gres = fromMaybe [] (lookupFsEnv kid_env fs)\\n (val_gres, typ_gres) = partition (isValNameSpace . greNameSpace) gres\\n\\n -- See Note [Children for duplicate record fields]\\n kid_env :: FastStringEnv [GlobalRdrElt]\\n kid_env = extendFsEnvList_C (++) emptyFsEnv\\n [(occNameFS (occName x), [x]) | x <- all_kids]\\n\\n\\n{- Note [Prioritise the value namespace in subordinate import lists]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider this program that defines a class that has both an associated type\\nnamed (#) and a method named (#)\\n\\n module M_assoc where\\n class C a b where\\n type a # b\\n (#) :: a -> b -> ()\\n module N_assoc where\\n import M_assoc( C((#)) )\\n\\nIn the import declaration, when we see the unadorned name (#) in the subordinate\\nimport list of C, which children should we bring into scope? Our options are:\\n\\n a) only the method (#)\\n b) only the associated type (#)\\n c) both the method and the associated type\\n\\nTo follow the precedent established by top-level items, we go with option (a).\\nIndeed, consider a slightly different program\\n\\n module M_top where\\n type family a # b\\n a # b = ()\\n module N_top where\\n import M_top( (#) )\\n\\nHere the import brings only the function (#) into scope, and one has to say\\n`type (#)` to get the type family.\\n-}\\n\\n-------------------------------\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused names}\\n* *\\n*********************************************************\\n-}\\n\\nreportUnusedNames :: TcGblEnv -> HscSource -> RnM ()\\nreportUnusedNames gbl_env hsc_src\\n = do { keep <- readTcRef (tcg_keep gbl_env)\\n ; traceRn \\"RUN\\" (ppr (tcg_dus gbl_env))\\n ; warnUnusedImportDecls gbl_env hsc_src\\n ; warnUnusedTopBinds $ unused_locals keep\\n ; warnMissingSignatures gbl_env\\n ; warnMissingKindSignatures gbl_env }\\n where\\n used_names :: NameSet -> NameSet\\n used_names keep = findUses (tcg_dus gbl_env) emptyNameSet `unionNameSet` keep\\n -- NB: currently, if f x = g, we only treat \'g\' as used if \'f\' is used\\n -- Hence findUses\\n\\n -- Collect the defined names from the in-scope environment\\n defined_names :: [GlobalRdrElt]\\n defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)\\n\\n kids_env = mkChildEnv defined_names\\n -- This is done in mkExports too; duplicated work\\n\\n gre_is_used :: NameSet -> GlobalRdrElt -> Bool\\n gre_is_used used_names gre0\\n = name `elemNameSet` used_names\\n || any (\\\\ gre -> greName gre `elemNameSet` used_names) (findChildren kids_env name)\\n -- A use of C implies a use of T,\\n -- if C was brought into scope by T(..) or T(C)\\n where\\n name = greName gre0\\n\\n -- Filter out the ones that are\\n -- (a) defined in this module, and\\n -- (b) not defined by a \'deriving\' clause\\n -- The latter have an Internal Name, so we can filter them out easily\\n unused_locals :: NameSet -> [GlobalRdrElt]\\n unused_locals keep =\\n let -- Note that defined_and_used, defined_but_not_used\\n -- are both [GRE]; that\'s why we need defined_and_used\\n -- rather than just used_names\\n _defined_and_used, defined_but_not_used :: [GlobalRdrElt]\\n (_defined_and_used, defined_but_not_used)\\n = partition (gre_is_used (used_names keep)) defined_names\\n\\n in filter is_unused_local defined_but_not_used\\n is_unused_local :: GlobalRdrElt -> Bool\\n is_unused_local gre = isLocalGRE gre\\n && isExternalName (greName gre)\\n\\n{- *********************************************************************\\n* *\\n Missing signatures\\n* *\\n********************************************************************* -}\\n\\n{-\\nNote [Missing signatures]\\n~~~~~~~~~~~~~~~~~~~~~~~~~\\nThere are four warning flags in play:\\n\\n * -Wmissing-exported-signatures\\n Warn about any exported top-level function/value without a type signature.\\n Does not include pattern synonyms.\\n\\n * -Wmissing-signatures\\n Warn about any top-level function/value without a type signature. Does not\\n include pattern synonyms. Takes priority over -Wmissing-exported-signatures.\\n\\n * -Wmissing-exported-pattern-synonym-signatures\\n Warn about any exported pattern synonym without a type signature.\\n\\n * -Wmissing-pattern-synonym-signatures\\n Warn about any pattern synonym without a type signature. Takes priority over\\n -Wmissing-exported-pattern-synonym-signatures.\\n\\n-}\\n\\n-- | Warn the user about top level binders that lack type signatures.\\n-- Called /after/ type inference, so that we can report the\\n-- inferred type of the function\\nwarnMissingSignatures :: TcGblEnv -> RnM ()\\nwarnMissingSignatures gbl_env\\n = do { let exports = availsToNameSet (tcg_exports gbl_env)\\n sig_ns = tcg_sigs gbl_env\\n -- We use sig_ns to exclude top-level bindings that are generated by GHC\\n binds = collectHsBindsBinders CollNoDictBinders $ tcg_binds gbl_env\\n pat_syns = tcg_patsyns gbl_env\\n\\n not_ghc_generated :: Name -> Bool\\n not_ghc_generated name = name `elemNameSet` sig_ns\\n\\n add_binding_warn :: Id -> RnM ()\\n add_binding_warn id =\\n when (not_ghc_generated name) $\\n do { env <- liftZonkM $ tcInitTidyEnv -- Why not use emptyTidyEnv?\\n ; let ty = tidyOpenType env (idType id)\\n missing = MissingTopLevelBindingSig name ty\\n diag = TcRnMissingSignature missing exported\\n ; addDiagnosticAt (getSrcSpan name) diag }\\n where\\n name = idName id\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n add_patsyn_warn :: PatSyn -> RnM ()\\n add_patsyn_warn ps =\\n when (not_ghc_generated name) $\\n addDiagnosticAt (getSrcSpan name)\\n (TcRnMissingSignature missing exported)\\n where\\n name = patSynName ps\\n missing = MissingPatSynSig ps\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n -- Warn about missing signatures\\n -- Do this only when we have a type to offer\\n -- See Note [Missing signatures]\\n ; mapM_ add_binding_warn binds\\n ; mapM_ add_patsyn_warn pat_syns\\n }\\n\\n-- | Warn the user about tycons that lack kind signatures.\\n-- Called /after/ type (and kind) inference, so that we can report the\\n-- inferred kinds.\\nwarnMissingKindSignatures :: TcGblEnv -> RnM ()\\nwarnMissingKindSignatures gbl_env\\n = do { cusks_enabled <- xoptM LangExt.CUSKs\\n ; mapM_ (add_ty_warn cusks_enabled) tcs\\n }\\n where\\n tcs = tcg_tcs gbl_env\\n ksig_ns = tcg_ksigs gbl_env\\n exports = availsToNameSet (tcg_exports gbl_env)\\n\\n has_kind_signature :: Name -> Bool\\n has_kind_signature name = name `elemNameSet` ksig_ns\\n\\n add_ty_warn :: Bool -> TyCon -> RnM ()\\n add_ty_warn cusks_enabled tyCon =\\n when (has_kind_signature name) $\\n addDiagnosticAt (getSrcSpan name) diag\\n where\\n name = tyConName tyCon\\n diag = TcRnMissingSignature missing exported\\n missing = MissingTyConKindSig tyCon cusks_enabled\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused imports}\\n* *\\n*********************************************************\\n\\nThis code finds which import declarations are unused. The\\nspecification and implementation notes are here:\\n https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/unused-imports\\n\\nSee also Note [Choosing the best import declaration] in GHC.Types.Name.Reader\\n-}\\n\\ntype ImportDeclUsage\\n = ( LImportDecl GhcRn -- The import declaration\\n , [GlobalRdrElt] -- What *is* used (normalised)\\n , [Name] -- What is imported but *not* used\\n , [NamespaceSpecifier GhcRn] ) -- Unused wildcards\\n\\nwarnUnusedImportDecls :: TcGblEnv -> HscSource -> RnM ()\\nwarnUnusedImportDecls gbl_env hsc_src\\n = do { uses <- readMutVar (tcg_used_gres gbl_env)\\n ; let imports = tcg_rn_imports gbl_env\\n rdr_env = tcg_rdr_env gbl_env\\n\\n -- We should only warn for unnecessary *user* imports, but deciding\\n -- minimal imports should take generated imports into account\\n ; let usageUserImports = findImportUsage (excludeGenerated imports) uses\\n usageAllImports = findImportUsage imports uses\\n\\n ; traceRn \\"warnUnusedImportDecls\\" $\\n (vcat [ text \\"Uses:\\" <+> ppr uses\\n , text \\"Usage all user imports: \\" <+> ppr usageUserImports\\n , text \\"Usage all imports: \\" <+> ppr usageAllImports])\\n\\n ; mapM_ (warnUnusedImport rdr_env) usageUserImports\\n\\n ; whenGOptM Opt_D_dump_minimal_imports $\\n printMinimalImports hsc_src usageAllImports }\\n\\n-- | Exclude generated imports\\nexcludeGenerated :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\nexcludeGenerated = filterOut (isGeneratedImport . ideclOrigin . ideclExt . unLoc)\\n\\nfindImportUsage :: [LImportDecl GhcRn]\\n -> [GlobalRdrElt]\\n -> [ImportDeclUsage]\\n\\nfindImportUsage imports used_gres\\n = map unused_decl imports\\n where\\n import_usage :: ImportMap\\n import_usage = mkImportMap used_gres\\n\\n unused_decl :: LImportDecl GhcRn -> ImportDeclUsage\\n unused_decl decl@(L _ (ImportDecl { ideclImportList = imps }))\\n = -- pprTrace \\"unused_decl\\" (vcat [ ppr decl\\n -- , text \\"used\\" <+> ppr used_gres\\n -- , text \\"unused\\" <+> ppr unused_names ]) $\\n (decl, used_gres, unused_names, unused_wcs)\\n where\\n used_gres = lookupImportMap decl import_usage\\n\\n used_gre_env = mkGlobalRdrEnv used_gres\\n used_parents = mkNameSet (mapMaybe greParent_maybe used_gres)\\n\\n (unused_names, unused_wcs) -- Not trivial; see eg #7454\\n = case imps of\\n Just (Exactly, imp_ies) ->\\n let unused = foldr (add_unused . unLoc) emptyUnusedNames imp_ies\\n nms = nameSetElemsStable (collectUnusedNames unused)\\n wcs = collectUnusedWildcards unused\\n in (nms, wcs)\\n _other -> ([], []) -- No explicit import list => no unused-name list\\n\\n add_unused :: IE GhcRn -> UnusedNames -> UnusedNames\\n add_unused (IEVar _ n _) acc = add_unused_name (lieWrappedName n) True acc\\n add_unused (IEThingAbs _ n _) acc = add_unused_name (lieWrappedName n) False acc\\n add_unused (IEThingAll _ _ n _) acc = add_unused_all (lieWrappedName n) acc\\n add_unused (IEThingWith _ p wc ns _) acc = add_wc_all (add_unused_with pn xs acc)\\n where pn = lieWrappedName p\\n xs = map lieWrappedName ns\\n add_wc_all = case wc of\\n NoIEWildcard -> id\\n IEWildcard _ -> add_unused_all pn\\n add_unused (IEWholeNamespace x ns_spec) acc = add_unused_wildcard ns_spec (iewn_names x) acc\\n add_unused _ acc = acc\\n\\n add_unused_name :: Name -> Bool -> UnusedNames -> UnusedNames\\n add_unused_name n is_ie_var acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | is_ie_var\\n , isFieldName n\\n -- See Note [Reporting unused imported duplicate record fields]\\n = let\\n fs = getOccFS n\\n (flds, flds_used) = lookupFsEnv acc_fs fs `orElse` (emptyNameSet, Any False)\\n acc_fs\' = extendFsEnv acc_fs fs (extendNameSet flds n, Any used S.<> flds_used)\\n in UnusedNames acc_ns acc_wcs acc_fs\'\\n\\n | used\\n = acc\\n\\n | otherwise\\n = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n where\\n used = isJust $ lookupGRE_Name used_gre_env n\\n\\n add_unused_all :: Name -> UnusedNames -> UnusedNames\\n add_unused_all n acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | Just {} <- lookupGRE_Name used_gre_env n = acc\\n | n `elemNameSet` used_parents = acc\\n | otherwise = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n\\n add_unused_with :: Name -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_with p ns acc\\n | all (`elemNameSet` acc1_ns) ns = add_unused_name p False acc1\\n | otherwise = acc1\\n where\\n acc1@(UnusedNames acc1_ns _ _) = foldr (\\\\n acc\' -> add_unused_name n False acc\') acc ns\\n -- If you use \'signum\' from Num, then the user may well have\\n -- imported Num(signum). We don\'t want to complain that\\n -- Num is not itself mentioned. Hence the two cases in add_unused_with.\\n\\n add_unused_wildcard :: NamespaceSpecifier GhcRn -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_wildcard ns_spec names acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | any_used = acc\\n | otherwise = UnusedNames acc_ns (ns_spec : acc_wcs) acc_fs\\n where\\n -- A wildcard `type ..` or `data ..` is used if at least one of\\n -- the names it expands to is used\\n any_used = any (isJust . lookupGRE_Name used_gre_env) names\\n\\n\\n-- | An accumulator for unused names in an import list.\\n--\\n-- See Note [Reporting unused imported duplicate record fields].\\ndata UnusedNames =\\n UnusedNames\\n { unused_names :: NameSet\\n -- ^ Unused \'Name\'s in an import list, not including record fields\\n -- that are plain \'IEVar\' imports (tracked by \'rec_fld_uses\')\\n -- or wildcard imports (tracked by \'unused_wildcards\').\\n , unused_wildcards :: [NamespaceSpecifier GhcRn]\\n -- ^ Unused wildcards @type ..@ or @data ..@ in an import list.\\n , rec_fld_uses :: FastStringEnv (NameSet, Any)\\n -- ^ Record fields imported without a parent (i.e. an \'IEVar\' import).\\n --\\n -- The \'Any\' value records whether any of the record fields\\n -- sharing the same underlying \'FastString\' have been used.\\n }\\n\\nemptyUnusedNames :: UnusedNames\\nemptyUnusedNames = UnusedNames emptyNameSet [] emptyFsEnv\\n\\ninstance Outputable UnusedNames where\\n ppr (UnusedNames nms wcs flds) =\\n text \\"UnusedNames\\" <+>\\n braces (ppr nms <+> ppr wcs <+> ppr (fmap (second getAny) flds))\\n\\n-- | Collect all unused names from a \'UnusedNames\' value.\\ncollectUnusedNames :: UnusedNames -> NameSet\\ncollectUnusedNames (UnusedNames { unused_names = nms, rec_fld_uses = flds })\\n = nms S.<> unused_flds\\n where\\n unused_flds = nonDetFoldFsEnv collect_unused emptyNameSet flds\\n collect_unused :: (NameSet, Any) -> NameSet -> NameSet\\n collect_unused (nms, Any at_least_one_name_is_used) acc\\n | at_least_one_name_is_used = acc\\n | otherwise = unionNameSet nms acc\\n\\ncollectUnusedWildcards :: UnusedNames -> [NamespaceSpecifier GhcRn]\\ncollectUnusedWildcards = unused_wildcards\\n\\n{- Note [Reporting unused imported duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have (#24035):\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M1 (R1(..), R2(..)) where\\n data R1 = MkR1 { fld :: Int }\\n data R2 = MkR2 { fld :: Int }\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M2 where\\n import M1 (R1(MkR1), R2, fld)\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nIn the import of \'M1\' in \'M2\', the \'fld\' import resolves to two separate GREs,\\nnamely R1(fld) and R2(fld). From the perspective of the renamer, and in particular\\nthe \'findImportUsage\' function, it\'s as if the user had imported the two names\\nseparately (even though no source syntax allows that).\\n\\nThis means that we need to be careful when reporting unused imports: the R2(fld)\\nimport is indeed unused, but because R1(fld) is used, we should not report\\nfld as unused altogether.\\n\\nTo achieve this, we keep track of record field imports without a parent (i.e.\\nusing the IEVar constructor) separately from other import items, using the\\nUnusedNames datatype.\\nOnce we have accumulated usages, we emit warnings for unused record fields\\nwithout parents one whole group (of record fields sharing the same textual name)\\nat a time, and only if *all* of the record fields in the group are unused;\\nsee \'collectUnusedNames\'.\\n\\nNote that this only applies to record fields imported without a parent. If we\\nhad:\\n\\n import M1 (R1(MkR1, fld), R2(fld))\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nthen of course we should report the second \'fld\' as unused.\\n-}\\n\\n\\n{- Note [The ImportMap]\\n~~~~~~~~~~~~~~~~~~~~~~~\\nThe ImportMap is a short-lived intermediate data structure records, for\\neach import declaration, what stuff brought into scope by that\\ndeclaration is actually used in the module.\\n\\nThe [GlobalRdrElt] are the things imported from that decl.\\n-}\\n\\ndata ImportMap = ImportMap\\n { im_imports :: Map RealSrcSpan [GlobalRdrElt]\\n -- ^ See [The ImportMap]\\n -- If loc :-> gres, then\\n -- \'loc\' = the end loc of the bestImport of each GRE in \'gres\'\\n , im_generatedImports :: Map ModuleName [GlobalRdrElt]\\n }\\n\\nmkImportMap :: [GlobalRdrElt] -> ImportMap\\n-- For each of a list of used GREs, find all the import decls that brought\\n-- it into scope; choose one of them (bestImport), and record\\n-- the RdrName in that import decl\'s entry in the ImportMap\\nmkImportMap = foldr insertImportMap $ ImportMap Map.empty Map.empty\\n\\ninsertImportMap :: GlobalRdrElt -> ImportMap -> ImportMap\\ninsertImportMap gre@(GRE { gre_imp = imp_specs }) importMap\\n | RealSrcSpan importSpan _ <- is_dloc best_imp_spec =\\n importMap{im_imports = insertElem importSpan gre $ im_imports importMap}\\n | GeneratedSrcSpan{} <- is_dloc best_imp_spec =\\n importMap{im_generatedImports = insertElem (moduleName $ is_mod best_imp_spec) gre $ im_generatedImports importMap}\\n | otherwise = importMap\\n where\\n best_imp_spec =\\n case bagToList imp_specs of\\n [] -> pprPanic \\"mkImportMap: GRE with no ImportSpecs\\" (ppr gre)\\n is:iss -> is_decl $ bestImport (is NE.:| iss)\\n\\n -- https://github.com/haskell/containers/issues/784\\n insertElem :: Ord k => k -> v -> Map k [v] -> Map k [v]\\n insertElem k v = flip Map.alter k $ \\\\case\\n Just vs -> Just (v : vs)\\n Nothing -> Just [v]\\n\\nlookupImportMap :: LImportDecl GhcRn -> ImportMap -> [GlobalRdrElt]\\nlookupImportMap (L srcSpan ImportDecl{ideclName = L _ modName}) importMap =\\n fromMaybe [] $\\n -- should match logic in insertImportMap\\n case locA srcSpan of\\n RealSrcSpan realSrcSpan _ -> realSrcSpan `Map.lookup` im_imports importMap\\n GeneratedSrcSpan{} -> modName `Map.lookup` im_generatedImports importMap\\n _ -> Nothing\\n\\nlieNames :: LIE (GhcPass p) -> [Located (IdP (GhcPass p))]\\nlieNames = _\\n\\nwarnUnusedImport :: GlobalRdrEnv -> ImportDeclUsage -> RnM ()\\nwarnUnusedImport rdr_env (L loc decl, used, unused, unused_wcs)\\n\\n -- Do not warn for \'import M()\'\\n -- See (UI1) in Note [Unused imports]\\n | Just (Exactly, _) <- ideclImportList decl\\n , null unused && null unused_wcs\\n = return ()\\n\\n -- Note [Do not warn about Prelude hiding]\\n | Just (EverythingBut, hides) <- ideclImportList decl\\n , not (null hides)\\n , pRELUDE_NAME == unLoc (ideclName decl)\\n = return ()\\n\\n -- Do not warn about import X as Rebindable\\n -- See (UI2) in Note [Unused imports]\\n | Just (L _ mod) <- ideclAs decl\\n , mod == rEBINDABLE_MOD_NAME\\n = return ()\\n\\n -- Nothing used; drop entire declaration\\n | null used\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl UnusedImportNone)\\n\\n -- Everything imported is used; nop\\n | null unused && null unused_wcs\\n = return ()\\n\\n -- Some imports are unused: make the `SrcSpan` cover only the unused\\n -- items instead of the whole import statement\\n | Just (_, imports) <- ideclImportList decl\\n , let unused_locs = [ locA loc | L loc ie <- imports\\n , name <- ieNames ie\\n , name `elem` unused ]\\n , loc1 : locs <- unused_locs\\n , let span = foldr1 combineSrcSpans ( loc1 NE.:| locs )\\n = addDiagnosticAt span (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n -- Some imports are unused\\n | otherwise\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n where\\n -- In warning message, pretty-print identifiers unqualified unconditionally\\n -- to improve the consistent for ambiguous/unambiguous identifiers.\\n -- See #14881.\\n possible_field n =\\n case lookupGRE_Name rdr_env n of\\n Just (GRE { gre_par = par, gre_info = IAmRecField info }) ->\\n let fld_occ :: OccName\\n fld_occ = nameOccName $ flSelector $ recFieldLabel info\\n in UnusedImportNameRecField par fld_occ\\n _ -> UnusedImportNameRegular n\\n\\n -- Print unused names in a deterministic (lexicographic) order\\n sort_unused :: [UnusedImportName]\\n sort_unused =\\n [ UnusedImportWildcard wc | wc <- unused_wcs ] ++\\n [ possible_field nm | nm <- sortBy (comparing nameOccName) unused ]\\n\\ngetMinimalImports :: [ImportDeclUsage] -> RnM [LImportDecl GhcRn]\\ngetMinimalImports ie_decls\\n = do { rdr_env <- getGlobalRdrEnv\\n ; fmap combine $ mapM (mk_minimal rdr_env) ie_decls }\\n where\\n mk_minimal rdr_env (L l decl, used_gres, unused, unused_wcs)\\n | null unused && null unused_wcs\\n , Just (Exactly, _) <- ideclImportList decl\\n = return (L l decl)\\n | otherwise\\n = do { let ImportDecl { ideclName = L _ mod_name\\n , ideclSource = is_boot\\n , ideclPkgQual = pkg_qual\\n , ideclExt = XImportDeclPass { ideclOrigin = origin } } = decl\\n ; iface <- loadSrcInterface doc (importDeclLookupScope origin)\\n mod_name is_boot pkg_qual\\n ; let used_avails = gresToAvailInfo used_gres\\n ; lies <- map (L l) <$> concatMapM (to_ie rdr_env iface) used_avails\\n ; return (L l (decl { ideclImportList = Just (Exactly, lies) })) }\\n where\\n doc = text \\"Compute minimal imports for\\" <+> ppr decl\\n\\n to_ie :: GlobalRdrEnv -> ModIface -> AvailInfo -> RnM [IE GhcRn]\\n -- The main trick here is that if we\'re importing all the constructors\\n -- we want to say \\"T(..)\\", but if we\'re importing only a subset we want\\n -- to say \\"T(A,B,C)\\". So we have to find out what the module exports.\\n to_ie rdr_env _ (Avail c) -- Note [Overloaded field import]\\n = do { let\\n gre = expectJust $ lookupGRE_Name rdr_env c\\n ; return $ [IEVar Nothing (to_ie_post_rn $ noLocA $ greName gre) Nothing] }\\n to_ie _ _ avail@(AvailTC n [_]) -- Exporting the main decl and nothing else\\n | availExportsDecl avail\\n = return [IEThingAbs Nothing (to_ie_post_rn $ noLocA n) Nothing]\\n to_ie rdr_env iface (AvailTC n cs) =\\n case [ xs | avail@(AvailTC x xs) <- mi_exports iface\\n , x == n\\n , availExportsDecl avail -- Note [Partial export]\\n ] of\\n [xs]\\n | all_used xs\\n -> return [IEThingAll (IEThingAllExt Nothing noAnn noAnn noAnn)\\n (NoNamespaceSpecifier noExtField)\\n (to_ie_post_rn $ noLocA n)\\n Nothing]\\n | otherwise\\n -> do { let ns_gres = map (expectJust . lookupGRE_Name rdr_env) cs\\n ns = map greName ns_gres\\n ; return [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n -- Note [Overloaded field import]\\n _other\\n -> do { let infos = map (expectJust . lookupGRE_Name rdr_env) cs\\n (ns_gres,fs_gres) = classifyGREs infos\\n ns = map greName (ns_gres ++ fs_gres)\\n fs = map fieldGREInfo fs_gres\\n ; return $\\n if all_non_overloaded fs\\n then map (\\\\nm -> IEVar Nothing (to_ie_post_rn_var $ noLocA nm) Nothing) ns\\n else [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n where\\n\\n all_used avail_cs = all (`elem` cs) avail_cs\\n\\n all_non_overloaded = all (not . flIsOverloaded . recFieldLabel)\\n\\n combine :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\n combine = map merge . NE.groupAllWith getKey\\n\\n getKey :: LImportDecl GhcRn -> (Bool, Maybe ModuleName, ModuleName)\\n getKey decl =\\n ( isImportDeclQualified . ideclQualified $ idecl -- is this qualified? (important that this be first)\\n , unLoc <$> ideclAs idecl -- what is the qualifier (inside Maybe monad)\\n , unLoc . ideclName $ idecl -- Module Name\\n )\\n where\\n idecl :: ImportDecl GhcRn\\n idecl = unLoc decl\\n\\n merge :: NonEmpty (LImportDecl GhcRn) -> LImportDecl GhcRn\\n merge decls@((L l decl) :| _) = L l (decl { ideclImportList = Just (Exactly, lies) })\\n where lies = concatMap snd $ mapMaybe (ideclImportList . unLoc) $ NE.toList decls\\n\\nclassifyGREs :: [GlobalRdrElt] -> ([GlobalRdrElt], [FieldGlobalRdrElt])\\nclassifyGREs = partition (not . isRecFldGRE)\\n\\nprintMinimalImports :: HscSource -> [ImportDeclUsage] -> RnM ()\\n-- See Note [Printing minimal imports]\\nprintMinimalImports hsc_src imports_w_usage\\n = do { imports\' <- excludeGenerated <$> getMinimalImports imports_w_usage\\n ; this_mod <- getModule\\n ; dflags <- getDynFlags\\n ; liftIO $ withFile (mkFilename dflags this_mod) WriteMode $ \\\\h ->\\n printForUser dflags h neverQualify AllTheWay (vcat (map ppr imports\'))\\n -- The neverQualify is important. We are printing Names\\n -- but they are in the context of an \'import\' decl, and\\n -- we never qualify things inside there\\n -- E.g. import Blag( f, b )\\n -- not import Blag( Blag.f, Blag.g )!\\n }\\n where\\n mkFilename dflags this_mod\\n | Just d <- dumpDir dflags = d basefn\\n | otherwise = basefn\\n where\\n suffix = case hsc_src of\\n HsBootFile -> \\".imports-boot\\"\\n HsSrcFile -> \\".imports\\"\\n HsigFile -> \\".imports\\"\\n basefn = moduleNameString (moduleName this_mod) ++ suffix\\n\\n\\nto_ie_post_rn_var :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn_var (L l n)\\n | isDataOcc $ occName n = L l (IEPattern noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n\\n\\nto_ie_post_rn :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn (L l n)\\n | isTcOcc occ && isSymOcc occ = L l (IEType noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n where occ = occName n\\n\\n{- Note [Do not warn about Prelude hiding]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWe do not warn about\\n import Prelude hiding( x, y )\\nbecause even if nothing else from Prelude is used, it may be essential to hide\\nx,y to avoid name-shadowing warnings. Example (#9061)\\n import Prelude hiding( log )\\n f x = log where log = ()\\n\\nNote [Unused imports]\\n~~~~~~~~~~~~~~~~~~~~~\\nIn `warnUnusedImport`, if we see an import with an explicit list imports, thus\\n import M( a, b )\\nand neither `a` nor `b` is used, we report the entire import decl as unused. We\\ncheck this by looking at the names that it brings into scope scope; if there are\\nno ununused names, don\'t report.\\n\\n(UI1) We don\'t want to complain about `import M()`, because that is often used to bring\\n M\'s /instances/ into scope. That is neatly dealt with by the \\"no unused\\n names\\" (nor unused wildcard imports) criterion.\\n\\n(UI2) We don\'t report a decl as unused if it has an `as Rebindable` qualifier.\\n See (KN1) in Note [Overview of known entities] in GHC.Builtin\\n\\n\\nNote [Printing minimal imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nTo print the minimal imports we walk over all import decls (both user-supplied\\nand generated), trim their import lists, then filter out generated decls.\\n\\nNB that\\n\\n * We do *not* change the \'qualified\' or \'as\' parts!\\n\\n * We do not discard a decl altogether; we might need instances\\n from it. Instead we just trim to an empty import list\\n\\nNote [Partial export]\\n~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have\\n\\n module A( op ) where\\n class C a where\\n op :: a -> a\\n\\n module B where\\n import A\\n f = ..op...\\n\\nThen the minimal import for module B is\\n import A( op )\\nnot\\n import A( C( op ) )\\nwhich we would usually generate if C was exported from B. Hence\\nthe availExportsDecl test when deciding what to generate.\\n\\n\\nNote [Overloaded field import]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nOn the other hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n data T = MkT { foo :: Int }\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( T(foo) )\\nbecause when DuplicateRecordFields is enabled, field selectors are\\nnot in scope without their enclosing datatype.\\n\\nOn the third hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n pattern MkT { foo } = Just foo\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( foo )\\nbecause foo doesn\'t have a parent. This might actually be ambiguous if A\\nexports another field called foo, but there is no good answer to return and this\\nis a very obscure corner, so it seems to be the best we can do. See\\nDRFPatSynExport for a test of this.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Errors}\\n* *\\n************************************************************************\\n-}\\n\\nbadImportItemErr\\n :: ModIface -> ImpDeclSpec -> IE GhcPs\\n -> IsSubordinateError\\n -> [AvailInfo]\\n -> TcRn (NonEmpty ImportLookupReason)\\nbadImportItemErr iface decl_spec ie sub avails = do\\n exts <- importLookupExtensions\\n let import_lookup_bad :: BadImportKind -> ImportLookupReason\\n import_lookup_bad k = ImportLookupBad k iface decl_spec ie exts\\n dflags <- getDynFlags\\n hsc_env <- getTopEnv\\n let rdr_env = mkGlobalRdrEnv\\n $ gresFromAvails hsc_env (Just imp_spec) all_avails\\n pure $ fmap import_lookup_bad (importErrorKind dflags rdr_env)\\n where\\n importErrorKind :: DynFlags -> GlobalRdrEnv -> NonEmpty BadImportKind\\n importErrorKind dflags rdr_env\\n | any checkIfTyCon avails = case sub of\\n IsNotSubordinate -> NE.singleton BadImportAvailTyCon\\n IsSubordinateError { subordinate_err_parent = gre\\n , subordinate_err_unavailable = unavailable\\n , subordinate_err_nontype = nontype\\n , subordinate_err_nondata = nondata }\\n -> NE.fromList $ catMaybes $\\n [ fmap (BadImportNotExportedSubordinates gre) (NE.nonEmpty unavailable)\\n , fmap (BadImportNonTypeSubordinates gre) (NE.nonEmpty nontype)\\n , fmap (BadImportNonDataSubordinates gre) (NE.nonEmpty nondata) ]\\n | any checkIfVarName avails = NE.singleton BadImportAvailVar\\n | Just con <- find checkIfDataCon avails = NE.singleton (BadImportAvailDataCon (availOccName con))\\n | otherwise = NE.singleton (BadImportNotExported suggs)\\n where\\n suggs = similar_suggs ++ fieldSelectorSuggestions rdr_env rdr\\n what_look = case sub of\\n IsNotSubordinate -> WL_TyCon_or_TermVar\\n IsSubordinateError { subordinate_err_parent = gre } ->\\n case greInfo gre of\\n IAmTyCon ClassFlavour\\n -> WL_TyCon_or_TermVar\\n _ -> WL_Term\\n similar_names =\\n similarNameSuggestions (Unbound.LF what_look WL_Global)\\n dflags rdr_env emptyLocalRdrEnv rdr\\n similar_suggs =\\n case NE.nonEmpty $ mapMaybe imported_item $ similar_names of\\n Just similar -> [ SuggestSimilarNames rdr similar ]\\n Nothing -> [ ]\\n\\n -- Only keep imported items, and set the \\"HowInScope\\" to\\n -- \\"Nothing\\" to avoid printing \\"imported from...\\" in the suggestion\\n -- error message.\\n imported_item (SimilarRdrName rdr_name gre (Just (ImportedBy {})))\\n = Just (SimilarRdrName rdr_name gre Nothing)\\n imported_item _ = Nothing\\n\\n checkIfDataCon = checkIfAvailMatches isDataConName\\n checkIfTyCon = checkIfAvailMatches isTyConName\\n checkIfVarName =\\n \\\\case\\n AvailTC{} -> False\\n Avail n -> importedFS == occNameFS (occName n)\\n && (isVarOcc <||> isFieldOcc) (occName n)\\n checkIfAvailMatches namePred =\\n \\\\case\\n AvailTC _ ns ->\\n case find (\\\\n -> importedFS == occNameFS (occName n)) ns of\\n Just n -> namePred n\\n Nothing -> False\\n Avail{} -> False\\n availOccName = occName . availName\\n rdr = ieName ie\\n importedFS = occNameFS $ rdrNameOcc rdr\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n all_avails = mi_exports iface\\n\\nimportLookupExtensions :: TcRn ImportLookupExtensions\\nimportLookupExtensions = do\\n ile_pattern_synonyms <- xoptM LangExt.PatternSynonyms\\n ile_explicit_namespaces <- xoptM LangExt.ExplicitNamespaces\\n return ImportLookupExtensions{ile_pattern_synonyms, ile_explicit_namespaces}\\n\\naddDupDeclErr :: NonEmpty GlobalRdrElt -> TcRn ()\\naddDupDeclErr gres@(gre :| _)\\n -- Report the error at the later location\\n = addErrAt (getSrcSpan (NE.last sorted_names)) $ (TcRnDuplicateDecls (greOccName gre) sorted_names)\\n where\\n sorted_names =\\n NE.sortBy (SrcLoc.leftmost_smallest `on` nameSrcSpan)\\n (fmap greName gres)\\n\\n-- This data decl will parse OK\\n-- data T = a Int\\n-- treating \\"a\\" as the constructor.\\n-- It is really hard to make the parser spot this malformation.\\n-- So the renamer has to check that the constructor is legal\\n--\\n-- We can get an operator as the constructor, even in the prefix form:\\n-- data T = :% Int Int\\n-- from interface files, which always print in prefix form\\n--\\n-- We also allow type constructor names, which are defined by \\"type data\\"\\n-- declarations. See Note [Type data declarations] in GHC.Rename.Module.\\n\\ncheckConName :: RdrName -> TcRn ()\\ncheckConName name\\n = checkErr (isRdrDataCon name || isRdrTc name) (TcRnIllegalDataCon name)\\n", "filetypes": ["haskell"]}}}' 2026-10-16 14:49:26,568 - DEBUG - POST b'http://127.0.0.1:37093/receive_messages' {'content-type': 'application/json', 'x-ycm-hmac': b'Rga7Yd4l4fgfufwYw+0sxzurvznImlBO0MPmgAlS4EY='} b'{"filepath": "/home/enrico/ghc/compiler/GHC/Rename/Names.hs", "line_num": 1, "column_num": 1, "working_dir": "/home/enrico/ghc", "file_data": {"/home/enrico/ghc/compiler/GHC/Rename/Names.hs": {"contents": "{-\\n(c) The GRASP/AQUA Project, Glasgow University, 1992-1998\\n\\nExtracting imported and top-level names in scope\\n-}\\n\\n{-# LANGUAGE NondecreasingIndentation #-}\\n{-# LANGUAGE TypeFamilies #-}\\n\\nmodule GHC.Rename.Names (\\n rnImports, getLocalNonValBinders, newRecordFieldLabel,\\n importsFromIface,\\n ImportUserSpec(..),\\n extendGlobalRdrEnvRn,\\n gresFromAvails,\\n calculateAvails,\\n reportUnusedNames,\\n checkConName,\\n mkChildEnv,\\n findChildren,\\n mkBadExportSubordinate,\\n findImportUsage,\\n getMinimalImports,\\n printMinimalImports,\\n renamePkgQual, renameRawPkgQual,\\n classifyGREs,\\n ImportDeclUsage,\\n rnNamespaceSpecifier\\n ) where\\n\\nimport GHC.Prelude hiding ( head, init, last, tail )\\n\\nimport GHC.Driver.Env\\nimport GHC.Driver.Session\\nimport GHC.Driver.Ppr\\n\\nimport GHC.Rename.Env\\nimport GHC.Rename.Fixity\\nimport GHC.Rename.Utils ( warnUnusedTopBinds )\\nimport GHC.Rename.Unbound\\nimport qualified GHC.Rename.Unbound as Unbound\\n\\nimport GHC.Tc.Errors.Types\\nimport GHC.Tc.Utils.Env\\nimport GHC.Tc.Utils.Monad\\nimport GHC.Tc.Types.LclEnv\\nimport GHC.Tc.Zonk.TcType ( tcInitTidyEnv )\\n\\nimport GHC.Hs\\nimport GHC.Iface.Load ( loadSrcInterface, loadSrcInterface_maybe )\\nimport GHC.Iface.Errors.Types\\n ( IfaceMessage(..), MissingInterfaceError, InterfaceLookingFor(..)\\n , LoadEssentialsReason(..) )\\nimport GHC.Iface.Syntax ( fromIfaceWarnings )\\nimport GHC.Builtin.Modules( pRELUDE_NAME, rEBINDABLE_MOD_NAME )\\nimport GHC.Parser.PostProcess ( setRdrNameSpace )\\nimport GHC.Core.TyCo.Tidy\\nimport GHC.Core.PatSyn\\nimport GHC.Core.TyCon ( TyCon, tyConName )\\nimport qualified GHC.LanguageExtensions as LangExt\\n\\nimport GHC.Utils.Outputable as Outputable\\nimport GHC.Utils.Misc as Utils\\nimport GHC.Utils.Panic\\n\\nimport GHC.Types.Fixity.Env\\nimport GHC.Types.SafeHaskell\\nimport GHC.Types.Name\\nimport GHC.Types.Name.Env\\nimport GHC.Types.Name.Set\\nimport GHC.Types.Name.Reader\\nimport GHC.Types.Avail\\nimport GHC.Types.FieldLabel\\nimport GHC.Types.Hint\\nimport GHC.Types.SourceFile\\nimport GHC.Types.SrcLoc as SrcLoc\\nimport GHC.Types.Basic (TyConFlavour (..), convImportLevel, VisArity)\\nimport GHC.Types.UnresolvedImport\\nimport GHC.Types.Id\\nimport GHC.Types.PkgQual\\nimport GHC.Types.GREInfo (ConInfo(..), ConFieldInfo (..), ConLikeInfo (ConIsData))\\n\\nimport GHC.Unit\\nimport GHC.Unit.Module.Warnings\\nimport GHC.Unit.Module.ModIface\\nimport GHC.Unit.Module.Imported\\nimport GHC.Unit.Module.Deps\\nimport GHC.Unit.Env\\n\\nimport GHC.Data.Bag\\nimport GHC.Data.FastString\\nimport GHC.Data.FastString.Env\\nimport GHC.Data.Maybe\\nimport GHC.Data.List.SetOps ( removeDups )\\n\\nimport Control.Arrow ( second )\\nimport Control.Monad\\nimport Data.Foldable ( for_ )\\nimport Data.IntMap ( IntMap )\\nimport qualified Data.IntMap as IntMap\\nimport Data.Map ( Map )\\nimport qualified Data.Map as Map\\nimport Data.Ord ( comparing )\\nimport Data.Semigroup ( Any(..) )\\nimport qualified Data.Semigroup as S\\nimport Data.List ( partition, find, sortBy )\\nimport Data.List.NonEmpty (NonEmpty(..))\\nimport qualified Data.List.NonEmpty as NE\\nimport Data.Function ( on )\\nimport qualified Data.Set as S\\nimport System.FilePath (())\\nimport System.IO\\n\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{rnImports}\\n* *\\n************************************************************************\\n\\nNote [Tracking Trust Transitively]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen we import a package as well as checking that the direct imports are safe\\naccording to the rules outlined in the Note [Safe Haskell Trust Check] in GHC.Driver.Main\\nwe must also check that these rules hold transitively for all dependent modules\\nand packages. Doing this without caching any trust information would be very\\nslow as we would need to touch all packages and interface files a module depends\\non. To avoid this we make use of the property that if a modules Safe Haskell\\nmode changes, this triggers a recompilation from that module in the dependency\\ngraph. So we can just worry mostly about direct imports.\\n\\nThere is one trust property that can change for a package though without\\nrecompilation being triggered: package trust. So we must check that all\\npackages a module transitively depends on to be trusted are still trusted when\\nwe are compiling this module (as due to recompilation avoidance some modules\\nbelow may not be considered trusted any more without recompilation being\\ntriggered).\\n\\nWe handle this by augmenting the existing transitive list of packages a module M\\ndepends on with a bool for each package that says if it must be trusted when the\\nmodule M is being checked for trust. This list of trust required packages for a\\nsingle import is gathered in the rnImportDecl function and stored in an\\nImportAvails data structure. The union of these trust required packages for all\\nimports is done by the rnImports function using the combine function which calls\\nthe plusImportAvails function that is a union operation for the ImportAvails\\ntype. This gives us in an ImportAvails structure all packages required to be\\ntrusted for the module we are currently compiling. Checking that these packages\\nare still trusted (and that direct imports are trusted) is done in\\nGHC.Driver.Main.checkSafeImports.\\n\\nSee the note below, [Trust Own Package] for a corner case in this method and\\nhow its handled.\\n\\n\\nNote [Trust Own Package]\\n~~~~~~~~~~~~~~~~~~~~~~~~\\nThere is a corner case of package trust checking that the usual transitive check\\ndoesn\'t cover. (For how the usual check operates see the Note [Tracking Trust\\nTransitively] below). The case is when you import a -XSafe module M and M\\nimports a -XTrustworthy module N. If N resides in a different package than M,\\nthen the usual check works as M will record a package dependency on N\'s package\\nand mark it as required to be trusted. If N resides in the same package as M\\nthough, then importing M should require its own package be trusted due to N\\n(since M is -XSafe so doesn\'t create this requirement by itself). The usual\\ncheck fails as a module doesn\'t record a package dependency of its own package.\\nSo instead we now have a bool field in a modules interface file that simply\\nstates if the module requires its own package to be trusted. This field avoids\\nus having to load all interface files that the module depends on to see if one\\nis trustworthy.\\n\\n\\nNote [Trust Transitive Property]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSo there is an interesting design question in regards to transitive trust\\nchecking. Say I have a module B compiled with -XSafe. B is dependent on a bunch\\nof modules and packages, some packages it requires to be trusted as its using\\n-XTrustworthy modules from them. Now if I have a module A that doesn\'t use safe\\nhaskell at all and simply imports B, should A inherit all the trust\\nrequirements from B? Should A now also require that a package p is trusted since\\nB required it?\\n\\nWe currently say no but saying yes also makes sense. The difference is, if a\\nmodule M that doesn\'t use Safe Haskell imports a module N that does, should all\\nthe trusted package requirements be dropped since M didn\'t declare that it cares\\nabout Safe Haskell (so -XSafe is more strongly associated with the module doing\\nthe importing) or should it be done still since the author of the module N that\\nuses Safe Haskell said they cared (so -XSafe is more strongly associated with\\nthe module that was compiled that used it).\\n\\nGoing with yes is a simpler semantics we think and harder for the user to stuff\\nup but it does mean that Safe Haskell will affect users who don\'t care about\\nSafe Haskell as they might grab a package from Cabal which uses safe haskell (say\\nnetwork) and that packages imports -XTrustworthy modules from another package\\n(say bytestring), so requires that package is trusted. The user may now get\\ncompilation errors in code that doesn\'t do anything with Safe Haskell simply\\nbecause they are using the network package. They will have to call \'ghc-pkg\\ntrust network\' to get everything working. Due to this invasive nature of going\\nwith yes we have gone with no for now.\\n-}\\n\\n-- | Process Import Decls. See \'rnImportDecl\' for a description of what\\n-- the return types represent.\\n-- Note: Do the non SOURCE ones first, so that we get a helpful warning\\n-- for SOURCE ones that are unnecessary\\nrnImports :: [(LImportDecl GhcPs, SDoc)]\\n -> RnM ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\nrnImports imports = do\\n tcg_env <- getGblEnv\\n -- NB: want an identity module here, because it\'s OK for a signature\\n -- module to import from its implementor\\n let this_mod = tcg_mod tcg_env\\n let (source, ordinary) = partition (is_source_import . fst) imports\\n is_source_import (d::LImportDecl GhcPs) = ideclSource (unLoc d) == IsBoot\\n stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary\\n stuff2 <- mapAndReportM (rnImportDecl this_mod) source\\n -- Safe Haskell: See Note [Tracking Trust Transitively]\\n let (decls, imp_user_spec, rdr_env, imp_avails) = combine (stuff1 ++ stuff2)\\n -- Update imp_boot_mods if imp_direct_mods mentions any of them\\n let merged_import_avail = clobberSourceImports imp_avails\\n return (decls, imp_user_spec, rdr_env, merged_import_avail)\\n\\n where\\n clobberSourceImports imp_avails =\\n imp_avails { imp_boot_mods = imp_boot_mods\' }\\n where\\n imp_boot_mods\' = mergeInstalledModuleEnv combJ id (const emptyInstalledModuleEnv)\\n (imp_boot_mods imp_avails)\\n (imp_direct_dep_mods imp_avails)\\n\\n combJ (GWIB _ IsBoot) (_, x) = Just x\\n combJ r _ = Just r\\n -- See Note [Combining ImportAvails]\\n combine :: [(LImportDecl GhcRn, ImportUserSpec, GlobalRdrEnv, ImportAvails)]\\n -> ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\n combine ss =\\n let (decls, imp_user_spec, rdr_env, imp_avails, finsts) = foldr\\n plus\\n ([], [], emptyGlobalRdrEnv, emptyImportAvails, emptyModuleSet)\\n ss\\n in (decls, imp_user_spec, rdr_env, imp_avails { imp_finsts = moduleSetElts finsts })\\n\\n plus (decl, us, gbl_env1, imp_avails1)\\n (decls, uss, gbl_env2, imp_avails2, finsts_set)\\n = ( decl:decls,\\n us:uss,\\n gbl_env1 `plusGlobalRdrEnv` gbl_env2,\\n imp_avails1\' `plusImportAvails` imp_avails2,\\n extendModuleSetList finsts_set new_finsts )\\n where\\n imp_avails1\' = imp_avails1 { imp_finsts = [] }\\n new_finsts = imp_finsts imp_avails1\\n\\n{-\\nNote [Combining ImportAvails]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nimp_finsts in ImportAvails is a list of family instance modules\\ntransitively depended on by an import. imp_finsts for a currently\\ncompiled module is a union of all the imp_finsts of imports.\\nComputing the union of two lists of size N is O(N^2) and if we\\ndo it to M imports we end up with O(M*N^2). That can get very\\nexpensive for bigger module hierarchies.\\n\\nUnion can be optimized to O(N log N) if we use a Set.\\nimp_finsts is converted back and forth between dep_finsts, so\\nchanging a type of imp_finsts means either paying for the conversions\\nor changing the type of dep_finsts as well.\\n\\nI\'ve measured that the conversions would cost 20% of allocations on my\\ntest case, so that can be ruled out.\\n\\nChanging the type of dep_finsts forces checkFamInsts to\\nget the module lists in non-deterministic order. If we wanted to restore\\nthe deterministic order, we\'d have to sort there, which is an additional\\ncost. As far as I can tell, using a non-deterministic order is fine there,\\nbut that\'s a brittle nonlocal property which I\'d like to avoid.\\n\\nAdditionally, dep_finsts is read from an interface file, so its \\"natural\\"\\ntype is a list. Which makes it a natural type for imp_finsts.\\n\\nSince rnImports.combine is really the only place that would benefit from\\nit being a Set, it makes sense to optimize the hot loop in rnImports.combine\\nwithout changing the representation.\\n\\nSo here\'s what we do: instead of naively merging ImportAvails with\\nplusImportAvails in a loop, we make plusImportAvails merge empty imp_finsts\\nand compute the union on the side using Sets. When we\'re done, we can\\nconvert it back to a list. One nice side effect of this approach is that\\nif there\'s a lot of overlap in the imp_finsts of imports, the\\nSet doesn\'t really need to grow and we don\'t need to allocate.\\n\\nRunning generateModules from #14693 with DEPTH=16, WIDTH=30 finishes in\\n23s before, and 11s after.\\n-}\\n\\n-- | Given a located import declaration @decl@ from @this_mod@,\\n-- calculate the following pieces of information:\\n--\\n-- 1. An updated \'LImportDecl\', where all unresolved \'RdrName\' in\\n-- the entity lists have been resolved into \'Name\'s,\\n--\\n-- 2. A \'GlobalRdrEnv\' representing the new identifiers that were\\n-- brought into scope (taking into account module qualification\\n-- and hiding),\\n--\\n-- 3. \'ImportAvails\' summarizing the identifiers that were imported\\n-- by this declaration, and\\n--\\n-- 4. A boolean \'AnyHpcUsage\' which is true if the imported module\\n-- used HPC.\\nrnImportDecl :: Module -> (LImportDecl GhcPs, SDoc)\\n -> RnM (LImportDecl GhcRn, ImportUserSpec , GlobalRdrEnv, ImportAvails)\\nrnImportDecl this_mod\\n (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name\\n , ideclPkgQual = raw_pkg_qual\\n , ideclSource = want_boot\\n , ideclSafe = mod_safe\\n , ideclLevelSpec = import_level\\n , ideclQualified = qual_style\\n , ideclExt = XImportDeclPass { ideclOrigin = origin }\\n , ideclAs = as_mod, ideclImportList = imp_details }), import_reason)\\n = setSrcSpanA loc $ do\\n\\n case raw_pkg_qual of\\n NoRawPkgQual -> pure ()\\n RawPkgQual {} -> do\\n pkg_imports <- xoptM LangExt.PackageImports\\n when (not pkg_imports) $ addErr TcRnPackageImportsDisabled\\n\\n let qual_only = isImportDeclQualified qual_style\\n generated = isGeneratedImport origin\\n\\n lookup_scope = importDeclLookupScope origin\\n\\n -- If there\'s an error in loadInterface, (e.g. interface\\n -- file not found) we get lots of spurious errors from \'filterImports\'\\n let imp_mod_name = unLoc loc_imp_mod_name\\n doc = ppr imp_mod_name <+> import_reason\\n\\n hsc_env <- getTopEnv\\n unit_env <- hsc_unit_env <$> getTopEnv\\n let pkg_qual = renameRawPkgQual unit_env imp_mod_name raw_pkg_qual\\n\\n -- Check for self-import, which confuses the typechecker (#9032)\\n -- ghc --make rejects self-import cycles already, but batch-mode may not\\n -- at least not until GHC.IfaceToCore.tcHiBootIface, which is too late to avoid\\n -- typechecker crashes. (Indirect self imports are not caught until\\n -- GHC.IfaceToCore, see #10337 tracking how to make this error better.)\\n --\\n -- Originally, we also allowed \'import {-# SOURCE #-} M\', but this\\n -- caused bug #10182: in one-shot mode, we should never load an hs-boot\\n -- file for the module we are compiling into the EPS. In principle,\\n -- it should be possible to support this mode of use, but we would have to\\n -- extend Provenance to support a local definition in a qualified location.\\n -- For now, we don\'t support it, but see #10336\\n when (imp_mod_name == moduleName this_mod &&\\n (case pkg_qual of -- If we have import \\"\\" M, then we should\\n -- check that \\"\\" is \\"this\\" (which is magic)\\n -- or the name of this_mod\'s package. Yurgh!\\n -- c.f. GHC.findModule, and #9997\\n NoPkgQual -> True\\n ThisPkg uid -> uid == homeUnitId_ (hsc_dflags hsc_env)\\n OtherPkg _ -> False))\\n (addErr (TcRnSelfImport imp_mod_name))\\n\\n -- Check for a missing import list (Opt_WarnMissingImportList also\\n -- checks for T(..) items but that is done in checkDodgyImport below)\\n case imp_details of\\n Just (Exactly, _) -> return () -- Explicit import list\\n _ | generated -> return () -- Do not bleat for generated imports\\n | qual_only -> return ()\\n | otherwise -> addDiagnostic (TcRnNoExplicitImportList imp_mod_name)\\n\\n\\n mb_iface <- loadSrcInterface_maybe doc lookup_scope imp_mod_name want_boot pkg_qual\\n iface <- case mb_iface of\\n Succeeded iface -> return iface\\n Failed err -> failWithTc $\\n importDeclLoadFailure origin imp_mod_name want_boot err\\n\\n -- Compiler sanity check: if the import didn\'t say\\n -- {-# SOURCE #-} we should not get a hi-boot file\\n warnPprTrace ((want_boot == NotBoot) && (mi_boot iface == IsBoot)) \\"rnImportDecl\\" (ppr imp_mod_name) $ do\\n\\n -- Issue a user warning for a redundant {- SOURCE -} import\\n -- NB that we arrange to read all the ordinary imports before\\n -- any of the {- SOURCE -} imports.\\n --\\n -- in --make and GHCi, the compilation manager checks for this,\\n -- and indeed we shouldn\'t do it here because the existence of\\n -- the non-boot module depends on the compilation order, which\\n -- is not deterministic. The hs-boot test can show this up.\\n dflags <- getDynFlags\\n warnIf ((want_boot == IsBoot) && (mi_boot iface == NotBoot) && isOneShot (ghcMode dflags))\\n (TcRnRedundantSourceImport imp_mod_name)\\n when (mod_safe && not (safeImportsOn dflags)) $\\n addErr (TcRnSafeImportsDisabled imp_mod_name)\\n\\n let imp_mod = mi_module iface\\n qual_mod_name = fmap unLoc as_mod `orElse` imp_mod_name\\n imp_spec = ImpDeclSpec { is_mod = imp_mod, is_qual = qual_only,\\n is_dloc = locA loc, is_as = qual_mod_name,\\n is_pkg_qual = pkg_qual, is_isboot = want_boot,\\n is_level = convImportLevel import_level }\\n\\n let filter_imports = do\\n -- filter the imports according to the import declaration\\n (new_imp_details, imp_user_list, gbl_env)\\n <- filterImports hsc_env iface imp_spec imp_details\\n -- for certain error messages, we\\u2019d like to know what could be\\n -- imported here, if everything were imported\\n potential_gres <- (\\\\(_,_,x) -> x) <$> filterImports hsc_env iface imp_spec Nothing\\n return (new_imp_details, imp_user_list, gbl_env, potential_gres)\\n\\n (new_imp_details, imp_user_list, gbl_env, potential_gres) <-\\n case origin of\\n ImplicitEssentialsImport ->\\n -- The implicit GHC.Essentials import does not bring anything into scope.\\n -- See Note [Finding GHC.Essentials] in GHC.Builtin.\\n return (Nothing, ImpUserDependOnly, emptyGlobalRdrEnv, emptyGlobalRdrEnv)\\n UserWrittenImport -> filter_imports\\n ImplicitPreludeImport -> filter_imports\\n PluginImport -> filter_imports\\n\\n let is_hiding | Just (EverythingBut,_) <- imp_details = True\\n | otherwise = False\\n\\n -- should the import be safe?\\n mod_safe\' = mod_safe\\n || (not generated && safeDirectImpsReq dflags)\\n || (generated && safeImplicitImpsReq dflags)\\n\\n hsc_env <- getTopEnv\\n let home_unit = hsc_home_unit hsc_env\\n other_home_units = hsc_all_home_unit_ids hsc_env\\n\\n imported_by\\n | isDependOnlyImport imp_user_list\\n = ImportedBySystem\\n | otherwise\\n = ImportedByUser $ ImportedModsVal\\n { imv_name = is_as imp_spec\\n , imv_span = locA loc\\n , imv_is_safe = mod_safe\'\\n , imv_is_hiding = is_hiding\\n , imv_all_exports = potential_gres\\n , imv_qualified = qual_only\\n , imv_is_level = convImportLevel import_level\\n }\\n imports = calculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by\\n\\n -- Complain if we import a deprecated module\\n case fromIfaceWarnings (mi_warns iface) of\\n WarnAll txt -> addDiagnostic (TcRnDeprecatedModule imp_mod_name txt)\\n _ -> return ()\\n\\n let new_imp_decl = ImportDecl\\n { ideclExt = ideclExt decl\\n , ideclName = ideclName decl\\n , ideclPkgQual = pkg_qual\\n , ideclSource = ideclSource decl\\n , ideclSafe = mod_safe\'\\n , ideclQualified = ideclQualified decl\\n , ideclAs = ideclAs decl\\n , ideclImportList = new_imp_details\\n , ideclLevelSpec = ideclLevelSpec decl\\n }\\n\\n return (L loc new_imp_decl, ImpUserSpec imp_spec imp_user_list, gbl_env, imports)\\n\\n-- | The error message to emit when we failed to load an interface.\\nimportDeclLoadFailure :: ImportDeclOrigin -> ModuleName -> IsBootInterface\\n -> MissingInterfaceError -> TcRnMessage\\nimportDeclLoadFailure ImplicitEssentialsImport _ _ err\\n = TcRnInterfaceError $ CantFindEssentials err LookingForEssentialsModule\\nimportDeclLoadFailure _ mod_name want_boot err\\n = TcRnInterfaceError $ Can\'tFindInterface err $ LookingForModule mod_name want_boot\\n\\n-- | Rename raw package imports\\nrenameRawPkgQual :: UnitEnv -> ModuleName -> RawPkgQual -> PkgQual\\nrenameRawPkgQual unit_env mn = \\\\case\\n NoRawPkgQual -> NoPkgQual\\n RawPkgQual _ fs -> renamePkgQual unit_env mn $ Just fs\\n\\n-- | Rename raw package imports\\nrenamePkgQual :: UnitEnv -> ModuleName -> Maybe FastString -> PkgQual\\nrenamePkgQual unit_env mn mb_pkg = case mb_pkg of\\n Nothing -> NoPkgQual\\n Just pkg_fs\\n | Just uid <- homeUnitId <$> ue_homeUnit unit_env\\n , pkg_fs == fsLit \\"this\\"\\n -> ThisPkg uid\\n\\n | Just (uid, _) <- find (fromMaybe False . fmap (== pkg_fs) . snd) home_names\\n -> ThisPkg uid\\n\\n | Just uid <- resolvePackageImport unit_state mn (PackageName pkg_fs)\\n -> OtherPkg uid\\n\\n | otherwise\\n -> OtherPkg (UnitId pkg_fs)\\n -- not really correct as pkg_fs is unlikely to be a valid unit-id but\\n -- we will report the failure later...\\n where\\n home_names =\\n [ (uid, mkFastString <$> thisPackageName (homeUnitEnv_dflags (ue_findHomeUnitEnv uid unit_env)))\\n | uid <- S.toList hpt_deps\\n ]\\n\\n unit_state = ue_homeUnitState unit_env\\n\\n hpt_deps :: S.Set UnitId\\n hpt_deps = homeUnitDepends unit_state\\n\\n\\n-- | Calculate the \'ImportAvails\' induced by an import of a particular\\n-- interface, but without \'imp_mods\'.\\ncalculateAvails :: HomeUnit\\n -> S.Set UnitId\\n -> ModIface\\n -> IsSafeImport\\n -> IsBootInterface\\n -> ImportedBy\\n -> ImportAvails\\ncalculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by =\\n let imp_mod = mi_module iface\\n imp_sem_mod= mi_semantic_module iface\\n orph_iface = mi_orphan iface\\n has_finsts = mi_finsts iface\\n deps = mi_deps iface\\n trust = getSafeMode $ mi_trust iface\\n trust_pkg = mi_trust_pkg iface\\n is_sig = mi_hsc_src iface == HsigFile\\n\\n -- If the module exports anything defined in this module, just\\n -- ignore it. Reason: otherwise it looks as if there are two\\n -- local definition sites for the thing, and an error gets\\n -- reported. Easiest thing is just to filter them out up\\n -- front. This situation only arises if a module imports\\n -- itself, or another module that imported it. (Necessarily,\\n -- this involves a loop.)\\n --\\n -- We do this *after* filterImports, so that if you say\\n -- module A where\\n -- import B( AType )\\n -- type AType = ...\\n --\\n -- module B( AType ) where\\n -- import {-# SOURCE #-} A( AType )\\n --\\n -- then you won\'t get a \'B does not export AType\' message.\\n\\n\\n -- Compute new transitive dependencies\\n --\\n -- \'dep_orphs\' and \'dep_finsts\' do NOT include the imported module\\n -- itself, but we DO need to include this module in \'imp_orphs\' and\\n -- \'imp_finsts\' if it defines an orphan or instance family; thus the\\n -- orph_iface/has_iface tests.\\n\\n deporphs = dep_orphs deps\\n depfinsts = dep_finsts deps\\n\\n orphans | orph_iface = assertPpr (not (imp_sem_mod `elem` deporphs)) (ppr imp_sem_mod <+> ppr deporphs) $\\n imp_sem_mod : deporphs\\n | otherwise = deporphs\\n\\n finsts | has_finsts = assertPpr (not (imp_sem_mod `elem` depfinsts)) (ppr imp_sem_mod <+> ppr depfinsts) $\\n imp_sem_mod : depfinsts\\n | otherwise = depfinsts\\n\\n -- Trusted packages are a lot like orphans.\\n trusted_pkgs | mod_safe\' = dep_trusted_pkgs deps\\n | otherwise = S.empty\\n\\n\\n pkg = moduleUnit (mi_module iface)\\n ipkg = toUnitId pkg\\n\\n -- Does this import mean we now require our own pkg\\n -- to be trusted? See Note [Trust Own Package]\\n ptrust = trust == Sf_Trustworthy || trust_pkg\\n pkg_trust_req\\n | isHomeUnit home_unit pkg = ptrust\\n | otherwise = False\\n\\n dependent_pkgs = if toUnitId pkg `S.member` other_home_units\\n then S.empty\\n else S.singleton (lvl, ipkg)\\n\\n lvl = case imported_by of\\n ImportedByUser imv -> imv_is_level imv\\n ImportedBySystem -> NormalLevel\\n\\n\\n direct_mods = if toUnitId pkg `S.member` other_home_units\\n then mkPlusModDeps (moduleUnitId imp_mod) lvl (GWIB (moduleName imp_mod) want_boot)\\n else emptyInstalledModuleEnv\\n\\n dep_boot_mods_map = mkModDeps (dep_boot_mods deps)\\n\\n\\n boot_mods\\n -- If we are looking for a boot module, it must be HPT\\n | IsBoot <- want_boot = extendInstalledModuleEnv dep_boot_mods_map (toUnitId <$> imp_mod) (GWIB (moduleName imp_mod) IsBoot)\\n -- Now we are importing A properly, so don\'t go looking for\\n -- A.hs-boot\\n | isHomeUnit home_unit pkg = dep_boot_mods_map\\n -- There\'s no boot files to find in external imports\\n | otherwise = emptyInstalledModuleEnv\\n\\n sig_mods =\\n if is_sig\\n then moduleName imp_mod : dep_sig_mods deps\\n else dep_sig_mods deps\\n\\n\\n in ImportAvails {\\n imp_mods = Map.singleton (mi_module iface) [imported_by],\\n imp_orphs = orphans,\\n imp_finsts = finsts,\\n imp_sig_mods = sig_mods,\\n imp_direct_dep_mods = direct_mods,\\n imp_dep_direct_pkgs = dependent_pkgs,\\n imp_boot_mods = boot_mods,\\n\\n -- Add in the imported modules trusted package\\n -- requirements. ONLY do this though if we import the\\n -- module as a safe import.\\n -- See Note [Tracking Trust Transitively]\\n -- and Note [Trust Transitive Property]\\n imp_trust_pkgs = trusted_pkgs,\\n -- Do we require our own pkg to be trusted?\\n -- See Note [Trust Own Package]\\n imp_trust_own_pkg = pkg_trust_req\\n }\\n\\nmkPlusModDeps :: UnitId -> ImportLevel -> ModuleNameWithIsBoot\\n -> InstalledModuleEnv (S.Set ImportLevel, ModuleNameWithIsBoot)\\nmkPlusModDeps uid st elt = extendInstalledModuleEnv emptyInstalledModuleEnv (mkModule uid (gwib_mod elt)) (S.singleton st, elt)\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{importsFromLocalDecls}\\n* *\\n************************************************************************\\n\\nFrom the top-level declarations of this module produce\\n * the lexical environment\\n * the ImportAvails\\ncreated by its bindings.\\n\\nNote [Top-level Names in Template Haskell decl quotes]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSee also: Note [Interactively-bound Ids in GHCi] in GHC.Driver.Env\\n Note [Looking up Exact RdrNames] in GHC.Rename.Env\\n\\nConsider a Template Haskell declaration quotation like this:\\n module M where\\n f x = h [d| f = 3 |]\\nWhen renaming the declarations inside [d| ...|], we treat the\\ntop level binders specially in two ways\\n\\n1. We give them an Internal Name, not (as usual) an External one.\\n This is done by GHC.Rename.Env.newTopSrcBinder.\\n\\n2. We make them *shadow* the outer bindings.\\n See Note [GlobalRdrEnv shadowing]\\n\\n3. We find out whether we are inside a [d| ... |] by testing the TH\\n level. This is a slight hack, because the level field was really\\n meant for the type checker, and here we are not interested in the\\n fields of Brack, hence the error thunks in thRnBrack.\\n-}\\n\\nextendGlobalRdrEnvRn :: [GlobalRdrElt]\\n -> MiniFixityEnv\\n -> RnM (TcGblEnv, TcLclEnv)\\n-- Updates both the GlobalRdrEnv and the FixityEnv\\n-- We return a new TcLclEnv only because we might have to\\n-- delete some bindings from it;\\n-- see Note [Top-level Names in Template Haskell decl quotes]\\n\\nextendGlobalRdrEnvRn new_gres new_fixities\\n = checkNoErrs $ -- See Note [Fail fast on duplicate definitions]\\n do { (gbl_env, lcl_env) <- getEnvs\\n ; level <- getThLevel\\n ; isGHCi <- getIsGHCi\\n ; let rdr_env = tcg_rdr_env gbl_env\\n fix_env = tcg_fix_env gbl_env\\n th_bndrs = getLclEnvThBndrs lcl_env\\n th_lvl = thLevelIndex level\\n\\n -- Delete new_occs from global and local envs\\n -- If we are in a TemplateHaskell decl bracket,\\n -- we are going to shadow them\\n -- See Note [GlobalRdrEnv shadowing]\\n inBracket = isBrackLevel level\\n\\n lcl_env_TH = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_rdr = minusLocalRdrEnv (tcl_rdr lcl_env) new_gres_env }) lcl_env\\n -- See Note [GlobalRdrEnv shadowing]\\n\\n lcl_env2 | inBracket = lcl_env_TH\\n | otherwise = lcl_env\\n\\n -- Deal with shadowing: see Note [GlobalRdrEnv shadowing]\\n want_shadowing = isGHCi || inBracket\\n rdr_env1 | want_shadowing = shadowNames False rdr_env new_gres_env\\n | otherwise = rdr_env\\n\\n lcl_env3 = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_th_bndrs = extendNameEnvList th_bndrs\\n [ ( n, (TopLevel, th_lvl) )\\n | n <- new_names ] }) lcl_env2\\n\\n ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres\\n\\n ; let fix_env\' = foldl\' extend_fix_env fix_env new_gres\\n gbl_env\' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env\' }\\n\\n ; traceRn \\"extendGlobalRdrEnvRn 2\\" (pprGlobalRdrEnv True rdr_env2)\\n ; return (gbl_env\', lcl_env3) }\\n where\\n new_names = map greName new_gres\\n new_gres_env = mkGlobalRdrEnv new_gres\\n\\n -- If there is a fixity decl for the gre, add it to the fixity env\\n extend_fix_env fix_env gre\\n | Just (L _ fi) <- lookupMiniFixityEnv new_fixities name\\n = extendNameEnv fix_env name (FixItem occ fi)\\n | otherwise\\n = fix_env\\n where\\n name = greName gre\\n occ = greOccName gre\\n\\n add_gre :: GlobalRdrEnv -> GlobalRdrElt -> RnM GlobalRdrEnv\\n -- Extend the GlobalRdrEnv with a LocalDef GRE\\n -- If there is already a LocalDef GRE with the same OccName,\\n -- report an error and discard the new GRE\\n -- This establishes INVARIANT 1 of GlobalRdrEnvs\\n add_gre env gre\\n | not (null dups) -- Same OccName defined twice\\n = do { addDupDeclErr (gre :| dups); return env }\\n\\n | otherwise\\n = return (extendGlobalRdrEnv env gre)\\n where\\n -- See Note [Reporting duplicate local declarations]\\n dups = filter isBadDupGRE\\n $ lookupGRE env (LookupOccName (greOccName gre) (RelevantGREsFOS WantBoth))\\n isBadDupGRE old_gre = isLocalGRE old_gre && greClashesWith gre old_gre\\n\\n{- Note [Fail fast on duplicate definitions]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIf there are duplicate bindings for the same thing, we want to fail\\nfast. Having two bindings for the same thing can cause follow-on errors.\\nExample (test T9975a):\\n data Test = Test { x :: Int }\\n pattern Test wat = Test { x = wat }\\nThis defines \'Test\' twice. The second defn has no field-names; and then\\nwe get an error from Test { x=wat }, saying \\"Test has no field \'x\'\\".\\n\\nEasiest thing is to bale out fast on duplicate definitions, which\\nwe do via `checkNoErrs` on `extendGlobalRdrEnvRn`.\\n\\nNote [Reporting duplicate local declarations]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn general, a single module may not define the same OccName multiple times. This\\nis checked in extendGlobalRdrEnvRn: when adding a new locally-defined GRE to the\\nGlobalRdrEnv we report an error if there are already duplicates in the\\nenvironment. This establishes INVARIANT 1 (see comments on GlobalRdrEnv in\\nGHC.Types.Name.Reader), which says that for a given OccName, all the\\nGlobalRdrElts to which it maps must have distinct \'greName\'s.\\n\\nFor example, the following will be rejected:\\n\\n f x = x\\n g x = x\\n f x = x -- Duplicate!\\n\\nUsers are allowed to introduce new GREs with the same OccName as an imported GRE,\\nas disambiguation is possible through the module system, e.g.:\\n\\n module M where\\n import N (f)\\n f x = x\\n g x = M.f x + N.f x\\n\\nIf both GREs are local, the general rule is that two GREs clash if they have\\nthe same OccName, i.e. they share a textual name and live in the same namespace.\\nHowever, there are additional clashes due to record fields:\\n\\n - a new variable clashes with previously defined record fields\\n which define field selectors,\\n\\n - a new record field shadows:\\n\\n - previously defined variables, if it defines a field selector,\\n - previously defined record fields, unless it is a duplicate record field.\\n\\nThis logic is implemented in the function \'GHC.Types.Name.Reader.greClashesWith\'.\\n\\nSee also Note [Skipping ambiguity errors at use sites of local declarations] in\\nGHC.Rename.Utils.\\n-}\\n\\n\\n{- *********************************************************************\\n* *\\n getLocalDeclBindersd@ returns the names for an HsDecl\\n It\'s used for source code.\\n\\n *** See Note [The Naming story] in GHC.Hs.Decls ****\\n* *\\n********************************************************************* -}\\n\\ngetLocalNonValBinders :: MiniFixityEnv -> HsGroup GhcPs\\n -> RnM ((TcGblEnv, TcLclEnv), NameSet)\\n-- Get all the top-level binders bound the group *except*\\n-- for value bindings, which are treated separately\\n-- Specifically we return AvailInfo for\\n-- * type decls (incl constructors and record selectors)\\n-- * class decls (including class ops)\\n-- * associated types\\n-- * foreign imports\\n-- * value signatures (in hs-boot files only)\\n\\ngetLocalNonValBinders fixity_env\\n (HsGroup { hs_valds = binds,\\n hs_tyclds = tycl_decls,\\n hs_fords = foreign_decls })\\n = do { -- Process all type/class decls *except* family instances\\n ; let inst_decls = tycl_decls >>= group_instds\\n ; dup_fields_ok <- xopt_DuplicateRecordFields <$> getDynFlags\\n ; has_sel <- xopt_FieldSelectors <$> getDynFlags\\n ; tc_gres\\n <- concatMapM\\n (new_tc dup_fields_ok has_sel)\\n (tyClGroupTyClDecls tycl_decls)\\n ; traceRn \\"getLocalNonValBinders 1\\" (ppr tc_gres)\\n ; envs <- extendGlobalRdrEnvRn tc_gres fixity_env\\n ; restoreEnvs envs $ do {\\n -- Bring these things into scope first\\n -- See Note [Looking up family names in family instances]\\n\\n -- Process all family instances\\n -- to bring new data constructors into scope\\n ; nti_gress <- mapM (new_assoc dup_fields_ok has_sel) inst_decls\\n\\n -- Finish off with value binders:\\n -- foreign decls and pattern synonyms for an ordinary module\\n -- type sigs in case of a hs-boot file only\\n ; is_boot <- tcIsHsBootOrSig\\n ; let val_bndrs\\n | is_boot = case binds of\\n ValBinds _ val_binds ->\\n -- In a hs-boot file, the value binders come from the\\n -- *signatures*, and there should be no foreign binders\\n [ L (l2l decl_loc) (unLoc n)\\n | L decl_loc (TypeSig _ _ ns _) <- (val_sigs val_binds), n <- ns]\\n _ -> panic \\"Non-ValBinds in hs-boot group\\"\\n | otherwise = for_hs_bndrs\\n ; val_gres <- mapM new_simple val_bndrs\\n\\n ; let avails = concat nti_gress ++ val_gres\\n new_bndrs = gresToNameSet avails `unionNameSet`\\n gresToNameSet tc_gres\\n ; traceRn \\"getLocalNonValBinders 2\\" (ppr avails)\\n ; envs <- extendGlobalRdrEnvRn avails fixity_env\\n ; return (envs, new_bndrs) } }\\n where\\n for_hs_bndrs :: [LocatedN RdrName]\\n for_hs_bndrs = hsForeignDeclsBinders foreign_decls\\n\\n -- the SrcSpan attached to the input should be the span of the\\n -- declaration, not just the name\\n new_simple :: LocatedN RdrName -> RnM GlobalRdrElt\\n new_simple rdr_name = do { nm <- newTopSrcBinder rdr_name\\n ; return (mkLocalVanillaGRE NoParent nm) }\\n\\n new_tc :: DuplicateRecordFields -> FieldSelectors -> LTyClDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_tc dup_fields_ok has_sel tc_decl -- NOT for type/data instances\\n = do { let TyDeclBinders (main_bndr, tc_flav) at_bndrs sig_bndrs\\n (LConsWithFields cons_with_flds flds) = hsLTyClDeclBinders tc_decl\\n ; tycon_name <- newTopSrcBinder $ la2la main_bndr\\n ; at_names <- mapM (newTopSrcBinder . la2la . fst) at_bndrs\\n ; sig_names <- mapM (newTopSrcBinder . la2la) sig_bndrs\\n ; con_names_with_flds <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst con_names_with_flds) flds\\n ; mapM_ (add_dup_fld_errs flds\') con_names_with_flds\\n ; let tc_gre = mkLocalTyConGRE (fmap (const tycon_name) tc_flav) tycon_name\\n fld_env = mk_fld_env con_names_with_flds flds\'\\n at_gres = zipWith (\\\\ (_, at_flav) at_nm -> mkLocalTyConGRE (fmap (const tycon_name) at_flav) at_nm)\\n at_bndrs at_names\\n sig_gres = map (mkLocalVanillaGRE (ParentIs tycon_name)) sig_names\\n con_gres = map (mkLocalConLikeGRE (ParentIs tycon_name)) fld_env\\n fld_gres = mkLocalFieldGREs (ParentIs tycon_name) fld_env\\n sub_gres = at_gres ++ sig_gres ++ con_gres ++ fld_gres\\n ; traceRn \\"getLocalNonValBinders new_tc\\" $\\n vcat [ text \\"tycon:\\" <+> ppr tycon_name\\n , text \\"tc_gre:\\" <+> ppr tc_gre\\n , text \\"sub_gres:\\" <+> ppr sub_gres ]\\n ; return $ tc_gre : sub_gres }\\n\\n -- Calculate the record field information, which feeds into the GlobalRdrElts\\n -- for DataCons and their fields. It\'s convenient to do this here where\\n -- we are working with a single datatype definition.\\n --\\n -- The information we needed was all set up for us:\\n -- see Note [Collecting record fields in data declarations] in GHC.Hs.Utils.\\n mk_fld_env :: [(Name, Either VisArity [Located Int])] -> IntMap FieldLabel\\n -> [(ConLikeName, ConInfo)]\\n mk_fld_env names flds =\\n [ (DataConName con, ConInfo (ConIsData (map fst names)) fld_info)\\n | (con, con_fl_indxs) <- names\\n , let fld_info = case fmap (map ((flds IntMap.!) . unLoc)) con_fl_indxs of\\n Left 0 -> ConIsNullary\\n Left arity -> ConHasPositionalArgs arity\\n Right [] -> ConIsNullary\\n Right (fld:flds) -> ConHasRecordFields $ fld NE.:| flds ]\\n\\n new_assoc :: DuplicateRecordFields -> FieldSelectors -> LInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_assoc _ _ (L _ (TyFamInstD {})) = return []\\n -- type instances don\'t bind new names\\n\\n new_assoc dup_fields_ok has_sel (L _ (DataFamInstD _ d))\\n = new_di dup_fields_ok has_sel Nothing d\\n new_assoc dup_fields_ok has_sel\\n (L _ (ClsInstD _ (ClsInstDecl { cid_poly_ty = inst_ty\\n , cid_decls = decls })))\\n = do -- First, attempt to grab the name of the class from the instance.\\n -- This step could fail if the instance is not headed by a class,\\n -- such as in the following examples:\\n --\\n -- (1) The class is headed by a bang pattern, such as in\\n -- `instance !Show Int` (#3811c)\\n -- (2) The class is headed by a type variable, such as in\\n -- `instance c` (#16385)\\n --\\n -- If looking up the class name fails, then mb_cls_gre will\\n -- be Nothing.\\n mb_cls_gre <- runMaybeT $ do\\n -- See (1) above\\n L loc cls_rdr <- MaybeT $ pure $ getLHsInstDeclClass_maybe inst_ty\\n -- See (2) above\\n MaybeT $ setSrcSpan (locA loc) $ lookupGlobalOccRn_maybe SameNameSpace cls_rdr\\n -- Assuming the previous step succeeded, process any associated data\\n -- family instances. If the previous step failed, bail out.\\n case mb_cls_gre of\\n Nothing\\n -> pure []\\n Just cls_gre\\n -> let cls_nm = greName cls_gre\\n in concatMapM (new_di dup_fields_ok has_sel (Just cls_nm) . unLoc) (data_fam_insts decls)\\n\\n data_fam_insts decls = concatMap get decls\\n where\\n get (L l (InstD _ (DataFamInstD { dfid_inst = d}))) = [L l d]\\n get _ = []\\n\\n new_di :: DuplicateRecordFields -> FieldSelectors\\n -> Maybe Name -- class name\\n -> DataFamInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_di dup_fields_ok has_sel mb_cls dfid@(DataFamInstDecl { dfid_eqn = ti_decl })\\n = do { main_name <- unLoc <$> lookupFamInstName mb_cls (feqn_tycon ti_decl)\\n ; let LConsWithFields cons_with_flds flds = hsDataFamInstBinders dfid\\n ; sub_names <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst sub_names) flds\\n ; mapM_ (add_dup_fld_errs flds\') sub_names\\n ; let fld_env = mk_fld_env sub_names flds\'\\n con_gres = map (mkLocalConLikeGRE (ParentIs main_name)) fld_env\\n field_gres = mkLocalFieldGREs (ParentIs main_name) fld_env\\n -- NB: the data family name is not bound here,\\n -- so we don\'t return a GlobalRdrElt for it here!\\n ; return $ con_gres ++ field_gres }\\n\\n -- Add errors if a constructor has a duplicate record field.\\n add_dup_fld_errs :: IntMap FieldLabel\\n -> (Name, Either VisArity [Located Int])\\n -> IOEnv (Env TcGblEnv TcLclEnv) ()\\n add_dup_fld_errs all_flds (con, con_flds_or_arity)\\n | Right con_flds <- con_flds_or_arity\\n , let (_, dups) = removeDups (comparing unLoc) con_flds\\n = for_ dups $ \\\\ dup_flds ->\\n -- Report the error at the location of the second occurrence\\n -- of the duplicate field.\\n let loc =\\n case dup_flds of\\n _ :| ( L loc _ : _) -> loc\\n L loc _ :| _ -> loc\\n dup_rdrs = fmap (nameRdrName . flSelector . (all_flds IntMap.!) . unLoc) dup_flds\\n in addErrAt loc $ TcRnDuplicateFieldName (RecordFieldDecl con) dup_rdrs\\n | otherwise\\n = return ()\\n\\nnewRecordFieldLabel :: DuplicateRecordFields -> FieldSelectors -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel\\nnewRecordFieldLabel _ _ [] _ = error \\"newRecordFieldLabel: datatype has no constructors!\\"\\nnewRecordFieldLabel dup_fields_ok has_sel (dc:_) (L loc (FieldOcc _ (L _ fld)))\\n = do { selName <- newTopSrcBinder $ L (l2l loc) $ field\\n ; return $ FieldLabel { flHasDuplicateRecordFields = dup_fields_ok\\n , flHasFieldSelector = has_sel\\n , flSelector = selName } }\\n where\\n fld_occ = rdrNameOcc fld\\n dc_fs = occNameFS $ nameOccName dc\\n field\\n -- Use an Exact RdrName as-is, to preserve the bindings\\n -- of an already renamer-resolved field and its use\\n -- sites. This is needed to correctly support record\\n -- selectors in Template Haskell. See Note [Binders in\\n -- Template Haskell] in \\"GHC.ThToHs\\" and Note [Looking up\\n -- Exact RdrNames] in \\"GHC.Rename.Env\\".\\n | isExact fld\\n = assertPpr (fieldOcc_maybe fld_occ == Just dc_fs)\\n (vcat [ text \\"newRecordFieldLabel: incorrect namespace for exact Name\\" <+> quotes (ppr fld)\\n , text \\"expected namespace:\\" <+> pprNameSpace (fieldName dc_fs)\\n , text \\" actual namespace:\\" <+> pprNameSpace (occNameSpace fld_occ) ])\\n fld\\n\\n -- Field names produced by the parser are namespaced with VarName.\\n -- Here we namespace them according to the first constructor.\\n -- See Note [Record field namespacing] in GHC.Types.Name.Occurrence.\\n | otherwise\\n = mkRdrUnqual $ varToRecFieldOcc dc_fs fld_occ\\n\\n{-\\nNote [Looking up family names in family instances]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider\\n\\n module M where\\n type family T a :: *\\n type instance M.T Int = Bool\\n\\nWe might think that we can simply use \'lookupOccRn\' when processing the type\\ninstance to look up \'M.T\'. Alas, we can\'t! The type family declaration is in\\nthe *same* HsGroup as the type instance declaration. Hence, as we are\\ncurrently collecting the binders declared in that HsGroup, these binders will\\nnot have been added to the global environment yet.\\n\\nSolution is simple: process the type family declarations first, extend\\nthe environment, and then process the type instances.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Filtering imports}\\n* *\\n************************************************************************\\n\\n@filterImports@ takes the @ExportEnv@ telling what the imported module makes\\navailable, and filters it through the import spec (if any).\\n\\nNote [Dealing with imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nFor import M( ies ), we take each AvailInfo from the mi_exports of M, and make\\n\\n imp_occ_env :: OccEnv (NameEnv ImpOccItem)\\n\\nThis map contains one entry for each OccName that M exports, mapping each OccName\\nto the following information:\\n\\n 1. the GlobalRdrElt corresponding to the OccName,\\n 2. whether this GlobalRdrElt was the parent in the AvailInfo we found\\n the OccName in.\\n 3. the GlobalRdrElts that were bundled together in the AvailInfo we found\\n this OccName in (not including the parent),\\n\\nWe need (2) and (3) during the construction of the OccEnv because of associated\\ntypes and bundled pattern synonyms, respectively.\\n(3) is explained in Note [Importing PatternSynonyms].\\n\\nTo explain (2), consider for example:\\n\\n module M where\\n class C a where { data T a }\\n instance C Int where { data T Int = T1 | T2 }\\n instance C Bool where { data T Int = T3 }\\n\\nHere, M\'s exports avails are (recalling the AvailTC invariant from GHC.Types.Avail)\\n\\n C(C,T), T(T,T1,T2,T3)\\n\\nNotice that T appears *twice*, once as a child and once as a parent. From\\nthese two exports, respectively, during construction of the imp_occ_env, we begin\\nby associating the following two elements with the key T:\\n\\n T -> ImpOccItem { imp_item = gre1, imp_bundled = [C,T] , imp_is_parent = False }\\n T -> ImpOccItem { imp_item = gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nwhere `gre1`, `gre2` are two GlobalRdrElts with greName T.\\nWe combine these (in function \'combine\' in \'mkImportOccEnv\') by discarding the\\nnon-parent item, thusly:\\n\\n T -> IE_ITem { imp_item = gre1 `plusGRE` gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nNote the `plusGRE`: this ensures we don\'t drop parent information;\\nsee Note [Preserve parent information when combining import OccEnvs].\\n\\nSo the overall imp_occ_env is:\\n\\n C -> ImpOccItem { imp_item = C, imp_bundled = [T ], imp_is_parent = True }\\n T -> ImpOccItem { imp_item = T , imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n T1 -> ImpOccItem { imp_item = T1, imp_bundled = [T1,T2,T3], imp_is_parent = False }\\n -- similarly for T2, T3\\n\\nNote that the imp_occ_env will have entries for data constructors too,\\nalthough we never look up data constructors.\\n\\nNote [Importing PatternSynonyms]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nAs described in Note [Dealing with imports], associated types can lead to the\\nsame Name appearing twice, both as a child and once as a parent, when\\nconstructing the imp_occ_env. The same thing can happen with pattern synonyms\\nif they are exported bundled with a type.\\n\\nA simplified example, based on #11959:\\n\\n {-# LANGUAGE PatternSynonyms #-}\\n module M (T(P), pattern P) where -- Duplicate export warning, but allowed\\n data T = MkT\\n pattern P = MkT\\n\\nHere we have T(P) and P in export_avails, and respectively construct both\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n P -> ImpOccItem { imp_item = P, imp_bundled = [] , imp_is_parent = False }\\n\\nWe combine these by dropping the one with no siblings, leaving us with:\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n\\nThat is, we simply discard the non-bundled Avail.\\n\\nNote [Importing DuplicateRecordFields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn filterImports, another complicating factor is DuplicateRecordFields.\\nSuppose we have:\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (S(foo), T(foo)) where\\n data S = MkS { foo :: Int }\\n data T = MkT { foo :: Int }\\n\\n module N where\\n import M (foo) -- this is allowed (A)\\n import M (S(foo)) -- this is allowed (B)\\n\\nHere M exports \'foo\' at two different OccNames, with different namespaces for\\nthe two construtors MkS and MkT. Then, when we look up \'foo\' in lookup_names\\nfor case (A), we have a variable foo but must look in all the record field\\nnamespaces to find the two fields (and hence two different Avails).\\nWhereas in case (B) we reach the lookup_ie case for IEThingWith,\\nwhich looks up \'S\' and then finds the unique \'foo\' amongst its children.\\n\\nSee T16745 for a test of this.\\n\\nNote [Preserve parent information when combining import OccEnvs]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen discarding one ImpOccItem in favour of another, as described in\\nNote [Dealing with imports], we must make sure to combine the GREs so that\\nwe don\'t lose information.\\n\\nConsider for example #24084:\\n\\n module M1 where { class C a where { type T a } }\\n module M2 ( module M1 ) where { import M1 }\\n module M3 where { import M2 ( C, T ); instance C () where T () = () }\\n\\nWhen processing the import list of `M3`, we will have two `Avail`s attached\\nto `T`, namely `C(C, T)` and `T(T)`. We combine them in the `combine` function\\nof `mkImportOccEnv`; as described in Note [Dealing with imports] we discard\\n`C(C, T)` in favour of `T(T)`. However, in doing so, we **must not**\\ndiscard the information want that `C` is the parent of `T`. Indeed,\\nlosing track of this information can cause errors when importing,\\nas we could get an error of the form\\n\\n \\u2018T\\u2019 is not a (visible) associated type of class \\u2018C\\u2019\\n\\nThis explains why we use `plusGRE` when combining the two ImpOccItems, even\\nthough we are discarding one in favour of the other.\\n-}\\n\\n-- | All the \'GlobalRdrElt\'s associated with an \'AvailInfo\'.\\ngresFromAvail :: HasDebugCallStack\\n => HscEnv -> Maybe ImportSpec -> AvailInfo -> [GlobalRdrElt]\\ngresFromAvail hsc_env prov avail =\\n [ mk_gre nm info\\n | nm <- availNames avail\\n , let info = lookupGREInfo hsc_env nm ]\\n where\\n\\n mk_gre n info\\n = case prov of\\n -- Nothing => bound locally\\n -- Just is => imported from \'is\'\\n Nothing -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = True, gre_imp = emptyBag\\n , gre_info = info }\\n Just is -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = False, gre_imp = unitBag is\\n , gre_info = info }\\n\\n-- | All the \'GlobalRdrElt\'s associated with a collection of \'AvailInfo\'s.\\ngresFromAvails :: HscEnv -> Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]\\ngresFromAvails hsc_env prov = concatMap (gresFromAvail hsc_env prov)\\n\\nimportsFromIface :: HscEnv -> ModIface -> ImpDeclSpec -> Maybe NameSet -> GlobalRdrEnv\\nimportsFromIface hsc_env iface decl_spec hidden = mkGlobalRdrEnv $ case hidden of\\n Nothing -> all_gres\\n Just hidden_names -> filter (not . (`elemNameSet` hidden_names) . greName) all_gres\\n where\\n all_gres = gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\nrnNamespaceSpecifier :: NamespaceSpecifier GhcPs -> NamespaceSpecifier GhcRn\\nrnNamespaceSpecifier (NoNamespaceSpecifier _) = NoNamespaceSpecifier noExtField\\nrnNamespaceSpecifier (TypeNamespaceSpecifier x) = TypeNamespaceSpecifier x\\nrnNamespaceSpecifier (DataNamespaceSpecifier x) = DataNamespaceSpecifier x\\n\\nfilterImports\\n :: HasDebugCallStack\\n => HscEnv\\n -> ModIface\\n -> ImpDeclSpec\\n -- ^ Import spec\\n -> Maybe (ImportListInterpretation, [LIE GhcPs])\\n -- ^ Whether this is a \\"hiding\\" import list\\n -> RnM (Maybe (ImportListInterpretation, [LIE GhcRn]), -- Import spec w/ Names\\n ImpUserList, -- same, but designed for storage in interfaces\\n GlobalRdrEnv) -- Same again, but in GRE form\\nfilterImports hsc_env iface decl_spec Nothing\\n = return (Nothing, ImpUserAll, importsFromIface hsc_env iface decl_spec Nothing)\\nfilterImports hsc_env iface decl_spec (Just (want_hiding, import_items))\\n = do -- check for errors, convert RdrNames to Names\\n items1 <- mapM lookup_lie import_items\\n\\n let items2 :: [(LIE GhcRn, [GlobalRdrElt])]\\n items2 = concat items1\\n -- NB we may have duplicates, and several items\\n -- for the same parent; e.g N(x) and N(y)\\n\\n (gres, imp_user_list) = case want_hiding of\\n Exactly ->\\n let gres = concatMap (gresFromIE decl_spec) items2\\n gre_env = mkGlobalRdrEnv gres\\n implicit_parents = mkNameSet $ mapMaybe parentOfImplicitlyImportedGRE gres\\n in (gre_env, ImpUserExplicit (gresToAvailInfo $ globalRdrEnvElts $ gre_env) implicit_parents)\\n EverythingBut ->\\n let hidden_names = mkNameSet $ concatMap (map greName . snd) items2\\n in (importsFromIface hsc_env iface decl_spec (Just hidden_names), ImpUserEverythingBut hidden_names)\\n\\n return (Just (want_hiding, map fst items2), imp_user_list, gres)\\n where\\n import_mod = mi_module iface\\n all_avails = mi_exports iface\\n imp_occ_env = mkImportOccEnv hsc_env decl_spec all_avails\\n\\n -- Look up a parent (type constructor, class or data constructor)\\n -- in an import.\\n lookup_parent :: IE GhcPs -> RdrName -> IELookupM ImpOccItem\\n lookup_parent ie rdr =\\n assertPpr (not $ isVarNameSpace ns)\\n (vcat [ text \\"filterImports lookup_parent: unexpected variable\\"\\n , text \\"rdr:\\" <+> ppr rdr\\n , text \\"namespace:\\" <+> pprNameSpace ns ]) $\\n do { xs <- lookup_names ie rdr\\n ; case xs of\\n cax :| [] -> return cax\\n _ -> pprPanic \\"filter_imports lookup_parent ambiguous\\" $\\n vcat [ text \\"rdr:\\" <+> ppr rdr\\n , text \\"lookups:\\" <+> ppr (fmap imp_item xs) ] }\\n -- Looking up non-variables is always unambiguous,\\n -- as there can be at most one corresponding item\\n -- in the imp_occ_env.\\n -- See item (1) of Note [Exporting duplicate declarations]\\n -- in GHC.Tc.Gen.Export.\\n where\\n occ = rdrNameOcc rdr\\n ns = occNameSpace occ\\n\\n -- Look up a RdrName used in an import, returning multiple values if there\\n -- are several fields with the same name exposed by the module\\n lookup_names :: IE GhcPs -> RdrName -> IELookupM (NonEmpty ImpOccItem)\\n lookup_names ie rdr\\n | isQual rdr\\n = failLookupWith (QualImportError rdr)\\n | otherwise\\n = case lookups of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n item:items -> return $ item :| items\\n where\\n lookups = concatMap nonDetNameEnvElts\\n $ lookupImpOccEnv (RelevantGREsFOS WantNormal) imp_occ_env (rdrNameOcc rdr)\\n\\n lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, [GlobalRdrElt])]\\n lookup_lie (L loc ieRdr)\\n = setSrcSpanA loc $\\n do (stuff, warns) <- run_lookup ([],[]) (lookup_ie ieRdr)\\n mapM_ (addTcRnDiagnostic <=< warning_msg) warns\\n return [ (L loc ie, gres) | (ie,gres) <- stuff ]\\n where\\n\\n -- Warn when importing T(..) and no children are brought in scope\\n warning_msg (DodgyImport reason) =\\n pure (TcRnDodgyImports reason)\\n warning_msg MissingImportList =\\n pure (TcRnMissingImportList ieRdr)\\n warning_msg (BadImportW ie sub) = do\\n -- \'BadImportW\' is only constructed below in \'bad_import_w\', in\\n -- the \'EverythingBut\' case, so here we assume a \'hiding\' clause.\\n (reason :| _) <- badImportItemErr iface decl_spec ie sub all_avails\\n pure (TcRnDodgyImports (DodgyImportsHiding reason))\\n warning_msg (DeprecatedExport n w) =\\n pure $ TcRnPragmaWarning\\n PragmaWarningExport\\n { pwarn_occname = occName n\\n , pwarn_impmod = moduleName import_mod }\\n w\\n\\n run_lookup :: a -> IELookupM a -> TcRn a\\n run_lookup def m = case m of\\n Failed err -> do\\n msgs <- lookup_err_msgs err\\n forM_ msgs $ \\\\msg -> addErr (TcRnImportLookup msg)\\n return def\\n Succeeded a -> return a\\n\\n lookup_err_msgs err = case err of\\n BadImport ie sub -> badImportItemErr iface decl_spec ie sub all_avails\\n IllegalImport -> pure $ NE.singleton ImportLookupIllegal\\n QualImportError rdr -> pure $ NE.singleton (ImportLookupQualified rdr)\\n\\n -- For each import item, we convert its RdrNames to Names,\\n -- and at the same time compute all the GlobalRdrElt corresponding\\n -- to what is actually imported by this item.\\n -- Returns Nothing on error.\\n --\\n -- Returns a list because, with DuplicateRecordFields, a naked\\n -- import/export of a record field can correspond to multiple\\n -- different GlobalRdrElts. See Note [Importing DuplicateRecordFields].\\n lookup_ie :: IE GhcPs\\n -> IELookupM ([(IE GhcRn, [GlobalRdrElt])], [IELookupWarning])\\n lookup_ie ie = handle_bad_import $\\n case ie of\\n IEVar _ (L l n) _ -> do\\n -- See Note [Importing DuplicateRecordFields]\\n xs <- lookup_names ie (ieWrappedName n)\\n let gres = map imp_item $ NE.toList xs\\n export_depr_warns\\n | want_hiding == Exactly\\n = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ( [ (IEVar Nothing (L l (replaceWrappedName n name)) noDocstring, [gre])\\n | gre <- gres\\n , let name = greName gre ]\\n , export_depr_warns )\\n\\n IEThingAll x ns_spec (L l tc) _ -> do\\n ImpOccItem { imp_item = gre\\n , imp_bundled = bundled_gres\\n , imp_is_parent = is_par\\n }\\n <- lookup_parent ie $ ieWrappedName tc\\n let name = greName gre\\n\\n child_gres :: [GlobalRdrElt]\\n child_gres\\n | is_par = filterByNamespaceSpecifierGREs ns_spec bundled_gres\\n | otherwise = []\\n\\n imp_list_warn\\n\\n | null child_gres\\n -- e.g. f(..) or T(..) where T is a type synonym\\n = [DodgyImport (DodgyImportsEmptyParent ie ns_spec gre)]\\n\\n -- e.g. import M( T(..) )\\n | not (is_qual decl_spec)\\n = [MissingImportList]\\n\\n | otherwise\\n = []\\n\\n renamed_ie = IEThingAll (x { ieta_warning = Nothing })\\n (rnNamespaceSpecifier ns_spec)\\n (L l (replaceWrappedName tc name))\\n noDocstring\\n export_depr_warn\\n | want_hiding == Exactly\\n = maybeToList $ mk_depr_export_warning gre\\n -- We don\'t want to warn about the children as they\\n -- are not explicitly mentioned; the warning will\\n -- be emitted later on if they are used\\n | otherwise = []\\n\\n return ( [(renamed_ie, gre:child_gres)]\\n , imp_list_warn ++ export_depr_warn)\\n\\n\\n IEThingAbs _ (L l tc\') _\\n | want_hiding == EverythingBut -- hiding ( C )\\n -- Here the \'C\' can be a data constructor\\n -- *or* a type/class, or even both\\n -> let tc = ieWrappedName tc\'\\n tc_name = lookup_parent ie tc\\n dc_name = lookup_parent ie (setRdrNameSpace tc srcDataName)\\n in\\n case catIELookupM [ tc_name, dc_name ] of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n names -> return ( [mkIEThingAbs tc\' l (imp_item name) | name <- names], [])\\n | otherwise\\n -> do ImpOccItem { imp_item = gre } <- lookup_parent ie (ieWrappedName tc\')\\n return ( [mkIEThingAbs tc\' l gre]\\n , maybeToList $ mk_depr_export_warning gre)\\n\\n IEThingWith (deprecation, ann) ltc@(L l rdr_tc) wc rdr_ns _ -> do\\n ImpOccItem { imp_item = gre, imp_bundled = subnames }\\n <- lookup_parent (IEThingAbs Nothing ltc noDocstring) (ieWrappedName rdr_tc)\\n let name = greName gre\\n\\n -- Look up the children in the sub-names of the parent\\n -- See Note [Importing DuplicateRecordFields]\\n let (children_errs, childnames) = lookupChildren subnames rdr_ns\\n\\n bad_import_warns <-\\n if null children_errs then return [] else\\n let items = map lce_wrapped_name children_errs\\n ie = IEThingWith (deprecation, ann) ltc wc items noDocstring\\n -- We are trying to import T( a,b,c,d ), and failed\\n -- to find \'b\' and \'d\'. So we make up an import item\\n -- to report as failing, namely T( b, d ).\\n -- c.f. #15413\\n subordinate_err = mkSubordinateError gre children_errs\\n in bad_import_w ie subordinate_err\\n\\n let name\' = replaceWrappedName rdr_tc name\\n childnames\' = map (to_ie_post_rn . fmap greName) childnames\\n gres = gre : map unLoc childnames\\n export_depr_warns\\n | want_hiding == Exactly = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ([ (IEThingWith (Nothing, ann) (L l name\') wc childnames\' noDocstring\\n ,gres)]\\n , bad_import_warns ++ export_depr_warns)\\n\\n IEWholeNamespace x ns_spec -> do\\n let mod_name = moduleName import_mod\\n names = map greName gres\\n renamed_ie = IEWholeNamespace x { iewn_warning = Nothing\\n , iewn_names = names }\\n (rnNamespaceSpecifier ns_spec)\\n gres = filterByNamespaceSpecifierGREs ns_spec $\\n gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n dodgy_warn\\n | null gres = [DodgyImport (DodgyImportsWildcard mod_name ns_spec)]\\n | otherwise = []\\n return ([(renamed_ie, gres)],\\n dodgy_warn)\\n\\n _other -> failLookupWith IllegalImport\\n -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed...\\n -- all of those constitute errors.\\n\\n where\\n mkIEThingAbs tc l gre\\n = (IEThingAbs Nothing (L l (replaceWrappedName tc n)) noDocstring, [gre])\\n where n = greName gre\\n\\n -- N.B. imports never have docstrings\\n noDocstring = Nothing\\n\\n handle_bad_import m = catchIELookup m $ \\\\case\\n BadImport ie sub -> do\\n ws <- bad_import_w ie sub\\n return ([], ws)\\n err -> failLookupWith err\\n\\n bad_import_w :: IE GhcPs -> IsSubordinateError -> IELookupM [IELookupWarning]\\n bad_import_w ie sub\\n | want_hiding == EverythingBut = return [BadImportW ie sub]\\n | otherwise = failLookupWith (BadImport ie sub)\\n\\n mk_depr_export_warning gre\\n = DeprecatedExport name <$> mi_export_warn_fn iface name\\n where\\n name = greName gre\\n\\n-- | Assuming a subordinate item could not be found, do another lookup for a\\n-- more specific error message.\\nmkBadExportSubordinate :: [GlobalRdrElt] -> LIEWrappedName GhcPs -> BadExportSubordinate\\nmkBadExportSubordinate child_gres n =\\n case lookupChildren child_gres [n] of\\n (LookupChildNonType {lce_nontype_item = g} : _, _) -> BadExportSubordinateNonType g\\n (LookupChildNonData {lce_nondata_item = g} : _, _) -> BadExportSubordinateNonData g\\n _ -> BadExportSubordinateNotFound n\\n\\ntype IELookupM = MaybeErr IELookupError\\n\\ndata IELookupWarning\\n = BadImportW (IE GhcPs) IsSubordinateError\\n | MissingImportList\\n | DodgyImport DodgyImportsReason\\n | DeprecatedExport Name (WarningTxt GhcRn)\\n\\n-- | Is this import/export item a subordinate or not?\\ndata IsSubordinateError\\n = IsSubordinateError { subordinate_err_parent :: !GlobalRdrElt\\n , subordinate_err_unavailable :: [FastString]\\n , subordinate_err_nontype :: [GlobalRdrElt]\\n , subordinate_err_nondata :: [GlobalRdrElt] }\\n | IsNotSubordinate\\n\\nmkSubordinateError :: GlobalRdrElt -> [LookupChildError] -> IsSubordinateError\\nmkSubordinateError gre children_errs = foldr add init_acc children_errs\\n where\\n init_acc :: IsSubordinateError\\n init_acc = IsSubordinateError gre [] [] []\\n\\n add :: LookupChildError -> IsSubordinateError -> IsSubordinateError\\n add children_err sub@IsSubordinateError{} =\\n case children_err of\\n LookupChildNonType{lce_nontype_item = g} ->\\n sub { subordinate_err_nontype = g : subordinate_err_nontype sub }\\n LookupChildNonData{lce_nondata_item = g} ->\\n sub { subordinate_err_nondata = g : subordinate_err_nondata sub }\\n LookupChildNotFound (L _ wname) ->\\n let fs = (occNameFS . rdrNameOcc . ieWrappedName) wname\\n in sub { subordinate_err_unavailable = fs : subordinate_err_unavailable sub }\\n add _ IsNotSubordinate = panic \\"mkSubordinateError: IsNotSubordinate\\"\\n\\ndata IELookupError\\n = QualImportError RdrName\\n | BadImport (IE GhcPs) IsSubordinateError\\n | IllegalImport\\n\\nfailLookupWith :: IELookupError -> IELookupM a\\nfailLookupWith err = Failed err\\n\\ncatchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a\\ncatchIELookup m h = case m of\\n Succeeded r -> return r\\n Failed err -> h err\\n\\ncatIELookupM :: [IELookupM a] -> [a]\\ncatIELookupM ms = [ a | Succeeded a <- ms ]\\n\\n-- | Information associated to an \'AvailInfo\' used in constructing\\n-- an \'OccEnv\' corresponding to imports.\\n--\\n-- See Note [Dealing with imports].\\ndata ImpOccItem\\n = ImpOccItem\\n { imp_item :: GlobalRdrElt\\n -- ^ The import item\\n , imp_bundled :: [GlobalRdrElt]\\n -- ^ Items bundled in the Avail this import item came from,\\n -- not including the import item itself if it is a parent.\\n , imp_is_parent :: Bool\\n -- ^ Is the import item a parent? See Note [Dealing with imports].\\n }\\n\\ninstance Outputable ImpOccItem where\\n ppr (ImpOccItem { imp_item = item, imp_bundled = bundled, imp_is_parent = is_par })\\n = braces $ hsep\\n [ text \\"ImpOccItem\\"\\n , if is_par then text \\"[is_par]\\" else empty\\n , ppr (greName item) <+> ppr (greParent item)\\n , braces $ text \\"bundled:\\" <+> ppr (map greName bundled) ]\\n\\n-- | Make an \'OccEnv\' of all the imports.\\n--\\n-- Complicated by the fact that associated data types and pattern synonyms\\n-- can appear twice. See Note [Dealing with imports].\\nmkImportOccEnv :: HscEnv -> ImpDeclSpec -> [IfaceExport] -> OccEnv (NameEnv ImpOccItem)\\nmkImportOccEnv hsc_env decl_spec all_avails =\\n mkOccEnv_C (plusNameEnv_C combine)\\n [ (occ, mkNameEnv [(nm, item)])\\n | avail <- all_avails\\n , let gres = gresFromAvail hsc_env (Just hiding_spec) avail\\n , gre <- gres\\n , let nm = greName gre\\n occ = greOccName gre\\n (is_parent, bundled) = case avail of\\n AvailTC c _\\n | c == nm -- (Recall the AvailTC invariant from GHC.Types.AvailInfo)\\n -> ( True, drop 1 gres ) -- \\"drop 1\\": don\'t include the parent itself.\\n | otherwise\\n -> ( False, gres )\\n _ -> ( False, [] )\\n item = ImpOccItem\\n { imp_item = gre\\n , imp_bundled = bundled\\n , imp_is_parent = is_parent }\\n ]\\n where\\n\\n hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\n -- See Note [Dealing with imports]\\n -- \'combine\' may be called for associated data types which appear\\n -- twice in the all_avails. In the example, we have two Avails for T,\\n -- namely T(T,T1,T2,T3) and C(C,T), and we combine them by dropping the\\n -- latter, in which T is not the parent.\\n combine :: ImpOccItem -> ImpOccItem -> ImpOccItem\\n combine item1@(ImpOccItem { imp_item = gre1, imp_is_parent = is_parent1 })\\n item2@(ImpOccItem { imp_item = gre2, imp_is_parent = is_parent2 })\\n | is_parent1 || is_parent2\\n , not (isRecFldGRE gre1 || isRecFldGRE gre2) -- NB: does not force GREInfo.\\n , let name1 = greName gre1\\n name2 = greName gre2\\n gre = gre1 `plusGRE` gre2\\n -- See Note [Preserve parent information when combining import OccEnvs]\\n = assertPpr (name1 == name2)\\n (ppr name1 <+> ppr name2) $\\n if is_parent1\\n then item1 { imp_item = gre }\\n else item2 { imp_item = gre }\\n -- Discard C(C,T) in favour of T(T, T1, T2, T3).\\n\\n -- \'combine\' may also be called for pattern synonyms which appear both\\n -- unassociated and associated (see Note [Importing PatternSynonyms]).\\n combine item1@(ImpOccItem { imp_item = c1, imp_bundled = kids1 })\\n item2@(ImpOccItem { imp_item = c2, imp_bundled = kids2 })\\n = assertPpr (greName c1 == greName c2\\n && (not (null kids1 && null kids2)))\\n (ppr c1 <+> ppr c2 <+> ppr kids1 <+> ppr kids2) $\\n if null kids1\\n then item2\\n else item1\\n -- Discard standalone pattern P in favour of T(P).\\n\\n-- | Essentially like @lookupGRE env (LookupOccName occ which_gres)@,\\n-- but working with \'ImpOccItem\'s instead of \'GlobalRdrElt\'s.\\nlookupImpOccEnv :: WhichGREs GREInfo\\n -> OccEnv (NameEnv ImpOccItem) -> OccName -> [NameEnv ImpOccItem]\\nlookupImpOccEnv which_gres env occ =\\n mapMaybe relevant_items $ lookupOccEnv_AllNameSpaces env occ\\n where\\n is_relevant :: ImpOccItem -> Bool\\n is_relevant (ImpOccItem { imp_item = gre }) =\\n greIsRelevant which_gres (occNameSpace occ) gre\\n relevant_items :: NameEnv ImpOccItem -> Maybe (NameEnv ImpOccItem)\\n relevant_items nms\\n | let nms\' = filterNameEnv is_relevant nms\\n = if isEmptyNameEnv nms\'\\n then Nothing\\n else Just nms\'\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{Import/Export Utils}\\n* *\\n************************************************************************\\n-}\\n\\n-- | Given an import\\\\/export spec, appropriately set the @gre_imp@ field\\n-- for the \'GlobalRdrElt\'s.\\ngresFromIE :: ImpDeclSpec -> (LIE GhcRn, [GlobalRdrElt]) -> [GlobalRdrElt]\\ngresFromIE decl_spec (L loc ie, gres)\\n = map set_gre_imp gres\\n where\\n is_explicit = case ie of\\n IEThingAll _ _ name _ -> \\\\n -> n == lieWrappedName name\\n IEWholeNamespace _ _ -> \\\\_ -> False\\n _ -> \\\\_ -> True\\n prov_fn name\\n = ImpSpec { is_decl = decl_spec, is_item = item_spec }\\n where\\n item_spec = ImpSome { is_explicit = is_explicit name\\n , is_iloc = locA loc }\\n set_gre_imp gre@( GRE { gre_name = nm } )\\n = gre { gre_imp = unitBag $ prov_fn nm }\\n\\nparentOfImplicitlyImportedGRE :: Outputable info => GlobalRdrEltX info -> Maybe Name\\nparentOfImplicitlyImportedGRE gre =\\n if any (explicit_import . is_item) $ gre_imp gre\\n then Nothing\\n else greParent_maybe gre\\n where\\n explicit_import :: ImpItemSpec -> Bool\\n explicit_import (ImpAll {}) =\\n pprPanic \\"parentOfImplicitlyImportedGRE: ImpAll\\" (ppr gre)\\n explicit_import (ImpSome { is_explicit }) = is_explicit\\n\\n{- Note [Children for duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider the module\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (F(foo, MkFInt, MkFBool)) where\\n data family F a\\n data instance F Int = MkFInt { foo :: Int }\\n data instance F Bool = MkFBool { foo :: Bool }\\n\\nThe `foo` in the export list refers to *both* selectors! For this\\nreason, lookupChildren builds an environment that maps the FastString\\nto a list of items, rather than a single item.\\n-}\\n\\nmkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]\\nmkChildEnv gres = foldr add emptyNameEnv gres\\n where\\n add gre env = case greParent gre of\\n ParentIs p -> extendNameEnv_Acc (:) Utils.singleton env p gre\\n NoParent -> env\\n\\nfindChildren :: NameEnv [a] -> Name -> [a]\\nfindChildren env n = lookupNameEnv env n `orElse` []\\n\\ndata LookupChildError\\n = LookupChildNotFound { lce_wrapped_name :: !(LIEWrappedName GhcPs) }\\n | LookupChildNonType { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nontype_item :: !GlobalRdrElt }\\n | LookupChildNonData { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nondata_item :: !GlobalRdrElt }\\n\\nlookupChildren :: [GlobalRdrElt]\\n -> [LIEWrappedName GhcPs]\\n -> ( [LookupChildError] -- The ones for which the lookup failed\\n , [LocatedA GlobalRdrElt] )\\n-- (lookupChildren all_kids rdr_items) maps each rdr_item to its\\n-- corresponding Name in all_kids, if the former exists\\n-- The matching is done by FastString, not OccName, so that\\n-- Cls( meth, AssocTy )\\n-- will correctly find AssocTy among the all_kids of Cls, even though\\n-- the RdrName for AssocTy may have a (bogus) DataName namespace\\n-- (Really the rdr_items should be FastStrings in the first place.)\\nlookupChildren all_kids rdr_items = (fails, successes)\\n where\\n mb_xs = map do_one rdr_items\\n fails = [ err | Failed err <- mb_xs ]\\n successes = [ ok | Succeeded oks <- mb_xs, ok <- NE.toList oks ]\\n\\n do_one :: LIEWrappedName GhcPs -> MaybeErr LookupChildError (NonEmpty (LocatedA GlobalRdrElt))\\n do_one item@(L l r) =\\n case r of\\n IEName{}\\n -- IEName (unadorned name) places no restriction on the namespace of\\n -- the imported entity, so we look in both `val_gres` and `typ_gres`.\\n -- In case of conflict (punning), the value namespace takes priority.\\n -- See Note [Prioritise the value namespace in subordinate import lists]\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEType{}\\n -- IEType (\'type\' namespace specifier) restricts the lookup to the\\n -- type namespace, i.e. to `typ_gres`. In case of failure, we check\\n -- `val_gres` to produce a more helpful error message.\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- val_gres -> Failed $ LookupChildNonType item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEData{}\\n -- IEData (\'data\' namespace specifier) restricts the lookup to the\\n -- data namespace, i.e. to `val_gres`. In case of failure, we check\\n -- `typ_gres` to produce a more helpful error message.\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- typ_gres -> Failed $ LookupChildNonData item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEPattern{} -> panic \\"lookupChildren: IEPattern\\" -- Never happens (invalid syntax)\\n IEDefault{} -> panic \\"lookupChildren: IEDefault\\" -- Never happens (invalid syntax)\\n where\\n fs = (occNameFS . rdrNameOcc . ieWrappedName) r\\n gres = fromMaybe [] (lookupFsEnv kid_env fs)\\n (val_gres, typ_gres) = partition (isValNameSpace . greNameSpace) gres\\n\\n -- See Note [Children for duplicate record fields]\\n kid_env :: FastStringEnv [GlobalRdrElt]\\n kid_env = extendFsEnvList_C (++) emptyFsEnv\\n [(occNameFS (occName x), [x]) | x <- all_kids]\\n\\n\\n{- Note [Prioritise the value namespace in subordinate import lists]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider this program that defines a class that has both an associated type\\nnamed (#) and a method named (#)\\n\\n module M_assoc where\\n class C a b where\\n type a # b\\n (#) :: a -> b -> ()\\n module N_assoc where\\n import M_assoc( C((#)) )\\n\\nIn the import declaration, when we see the unadorned name (#) in the subordinate\\nimport list of C, which children should we bring into scope? Our options are:\\n\\n a) only the method (#)\\n b) only the associated type (#)\\n c) both the method and the associated type\\n\\nTo follow the precedent established by top-level items, we go with option (a).\\nIndeed, consider a slightly different program\\n\\n module M_top where\\n type family a # b\\n a # b = ()\\n module N_top where\\n import M_top( (#) )\\n\\nHere the import brings only the function (#) into scope, and one has to say\\n`type (#)` to get the type family.\\n-}\\n\\n-------------------------------\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused names}\\n* *\\n*********************************************************\\n-}\\n\\nreportUnusedNames :: TcGblEnv -> HscSource -> RnM ()\\nreportUnusedNames gbl_env hsc_src\\n = do { keep <- readTcRef (tcg_keep gbl_env)\\n ; traceRn \\"RUN\\" (ppr (tcg_dus gbl_env))\\n ; warnUnusedImportDecls gbl_env hsc_src\\n ; warnUnusedTopBinds $ unused_locals keep\\n ; warnMissingSignatures gbl_env\\n ; warnMissingKindSignatures gbl_env }\\n where\\n used_names :: NameSet -> NameSet\\n used_names keep = findUses (tcg_dus gbl_env) emptyNameSet `unionNameSet` keep\\n -- NB: currently, if f x = g, we only treat \'g\' as used if \'f\' is used\\n -- Hence findUses\\n\\n -- Collect the defined names from the in-scope environment\\n defined_names :: [GlobalRdrElt]\\n defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)\\n\\n kids_env = mkChildEnv defined_names\\n -- This is done in mkExports too; duplicated work\\n\\n gre_is_used :: NameSet -> GlobalRdrElt -> Bool\\n gre_is_used used_names gre0\\n = name `elemNameSet` used_names\\n || any (\\\\ gre -> greName gre `elemNameSet` used_names) (findChildren kids_env name)\\n -- A use of C implies a use of T,\\n -- if C was brought into scope by T(..) or T(C)\\n where\\n name = greName gre0\\n\\n -- Filter out the ones that are\\n -- (a) defined in this module, and\\n -- (b) not defined by a \'deriving\' clause\\n -- The latter have an Internal Name, so we can filter them out easily\\n unused_locals :: NameSet -> [GlobalRdrElt]\\n unused_locals keep =\\n let -- Note that defined_and_used, defined_but_not_used\\n -- are both [GRE]; that\'s why we need defined_and_used\\n -- rather than just used_names\\n _defined_and_used, defined_but_not_used :: [GlobalRdrElt]\\n (_defined_and_used, defined_but_not_used)\\n = partition (gre_is_used (used_names keep)) defined_names\\n\\n in filter is_unused_local defined_but_not_used\\n is_unused_local :: GlobalRdrElt -> Bool\\n is_unused_local gre = isLocalGRE gre\\n && isExternalName (greName gre)\\n\\n{- *********************************************************************\\n* *\\n Missing signatures\\n* *\\n********************************************************************* -}\\n\\n{-\\nNote [Missing signatures]\\n~~~~~~~~~~~~~~~~~~~~~~~~~\\nThere are four warning flags in play:\\n\\n * -Wmissing-exported-signatures\\n Warn about any exported top-level function/value without a type signature.\\n Does not include pattern synonyms.\\n\\n * -Wmissing-signatures\\n Warn about any top-level function/value without a type signature. Does not\\n include pattern synonyms. Takes priority over -Wmissing-exported-signatures.\\n\\n * -Wmissing-exported-pattern-synonym-signatures\\n Warn about any exported pattern synonym without a type signature.\\n\\n * -Wmissing-pattern-synonym-signatures\\n Warn about any pattern synonym without a type signature. Takes priority over\\n -Wmissing-exported-pattern-synonym-signatures.\\n\\n-}\\n\\n-- | Warn the user about top level binders that lack type signatures.\\n-- Called /after/ type inference, so that we can report the\\n-- inferred type of the function\\nwarnMissingSignatures :: TcGblEnv -> RnM ()\\nwarnMissingSignatures gbl_env\\n = do { let exports = availsToNameSet (tcg_exports gbl_env)\\n sig_ns = tcg_sigs gbl_env\\n -- We use sig_ns to exclude top-level bindings that are generated by GHC\\n binds = collectHsBindsBinders CollNoDictBinders $ tcg_binds gbl_env\\n pat_syns = tcg_patsyns gbl_env\\n\\n not_ghc_generated :: Name -> Bool\\n not_ghc_generated name = name `elemNameSet` sig_ns\\n\\n add_binding_warn :: Id -> RnM ()\\n add_binding_warn id =\\n when (not_ghc_generated name) $\\n do { env <- liftZonkM $ tcInitTidyEnv -- Why not use emptyTidyEnv?\\n ; let ty = tidyOpenType env (idType id)\\n missing = MissingTopLevelBindingSig name ty\\n diag = TcRnMissingSignature missing exported\\n ; addDiagnosticAt (getSrcSpan name) diag }\\n where\\n name = idName id\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n add_patsyn_warn :: PatSyn -> RnM ()\\n add_patsyn_warn ps =\\n when (not_ghc_generated name) $\\n addDiagnosticAt (getSrcSpan name)\\n (TcRnMissingSignature missing exported)\\n where\\n name = patSynName ps\\n missing = MissingPatSynSig ps\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n -- Warn about missing signatures\\n -- Do this only when we have a type to offer\\n -- See Note [Missing signatures]\\n ; mapM_ add_binding_warn binds\\n ; mapM_ add_patsyn_warn pat_syns\\n }\\n\\n-- | Warn the user about tycons that lack kind signatures.\\n-- Called /after/ type (and kind) inference, so that we can report the\\n-- inferred kinds.\\nwarnMissingKindSignatures :: TcGblEnv -> RnM ()\\nwarnMissingKindSignatures gbl_env\\n = do { cusks_enabled <- xoptM LangExt.CUSKs\\n ; mapM_ (add_ty_warn cusks_enabled) tcs\\n }\\n where\\n tcs = tcg_tcs gbl_env\\n ksig_ns = tcg_ksigs gbl_env\\n exports = availsToNameSet (tcg_exports gbl_env)\\n\\n has_kind_signature :: Name -> Bool\\n has_kind_signature name = name `elemNameSet` ksig_ns\\n\\n add_ty_warn :: Bool -> TyCon -> RnM ()\\n add_ty_warn cusks_enabled tyCon =\\n when (has_kind_signature name) $\\n addDiagnosticAt (getSrcSpan name) diag\\n where\\n name = tyConName tyCon\\n diag = TcRnMissingSignature missing exported\\n missing = MissingTyConKindSig tyCon cusks_enabled\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused imports}\\n* *\\n*********************************************************\\n\\nThis code finds which import declarations are unused. The\\nspecification and implementation notes are here:\\n https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/unused-imports\\n\\nSee also Note [Choosing the best import declaration] in GHC.Types.Name.Reader\\n-}\\n\\ntype ImportDeclUsage\\n = ( LImportDecl GhcRn -- The import declaration\\n , [GlobalRdrElt] -- What *is* used (normalised)\\n , [Name] -- What is imported but *not* used\\n , [NamespaceSpecifier GhcRn] ) -- Unused wildcards\\n\\nwarnUnusedImportDecls :: TcGblEnv -> HscSource -> RnM ()\\nwarnUnusedImportDecls gbl_env hsc_src\\n = do { uses <- readMutVar (tcg_used_gres gbl_env)\\n ; let imports = tcg_rn_imports gbl_env\\n rdr_env = tcg_rdr_env gbl_env\\n\\n -- We should only warn for unnecessary *user* imports, but deciding\\n -- minimal imports should take generated imports into account\\n ; let usageUserImports = findImportUsage (excludeGenerated imports) uses\\n usageAllImports = findImportUsage imports uses\\n\\n ; traceRn \\"warnUnusedImportDecls\\" $\\n (vcat [ text \\"Uses:\\" <+> ppr uses\\n , text \\"Usage all user imports: \\" <+> ppr usageUserImports\\n , text \\"Usage all imports: \\" <+> ppr usageAllImports])\\n\\n ; mapM_ (warnUnusedImport rdr_env) usageUserImports\\n\\n ; whenGOptM Opt_D_dump_minimal_imports $\\n printMinimalImports hsc_src usageAllImports }\\n\\n-- | Exclude generated imports\\nexcludeGenerated :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\nexcludeGenerated = filterOut (isGeneratedImport . ideclOrigin . ideclExt . unLoc)\\n\\nfindImportUsage :: [LImportDecl GhcRn]\\n -> [GlobalRdrElt]\\n -> [ImportDeclUsage]\\n\\nfindImportUsage imports used_gres\\n = map unused_decl imports\\n where\\n import_usage :: ImportMap\\n import_usage = mkImportMap used_gres\\n\\n unused_decl :: LImportDecl GhcRn -> ImportDeclUsage\\n unused_decl decl@(L _ (ImportDecl { ideclImportList = imps }))\\n = -- pprTrace \\"unused_decl\\" (vcat [ ppr decl\\n -- , text \\"used\\" <+> ppr used_gres\\n -- , text \\"unused\\" <+> ppr unused_names ]) $\\n (decl, used_gres, unused_names, unused_wcs)\\n where\\n used_gres = lookupImportMap decl import_usage\\n\\n used_gre_env = mkGlobalRdrEnv used_gres\\n used_parents = mkNameSet (mapMaybe greParent_maybe used_gres)\\n\\n (unused_names, unused_wcs) -- Not trivial; see eg #7454\\n = case imps of\\n Just (Exactly, imp_ies) ->\\n let unused = foldr (add_unused . unLoc) emptyUnusedNames imp_ies\\n nms = nameSetElemsStable (collectUnusedNames unused)\\n wcs = collectUnusedWildcards unused\\n in (nms, wcs)\\n _other -> ([], []) -- No explicit import list => no unused-name list\\n\\n add_unused :: IE GhcRn -> UnusedNames -> UnusedNames\\n add_unused (IEVar _ n _) acc = add_unused_name (lieWrappedName n) True acc\\n add_unused (IEThingAbs _ n _) acc = add_unused_name (lieWrappedName n) False acc\\n add_unused (IEThingAll _ _ n _) acc = add_unused_all (lieWrappedName n) acc\\n add_unused (IEThingWith _ p wc ns _) acc = add_wc_all (add_unused_with pn xs acc)\\n where pn = lieWrappedName p\\n xs = map lieWrappedName ns\\n add_wc_all = case wc of\\n NoIEWildcard -> id\\n IEWildcard _ -> add_unused_all pn\\n add_unused (IEWholeNamespace x ns_spec) acc = add_unused_wildcard ns_spec (iewn_names x) acc\\n add_unused _ acc = acc\\n\\n add_unused_name :: Name -> Bool -> UnusedNames -> UnusedNames\\n add_unused_name n is_ie_var acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | is_ie_var\\n , isFieldName n\\n -- See Note [Reporting unused imported duplicate record fields]\\n = let\\n fs = getOccFS n\\n (flds, flds_used) = lookupFsEnv acc_fs fs `orElse` (emptyNameSet, Any False)\\n acc_fs\' = extendFsEnv acc_fs fs (extendNameSet flds n, Any used S.<> flds_used)\\n in UnusedNames acc_ns acc_wcs acc_fs\'\\n\\n | used\\n = acc\\n\\n | otherwise\\n = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n where\\n used = isJust $ lookupGRE_Name used_gre_env n\\n\\n add_unused_all :: Name -> UnusedNames -> UnusedNames\\n add_unused_all n acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | Just {} <- lookupGRE_Name used_gre_env n = acc\\n | n `elemNameSet` used_parents = acc\\n | otherwise = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n\\n add_unused_with :: Name -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_with p ns acc\\n | all (`elemNameSet` acc1_ns) ns = add_unused_name p False acc1\\n | otherwise = acc1\\n where\\n acc1@(UnusedNames acc1_ns _ _) = foldr (\\\\n acc\' -> add_unused_name n False acc\') acc ns\\n -- If you use \'signum\' from Num, then the user may well have\\n -- imported Num(signum). We don\'t want to complain that\\n -- Num is not itself mentioned. Hence the two cases in add_unused_with.\\n\\n add_unused_wildcard :: NamespaceSpecifier GhcRn -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_wildcard ns_spec names acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | any_used = acc\\n | otherwise = UnusedNames acc_ns (ns_spec : acc_wcs) acc_fs\\n where\\n -- A wildcard `type ..` or `data ..` is used if at least one of\\n -- the names it expands to is used\\n any_used = any (isJust . lookupGRE_Name used_gre_env) names\\n\\n\\n-- | An accumulator for unused names in an import list.\\n--\\n-- See Note [Reporting unused imported duplicate record fields].\\ndata UnusedNames =\\n UnusedNames\\n { unused_names :: NameSet\\n -- ^ Unused \'Name\'s in an import list, not including record fields\\n -- that are plain \'IEVar\' imports (tracked by \'rec_fld_uses\')\\n -- or wildcard imports (tracked by \'unused_wildcards\').\\n , unused_wildcards :: [NamespaceSpecifier GhcRn]\\n -- ^ Unused wildcards @type ..@ or @data ..@ in an import list.\\n , rec_fld_uses :: FastStringEnv (NameSet, Any)\\n -- ^ Record fields imported without a parent (i.e. an \'IEVar\' import).\\n --\\n -- The \'Any\' value records whether any of the record fields\\n -- sharing the same underlying \'FastString\' have been used.\\n }\\n\\nemptyUnusedNames :: UnusedNames\\nemptyUnusedNames = UnusedNames emptyNameSet [] emptyFsEnv\\n\\ninstance Outputable UnusedNames where\\n ppr (UnusedNames nms wcs flds) =\\n text \\"UnusedNames\\" <+>\\n braces (ppr nms <+> ppr wcs <+> ppr (fmap (second getAny) flds))\\n\\n-- | Collect all unused names from a \'UnusedNames\' value.\\ncollectUnusedNames :: UnusedNames -> NameSet\\ncollectUnusedNames (UnusedNames { unused_names = nms, rec_fld_uses = flds })\\n = nms S.<> unused_flds\\n where\\n unused_flds = nonDetFoldFsEnv collect_unused emptyNameSet flds\\n collect_unused :: (NameSet, Any) -> NameSet -> NameSet\\n collect_unused (nms, Any at_least_one_name_is_used) acc\\n | at_least_one_name_is_used = acc\\n | otherwise = unionNameSet nms acc\\n\\ncollectUnusedWildcards :: UnusedNames -> [NamespaceSpecifier GhcRn]\\ncollectUnusedWildcards = unused_wildcards\\n\\n{- Note [Reporting unused imported duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have (#24035):\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M1 (R1(..), R2(..)) where\\n data R1 = MkR1 { fld :: Int }\\n data R2 = MkR2 { fld :: Int }\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M2 where\\n import M1 (R1(MkR1), R2, fld)\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nIn the import of \'M1\' in \'M2\', the \'fld\' import resolves to two separate GREs,\\nnamely R1(fld) and R2(fld). From the perspective of the renamer, and in particular\\nthe \'findImportUsage\' function, it\'s as if the user had imported the two names\\nseparately (even though no source syntax allows that).\\n\\nThis means that we need to be careful when reporting unused imports: the R2(fld)\\nimport is indeed unused, but because R1(fld) is used, we should not report\\nfld as unused altogether.\\n\\nTo achieve this, we keep track of record field imports without a parent (i.e.\\nusing the IEVar constructor) separately from other import items, using the\\nUnusedNames datatype.\\nOnce we have accumulated usages, we emit warnings for unused record fields\\nwithout parents one whole group (of record fields sharing the same textual name)\\nat a time, and only if *all* of the record fields in the group are unused;\\nsee \'collectUnusedNames\'.\\n\\nNote that this only applies to record fields imported without a parent. If we\\nhad:\\n\\n import M1 (R1(MkR1, fld), R2(fld))\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nthen of course we should report the second \'fld\' as unused.\\n-}\\n\\n\\n{- Note [The ImportMap]\\n~~~~~~~~~~~~~~~~~~~~~~~\\nThe ImportMap is a short-lived intermediate data structure records, for\\neach import declaration, what stuff brought into scope by that\\ndeclaration is actually used in the module.\\n\\nThe [GlobalRdrElt] are the things imported from that decl.\\n-}\\n\\ndata ImportMap = ImportMap\\n { im_imports :: Map RealSrcSpan [GlobalRdrElt]\\n -- ^ See [The ImportMap]\\n -- If loc :-> gres, then\\n -- \'loc\' = the end loc of the bestImport of each GRE in \'gres\'\\n , im_generatedImports :: Map ModuleName [GlobalRdrElt]\\n }\\n\\nmkImportMap :: [GlobalRdrElt] -> ImportMap\\n-- For each of a list of used GREs, find all the import decls that brought\\n-- it into scope; choose one of them (bestImport), and record\\n-- the RdrName in that import decl\'s entry in the ImportMap\\nmkImportMap = foldr insertImportMap $ ImportMap Map.empty Map.empty\\n\\ninsertImportMap :: GlobalRdrElt -> ImportMap -> ImportMap\\ninsertImportMap gre@(GRE { gre_imp = imp_specs }) importMap\\n | RealSrcSpan importSpan _ <- is_dloc best_imp_spec =\\n importMap{im_imports = insertElem importSpan gre $ im_imports importMap}\\n | GeneratedSrcSpan{} <- is_dloc best_imp_spec =\\n importMap{im_generatedImports = insertElem (moduleName $ is_mod best_imp_spec) gre $ im_generatedImports importMap}\\n | otherwise = importMap\\n where\\n best_imp_spec =\\n case bagToList imp_specs of\\n [] -> pprPanic \\"mkImportMap: GRE with no ImportSpecs\\" (ppr gre)\\n is:iss -> is_decl $ bestImport (is NE.:| iss)\\n\\n -- https://github.com/haskell/containers/issues/784\\n insertElem :: Ord k => k -> v -> Map k [v] -> Map k [v]\\n insertElem k v = flip Map.alter k $ \\\\case\\n Just vs -> Just (v : vs)\\n Nothing -> Just [v]\\n\\nlookupImportMap :: LImportDecl GhcRn -> ImportMap -> [GlobalRdrElt]\\nlookupImportMap (L srcSpan ImportDecl{ideclName = L _ modName}) importMap =\\n fromMaybe [] $\\n -- should match logic in insertImportMap\\n case locA srcSpan of\\n RealSrcSpan realSrcSpan _ -> realSrcSpan `Map.lookup` im_imports importMap\\n GeneratedSrcSpan{} -> modName `Map.lookup` im_generatedImports importMap\\n _ -> Nothing\\n\\nlieNames :: LIE (GhcPass p) -> [Located (IdP (GhcPass p))]\\nlieNames = _\\n\\nwarnUnusedImport :: GlobalRdrEnv -> ImportDeclUsage -> RnM ()\\nwarnUnusedImport rdr_env (L loc decl, used, unused, unused_wcs)\\n\\n -- Do not warn for \'import M()\'\\n -- See (UI1) in Note [Unused imports]\\n | Just (Exactly, _) <- ideclImportList decl\\n , null unused && null unused_wcs\\n = return ()\\n\\n -- Note [Do not warn about Prelude hiding]\\n | Just (EverythingBut, hides) <- ideclImportList decl\\n , not (null hides)\\n , pRELUDE_NAME == unLoc (ideclName decl)\\n = return ()\\n\\n -- Do not warn about import X as Rebindable\\n -- See (UI2) in Note [Unused imports]\\n | Just (L _ mod) <- ideclAs decl\\n , mod == rEBINDABLE_MOD_NAME\\n = return ()\\n\\n -- Nothing used; drop entire declaration\\n | null used\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl UnusedImportNone)\\n\\n -- Everything imported is used; nop\\n | null unused && null unused_wcs\\n = return ()\\n\\n -- Some imports are unused: make the `SrcSpan` cover only the unused\\n -- items instead of the whole import statement\\n | Just (_, imports) <- ideclImportList decl\\n , let unused_locs = [ locA loc | L loc ie <- imports\\n , name <- ieNames ie\\n , name `elem` unused ]\\n , loc1 : locs <- unused_locs\\n , let span = foldr1 combineSrcSpans ( loc1 NE.:| locs )\\n = addDiagnosticAt span (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n -- Some imports are unused\\n | otherwise\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n where\\n -- In warning message, pretty-print identifiers unqualified unconditionally\\n -- to improve the consistent for ambiguous/unambiguous identifiers.\\n -- See #14881.\\n possible_field n =\\n case lookupGRE_Name rdr_env n of\\n Just (GRE { gre_par = par, gre_info = IAmRecField info }) ->\\n let fld_occ :: OccName\\n fld_occ = nameOccName $ flSelector $ recFieldLabel info\\n in UnusedImportNameRecField par fld_occ\\n _ -> UnusedImportNameRegular n\\n\\n -- Print unused names in a deterministic (lexicographic) order\\n sort_unused :: [UnusedImportName]\\n sort_unused =\\n [ UnusedImportWildcard wc | wc <- unused_wcs ] ++\\n [ possible_field nm | nm <- sortBy (comparing nameOccName) unused ]\\n\\ngetMinimalImports :: [ImportDeclUsage] -> RnM [LImportDecl GhcRn]\\ngetMinimalImports ie_decls\\n = do { rdr_env <- getGlobalRdrEnv\\n ; fmap combine $ mapM (mk_minimal rdr_env) ie_decls }\\n where\\n mk_minimal rdr_env (L l decl, used_gres, unused, unused_wcs)\\n | null unused && null unused_wcs\\n , Just (Exactly, _) <- ideclImportList decl\\n = return (L l decl)\\n | otherwise\\n = do { let ImportDecl { ideclName = L _ mod_name\\n , ideclSource = is_boot\\n , ideclPkgQual = pkg_qual\\n , ideclExt = XImportDeclPass { ideclOrigin = origin } } = decl\\n ; iface <- loadSrcInterface doc (importDeclLookupScope origin)\\n mod_name is_boot pkg_qual\\n ; let used_avails = gresToAvailInfo used_gres\\n ; lies <- map (L l) <$> concatMapM (to_ie rdr_env iface) used_avails\\n ; return (L l (decl { ideclImportList = Just (Exactly, lies) })) }\\n where\\n doc = text \\"Compute minimal imports for\\" <+> ppr decl\\n\\n to_ie :: GlobalRdrEnv -> ModIface -> AvailInfo -> RnM [IE GhcRn]\\n -- The main trick here is that if we\'re importing all the constructors\\n -- we want to say \\"T(..)\\", but if we\'re importing only a subset we want\\n -- to say \\"T(A,B,C)\\". So we have to find out what the module exports.\\n to_ie rdr_env _ (Avail c) -- Note [Overloaded field import]\\n = do { let\\n gre = expectJust $ lookupGRE_Name rdr_env c\\n ; return $ [IEVar Nothing (to_ie_post_rn $ noLocA $ greName gre) Nothing] }\\n to_ie _ _ avail@(AvailTC n [_]) -- Exporting the main decl and nothing else\\n | availExportsDecl avail\\n = return [IEThingAbs Nothing (to_ie_post_rn $ noLocA n) Nothing]\\n to_ie rdr_env iface (AvailTC n cs) =\\n case [ xs | avail@(AvailTC x xs) <- mi_exports iface\\n , x == n\\n , availExportsDecl avail -- Note [Partial export]\\n ] of\\n [xs]\\n | all_used xs\\n -> return [IEThingAll (IEThingAllExt Nothing noAnn noAnn noAnn)\\n (NoNamespaceSpecifier noExtField)\\n (to_ie_post_rn $ noLocA n)\\n Nothing]\\n | otherwise\\n -> do { let ns_gres = map (expectJust . lookupGRE_Name rdr_env) cs\\n ns = map greName ns_gres\\n ; return [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n -- Note [Overloaded field import]\\n _other\\n -> do { let infos = map (expectJust . lookupGRE_Name rdr_env) cs\\n (ns_gres,fs_gres) = classifyGREs infos\\n ns = map greName (ns_gres ++ fs_gres)\\n fs = map fieldGREInfo fs_gres\\n ; return $\\n if all_non_overloaded fs\\n then map (\\\\nm -> IEVar Nothing (to_ie_post_rn_var $ noLocA nm) Nothing) ns\\n else [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n where\\n\\n all_used avail_cs = all (`elem` cs) avail_cs\\n\\n all_non_overloaded = all (not . flIsOverloaded . recFieldLabel)\\n\\n combine :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\n combine = map merge . NE.groupAllWith getKey\\n\\n getKey :: LImportDecl GhcRn -> (Bool, Maybe ModuleName, ModuleName)\\n getKey decl =\\n ( isImportDeclQualified . ideclQualified $ idecl -- is this qualified? (important that this be first)\\n , unLoc <$> ideclAs idecl -- what is the qualifier (inside Maybe monad)\\n , unLoc . ideclName $ idecl -- Module Name\\n )\\n where\\n idecl :: ImportDecl GhcRn\\n idecl = unLoc decl\\n\\n merge :: NonEmpty (LImportDecl GhcRn) -> LImportDecl GhcRn\\n merge decls@((L l decl) :| _) = L l (decl { ideclImportList = Just (Exactly, lies) })\\n where lies = concatMap snd $ mapMaybe (ideclImportList . unLoc) $ NE.toList decls\\n\\nclassifyGREs :: [GlobalRdrElt] -> ([GlobalRdrElt], [FieldGlobalRdrElt])\\nclassifyGREs = partition (not . isRecFldGRE)\\n\\nprintMinimalImports :: HscSource -> [ImportDeclUsage] -> RnM ()\\n-- See Note [Printing minimal imports]\\nprintMinimalImports hsc_src imports_w_usage\\n = do { imports\' <- excludeGenerated <$> getMinimalImports imports_w_usage\\n ; this_mod <- getModule\\n ; dflags <- getDynFlags\\n ; liftIO $ withFile (mkFilename dflags this_mod) WriteMode $ \\\\h ->\\n printForUser dflags h neverQualify AllTheWay (vcat (map ppr imports\'))\\n -- The neverQualify is important. We are printing Names\\n -- but they are in the context of an \'import\' decl, and\\n -- we never qualify things inside there\\n -- E.g. import Blag( f, b )\\n -- not import Blag( Blag.f, Blag.g )!\\n }\\n where\\n mkFilename dflags this_mod\\n | Just d <- dumpDir dflags = d basefn\\n | otherwise = basefn\\n where\\n suffix = case hsc_src of\\n HsBootFile -> \\".imports-boot\\"\\n HsSrcFile -> \\".imports\\"\\n HsigFile -> \\".imports\\"\\n basefn = moduleNameString (moduleName this_mod) ++ suffix\\n\\n\\nto_ie_post_rn_var :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn_var (L l n)\\n | isDataOcc $ occName n = L l (IEPattern noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n\\n\\nto_ie_post_rn :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn (L l n)\\n | isTcOcc occ && isSymOcc occ = L l (IEType noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n where occ = occName n\\n\\n{- Note [Do not warn about Prelude hiding]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWe do not warn about\\n import Prelude hiding( x, y )\\nbecause even if nothing else from Prelude is used, it may be essential to hide\\nx,y to avoid name-shadowing warnings. Example (#9061)\\n import Prelude hiding( log )\\n f x = log where log = ()\\n\\nNote [Unused imports]\\n~~~~~~~~~~~~~~~~~~~~~\\nIn `warnUnusedImport`, if we see an import with an explicit list imports, thus\\n import M( a, b )\\nand neither `a` nor `b` is used, we report the entire import decl as unused. We\\ncheck this by looking at the names that it brings into scope scope; if there are\\nno ununused names, don\'t report.\\n\\n(UI1) We don\'t want to complain about `import M()`, because that is often used to bring\\n M\'s /instances/ into scope. That is neatly dealt with by the \\"no unused\\n names\\" (nor unused wildcard imports) criterion.\\n\\n(UI2) We don\'t report a decl as unused if it has an `as Rebindable` qualifier.\\n See (KN1) in Note [Overview of known entities] in GHC.Builtin\\n\\n\\nNote [Printing minimal imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nTo print the minimal imports we walk over all import decls (both user-supplied\\nand generated), trim their import lists, then filter out generated decls.\\n\\nNB that\\n\\n * We do *not* change the \'qualified\' or \'as\' parts!\\n\\n * We do not discard a decl altogether; we might need instances\\n from it. Instead we just trim to an empty import list\\n\\nNote [Partial export]\\n~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have\\n\\n module A( op ) where\\n class C a where\\n op :: a -> a\\n\\n module B where\\n import A\\n f = ..op...\\n\\nThen the minimal import for module B is\\n import A( op )\\nnot\\n import A( C( op ) )\\nwhich we would usually generate if C was exported from B. Hence\\nthe availExportsDecl test when deciding what to generate.\\n\\n\\nNote [Overloaded field import]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nOn the other hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n data T = MkT { foo :: Int }\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( T(foo) )\\nbecause when DuplicateRecordFields is enabled, field selectors are\\nnot in scope without their enclosing datatype.\\n\\nOn the third hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n pattern MkT { foo } = Just foo\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( foo )\\nbecause foo doesn\'t have a parent. This might actually be ambiguous if A\\nexports another field called foo, but there is no good answer to return and this\\nis a very obscure corner, so it seems to be the best we can do. See\\nDRFPatSynExport for a test of this.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Errors}\\n* *\\n************************************************************************\\n-}\\n\\nbadImportItemErr\\n :: ModIface -> ImpDeclSpec -> IE GhcPs\\n -> IsSubordinateError\\n -> [AvailInfo]\\n -> TcRn (NonEmpty ImportLookupReason)\\nbadImportItemErr iface decl_spec ie sub avails = do\\n exts <- importLookupExtensions\\n let import_lookup_bad :: BadImportKind -> ImportLookupReason\\n import_lookup_bad k = ImportLookupBad k iface decl_spec ie exts\\n dflags <- getDynFlags\\n hsc_env <- getTopEnv\\n let rdr_env = mkGlobalRdrEnv\\n $ gresFromAvails hsc_env (Just imp_spec) all_avails\\n pure $ fmap import_lookup_bad (importErrorKind dflags rdr_env)\\n where\\n importErrorKind :: DynFlags -> GlobalRdrEnv -> NonEmpty BadImportKind\\n importErrorKind dflags rdr_env\\n | any checkIfTyCon avails = case sub of\\n IsNotSubordinate -> NE.singleton BadImportAvailTyCon\\n IsSubordinateError { subordinate_err_parent = gre\\n , subordinate_err_unavailable = unavailable\\n , subordinate_err_nontype = nontype\\n , subordinate_err_nondata = nondata }\\n -> NE.fromList $ catMaybes $\\n [ fmap (BadImportNotExportedSubordinates gre) (NE.nonEmpty unavailable)\\n , fmap (BadImportNonTypeSubordinates gre) (NE.nonEmpty nontype)\\n , fmap (BadImportNonDataSubordinates gre) (NE.nonEmpty nondata) ]\\n | any checkIfVarName avails = NE.singleton BadImportAvailVar\\n | Just con <- find checkIfDataCon avails = NE.singleton (BadImportAvailDataCon (availOccName con))\\n | otherwise = NE.singleton (BadImportNotExported suggs)\\n where\\n suggs = similar_suggs ++ fieldSelectorSuggestions rdr_env rdr\\n what_look = case sub of\\n IsNotSubordinate -> WL_TyCon_or_TermVar\\n IsSubordinateError { subordinate_err_parent = gre } ->\\n case greInfo gre of\\n IAmTyCon ClassFlavour\\n -> WL_TyCon_or_TermVar\\n _ -> WL_Term\\n similar_names =\\n similarNameSuggestions (Unbound.LF what_look WL_Global)\\n dflags rdr_env emptyLocalRdrEnv rdr\\n similar_suggs =\\n case NE.nonEmpty $ mapMaybe imported_item $ similar_names of\\n Just similar -> [ SuggestSimilarNames rdr similar ]\\n Nothing -> [ ]\\n\\n -- Only keep imported items, and set the \\"HowInScope\\" to\\n -- \\"Nothing\\" to avoid printing \\"imported from...\\" in the suggestion\\n -- error message.\\n imported_item (SimilarRdrName rdr_name gre (Just (ImportedBy {})))\\n = Just (SimilarRdrName rdr_name gre Nothing)\\n imported_item _ = Nothing\\n\\n checkIfDataCon = checkIfAvailMatches isDataConName\\n checkIfTyCon = checkIfAvailMatches isTyConName\\n checkIfVarName =\\n \\\\case\\n AvailTC{} -> False\\n Avail n -> importedFS == occNameFS (occName n)\\n && (isVarOcc <||> isFieldOcc) (occName n)\\n checkIfAvailMatches namePred =\\n \\\\case\\n AvailTC _ ns ->\\n case find (\\\\n -> importedFS == occNameFS (occName n)) ns of\\n Just n -> namePred n\\n Nothing -> False\\n Avail{} -> False\\n availOccName = occName . availName\\n rdr = ieName ie\\n importedFS = occNameFS $ rdrNameOcc rdr\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n all_avails = mi_exports iface\\n\\nimportLookupExtensions :: TcRn ImportLookupExtensions\\nimportLookupExtensions = do\\n ile_pattern_synonyms <- xoptM LangExt.PatternSynonyms\\n ile_explicit_namespaces <- xoptM LangExt.ExplicitNamespaces\\n return ImportLookupExtensions{ile_pattern_synonyms, ile_explicit_namespaces}\\n\\naddDupDeclErr :: NonEmpty GlobalRdrElt -> TcRn ()\\naddDupDeclErr gres@(gre :| _)\\n -- Report the error at the later location\\n = addErrAt (getSrcSpan (NE.last sorted_names)) $ (TcRnDuplicateDecls (greOccName gre) sorted_names)\\n where\\n sorted_names =\\n NE.sortBy (SrcLoc.leftmost_smallest `on` nameSrcSpan)\\n (fmap greName gres)\\n\\n-- This data decl will parse OK\\n-- data T = a Int\\n-- treating \\"a\\" as the constructor.\\n-- It is really hard to make the parser spot this malformation.\\n-- So the renamer has to check that the constructor is legal\\n--\\n-- We can get an operator as the constructor, even in the prefix form:\\n-- data T = :% Int Int\\n-- from interface files, which always print in prefix form\\n--\\n-- We also allow type constructor names, which are defined by \\"type data\\"\\n-- declarations. See Note [Type data declarations] in GHC.Rename.Module.\\n\\ncheckConName :: RdrName -> TcRn ()\\ncheckConName name\\n = checkErr (isRdrDataCon name || isRdrTc name) (TcRnIllegalDataCon name)\\n", "filetypes": ["haskell"]}}}' 2026-10-16 14:49:27,328 - DEBUG - POST b'http://127.0.0.1:37093/event_notification' {'content-type': 'application/json', 'x-ycm-hmac': b'KFJjVQM2CIyJJTLgXoy+AjOrxP5lCK2XufR47lxDhsY='} b'{"filepath": "/home/enrico/ghc/compiler/GHC/Rename/Names.hs", "line_num": 2248, "column_num": 10, "working_dir": "/home/enrico/ghc", "file_data": {"/home/enrico/ghc/compiler/GHC/Rename/Names.hs": {"contents": "{-\\n(c) The GRASP/AQUA Project, Glasgow University, 1992-1998\\n\\nExtracting imported and top-level names in scope\\n-}\\n\\n{-# LANGUAGE NondecreasingIndentation #-}\\n{-# LANGUAGE TypeFamilies #-}\\n\\nmodule GHC.Rename.Names (\\n rnImports, getLocalNonValBinders, newRecordFieldLabel,\\n importsFromIface,\\n ImportUserSpec(..),\\n extendGlobalRdrEnvRn,\\n gresFromAvails,\\n calculateAvails,\\n reportUnusedNames,\\n checkConName,\\n mkChildEnv,\\n findChildren,\\n mkBadExportSubordinate,\\n findImportUsage,\\n getMinimalImports,\\n printMinimalImports,\\n renamePkgQual, renameRawPkgQual,\\n classifyGREs,\\n ImportDeclUsage,\\n rnNamespaceSpecifier\\n ) where\\n\\nimport GHC.Prelude hiding ( head, init, last, tail )\\n\\nimport GHC.Driver.Env\\nimport GHC.Driver.Session\\nimport GHC.Driver.Ppr\\n\\nimport GHC.Rename.Env\\nimport GHC.Rename.Fixity\\nimport GHC.Rename.Utils ( warnUnusedTopBinds )\\nimport GHC.Rename.Unbound\\nimport qualified GHC.Rename.Unbound as Unbound\\n\\nimport GHC.Tc.Errors.Types\\nimport GHC.Tc.Utils.Env\\nimport GHC.Tc.Utils.Monad\\nimport GHC.Tc.Types.LclEnv\\nimport GHC.Tc.Zonk.TcType ( tcInitTidyEnv )\\n\\nimport GHC.Hs\\nimport GHC.Iface.Load ( loadSrcInterface, loadSrcInterface_maybe )\\nimport GHC.Iface.Errors.Types\\n ( IfaceMessage(..), MissingInterfaceError, InterfaceLookingFor(..)\\n , LoadEssentialsReason(..) )\\nimport GHC.Iface.Syntax ( fromIfaceWarnings )\\nimport GHC.Builtin.Modules( pRELUDE_NAME, rEBINDABLE_MOD_NAME )\\nimport GHC.Parser.PostProcess ( setRdrNameSpace )\\nimport GHC.Core.TyCo.Tidy\\nimport GHC.Core.PatSyn\\nimport GHC.Core.TyCon ( TyCon, tyConName )\\nimport qualified GHC.LanguageExtensions as LangExt\\n\\nimport GHC.Utils.Outputable as Outputable\\nimport GHC.Utils.Misc as Utils\\nimport GHC.Utils.Panic\\n\\nimport GHC.Types.Fixity.Env\\nimport GHC.Types.SafeHaskell\\nimport GHC.Types.Name\\nimport GHC.Types.Name.Env\\nimport GHC.Types.Name.Set\\nimport GHC.Types.Name.Reader\\nimport GHC.Types.Avail\\nimport GHC.Types.FieldLabel\\nimport GHC.Types.Hint\\nimport GHC.Types.SourceFile\\nimport GHC.Types.SrcLoc as SrcLoc\\nimport GHC.Types.Basic (TyConFlavour (..), convImportLevel, VisArity)\\nimport GHC.Types.UnresolvedImport\\nimport GHC.Types.Id\\nimport GHC.Types.PkgQual\\nimport GHC.Types.GREInfo (ConInfo(..), ConFieldInfo (..), ConLikeInfo (ConIsData))\\n\\nimport GHC.Unit\\nimport GHC.Unit.Module.Warnings\\nimport GHC.Unit.Module.ModIface\\nimport GHC.Unit.Module.Imported\\nimport GHC.Unit.Module.Deps\\nimport GHC.Unit.Env\\n\\nimport GHC.Data.Bag\\nimport GHC.Data.FastString\\nimport GHC.Data.FastString.Env\\nimport GHC.Data.Maybe\\nimport GHC.Data.List.SetOps ( removeDups )\\n\\nimport Control.Arrow ( second )\\nimport Control.Monad\\nimport Data.Foldable ( for_ )\\nimport Data.IntMap ( IntMap )\\nimport qualified Data.IntMap as IntMap\\nimport Data.Map ( Map )\\nimport qualified Data.Map as Map\\nimport Data.Ord ( comparing )\\nimport Data.Semigroup ( Any(..) )\\nimport qualified Data.Semigroup as S\\nimport Data.List ( partition, find, sortBy )\\nimport Data.List.NonEmpty (NonEmpty(..))\\nimport qualified Data.List.NonEmpty as NE\\nimport Data.Function ( on )\\nimport qualified Data.Set as S\\nimport System.FilePath (())\\nimport System.IO\\n\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{rnImports}\\n* *\\n************************************************************************\\n\\nNote [Tracking Trust Transitively]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen we import a package as well as checking that the direct imports are safe\\naccording to the rules outlined in the Note [Safe Haskell Trust Check] in GHC.Driver.Main\\nwe must also check that these rules hold transitively for all dependent modules\\nand packages. Doing this without caching any trust information would be very\\nslow as we would need to touch all packages and interface files a module depends\\non. To avoid this we make use of the property that if a modules Safe Haskell\\nmode changes, this triggers a recompilation from that module in the dependency\\ngraph. So we can just worry mostly about direct imports.\\n\\nThere is one trust property that can change for a package though without\\nrecompilation being triggered: package trust. So we must check that all\\npackages a module transitively depends on to be trusted are still trusted when\\nwe are compiling this module (as due to recompilation avoidance some modules\\nbelow may not be considered trusted any more without recompilation being\\ntriggered).\\n\\nWe handle this by augmenting the existing transitive list of packages a module M\\ndepends on with a bool for each package that says if it must be trusted when the\\nmodule M is being checked for trust. This list of trust required packages for a\\nsingle import is gathered in the rnImportDecl function and stored in an\\nImportAvails data structure. The union of these trust required packages for all\\nimports is done by the rnImports function using the combine function which calls\\nthe plusImportAvails function that is a union operation for the ImportAvails\\ntype. This gives us in an ImportAvails structure all packages required to be\\ntrusted for the module we are currently compiling. Checking that these packages\\nare still trusted (and that direct imports are trusted) is done in\\nGHC.Driver.Main.checkSafeImports.\\n\\nSee the note below, [Trust Own Package] for a corner case in this method and\\nhow its handled.\\n\\n\\nNote [Trust Own Package]\\n~~~~~~~~~~~~~~~~~~~~~~~~\\nThere is a corner case of package trust checking that the usual transitive check\\ndoesn\'t cover. (For how the usual check operates see the Note [Tracking Trust\\nTransitively] below). The case is when you import a -XSafe module M and M\\nimports a -XTrustworthy module N. If N resides in a different package than M,\\nthen the usual check works as M will record a package dependency on N\'s package\\nand mark it as required to be trusted. If N resides in the same package as M\\nthough, then importing M should require its own package be trusted due to N\\n(since M is -XSafe so doesn\'t create this requirement by itself). The usual\\ncheck fails as a module doesn\'t record a package dependency of its own package.\\nSo instead we now have a bool field in a modules interface file that simply\\nstates if the module requires its own package to be trusted. This field avoids\\nus having to load all interface files that the module depends on to see if one\\nis trustworthy.\\n\\n\\nNote [Trust Transitive Property]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSo there is an interesting design question in regards to transitive trust\\nchecking. Say I have a module B compiled with -XSafe. B is dependent on a bunch\\nof modules and packages, some packages it requires to be trusted as its using\\n-XTrustworthy modules from them. Now if I have a module A that doesn\'t use safe\\nhaskell at all and simply imports B, should A inherit all the trust\\nrequirements from B? Should A now also require that a package p is trusted since\\nB required it?\\n\\nWe currently say no but saying yes also makes sense. The difference is, if a\\nmodule M that doesn\'t use Safe Haskell imports a module N that does, should all\\nthe trusted package requirements be dropped since M didn\'t declare that it cares\\nabout Safe Haskell (so -XSafe is more strongly associated with the module doing\\nthe importing) or should it be done still since the author of the module N that\\nuses Safe Haskell said they cared (so -XSafe is more strongly associated with\\nthe module that was compiled that used it).\\n\\nGoing with yes is a simpler semantics we think and harder for the user to stuff\\nup but it does mean that Safe Haskell will affect users who don\'t care about\\nSafe Haskell as they might grab a package from Cabal which uses safe haskell (say\\nnetwork) and that packages imports -XTrustworthy modules from another package\\n(say bytestring), so requires that package is trusted. The user may now get\\ncompilation errors in code that doesn\'t do anything with Safe Haskell simply\\nbecause they are using the network package. They will have to call \'ghc-pkg\\ntrust network\' to get everything working. Due to this invasive nature of going\\nwith yes we have gone with no for now.\\n-}\\n\\n-- | Process Import Decls. See \'rnImportDecl\' for a description of what\\n-- the return types represent.\\n-- Note: Do the non SOURCE ones first, so that we get a helpful warning\\n-- for SOURCE ones that are unnecessary\\nrnImports :: [(LImportDecl GhcPs, SDoc)]\\n -> RnM ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\nrnImports imports = do\\n tcg_env <- getGblEnv\\n -- NB: want an identity module here, because it\'s OK for a signature\\n -- module to import from its implementor\\n let this_mod = tcg_mod tcg_env\\n let (source, ordinary) = partition (is_source_import . fst) imports\\n is_source_import (d::LImportDecl GhcPs) = ideclSource (unLoc d) == IsBoot\\n stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary\\n stuff2 <- mapAndReportM (rnImportDecl this_mod) source\\n -- Safe Haskell: See Note [Tracking Trust Transitively]\\n let (decls, imp_user_spec, rdr_env, imp_avails) = combine (stuff1 ++ stuff2)\\n -- Update imp_boot_mods if imp_direct_mods mentions any of them\\n let merged_import_avail = clobberSourceImports imp_avails\\n return (decls, imp_user_spec, rdr_env, merged_import_avail)\\n\\n where\\n clobberSourceImports imp_avails =\\n imp_avails { imp_boot_mods = imp_boot_mods\' }\\n where\\n imp_boot_mods\' = mergeInstalledModuleEnv combJ id (const emptyInstalledModuleEnv)\\n (imp_boot_mods imp_avails)\\n (imp_direct_dep_mods imp_avails)\\n\\n combJ (GWIB _ IsBoot) (_, x) = Just x\\n combJ r _ = Just r\\n -- See Note [Combining ImportAvails]\\n combine :: [(LImportDecl GhcRn, ImportUserSpec, GlobalRdrEnv, ImportAvails)]\\n -> ([LImportDecl GhcRn], [ImportUserSpec], GlobalRdrEnv, ImportAvails)\\n combine ss =\\n let (decls, imp_user_spec, rdr_env, imp_avails, finsts) = foldr\\n plus\\n ([], [], emptyGlobalRdrEnv, emptyImportAvails, emptyModuleSet)\\n ss\\n in (decls, imp_user_spec, rdr_env, imp_avails { imp_finsts = moduleSetElts finsts })\\n\\n plus (decl, us, gbl_env1, imp_avails1)\\n (decls, uss, gbl_env2, imp_avails2, finsts_set)\\n = ( decl:decls,\\n us:uss,\\n gbl_env1 `plusGlobalRdrEnv` gbl_env2,\\n imp_avails1\' `plusImportAvails` imp_avails2,\\n extendModuleSetList finsts_set new_finsts )\\n where\\n imp_avails1\' = imp_avails1 { imp_finsts = [] }\\n new_finsts = imp_finsts imp_avails1\\n\\n{-\\nNote [Combining ImportAvails]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nimp_finsts in ImportAvails is a list of family instance modules\\ntransitively depended on by an import. imp_finsts for a currently\\ncompiled module is a union of all the imp_finsts of imports.\\nComputing the union of two lists of size N is O(N^2) and if we\\ndo it to M imports we end up with O(M*N^2). That can get very\\nexpensive for bigger module hierarchies.\\n\\nUnion can be optimized to O(N log N) if we use a Set.\\nimp_finsts is converted back and forth between dep_finsts, so\\nchanging a type of imp_finsts means either paying for the conversions\\nor changing the type of dep_finsts as well.\\n\\nI\'ve measured that the conversions would cost 20% of allocations on my\\ntest case, so that can be ruled out.\\n\\nChanging the type of dep_finsts forces checkFamInsts to\\nget the module lists in non-deterministic order. If we wanted to restore\\nthe deterministic order, we\'d have to sort there, which is an additional\\ncost. As far as I can tell, using a non-deterministic order is fine there,\\nbut that\'s a brittle nonlocal property which I\'d like to avoid.\\n\\nAdditionally, dep_finsts is read from an interface file, so its \\"natural\\"\\ntype is a list. Which makes it a natural type for imp_finsts.\\n\\nSince rnImports.combine is really the only place that would benefit from\\nit being a Set, it makes sense to optimize the hot loop in rnImports.combine\\nwithout changing the representation.\\n\\nSo here\'s what we do: instead of naively merging ImportAvails with\\nplusImportAvails in a loop, we make plusImportAvails merge empty imp_finsts\\nand compute the union on the side using Sets. When we\'re done, we can\\nconvert it back to a list. One nice side effect of this approach is that\\nif there\'s a lot of overlap in the imp_finsts of imports, the\\nSet doesn\'t really need to grow and we don\'t need to allocate.\\n\\nRunning generateModules from #14693 with DEPTH=16, WIDTH=30 finishes in\\n23s before, and 11s after.\\n-}\\n\\n-- | Given a located import declaration @decl@ from @this_mod@,\\n-- calculate the following pieces of information:\\n--\\n-- 1. An updated \'LImportDecl\', where all unresolved \'RdrName\' in\\n-- the entity lists have been resolved into \'Name\'s,\\n--\\n-- 2. A \'GlobalRdrEnv\' representing the new identifiers that were\\n-- brought into scope (taking into account module qualification\\n-- and hiding),\\n--\\n-- 3. \'ImportAvails\' summarizing the identifiers that were imported\\n-- by this declaration, and\\n--\\n-- 4. A boolean \'AnyHpcUsage\' which is true if the imported module\\n-- used HPC.\\nrnImportDecl :: Module -> (LImportDecl GhcPs, SDoc)\\n -> RnM (LImportDecl GhcRn, ImportUserSpec , GlobalRdrEnv, ImportAvails)\\nrnImportDecl this_mod\\n (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name\\n , ideclPkgQual = raw_pkg_qual\\n , ideclSource = want_boot\\n , ideclSafe = mod_safe\\n , ideclLevelSpec = import_level\\n , ideclQualified = qual_style\\n , ideclExt = XImportDeclPass { ideclOrigin = origin }\\n , ideclAs = as_mod, ideclImportList = imp_details }), import_reason)\\n = setSrcSpanA loc $ do\\n\\n case raw_pkg_qual of\\n NoRawPkgQual -> pure ()\\n RawPkgQual {} -> do\\n pkg_imports <- xoptM LangExt.PackageImports\\n when (not pkg_imports) $ addErr TcRnPackageImportsDisabled\\n\\n let qual_only = isImportDeclQualified qual_style\\n generated = isGeneratedImport origin\\n\\n lookup_scope = importDeclLookupScope origin\\n\\n -- If there\'s an error in loadInterface, (e.g. interface\\n -- file not found) we get lots of spurious errors from \'filterImports\'\\n let imp_mod_name = unLoc loc_imp_mod_name\\n doc = ppr imp_mod_name <+> import_reason\\n\\n hsc_env <- getTopEnv\\n unit_env <- hsc_unit_env <$> getTopEnv\\n let pkg_qual = renameRawPkgQual unit_env imp_mod_name raw_pkg_qual\\n\\n -- Check for self-import, which confuses the typechecker (#9032)\\n -- ghc --make rejects self-import cycles already, but batch-mode may not\\n -- at least not until GHC.IfaceToCore.tcHiBootIface, which is too late to avoid\\n -- typechecker crashes. (Indirect self imports are not caught until\\n -- GHC.IfaceToCore, see #10337 tracking how to make this error better.)\\n --\\n -- Originally, we also allowed \'import {-# SOURCE #-} M\', but this\\n -- caused bug #10182: in one-shot mode, we should never load an hs-boot\\n -- file for the module we are compiling into the EPS. In principle,\\n -- it should be possible to support this mode of use, but we would have to\\n -- extend Provenance to support a local definition in a qualified location.\\n -- For now, we don\'t support it, but see #10336\\n when (imp_mod_name == moduleName this_mod &&\\n (case pkg_qual of -- If we have import \\"\\" M, then we should\\n -- check that \\"\\" is \\"this\\" (which is magic)\\n -- or the name of this_mod\'s package. Yurgh!\\n -- c.f. GHC.findModule, and #9997\\n NoPkgQual -> True\\n ThisPkg uid -> uid == homeUnitId_ (hsc_dflags hsc_env)\\n OtherPkg _ -> False))\\n (addErr (TcRnSelfImport imp_mod_name))\\n\\n -- Check for a missing import list (Opt_WarnMissingImportList also\\n -- checks for T(..) items but that is done in checkDodgyImport below)\\n case imp_details of\\n Just (Exactly, _) -> return () -- Explicit import list\\n _ | generated -> return () -- Do not bleat for generated imports\\n | qual_only -> return ()\\n | otherwise -> addDiagnostic (TcRnNoExplicitImportList imp_mod_name)\\n\\n\\n mb_iface <- loadSrcInterface_maybe doc lookup_scope imp_mod_name want_boot pkg_qual\\n iface <- case mb_iface of\\n Succeeded iface -> return iface\\n Failed err -> failWithTc $\\n importDeclLoadFailure origin imp_mod_name want_boot err\\n\\n -- Compiler sanity check: if the import didn\'t say\\n -- {-# SOURCE #-} we should not get a hi-boot file\\n warnPprTrace ((want_boot == NotBoot) && (mi_boot iface == IsBoot)) \\"rnImportDecl\\" (ppr imp_mod_name) $ do\\n\\n -- Issue a user warning for a redundant {- SOURCE -} import\\n -- NB that we arrange to read all the ordinary imports before\\n -- any of the {- SOURCE -} imports.\\n --\\n -- in --make and GHCi, the compilation manager checks for this,\\n -- and indeed we shouldn\'t do it here because the existence of\\n -- the non-boot module depends on the compilation order, which\\n -- is not deterministic. The hs-boot test can show this up.\\n dflags <- getDynFlags\\n warnIf ((want_boot == IsBoot) && (mi_boot iface == NotBoot) && isOneShot (ghcMode dflags))\\n (TcRnRedundantSourceImport imp_mod_name)\\n when (mod_safe && not (safeImportsOn dflags)) $\\n addErr (TcRnSafeImportsDisabled imp_mod_name)\\n\\n let imp_mod = mi_module iface\\n qual_mod_name = fmap unLoc as_mod `orElse` imp_mod_name\\n imp_spec = ImpDeclSpec { is_mod = imp_mod, is_qual = qual_only,\\n is_dloc = locA loc, is_as = qual_mod_name,\\n is_pkg_qual = pkg_qual, is_isboot = want_boot,\\n is_level = convImportLevel import_level }\\n\\n let filter_imports = do\\n -- filter the imports according to the import declaration\\n (new_imp_details, imp_user_list, gbl_env)\\n <- filterImports hsc_env iface imp_spec imp_details\\n -- for certain error messages, we\\u2019d like to know what could be\\n -- imported here, if everything were imported\\n potential_gres <- (\\\\(_,_,x) -> x) <$> filterImports hsc_env iface imp_spec Nothing\\n return (new_imp_details, imp_user_list, gbl_env, potential_gres)\\n\\n (new_imp_details, imp_user_list, gbl_env, potential_gres) <-\\n case origin of\\n ImplicitEssentialsImport ->\\n -- The implicit GHC.Essentials import does not bring anything into scope.\\n -- See Note [Finding GHC.Essentials] in GHC.Builtin.\\n return (Nothing, ImpUserDependOnly, emptyGlobalRdrEnv, emptyGlobalRdrEnv)\\n UserWrittenImport -> filter_imports\\n ImplicitPreludeImport -> filter_imports\\n PluginImport -> filter_imports\\n\\n let is_hiding | Just (EverythingBut,_) <- imp_details = True\\n | otherwise = False\\n\\n -- should the import be safe?\\n mod_safe\' = mod_safe\\n || (not generated && safeDirectImpsReq dflags)\\n || (generated && safeImplicitImpsReq dflags)\\n\\n hsc_env <- getTopEnv\\n let home_unit = hsc_home_unit hsc_env\\n other_home_units = hsc_all_home_unit_ids hsc_env\\n\\n imported_by\\n | isDependOnlyImport imp_user_list\\n = ImportedBySystem\\n | otherwise\\n = ImportedByUser $ ImportedModsVal\\n { imv_name = is_as imp_spec\\n , imv_span = locA loc\\n , imv_is_safe = mod_safe\'\\n , imv_is_hiding = is_hiding\\n , imv_all_exports = potential_gres\\n , imv_qualified = qual_only\\n , imv_is_level = convImportLevel import_level\\n }\\n imports = calculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by\\n\\n -- Complain if we import a deprecated module\\n case fromIfaceWarnings (mi_warns iface) of\\n WarnAll txt -> addDiagnostic (TcRnDeprecatedModule imp_mod_name txt)\\n _ -> return ()\\n\\n let new_imp_decl = ImportDecl\\n { ideclExt = ideclExt decl\\n , ideclName = ideclName decl\\n , ideclPkgQual = pkg_qual\\n , ideclSource = ideclSource decl\\n , ideclSafe = mod_safe\'\\n , ideclQualified = ideclQualified decl\\n , ideclAs = ideclAs decl\\n , ideclImportList = new_imp_details\\n , ideclLevelSpec = ideclLevelSpec decl\\n }\\n\\n return (L loc new_imp_decl, ImpUserSpec imp_spec imp_user_list, gbl_env, imports)\\n\\n-- | The error message to emit when we failed to load an interface.\\nimportDeclLoadFailure :: ImportDeclOrigin -> ModuleName -> IsBootInterface\\n -> MissingInterfaceError -> TcRnMessage\\nimportDeclLoadFailure ImplicitEssentialsImport _ _ err\\n = TcRnInterfaceError $ CantFindEssentials err LookingForEssentialsModule\\nimportDeclLoadFailure _ mod_name want_boot err\\n = TcRnInterfaceError $ Can\'tFindInterface err $ LookingForModule mod_name want_boot\\n\\n-- | Rename raw package imports\\nrenameRawPkgQual :: UnitEnv -> ModuleName -> RawPkgQual -> PkgQual\\nrenameRawPkgQual unit_env mn = \\\\case\\n NoRawPkgQual -> NoPkgQual\\n RawPkgQual _ fs -> renamePkgQual unit_env mn $ Just fs\\n\\n-- | Rename raw package imports\\nrenamePkgQual :: UnitEnv -> ModuleName -> Maybe FastString -> PkgQual\\nrenamePkgQual unit_env mn mb_pkg = case mb_pkg of\\n Nothing -> NoPkgQual\\n Just pkg_fs\\n | Just uid <- homeUnitId <$> ue_homeUnit unit_env\\n , pkg_fs == fsLit \\"this\\"\\n -> ThisPkg uid\\n\\n | Just (uid, _) <- find (fromMaybe False . fmap (== pkg_fs) . snd) home_names\\n -> ThisPkg uid\\n\\n | Just uid <- resolvePackageImport unit_state mn (PackageName pkg_fs)\\n -> OtherPkg uid\\n\\n | otherwise\\n -> OtherPkg (UnitId pkg_fs)\\n -- not really correct as pkg_fs is unlikely to be a valid unit-id but\\n -- we will report the failure later...\\n where\\n home_names =\\n [ (uid, mkFastString <$> thisPackageName (homeUnitEnv_dflags (ue_findHomeUnitEnv uid unit_env)))\\n | uid <- S.toList hpt_deps\\n ]\\n\\n unit_state = ue_homeUnitState unit_env\\n\\n hpt_deps :: S.Set UnitId\\n hpt_deps = homeUnitDepends unit_state\\n\\n\\n-- | Calculate the \'ImportAvails\' induced by an import of a particular\\n-- interface, but without \'imp_mods\'.\\ncalculateAvails :: HomeUnit\\n -> S.Set UnitId\\n -> ModIface\\n -> IsSafeImport\\n -> IsBootInterface\\n -> ImportedBy\\n -> ImportAvails\\ncalculateAvails home_unit other_home_units iface mod_safe\' want_boot imported_by =\\n let imp_mod = mi_module iface\\n imp_sem_mod= mi_semantic_module iface\\n orph_iface = mi_orphan iface\\n has_finsts = mi_finsts iface\\n deps = mi_deps iface\\n trust = getSafeMode $ mi_trust iface\\n trust_pkg = mi_trust_pkg iface\\n is_sig = mi_hsc_src iface == HsigFile\\n\\n -- If the module exports anything defined in this module, just\\n -- ignore it. Reason: otherwise it looks as if there are two\\n -- local definition sites for the thing, and an error gets\\n -- reported. Easiest thing is just to filter them out up\\n -- front. This situation only arises if a module imports\\n -- itself, or another module that imported it. (Necessarily,\\n -- this involves a loop.)\\n --\\n -- We do this *after* filterImports, so that if you say\\n -- module A where\\n -- import B( AType )\\n -- type AType = ...\\n --\\n -- module B( AType ) where\\n -- import {-# SOURCE #-} A( AType )\\n --\\n -- then you won\'t get a \'B does not export AType\' message.\\n\\n\\n -- Compute new transitive dependencies\\n --\\n -- \'dep_orphs\' and \'dep_finsts\' do NOT include the imported module\\n -- itself, but we DO need to include this module in \'imp_orphs\' and\\n -- \'imp_finsts\' if it defines an orphan or instance family; thus the\\n -- orph_iface/has_iface tests.\\n\\n deporphs = dep_orphs deps\\n depfinsts = dep_finsts deps\\n\\n orphans | orph_iface = assertPpr (not (imp_sem_mod `elem` deporphs)) (ppr imp_sem_mod <+> ppr deporphs) $\\n imp_sem_mod : deporphs\\n | otherwise = deporphs\\n\\n finsts | has_finsts = assertPpr (not (imp_sem_mod `elem` depfinsts)) (ppr imp_sem_mod <+> ppr depfinsts) $\\n imp_sem_mod : depfinsts\\n | otherwise = depfinsts\\n\\n -- Trusted packages are a lot like orphans.\\n trusted_pkgs | mod_safe\' = dep_trusted_pkgs deps\\n | otherwise = S.empty\\n\\n\\n pkg = moduleUnit (mi_module iface)\\n ipkg = toUnitId pkg\\n\\n -- Does this import mean we now require our own pkg\\n -- to be trusted? See Note [Trust Own Package]\\n ptrust = trust == Sf_Trustworthy || trust_pkg\\n pkg_trust_req\\n | isHomeUnit home_unit pkg = ptrust\\n | otherwise = False\\n\\n dependent_pkgs = if toUnitId pkg `S.member` other_home_units\\n then S.empty\\n else S.singleton (lvl, ipkg)\\n\\n lvl = case imported_by of\\n ImportedByUser imv -> imv_is_level imv\\n ImportedBySystem -> NormalLevel\\n\\n\\n direct_mods = if toUnitId pkg `S.member` other_home_units\\n then mkPlusModDeps (moduleUnitId imp_mod) lvl (GWIB (moduleName imp_mod) want_boot)\\n else emptyInstalledModuleEnv\\n\\n dep_boot_mods_map = mkModDeps (dep_boot_mods deps)\\n\\n\\n boot_mods\\n -- If we are looking for a boot module, it must be HPT\\n | IsBoot <- want_boot = extendInstalledModuleEnv dep_boot_mods_map (toUnitId <$> imp_mod) (GWIB (moduleName imp_mod) IsBoot)\\n -- Now we are importing A properly, so don\'t go looking for\\n -- A.hs-boot\\n | isHomeUnit home_unit pkg = dep_boot_mods_map\\n -- There\'s no boot files to find in external imports\\n | otherwise = emptyInstalledModuleEnv\\n\\n sig_mods =\\n if is_sig\\n then moduleName imp_mod : dep_sig_mods deps\\n else dep_sig_mods deps\\n\\n\\n in ImportAvails {\\n imp_mods = Map.singleton (mi_module iface) [imported_by],\\n imp_orphs = orphans,\\n imp_finsts = finsts,\\n imp_sig_mods = sig_mods,\\n imp_direct_dep_mods = direct_mods,\\n imp_dep_direct_pkgs = dependent_pkgs,\\n imp_boot_mods = boot_mods,\\n\\n -- Add in the imported modules trusted package\\n -- requirements. ONLY do this though if we import the\\n -- module as a safe import.\\n -- See Note [Tracking Trust Transitively]\\n -- and Note [Trust Transitive Property]\\n imp_trust_pkgs = trusted_pkgs,\\n -- Do we require our own pkg to be trusted?\\n -- See Note [Trust Own Package]\\n imp_trust_own_pkg = pkg_trust_req\\n }\\n\\nmkPlusModDeps :: UnitId -> ImportLevel -> ModuleNameWithIsBoot\\n -> InstalledModuleEnv (S.Set ImportLevel, ModuleNameWithIsBoot)\\nmkPlusModDeps uid st elt = extendInstalledModuleEnv emptyInstalledModuleEnv (mkModule uid (gwib_mod elt)) (S.singleton st, elt)\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{importsFromLocalDecls}\\n* *\\n************************************************************************\\n\\nFrom the top-level declarations of this module produce\\n * the lexical environment\\n * the ImportAvails\\ncreated by its bindings.\\n\\nNote [Top-level Names in Template Haskell decl quotes]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSee also: Note [Interactively-bound Ids in GHCi] in GHC.Driver.Env\\n Note [Looking up Exact RdrNames] in GHC.Rename.Env\\n\\nConsider a Template Haskell declaration quotation like this:\\n module M where\\n f x = h [d| f = 3 |]\\nWhen renaming the declarations inside [d| ...|], we treat the\\ntop level binders specially in two ways\\n\\n1. We give them an Internal Name, not (as usual) an External one.\\n This is done by GHC.Rename.Env.newTopSrcBinder.\\n\\n2. We make them *shadow* the outer bindings.\\n See Note [GlobalRdrEnv shadowing]\\n\\n3. We find out whether we are inside a [d| ... |] by testing the TH\\n level. This is a slight hack, because the level field was really\\n meant for the type checker, and here we are not interested in the\\n fields of Brack, hence the error thunks in thRnBrack.\\n-}\\n\\nextendGlobalRdrEnvRn :: [GlobalRdrElt]\\n -> MiniFixityEnv\\n -> RnM (TcGblEnv, TcLclEnv)\\n-- Updates both the GlobalRdrEnv and the FixityEnv\\n-- We return a new TcLclEnv only because we might have to\\n-- delete some bindings from it;\\n-- see Note [Top-level Names in Template Haskell decl quotes]\\n\\nextendGlobalRdrEnvRn new_gres new_fixities\\n = checkNoErrs $ -- See Note [Fail fast on duplicate definitions]\\n do { (gbl_env, lcl_env) <- getEnvs\\n ; level <- getThLevel\\n ; isGHCi <- getIsGHCi\\n ; let rdr_env = tcg_rdr_env gbl_env\\n fix_env = tcg_fix_env gbl_env\\n th_bndrs = getLclEnvThBndrs lcl_env\\n th_lvl = thLevelIndex level\\n\\n -- Delete new_occs from global and local envs\\n -- If we are in a TemplateHaskell decl bracket,\\n -- we are going to shadow them\\n -- See Note [GlobalRdrEnv shadowing]\\n inBracket = isBrackLevel level\\n\\n lcl_env_TH = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_rdr = minusLocalRdrEnv (tcl_rdr lcl_env) new_gres_env }) lcl_env\\n -- See Note [GlobalRdrEnv shadowing]\\n\\n lcl_env2 | inBracket = lcl_env_TH\\n | otherwise = lcl_env\\n\\n -- Deal with shadowing: see Note [GlobalRdrEnv shadowing]\\n want_shadowing = isGHCi || inBracket\\n rdr_env1 | want_shadowing = shadowNames False rdr_env new_gres_env\\n | otherwise = rdr_env\\n\\n lcl_env3 = modifyLclCtxt (\\\\lcl_env -> lcl_env { tcl_th_bndrs = extendNameEnvList th_bndrs\\n [ ( n, (TopLevel, th_lvl) )\\n | n <- new_names ] }) lcl_env2\\n\\n ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres\\n\\n ; let fix_env\' = foldl\' extend_fix_env fix_env new_gres\\n gbl_env\' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env\' }\\n\\n ; traceRn \\"extendGlobalRdrEnvRn 2\\" (pprGlobalRdrEnv True rdr_env2)\\n ; return (gbl_env\', lcl_env3) }\\n where\\n new_names = map greName new_gres\\n new_gres_env = mkGlobalRdrEnv new_gres\\n\\n -- If there is a fixity decl for the gre, add it to the fixity env\\n extend_fix_env fix_env gre\\n | Just (L _ fi) <- lookupMiniFixityEnv new_fixities name\\n = extendNameEnv fix_env name (FixItem occ fi)\\n | otherwise\\n = fix_env\\n where\\n name = greName gre\\n occ = greOccName gre\\n\\n add_gre :: GlobalRdrEnv -> GlobalRdrElt -> RnM GlobalRdrEnv\\n -- Extend the GlobalRdrEnv with a LocalDef GRE\\n -- If there is already a LocalDef GRE with the same OccName,\\n -- report an error and discard the new GRE\\n -- This establishes INVARIANT 1 of GlobalRdrEnvs\\n add_gre env gre\\n | not (null dups) -- Same OccName defined twice\\n = do { addDupDeclErr (gre :| dups); return env }\\n\\n | otherwise\\n = return (extendGlobalRdrEnv env gre)\\n where\\n -- See Note [Reporting duplicate local declarations]\\n dups = filter isBadDupGRE\\n $ lookupGRE env (LookupOccName (greOccName gre) (RelevantGREsFOS WantBoth))\\n isBadDupGRE old_gre = isLocalGRE old_gre && greClashesWith gre old_gre\\n\\n{- Note [Fail fast on duplicate definitions]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIf there are duplicate bindings for the same thing, we want to fail\\nfast. Having two bindings for the same thing can cause follow-on errors.\\nExample (test T9975a):\\n data Test = Test { x :: Int }\\n pattern Test wat = Test { x = wat }\\nThis defines \'Test\' twice. The second defn has no field-names; and then\\nwe get an error from Test { x=wat }, saying \\"Test has no field \'x\'\\".\\n\\nEasiest thing is to bale out fast on duplicate definitions, which\\nwe do via `checkNoErrs` on `extendGlobalRdrEnvRn`.\\n\\nNote [Reporting duplicate local declarations]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn general, a single module may not define the same OccName multiple times. This\\nis checked in extendGlobalRdrEnvRn: when adding a new locally-defined GRE to the\\nGlobalRdrEnv we report an error if there are already duplicates in the\\nenvironment. This establishes INVARIANT 1 (see comments on GlobalRdrEnv in\\nGHC.Types.Name.Reader), which says that for a given OccName, all the\\nGlobalRdrElts to which it maps must have distinct \'greName\'s.\\n\\nFor example, the following will be rejected:\\n\\n f x = x\\n g x = x\\n f x = x -- Duplicate!\\n\\nUsers are allowed to introduce new GREs with the same OccName as an imported GRE,\\nas disambiguation is possible through the module system, e.g.:\\n\\n module M where\\n import N (f)\\n f x = x\\n g x = M.f x + N.f x\\n\\nIf both GREs are local, the general rule is that two GREs clash if they have\\nthe same OccName, i.e. they share a textual name and live in the same namespace.\\nHowever, there are additional clashes due to record fields:\\n\\n - a new variable clashes with previously defined record fields\\n which define field selectors,\\n\\n - a new record field shadows:\\n\\n - previously defined variables, if it defines a field selector,\\n - previously defined record fields, unless it is a duplicate record field.\\n\\nThis logic is implemented in the function \'GHC.Types.Name.Reader.greClashesWith\'.\\n\\nSee also Note [Skipping ambiguity errors at use sites of local declarations] in\\nGHC.Rename.Utils.\\n-}\\n\\n\\n{- *********************************************************************\\n* *\\n getLocalDeclBindersd@ returns the names for an HsDecl\\n It\'s used for source code.\\n\\n *** See Note [The Naming story] in GHC.Hs.Decls ****\\n* *\\n********************************************************************* -}\\n\\ngetLocalNonValBinders :: MiniFixityEnv -> HsGroup GhcPs\\n -> RnM ((TcGblEnv, TcLclEnv), NameSet)\\n-- Get all the top-level binders bound the group *except*\\n-- for value bindings, which are treated separately\\n-- Specifically we return AvailInfo for\\n-- * type decls (incl constructors and record selectors)\\n-- * class decls (including class ops)\\n-- * associated types\\n-- * foreign imports\\n-- * value signatures (in hs-boot files only)\\n\\ngetLocalNonValBinders fixity_env\\n (HsGroup { hs_valds = binds,\\n hs_tyclds = tycl_decls,\\n hs_fords = foreign_decls })\\n = do { -- Process all type/class decls *except* family instances\\n ; let inst_decls = tycl_decls >>= group_instds\\n ; dup_fields_ok <- xopt_DuplicateRecordFields <$> getDynFlags\\n ; has_sel <- xopt_FieldSelectors <$> getDynFlags\\n ; tc_gres\\n <- concatMapM\\n (new_tc dup_fields_ok has_sel)\\n (tyClGroupTyClDecls tycl_decls)\\n ; traceRn \\"getLocalNonValBinders 1\\" (ppr tc_gres)\\n ; envs <- extendGlobalRdrEnvRn tc_gres fixity_env\\n ; restoreEnvs envs $ do {\\n -- Bring these things into scope first\\n -- See Note [Looking up family names in family instances]\\n\\n -- Process all family instances\\n -- to bring new data constructors into scope\\n ; nti_gress <- mapM (new_assoc dup_fields_ok has_sel) inst_decls\\n\\n -- Finish off with value binders:\\n -- foreign decls and pattern synonyms for an ordinary module\\n -- type sigs in case of a hs-boot file only\\n ; is_boot <- tcIsHsBootOrSig\\n ; let val_bndrs\\n | is_boot = case binds of\\n ValBinds _ val_binds ->\\n -- In a hs-boot file, the value binders come from the\\n -- *signatures*, and there should be no foreign binders\\n [ L (l2l decl_loc) (unLoc n)\\n | L decl_loc (TypeSig _ _ ns _) <- (val_sigs val_binds), n <- ns]\\n _ -> panic \\"Non-ValBinds in hs-boot group\\"\\n | otherwise = for_hs_bndrs\\n ; val_gres <- mapM new_simple val_bndrs\\n\\n ; let avails = concat nti_gress ++ val_gres\\n new_bndrs = gresToNameSet avails `unionNameSet`\\n gresToNameSet tc_gres\\n ; traceRn \\"getLocalNonValBinders 2\\" (ppr avails)\\n ; envs <- extendGlobalRdrEnvRn avails fixity_env\\n ; return (envs, new_bndrs) } }\\n where\\n for_hs_bndrs :: [LocatedN RdrName]\\n for_hs_bndrs = hsForeignDeclsBinders foreign_decls\\n\\n -- the SrcSpan attached to the input should be the span of the\\n -- declaration, not just the name\\n new_simple :: LocatedN RdrName -> RnM GlobalRdrElt\\n new_simple rdr_name = do { nm <- newTopSrcBinder rdr_name\\n ; return (mkLocalVanillaGRE NoParent nm) }\\n\\n new_tc :: DuplicateRecordFields -> FieldSelectors -> LTyClDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_tc dup_fields_ok has_sel tc_decl -- NOT for type/data instances\\n = do { let TyDeclBinders (main_bndr, tc_flav) at_bndrs sig_bndrs\\n (LConsWithFields cons_with_flds flds) = hsLTyClDeclBinders tc_decl\\n ; tycon_name <- newTopSrcBinder $ la2la main_bndr\\n ; at_names <- mapM (newTopSrcBinder . la2la . fst) at_bndrs\\n ; sig_names <- mapM (newTopSrcBinder . la2la) sig_bndrs\\n ; con_names_with_flds <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst con_names_with_flds) flds\\n ; mapM_ (add_dup_fld_errs flds\') con_names_with_flds\\n ; let tc_gre = mkLocalTyConGRE (fmap (const tycon_name) tc_flav) tycon_name\\n fld_env = mk_fld_env con_names_with_flds flds\'\\n at_gres = zipWith (\\\\ (_, at_flav) at_nm -> mkLocalTyConGRE (fmap (const tycon_name) at_flav) at_nm)\\n at_bndrs at_names\\n sig_gres = map (mkLocalVanillaGRE (ParentIs tycon_name)) sig_names\\n con_gres = map (mkLocalConLikeGRE (ParentIs tycon_name)) fld_env\\n fld_gres = mkLocalFieldGREs (ParentIs tycon_name) fld_env\\n sub_gres = at_gres ++ sig_gres ++ con_gres ++ fld_gres\\n ; traceRn \\"getLocalNonValBinders new_tc\\" $\\n vcat [ text \\"tycon:\\" <+> ppr tycon_name\\n , text \\"tc_gre:\\" <+> ppr tc_gre\\n , text \\"sub_gres:\\" <+> ppr sub_gres ]\\n ; return $ tc_gre : sub_gres }\\n\\n -- Calculate the record field information, which feeds into the GlobalRdrElts\\n -- for DataCons and their fields. It\'s convenient to do this here where\\n -- we are working with a single datatype definition.\\n --\\n -- The information we needed was all set up for us:\\n -- see Note [Collecting record fields in data declarations] in GHC.Hs.Utils.\\n mk_fld_env :: [(Name, Either VisArity [Located Int])] -> IntMap FieldLabel\\n -> [(ConLikeName, ConInfo)]\\n mk_fld_env names flds =\\n [ (DataConName con, ConInfo (ConIsData (map fst names)) fld_info)\\n | (con, con_fl_indxs) <- names\\n , let fld_info = case fmap (map ((flds IntMap.!) . unLoc)) con_fl_indxs of\\n Left 0 -> ConIsNullary\\n Left arity -> ConHasPositionalArgs arity\\n Right [] -> ConIsNullary\\n Right (fld:flds) -> ConHasRecordFields $ fld NE.:| flds ]\\n\\n new_assoc :: DuplicateRecordFields -> FieldSelectors -> LInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_assoc _ _ (L _ (TyFamInstD {})) = return []\\n -- type instances don\'t bind new names\\n\\n new_assoc dup_fields_ok has_sel (L _ (DataFamInstD _ d))\\n = new_di dup_fields_ok has_sel Nothing d\\n new_assoc dup_fields_ok has_sel\\n (L _ (ClsInstD _ (ClsInstDecl { cid_poly_ty = inst_ty\\n , cid_decls = decls })))\\n = do -- First, attempt to grab the name of the class from the instance.\\n -- This step could fail if the instance is not headed by a class,\\n -- such as in the following examples:\\n --\\n -- (1) The class is headed by a bang pattern, such as in\\n -- `instance !Show Int` (#3811c)\\n -- (2) The class is headed by a type variable, such as in\\n -- `instance c` (#16385)\\n --\\n -- If looking up the class name fails, then mb_cls_gre will\\n -- be Nothing.\\n mb_cls_gre <- runMaybeT $ do\\n -- See (1) above\\n L loc cls_rdr <- MaybeT $ pure $ getLHsInstDeclClass_maybe inst_ty\\n -- See (2) above\\n MaybeT $ setSrcSpan (locA loc) $ lookupGlobalOccRn_maybe SameNameSpace cls_rdr\\n -- Assuming the previous step succeeded, process any associated data\\n -- family instances. If the previous step failed, bail out.\\n case mb_cls_gre of\\n Nothing\\n -> pure []\\n Just cls_gre\\n -> let cls_nm = greName cls_gre\\n in concatMapM (new_di dup_fields_ok has_sel (Just cls_nm) . unLoc) (data_fam_insts decls)\\n\\n data_fam_insts decls = concatMap get decls\\n where\\n get (L l (InstD _ (DataFamInstD { dfid_inst = d}))) = [L l d]\\n get _ = []\\n\\n new_di :: DuplicateRecordFields -> FieldSelectors\\n -> Maybe Name -- class name\\n -> DataFamInstDecl GhcPs\\n -> RnM [GlobalRdrElt]\\n new_di dup_fields_ok has_sel mb_cls dfid@(DataFamInstDecl { dfid_eqn = ti_decl })\\n = do { main_name <- unLoc <$> lookupFamInstName mb_cls (feqn_tycon ti_decl)\\n ; let LConsWithFields cons_with_flds flds = hsDataFamInstBinders dfid\\n ; sub_names <- mapM (\\\\(con,flds) -> (,flds) <$> newTopSrcBinder (la2la con)) cons_with_flds\\n ; flds\' <- mapM (newRecordFieldLabel dup_fields_ok has_sel $ map fst sub_names) flds\\n ; mapM_ (add_dup_fld_errs flds\') sub_names\\n ; let fld_env = mk_fld_env sub_names flds\'\\n con_gres = map (mkLocalConLikeGRE (ParentIs main_name)) fld_env\\n field_gres = mkLocalFieldGREs (ParentIs main_name) fld_env\\n -- NB: the data family name is not bound here,\\n -- so we don\'t return a GlobalRdrElt for it here!\\n ; return $ con_gres ++ field_gres }\\n\\n -- Add errors if a constructor has a duplicate record field.\\n add_dup_fld_errs :: IntMap FieldLabel\\n -> (Name, Either VisArity [Located Int])\\n -> IOEnv (Env TcGblEnv TcLclEnv) ()\\n add_dup_fld_errs all_flds (con, con_flds_or_arity)\\n | Right con_flds <- con_flds_or_arity\\n , let (_, dups) = removeDups (comparing unLoc) con_flds\\n = for_ dups $ \\\\ dup_flds ->\\n -- Report the error at the location of the second occurrence\\n -- of the duplicate field.\\n let loc =\\n case dup_flds of\\n _ :| ( L loc _ : _) -> loc\\n L loc _ :| _ -> loc\\n dup_rdrs = fmap (nameRdrName . flSelector . (all_flds IntMap.!) . unLoc) dup_flds\\n in addErrAt loc $ TcRnDuplicateFieldName (RecordFieldDecl con) dup_rdrs\\n | otherwise\\n = return ()\\n\\nnewRecordFieldLabel :: DuplicateRecordFields -> FieldSelectors -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel\\nnewRecordFieldLabel _ _ [] _ = error \\"newRecordFieldLabel: datatype has no constructors!\\"\\nnewRecordFieldLabel dup_fields_ok has_sel (dc:_) (L loc (FieldOcc _ (L _ fld)))\\n = do { selName <- newTopSrcBinder $ L (l2l loc) $ field\\n ; return $ FieldLabel { flHasDuplicateRecordFields = dup_fields_ok\\n , flHasFieldSelector = has_sel\\n , flSelector = selName } }\\n where\\n fld_occ = rdrNameOcc fld\\n dc_fs = occNameFS $ nameOccName dc\\n field\\n -- Use an Exact RdrName as-is, to preserve the bindings\\n -- of an already renamer-resolved field and its use\\n -- sites. This is needed to correctly support record\\n -- selectors in Template Haskell. See Note [Binders in\\n -- Template Haskell] in \\"GHC.ThToHs\\" and Note [Looking up\\n -- Exact RdrNames] in \\"GHC.Rename.Env\\".\\n | isExact fld\\n = assertPpr (fieldOcc_maybe fld_occ == Just dc_fs)\\n (vcat [ text \\"newRecordFieldLabel: incorrect namespace for exact Name\\" <+> quotes (ppr fld)\\n , text \\"expected namespace:\\" <+> pprNameSpace (fieldName dc_fs)\\n , text \\" actual namespace:\\" <+> pprNameSpace (occNameSpace fld_occ) ])\\n fld\\n\\n -- Field names produced by the parser are namespaced with VarName.\\n -- Here we namespace them according to the first constructor.\\n -- See Note [Record field namespacing] in GHC.Types.Name.Occurrence.\\n | otherwise\\n = mkRdrUnqual $ varToRecFieldOcc dc_fs fld_occ\\n\\n{-\\nNote [Looking up family names in family instances]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider\\n\\n module M where\\n type family T a :: *\\n type instance M.T Int = Bool\\n\\nWe might think that we can simply use \'lookupOccRn\' when processing the type\\ninstance to look up \'M.T\'. Alas, we can\'t! The type family declaration is in\\nthe *same* HsGroup as the type instance declaration. Hence, as we are\\ncurrently collecting the binders declared in that HsGroup, these binders will\\nnot have been added to the global environment yet.\\n\\nSolution is simple: process the type family declarations first, extend\\nthe environment, and then process the type instances.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Filtering imports}\\n* *\\n************************************************************************\\n\\n@filterImports@ takes the @ExportEnv@ telling what the imported module makes\\navailable, and filters it through the import spec (if any).\\n\\nNote [Dealing with imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nFor import M( ies ), we take each AvailInfo from the mi_exports of M, and make\\n\\n imp_occ_env :: OccEnv (NameEnv ImpOccItem)\\n\\nThis map contains one entry for each OccName that M exports, mapping each OccName\\nto the following information:\\n\\n 1. the GlobalRdrElt corresponding to the OccName,\\n 2. whether this GlobalRdrElt was the parent in the AvailInfo we found\\n the OccName in.\\n 3. the GlobalRdrElts that were bundled together in the AvailInfo we found\\n this OccName in (not including the parent),\\n\\nWe need (2) and (3) during the construction of the OccEnv because of associated\\ntypes and bundled pattern synonyms, respectively.\\n(3) is explained in Note [Importing PatternSynonyms].\\n\\nTo explain (2), consider for example:\\n\\n module M where\\n class C a where { data T a }\\n instance C Int where { data T Int = T1 | T2 }\\n instance C Bool where { data T Int = T3 }\\n\\nHere, M\'s exports avails are (recalling the AvailTC invariant from GHC.Types.Avail)\\n\\n C(C,T), T(T,T1,T2,T3)\\n\\nNotice that T appears *twice*, once as a child and once as a parent. From\\nthese two exports, respectively, during construction of the imp_occ_env, we begin\\nby associating the following two elements with the key T:\\n\\n T -> ImpOccItem { imp_item = gre1, imp_bundled = [C,T] , imp_is_parent = False }\\n T -> ImpOccItem { imp_item = gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nwhere `gre1`, `gre2` are two GlobalRdrElts with greName T.\\nWe combine these (in function \'combine\' in \'mkImportOccEnv\') by discarding the\\nnon-parent item, thusly:\\n\\n T -> IE_ITem { imp_item = gre1 `plusGRE` gre2, imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n\\nNote the `plusGRE`: this ensures we don\'t drop parent information;\\nsee Note [Preserve parent information when combining import OccEnvs].\\n\\nSo the overall imp_occ_env is:\\n\\n C -> ImpOccItem { imp_item = C, imp_bundled = [T ], imp_is_parent = True }\\n T -> ImpOccItem { imp_item = T , imp_bundled = [T1,T2,T3], imp_is_parent = True }\\n T1 -> ImpOccItem { imp_item = T1, imp_bundled = [T1,T2,T3], imp_is_parent = False }\\n -- similarly for T2, T3\\n\\nNote that the imp_occ_env will have entries for data constructors too,\\nalthough we never look up data constructors.\\n\\nNote [Importing PatternSynonyms]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nAs described in Note [Dealing with imports], associated types can lead to the\\nsame Name appearing twice, both as a child and once as a parent, when\\nconstructing the imp_occ_env. The same thing can happen with pattern synonyms\\nif they are exported bundled with a type.\\n\\nA simplified example, based on #11959:\\n\\n {-# LANGUAGE PatternSynonyms #-}\\n module M (T(P), pattern P) where -- Duplicate export warning, but allowed\\n data T = MkT\\n pattern P = MkT\\n\\nHere we have T(P) and P in export_avails, and respectively construct both\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n P -> ImpOccItem { imp_item = P, imp_bundled = [] , imp_is_parent = False }\\n\\nWe combine these by dropping the one with no siblings, leaving us with:\\n\\n P -> ImpOccItem { imp_item = P, imp_bundled = [P], imp_is_parent = False }\\n\\nThat is, we simply discard the non-bundled Avail.\\n\\nNote [Importing DuplicateRecordFields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nIn filterImports, another complicating factor is DuplicateRecordFields.\\nSuppose we have:\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (S(foo), T(foo)) where\\n data S = MkS { foo :: Int }\\n data T = MkT { foo :: Int }\\n\\n module N where\\n import M (foo) -- this is allowed (A)\\n import M (S(foo)) -- this is allowed (B)\\n\\nHere M exports \'foo\' at two different OccNames, with different namespaces for\\nthe two construtors MkS and MkT. Then, when we look up \'foo\' in lookup_names\\nfor case (A), we have a variable foo but must look in all the record field\\nnamespaces to find the two fields (and hence two different Avails).\\nWhereas in case (B) we reach the lookup_ie case for IEThingWith,\\nwhich looks up \'S\' and then finds the unique \'foo\' amongst its children.\\n\\nSee T16745 for a test of this.\\n\\nNote [Preserve parent information when combining import OccEnvs]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWhen discarding one ImpOccItem in favour of another, as described in\\nNote [Dealing with imports], we must make sure to combine the GREs so that\\nwe don\'t lose information.\\n\\nConsider for example #24084:\\n\\n module M1 where { class C a where { type T a } }\\n module M2 ( module M1 ) where { import M1 }\\n module M3 where { import M2 ( C, T ); instance C () where T () = () }\\n\\nWhen processing the import list of `M3`, we will have two `Avail`s attached\\nto `T`, namely `C(C, T)` and `T(T)`. We combine them in the `combine` function\\nof `mkImportOccEnv`; as described in Note [Dealing with imports] we discard\\n`C(C, T)` in favour of `T(T)`. However, in doing so, we **must not**\\ndiscard the information want that `C` is the parent of `T`. Indeed,\\nlosing track of this information can cause errors when importing,\\nas we could get an error of the form\\n\\n \\u2018T\\u2019 is not a (visible) associated type of class \\u2018C\\u2019\\n\\nThis explains why we use `plusGRE` when combining the two ImpOccItems, even\\nthough we are discarding one in favour of the other.\\n-}\\n\\n-- | All the \'GlobalRdrElt\'s associated with an \'AvailInfo\'.\\ngresFromAvail :: HasDebugCallStack\\n => HscEnv -> Maybe ImportSpec -> AvailInfo -> [GlobalRdrElt]\\ngresFromAvail hsc_env prov avail =\\n [ mk_gre nm info\\n | nm <- availNames avail\\n , let info = lookupGREInfo hsc_env nm ]\\n where\\n\\n mk_gre n info\\n = case prov of\\n -- Nothing => bound locally\\n -- Just is => imported from \'is\'\\n Nothing -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = True, gre_imp = emptyBag\\n , gre_info = info }\\n Just is -> GRE { gre_name = n, gre_par = mkParent n avail\\n , gre_lcl = False, gre_imp = unitBag is\\n , gre_info = info }\\n\\n-- | All the \'GlobalRdrElt\'s associated with a collection of \'AvailInfo\'s.\\ngresFromAvails :: HscEnv -> Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]\\ngresFromAvails hsc_env prov = concatMap (gresFromAvail hsc_env prov)\\n\\nimportsFromIface :: HscEnv -> ModIface -> ImpDeclSpec -> Maybe NameSet -> GlobalRdrEnv\\nimportsFromIface hsc_env iface decl_spec hidden = mkGlobalRdrEnv $ case hidden of\\n Nothing -> all_gres\\n Just hidden_names -> filter (not . (`elemNameSet` hidden_names) . greName) all_gres\\n where\\n all_gres = gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\nrnNamespaceSpecifier :: NamespaceSpecifier GhcPs -> NamespaceSpecifier GhcRn\\nrnNamespaceSpecifier (NoNamespaceSpecifier _) = NoNamespaceSpecifier noExtField\\nrnNamespaceSpecifier (TypeNamespaceSpecifier x) = TypeNamespaceSpecifier x\\nrnNamespaceSpecifier (DataNamespaceSpecifier x) = DataNamespaceSpecifier x\\n\\nfilterImports\\n :: HasDebugCallStack\\n => HscEnv\\n -> ModIface\\n -> ImpDeclSpec\\n -- ^ Import spec\\n -> Maybe (ImportListInterpretation, [LIE GhcPs])\\n -- ^ Whether this is a \\"hiding\\" import list\\n -> RnM (Maybe (ImportListInterpretation, [LIE GhcRn]), -- Import spec w/ Names\\n ImpUserList, -- same, but designed for storage in interfaces\\n GlobalRdrEnv) -- Same again, but in GRE form\\nfilterImports hsc_env iface decl_spec Nothing\\n = return (Nothing, ImpUserAll, importsFromIface hsc_env iface decl_spec Nothing)\\nfilterImports hsc_env iface decl_spec (Just (want_hiding, import_items))\\n = do -- check for errors, convert RdrNames to Names\\n items1 <- mapM lookup_lie import_items\\n\\n let items2 :: [(LIE GhcRn, [GlobalRdrElt])]\\n items2 = concat items1\\n -- NB we may have duplicates, and several items\\n -- for the same parent; e.g N(x) and N(y)\\n\\n (gres, imp_user_list) = case want_hiding of\\n Exactly ->\\n let gres = concatMap (gresFromIE decl_spec) items2\\n gre_env = mkGlobalRdrEnv gres\\n implicit_parents = mkNameSet $ mapMaybe parentOfImplicitlyImportedGRE gres\\n in (gre_env, ImpUserExplicit (gresToAvailInfo $ globalRdrEnvElts $ gre_env) implicit_parents)\\n EverythingBut ->\\n let hidden_names = mkNameSet $ concatMap (map greName . snd) items2\\n in (importsFromIface hsc_env iface decl_spec (Just hidden_names), ImpUserEverythingBut hidden_names)\\n\\n return (Just (want_hiding, map fst items2), imp_user_list, gres)\\n where\\n import_mod = mi_module iface\\n all_avails = mi_exports iface\\n imp_occ_env = mkImportOccEnv hsc_env decl_spec all_avails\\n\\n -- Look up a parent (type constructor, class or data constructor)\\n -- in an import.\\n lookup_parent :: IE GhcPs -> RdrName -> IELookupM ImpOccItem\\n lookup_parent ie rdr =\\n assertPpr (not $ isVarNameSpace ns)\\n (vcat [ text \\"filterImports lookup_parent: unexpected variable\\"\\n , text \\"rdr:\\" <+> ppr rdr\\n , text \\"namespace:\\" <+> pprNameSpace ns ]) $\\n do { xs <- lookup_names ie rdr\\n ; case xs of\\n cax :| [] -> return cax\\n _ -> pprPanic \\"filter_imports lookup_parent ambiguous\\" $\\n vcat [ text \\"rdr:\\" <+> ppr rdr\\n , text \\"lookups:\\" <+> ppr (fmap imp_item xs) ] }\\n -- Looking up non-variables is always unambiguous,\\n -- as there can be at most one corresponding item\\n -- in the imp_occ_env.\\n -- See item (1) of Note [Exporting duplicate declarations]\\n -- in GHC.Tc.Gen.Export.\\n where\\n occ = rdrNameOcc rdr\\n ns = occNameSpace occ\\n\\n -- Look up a RdrName used in an import, returning multiple values if there\\n -- are several fields with the same name exposed by the module\\n lookup_names :: IE GhcPs -> RdrName -> IELookupM (NonEmpty ImpOccItem)\\n lookup_names ie rdr\\n | isQual rdr\\n = failLookupWith (QualImportError rdr)\\n | otherwise\\n = case lookups of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n item:items -> return $ item :| items\\n where\\n lookups = concatMap nonDetNameEnvElts\\n $ lookupImpOccEnv (RelevantGREsFOS WantNormal) imp_occ_env (rdrNameOcc rdr)\\n\\n lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, [GlobalRdrElt])]\\n lookup_lie (L loc ieRdr)\\n = setSrcSpanA loc $\\n do (stuff, warns) <- run_lookup ([],[]) (lookup_ie ieRdr)\\n mapM_ (addTcRnDiagnostic <=< warning_msg) warns\\n return [ (L loc ie, gres) | (ie,gres) <- stuff ]\\n where\\n\\n -- Warn when importing T(..) and no children are brought in scope\\n warning_msg (DodgyImport reason) =\\n pure (TcRnDodgyImports reason)\\n warning_msg MissingImportList =\\n pure (TcRnMissingImportList ieRdr)\\n warning_msg (BadImportW ie sub) = do\\n -- \'BadImportW\' is only constructed below in \'bad_import_w\', in\\n -- the \'EverythingBut\' case, so here we assume a \'hiding\' clause.\\n (reason :| _) <- badImportItemErr iface decl_spec ie sub all_avails\\n pure (TcRnDodgyImports (DodgyImportsHiding reason))\\n warning_msg (DeprecatedExport n w) =\\n pure $ TcRnPragmaWarning\\n PragmaWarningExport\\n { pwarn_occname = occName n\\n , pwarn_impmod = moduleName import_mod }\\n w\\n\\n run_lookup :: a -> IELookupM a -> TcRn a\\n run_lookup def m = case m of\\n Failed err -> do\\n msgs <- lookup_err_msgs err\\n forM_ msgs $ \\\\msg -> addErr (TcRnImportLookup msg)\\n return def\\n Succeeded a -> return a\\n\\n lookup_err_msgs err = case err of\\n BadImport ie sub -> badImportItemErr iface decl_spec ie sub all_avails\\n IllegalImport -> pure $ NE.singleton ImportLookupIllegal\\n QualImportError rdr -> pure $ NE.singleton (ImportLookupQualified rdr)\\n\\n -- For each import item, we convert its RdrNames to Names,\\n -- and at the same time compute all the GlobalRdrElt corresponding\\n -- to what is actually imported by this item.\\n -- Returns Nothing on error.\\n --\\n -- Returns a list because, with DuplicateRecordFields, a naked\\n -- import/export of a record field can correspond to multiple\\n -- different GlobalRdrElts. See Note [Importing DuplicateRecordFields].\\n lookup_ie :: IE GhcPs\\n -> IELookupM ([(IE GhcRn, [GlobalRdrElt])], [IELookupWarning])\\n lookup_ie ie = handle_bad_import $\\n case ie of\\n IEVar _ (L l n) _ -> do\\n -- See Note [Importing DuplicateRecordFields]\\n xs <- lookup_names ie (ieWrappedName n)\\n let gres = map imp_item $ NE.toList xs\\n export_depr_warns\\n | want_hiding == Exactly\\n = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ( [ (IEVar Nothing (L l (replaceWrappedName n name)) noDocstring, [gre])\\n | gre <- gres\\n , let name = greName gre ]\\n , export_depr_warns )\\n\\n IEThingAll x ns_spec (L l tc) _ -> do\\n ImpOccItem { imp_item = gre\\n , imp_bundled = bundled_gres\\n , imp_is_parent = is_par\\n }\\n <- lookup_parent ie $ ieWrappedName tc\\n let name = greName gre\\n\\n child_gres :: [GlobalRdrElt]\\n child_gres\\n | is_par = filterByNamespaceSpecifierGREs ns_spec bundled_gres\\n | otherwise = []\\n\\n imp_list_warn\\n\\n | null child_gres\\n -- e.g. f(..) or T(..) where T is a type synonym\\n = [DodgyImport (DodgyImportsEmptyParent ie ns_spec gre)]\\n\\n -- e.g. import M( T(..) )\\n | not (is_qual decl_spec)\\n = [MissingImportList]\\n\\n | otherwise\\n = []\\n\\n renamed_ie = IEThingAll (x { ieta_warning = Nothing })\\n (rnNamespaceSpecifier ns_spec)\\n (L l (replaceWrappedName tc name))\\n noDocstring\\n export_depr_warn\\n | want_hiding == Exactly\\n = maybeToList $ mk_depr_export_warning gre\\n -- We don\'t want to warn about the children as they\\n -- are not explicitly mentioned; the warning will\\n -- be emitted later on if they are used\\n | otherwise = []\\n\\n return ( [(renamed_ie, gre:child_gres)]\\n , imp_list_warn ++ export_depr_warn)\\n\\n\\n IEThingAbs _ (L l tc\') _\\n | want_hiding == EverythingBut -- hiding ( C )\\n -- Here the \'C\' can be a data constructor\\n -- *or* a type/class, or even both\\n -> let tc = ieWrappedName tc\'\\n tc_name = lookup_parent ie tc\\n dc_name = lookup_parent ie (setRdrNameSpace tc srcDataName)\\n in\\n case catIELookupM [ tc_name, dc_name ] of\\n [] -> failLookupWith (BadImport ie IsNotSubordinate)\\n names -> return ( [mkIEThingAbs tc\' l (imp_item name) | name <- names], [])\\n | otherwise\\n -> do ImpOccItem { imp_item = gre } <- lookup_parent ie (ieWrappedName tc\')\\n return ( [mkIEThingAbs tc\' l gre]\\n , maybeToList $ mk_depr_export_warning gre)\\n\\n IEThingWith (deprecation, ann) ltc@(L l rdr_tc) wc rdr_ns _ -> do\\n ImpOccItem { imp_item = gre, imp_bundled = subnames }\\n <- lookup_parent (IEThingAbs Nothing ltc noDocstring) (ieWrappedName rdr_tc)\\n let name = greName gre\\n\\n -- Look up the children in the sub-names of the parent\\n -- See Note [Importing DuplicateRecordFields]\\n let (children_errs, childnames) = lookupChildren subnames rdr_ns\\n\\n bad_import_warns <-\\n if null children_errs then return [] else\\n let items = map lce_wrapped_name children_errs\\n ie = IEThingWith (deprecation, ann) ltc wc items noDocstring\\n -- We are trying to import T( a,b,c,d ), and failed\\n -- to find \'b\' and \'d\'. So we make up an import item\\n -- to report as failing, namely T( b, d ).\\n -- c.f. #15413\\n subordinate_err = mkSubordinateError gre children_errs\\n in bad_import_w ie subordinate_err\\n\\n let name\' = replaceWrappedName rdr_tc name\\n childnames\' = map (to_ie_post_rn . fmap greName) childnames\\n gres = gre : map unLoc childnames\\n export_depr_warns\\n | want_hiding == Exactly = mapMaybe mk_depr_export_warning gres\\n | otherwise = []\\n return ([ (IEThingWith (Nothing, ann) (L l name\') wc childnames\' noDocstring\\n ,gres)]\\n , bad_import_warns ++ export_depr_warns)\\n\\n IEWholeNamespace x ns_spec -> do\\n let mod_name = moduleName import_mod\\n names = map greName gres\\n renamed_ie = IEWholeNamespace x { iewn_warning = Nothing\\n , iewn_names = names }\\n (rnNamespaceSpecifier ns_spec)\\n gres = filterByNamespaceSpecifierGREs ns_spec $\\n gresFromAvails hsc_env (Just imp_spec) (mi_exports iface)\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n dodgy_warn\\n | null gres = [DodgyImport (DodgyImportsWildcard mod_name ns_spec)]\\n | otherwise = []\\n return ([(renamed_ie, gres)],\\n dodgy_warn)\\n\\n _other -> failLookupWith IllegalImport\\n -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed...\\n -- all of those constitute errors.\\n\\n where\\n mkIEThingAbs tc l gre\\n = (IEThingAbs Nothing (L l (replaceWrappedName tc n)) noDocstring, [gre])\\n where n = greName gre\\n\\n -- N.B. imports never have docstrings\\n noDocstring = Nothing\\n\\n handle_bad_import m = catchIELookup m $ \\\\case\\n BadImport ie sub -> do\\n ws <- bad_import_w ie sub\\n return ([], ws)\\n err -> failLookupWith err\\n\\n bad_import_w :: IE GhcPs -> IsSubordinateError -> IELookupM [IELookupWarning]\\n bad_import_w ie sub\\n | want_hiding == EverythingBut = return [BadImportW ie sub]\\n | otherwise = failLookupWith (BadImport ie sub)\\n\\n mk_depr_export_warning gre\\n = DeprecatedExport name <$> mi_export_warn_fn iface name\\n where\\n name = greName gre\\n\\n-- | Assuming a subordinate item could not be found, do another lookup for a\\n-- more specific error message.\\nmkBadExportSubordinate :: [GlobalRdrElt] -> LIEWrappedName GhcPs -> BadExportSubordinate\\nmkBadExportSubordinate child_gres n =\\n case lookupChildren child_gres [n] of\\n (LookupChildNonType {lce_nontype_item = g} : _, _) -> BadExportSubordinateNonType g\\n (LookupChildNonData {lce_nondata_item = g} : _, _) -> BadExportSubordinateNonData g\\n _ -> BadExportSubordinateNotFound n\\n\\ntype IELookupM = MaybeErr IELookupError\\n\\ndata IELookupWarning\\n = BadImportW (IE GhcPs) IsSubordinateError\\n | MissingImportList\\n | DodgyImport DodgyImportsReason\\n | DeprecatedExport Name (WarningTxt GhcRn)\\n\\n-- | Is this import/export item a subordinate or not?\\ndata IsSubordinateError\\n = IsSubordinateError { subordinate_err_parent :: !GlobalRdrElt\\n , subordinate_err_unavailable :: [FastString]\\n , subordinate_err_nontype :: [GlobalRdrElt]\\n , subordinate_err_nondata :: [GlobalRdrElt] }\\n | IsNotSubordinate\\n\\nmkSubordinateError :: GlobalRdrElt -> [LookupChildError] -> IsSubordinateError\\nmkSubordinateError gre children_errs = foldr add init_acc children_errs\\n where\\n init_acc :: IsSubordinateError\\n init_acc = IsSubordinateError gre [] [] []\\n\\n add :: LookupChildError -> IsSubordinateError -> IsSubordinateError\\n add children_err sub@IsSubordinateError{} =\\n case children_err of\\n LookupChildNonType{lce_nontype_item = g} ->\\n sub { subordinate_err_nontype = g : subordinate_err_nontype sub }\\n LookupChildNonData{lce_nondata_item = g} ->\\n sub { subordinate_err_nondata = g : subordinate_err_nondata sub }\\n LookupChildNotFound (L _ wname) ->\\n let fs = (occNameFS . rdrNameOcc . ieWrappedName) wname\\n in sub { subordinate_err_unavailable = fs : subordinate_err_unavailable sub }\\n add _ IsNotSubordinate = panic \\"mkSubordinateError: IsNotSubordinate\\"\\n\\ndata IELookupError\\n = QualImportError RdrName\\n | BadImport (IE GhcPs) IsSubordinateError\\n | IllegalImport\\n\\nfailLookupWith :: IELookupError -> IELookupM a\\nfailLookupWith err = Failed err\\n\\ncatchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a\\ncatchIELookup m h = case m of\\n Succeeded r -> return r\\n Failed err -> h err\\n\\ncatIELookupM :: [IELookupM a] -> [a]\\ncatIELookupM ms = [ a | Succeeded a <- ms ]\\n\\n-- | Information associated to an \'AvailInfo\' used in constructing\\n-- an \'OccEnv\' corresponding to imports.\\n--\\n-- See Note [Dealing with imports].\\ndata ImpOccItem\\n = ImpOccItem\\n { imp_item :: GlobalRdrElt\\n -- ^ The import item\\n , imp_bundled :: [GlobalRdrElt]\\n -- ^ Items bundled in the Avail this import item came from,\\n -- not including the import item itself if it is a parent.\\n , imp_is_parent :: Bool\\n -- ^ Is the import item a parent? See Note [Dealing with imports].\\n }\\n\\ninstance Outputable ImpOccItem where\\n ppr (ImpOccItem { imp_item = item, imp_bundled = bundled, imp_is_parent = is_par })\\n = braces $ hsep\\n [ text \\"ImpOccItem\\"\\n , if is_par then text \\"[is_par]\\" else empty\\n , ppr (greName item) <+> ppr (greParent item)\\n , braces $ text \\"bundled:\\" <+> ppr (map greName bundled) ]\\n\\n-- | Make an \'OccEnv\' of all the imports.\\n--\\n-- Complicated by the fact that associated data types and pattern synonyms\\n-- can appear twice. See Note [Dealing with imports].\\nmkImportOccEnv :: HscEnv -> ImpDeclSpec -> [IfaceExport] -> OccEnv (NameEnv ImpOccItem)\\nmkImportOccEnv hsc_env decl_spec all_avails =\\n mkOccEnv_C (plusNameEnv_C combine)\\n [ (occ, mkNameEnv [(nm, item)])\\n | avail <- all_avails\\n , let gres = gresFromAvail hsc_env (Just hiding_spec) avail\\n , gre <- gres\\n , let nm = greName gre\\n occ = greOccName gre\\n (is_parent, bundled) = case avail of\\n AvailTC c _\\n | c == nm -- (Recall the AvailTC invariant from GHC.Types.AvailInfo)\\n -> ( True, drop 1 gres ) -- \\"drop 1\\": don\'t include the parent itself.\\n | otherwise\\n -> ( False, gres )\\n _ -> ( False, [] )\\n item = ImpOccItem\\n { imp_item = gre\\n , imp_bundled = bundled\\n , imp_is_parent = is_parent }\\n ]\\n where\\n\\n hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n\\n -- See Note [Dealing with imports]\\n -- \'combine\' may be called for associated data types which appear\\n -- twice in the all_avails. In the example, we have two Avails for T,\\n -- namely T(T,T1,T2,T3) and C(C,T), and we combine them by dropping the\\n -- latter, in which T is not the parent.\\n combine :: ImpOccItem -> ImpOccItem -> ImpOccItem\\n combine item1@(ImpOccItem { imp_item = gre1, imp_is_parent = is_parent1 })\\n item2@(ImpOccItem { imp_item = gre2, imp_is_parent = is_parent2 })\\n | is_parent1 || is_parent2\\n , not (isRecFldGRE gre1 || isRecFldGRE gre2) -- NB: does not force GREInfo.\\n , let name1 = greName gre1\\n name2 = greName gre2\\n gre = gre1 `plusGRE` gre2\\n -- See Note [Preserve parent information when combining import OccEnvs]\\n = assertPpr (name1 == name2)\\n (ppr name1 <+> ppr name2) $\\n if is_parent1\\n then item1 { imp_item = gre }\\n else item2 { imp_item = gre }\\n -- Discard C(C,T) in favour of T(T, T1, T2, T3).\\n\\n -- \'combine\' may also be called for pattern synonyms which appear both\\n -- unassociated and associated (see Note [Importing PatternSynonyms]).\\n combine item1@(ImpOccItem { imp_item = c1, imp_bundled = kids1 })\\n item2@(ImpOccItem { imp_item = c2, imp_bundled = kids2 })\\n = assertPpr (greName c1 == greName c2\\n && (not (null kids1 && null kids2)))\\n (ppr c1 <+> ppr c2 <+> ppr kids1 <+> ppr kids2) $\\n if null kids1\\n then item2\\n else item1\\n -- Discard standalone pattern P in favour of T(P).\\n\\n-- | Essentially like @lookupGRE env (LookupOccName occ which_gres)@,\\n-- but working with \'ImpOccItem\'s instead of \'GlobalRdrElt\'s.\\nlookupImpOccEnv :: WhichGREs GREInfo\\n -> OccEnv (NameEnv ImpOccItem) -> OccName -> [NameEnv ImpOccItem]\\nlookupImpOccEnv which_gres env occ =\\n mapMaybe relevant_items $ lookupOccEnv_AllNameSpaces env occ\\n where\\n is_relevant :: ImpOccItem -> Bool\\n is_relevant (ImpOccItem { imp_item = gre }) =\\n greIsRelevant which_gres (occNameSpace occ) gre\\n relevant_items :: NameEnv ImpOccItem -> Maybe (NameEnv ImpOccItem)\\n relevant_items nms\\n | let nms\' = filterNameEnv is_relevant nms\\n = if isEmptyNameEnv nms\'\\n then Nothing\\n else Just nms\'\\n\\n{-\\n************************************************************************\\n* *\\n\\\\subsection{Import/Export Utils}\\n* *\\n************************************************************************\\n-}\\n\\n-- | Given an import\\\\/export spec, appropriately set the @gre_imp@ field\\n-- for the \'GlobalRdrElt\'s.\\ngresFromIE :: ImpDeclSpec -> (LIE GhcRn, [GlobalRdrElt]) -> [GlobalRdrElt]\\ngresFromIE decl_spec (L loc ie, gres)\\n = map set_gre_imp gres\\n where\\n is_explicit = case ie of\\n IEThingAll _ _ name _ -> \\\\n -> n == lieWrappedName name\\n IEWholeNamespace _ _ -> \\\\_ -> False\\n _ -> \\\\_ -> True\\n prov_fn name\\n = ImpSpec { is_decl = decl_spec, is_item = item_spec }\\n where\\n item_spec = ImpSome { is_explicit = is_explicit name\\n , is_iloc = locA loc }\\n set_gre_imp gre@( GRE { gre_name = nm } )\\n = gre { gre_imp = unitBag $ prov_fn nm }\\n\\nparentOfImplicitlyImportedGRE :: Outputable info => GlobalRdrEltX info -> Maybe Name\\nparentOfImplicitlyImportedGRE gre =\\n if any (explicit_import . is_item) $ gre_imp gre\\n then Nothing\\n else greParent_maybe gre\\n where\\n explicit_import :: ImpItemSpec -> Bool\\n explicit_import (ImpAll {}) =\\n pprPanic \\"parentOfImplicitlyImportedGRE: ImpAll\\" (ppr gre)\\n explicit_import (ImpSome { is_explicit }) = is_explicit\\n\\n{- Note [Children for duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider the module\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M (F(foo, MkFInt, MkFBool)) where\\n data family F a\\n data instance F Int = MkFInt { foo :: Int }\\n data instance F Bool = MkFBool { foo :: Bool }\\n\\nThe `foo` in the export list refers to *both* selectors! For this\\nreason, lookupChildren builds an environment that maps the FastString\\nto a list of items, rather than a single item.\\n-}\\n\\nmkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]\\nmkChildEnv gres = foldr add emptyNameEnv gres\\n where\\n add gre env = case greParent gre of\\n ParentIs p -> extendNameEnv_Acc (:) Utils.singleton env p gre\\n NoParent -> env\\n\\nfindChildren :: NameEnv [a] -> Name -> [a]\\nfindChildren env n = lookupNameEnv env n `orElse` []\\n\\ndata LookupChildError\\n = LookupChildNotFound { lce_wrapped_name :: !(LIEWrappedName GhcPs) }\\n | LookupChildNonType { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nontype_item :: !GlobalRdrElt }\\n | LookupChildNonData { lce_wrapped_name :: !(LIEWrappedName GhcPs)\\n , lce_nondata_item :: !GlobalRdrElt }\\n\\nlookupChildren :: [GlobalRdrElt]\\n -> [LIEWrappedName GhcPs]\\n -> ( [LookupChildError] -- The ones for which the lookup failed\\n , [LocatedA GlobalRdrElt] )\\n-- (lookupChildren all_kids rdr_items) maps each rdr_item to its\\n-- corresponding Name in all_kids, if the former exists\\n-- The matching is done by FastString, not OccName, so that\\n-- Cls( meth, AssocTy )\\n-- will correctly find AssocTy among the all_kids of Cls, even though\\n-- the RdrName for AssocTy may have a (bogus) DataName namespace\\n-- (Really the rdr_items should be FastStrings in the first place.)\\nlookupChildren all_kids rdr_items = (fails, successes)\\n where\\n mb_xs = map do_one rdr_items\\n fails = [ err | Failed err <- mb_xs ]\\n successes = [ ok | Succeeded oks <- mb_xs, ok <- NE.toList oks ]\\n\\n do_one :: LIEWrappedName GhcPs -> MaybeErr LookupChildError (NonEmpty (LocatedA GlobalRdrElt))\\n do_one item@(L l r) =\\n case r of\\n IEName{}\\n -- IEName (unadorned name) places no restriction on the namespace of\\n -- the imported entity, so we look in both `val_gres` and `typ_gres`.\\n -- In case of conflict (punning), the value namespace takes priority.\\n -- See Note [Prioritise the value namespace in subordinate import lists]\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEType{}\\n -- IEType (\'type\' namespace specifier) restricts the lookup to the\\n -- type namespace, i.e. to `typ_gres`. In case of failure, we check\\n -- `val_gres` to produce a more helpful error message.\\n | (gre:gres) <- typ_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- val_gres -> Failed $ LookupChildNonType item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEData{}\\n -- IEData (\'data\' namespace specifier) restricts the lookup to the\\n -- data namespace, i.e. to `val_gres`. In case of failure, we check\\n -- `typ_gres` to produce a more helpful error message.\\n | (gre:gres) <- val_gres -> Succeeded $ fmap (L l) (gre:|gres)\\n | (gre:_) <- typ_gres -> Failed $ LookupChildNonData item gre\\n | otherwise -> Failed $ LookupChildNotFound item\\n\\n IEPattern{} -> panic \\"lookupChildren: IEPattern\\" -- Never happens (invalid syntax)\\n IEDefault{} -> panic \\"lookupChildren: IEDefault\\" -- Never happens (invalid syntax)\\n where\\n fs = (occNameFS . rdrNameOcc . ieWrappedName) r\\n gres = fromMaybe [] (lookupFsEnv kid_env fs)\\n (val_gres, typ_gres) = partition (isValNameSpace . greNameSpace) gres\\n\\n -- See Note [Children for duplicate record fields]\\n kid_env :: FastStringEnv [GlobalRdrElt]\\n kid_env = extendFsEnvList_C (++) emptyFsEnv\\n [(occNameFS (occName x), [x]) | x <- all_kids]\\n\\n\\n{- Note [Prioritise the value namespace in subordinate import lists]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nConsider this program that defines a class that has both an associated type\\nnamed (#) and a method named (#)\\n\\n module M_assoc where\\n class C a b where\\n type a # b\\n (#) :: a -> b -> ()\\n module N_assoc where\\n import M_assoc( C((#)) )\\n\\nIn the import declaration, when we see the unadorned name (#) in the subordinate\\nimport list of C, which children should we bring into scope? Our options are:\\n\\n a) only the method (#)\\n b) only the associated type (#)\\n c) both the method and the associated type\\n\\nTo follow the precedent established by top-level items, we go with option (a).\\nIndeed, consider a slightly different program\\n\\n module M_top where\\n type family a # b\\n a # b = ()\\n module N_top where\\n import M_top( (#) )\\n\\nHere the import brings only the function (#) into scope, and one has to say\\n`type (#)` to get the type family.\\n-}\\n\\n-------------------------------\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused names}\\n* *\\n*********************************************************\\n-}\\n\\nreportUnusedNames :: TcGblEnv -> HscSource -> RnM ()\\nreportUnusedNames gbl_env hsc_src\\n = do { keep <- readTcRef (tcg_keep gbl_env)\\n ; traceRn \\"RUN\\" (ppr (tcg_dus gbl_env))\\n ; warnUnusedImportDecls gbl_env hsc_src\\n ; warnUnusedTopBinds $ unused_locals keep\\n ; warnMissingSignatures gbl_env\\n ; warnMissingKindSignatures gbl_env }\\n where\\n used_names :: NameSet -> NameSet\\n used_names keep = findUses (tcg_dus gbl_env) emptyNameSet `unionNameSet` keep\\n -- NB: currently, if f x = g, we only treat \'g\' as used if \'f\' is used\\n -- Hence findUses\\n\\n -- Collect the defined names from the in-scope environment\\n defined_names :: [GlobalRdrElt]\\n defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)\\n\\n kids_env = mkChildEnv defined_names\\n -- This is done in mkExports too; duplicated work\\n\\n gre_is_used :: NameSet -> GlobalRdrElt -> Bool\\n gre_is_used used_names gre0\\n = name `elemNameSet` used_names\\n || any (\\\\ gre -> greName gre `elemNameSet` used_names) (findChildren kids_env name)\\n -- A use of C implies a use of T,\\n -- if C was brought into scope by T(..) or T(C)\\n where\\n name = greName gre0\\n\\n -- Filter out the ones that are\\n -- (a) defined in this module, and\\n -- (b) not defined by a \'deriving\' clause\\n -- The latter have an Internal Name, so we can filter them out easily\\n unused_locals :: NameSet -> [GlobalRdrElt]\\n unused_locals keep =\\n let -- Note that defined_and_used, defined_but_not_used\\n -- are both [GRE]; that\'s why we need defined_and_used\\n -- rather than just used_names\\n _defined_and_used, defined_but_not_used :: [GlobalRdrElt]\\n (_defined_and_used, defined_but_not_used)\\n = partition (gre_is_used (used_names keep)) defined_names\\n\\n in filter is_unused_local defined_but_not_used\\n is_unused_local :: GlobalRdrElt -> Bool\\n is_unused_local gre = isLocalGRE gre\\n && isExternalName (greName gre)\\n\\n{- *********************************************************************\\n* *\\n Missing signatures\\n* *\\n********************************************************************* -}\\n\\n{-\\nNote [Missing signatures]\\n~~~~~~~~~~~~~~~~~~~~~~~~~\\nThere are four warning flags in play:\\n\\n * -Wmissing-exported-signatures\\n Warn about any exported top-level function/value without a type signature.\\n Does not include pattern synonyms.\\n\\n * -Wmissing-signatures\\n Warn about any top-level function/value without a type signature. Does not\\n include pattern synonyms. Takes priority over -Wmissing-exported-signatures.\\n\\n * -Wmissing-exported-pattern-synonym-signatures\\n Warn about any exported pattern synonym without a type signature.\\n\\n * -Wmissing-pattern-synonym-signatures\\n Warn about any pattern synonym without a type signature. Takes priority over\\n -Wmissing-exported-pattern-synonym-signatures.\\n\\n-}\\n\\n-- | Warn the user about top level binders that lack type signatures.\\n-- Called /after/ type inference, so that we can report the\\n-- inferred type of the function\\nwarnMissingSignatures :: TcGblEnv -> RnM ()\\nwarnMissingSignatures gbl_env\\n = do { let exports = availsToNameSet (tcg_exports gbl_env)\\n sig_ns = tcg_sigs gbl_env\\n -- We use sig_ns to exclude top-level bindings that are generated by GHC\\n binds = collectHsBindsBinders CollNoDictBinders $ tcg_binds gbl_env\\n pat_syns = tcg_patsyns gbl_env\\n\\n not_ghc_generated :: Name -> Bool\\n not_ghc_generated name = name `elemNameSet` sig_ns\\n\\n add_binding_warn :: Id -> RnM ()\\n add_binding_warn id =\\n when (not_ghc_generated name) $\\n do { env <- liftZonkM $ tcInitTidyEnv -- Why not use emptyTidyEnv?\\n ; let ty = tidyOpenType env (idType id)\\n missing = MissingTopLevelBindingSig name ty\\n diag = TcRnMissingSignature missing exported\\n ; addDiagnosticAt (getSrcSpan name) diag }\\n where\\n name = idName id\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n add_patsyn_warn :: PatSyn -> RnM ()\\n add_patsyn_warn ps =\\n when (not_ghc_generated name) $\\n addDiagnosticAt (getSrcSpan name)\\n (TcRnMissingSignature missing exported)\\n where\\n name = patSynName ps\\n missing = MissingPatSynSig ps\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n -- Warn about missing signatures\\n -- Do this only when we have a type to offer\\n -- See Note [Missing signatures]\\n ; mapM_ add_binding_warn binds\\n ; mapM_ add_patsyn_warn pat_syns\\n }\\n\\n-- | Warn the user about tycons that lack kind signatures.\\n-- Called /after/ type (and kind) inference, so that we can report the\\n-- inferred kinds.\\nwarnMissingKindSignatures :: TcGblEnv -> RnM ()\\nwarnMissingKindSignatures gbl_env\\n = do { cusks_enabled <- xoptM LangExt.CUSKs\\n ; mapM_ (add_ty_warn cusks_enabled) tcs\\n }\\n where\\n tcs = tcg_tcs gbl_env\\n ksig_ns = tcg_ksigs gbl_env\\n exports = availsToNameSet (tcg_exports gbl_env)\\n\\n has_kind_signature :: Name -> Bool\\n has_kind_signature name = name `elemNameSet` ksig_ns\\n\\n add_ty_warn :: Bool -> TyCon -> RnM ()\\n add_ty_warn cusks_enabled tyCon =\\n when (has_kind_signature name) $\\n addDiagnosticAt (getSrcSpan name) diag\\n where\\n name = tyConName tyCon\\n diag = TcRnMissingSignature missing exported\\n missing = MissingTyConKindSig tyCon cusks_enabled\\n exported = if name `elemNameSet` exports\\n then IsExported\\n else IsNotExported\\n\\n{-\\n*********************************************************\\n* *\\n\\\\subsection{Unused imports}\\n* *\\n*********************************************************\\n\\nThis code finds which import declarations are unused. The\\nspecification and implementation notes are here:\\n https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/unused-imports\\n\\nSee also Note [Choosing the best import declaration] in GHC.Types.Name.Reader\\n-}\\n\\ntype ImportDeclUsage\\n = ( LImportDecl GhcRn -- The import declaration\\n , [GlobalRdrElt] -- What *is* used (normalised)\\n , [Name] -- What is imported but *not* used\\n , [NamespaceSpecifier GhcRn] ) -- Unused wildcards\\n\\nwarnUnusedImportDecls :: TcGblEnv -> HscSource -> RnM ()\\nwarnUnusedImportDecls gbl_env hsc_src\\n = do { uses <- readMutVar (tcg_used_gres gbl_env)\\n ; let imports = tcg_rn_imports gbl_env\\n rdr_env = tcg_rdr_env gbl_env\\n\\n -- We should only warn for unnecessary *user* imports, but deciding\\n -- minimal imports should take generated imports into account\\n ; let usageUserImports = findImportUsage (excludeGenerated imports) uses\\n usageAllImports = findImportUsage imports uses\\n\\n ; traceRn \\"warnUnusedImportDecls\\" $\\n (vcat [ text \\"Uses:\\" <+> ppr uses\\n , text \\"Usage all user imports: \\" <+> ppr usageUserImports\\n , text \\"Usage all imports: \\" <+> ppr usageAllImports])\\n\\n ; mapM_ (warnUnusedImport rdr_env) usageUserImports\\n\\n ; whenGOptM Opt_D_dump_minimal_imports $\\n printMinimalImports hsc_src usageAllImports }\\n\\n-- | Exclude generated imports\\nexcludeGenerated :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\nexcludeGenerated = filterOut (isGeneratedImport . ideclOrigin . ideclExt . unLoc)\\n\\nfindImportUsage :: [LImportDecl GhcRn]\\n -> [GlobalRdrElt]\\n -> [ImportDeclUsage]\\n\\nfindImportUsage imports used_gres\\n = map unused_decl imports\\n where\\n import_usage :: ImportMap\\n import_usage = mkImportMap used_gres\\n\\n unused_decl :: LImportDecl GhcRn -> ImportDeclUsage\\n unused_decl decl@(L _ (ImportDecl { ideclImportList = imps }))\\n = -- pprTrace \\"unused_decl\\" (vcat [ ppr decl\\n -- , text \\"used\\" <+> ppr used_gres\\n -- , text \\"unused\\" <+> ppr unused_names ]) $\\n (decl, used_gres, unused_names, unused_wcs)\\n where\\n used_gres = lookupImportMap decl import_usage\\n\\n used_gre_env = mkGlobalRdrEnv used_gres\\n used_parents = mkNameSet (mapMaybe greParent_maybe used_gres)\\n\\n (unused_names, unused_wcs) -- Not trivial; see eg #7454\\n = case imps of\\n Just (Exactly, imp_ies) ->\\n let unused = foldr (add_unused . unLoc) emptyUnusedNames imp_ies\\n nms = nameSetElemsStable (collectUnusedNames unused)\\n wcs = collectUnusedWildcards unused\\n in (nms, wcs)\\n _other -> ([], []) -- No explicit import list => no unused-name list\\n\\n add_unused :: IE GhcRn -> UnusedNames -> UnusedNames\\n add_unused (IEVar _ n _) acc = add_unused_name (lieWrappedName n) True acc\\n add_unused (IEThingAbs _ n _) acc = add_unused_name (lieWrappedName n) False acc\\n add_unused (IEThingAll _ _ n _) acc = add_unused_all (lieWrappedName n) acc\\n add_unused (IEThingWith _ p wc ns _) acc = add_wc_all (add_unused_with pn xs acc)\\n where pn = lieWrappedName p\\n xs = map lieWrappedName ns\\n add_wc_all = case wc of\\n NoIEWildcard -> id\\n IEWildcard _ -> add_unused_all pn\\n add_unused (IEWholeNamespace x ns_spec) acc = add_unused_wildcard ns_spec (iewn_names x) acc\\n add_unused _ acc = acc\\n\\n add_unused_name :: Name -> Bool -> UnusedNames -> UnusedNames\\n add_unused_name n is_ie_var acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | is_ie_var\\n , isFieldName n\\n -- See Note [Reporting unused imported duplicate record fields]\\n = let\\n fs = getOccFS n\\n (flds, flds_used) = lookupFsEnv acc_fs fs `orElse` (emptyNameSet, Any False)\\n acc_fs\' = extendFsEnv acc_fs fs (extendNameSet flds n, Any used S.<> flds_used)\\n in UnusedNames acc_ns acc_wcs acc_fs\'\\n\\n | used\\n = acc\\n\\n | otherwise\\n = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n where\\n used = isJust $ lookupGRE_Name used_gre_env n\\n\\n add_unused_all :: Name -> UnusedNames -> UnusedNames\\n add_unused_all n acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | Just {} <- lookupGRE_Name used_gre_env n = acc\\n | n `elemNameSet` used_parents = acc\\n | otherwise = UnusedNames (acc_ns `extendNameSet` n) acc_wcs acc_fs\\n\\n add_unused_with :: Name -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_with p ns acc\\n | all (`elemNameSet` acc1_ns) ns = add_unused_name p False acc1\\n | otherwise = acc1\\n where\\n acc1@(UnusedNames acc1_ns _ _) = foldr (\\\\n acc\' -> add_unused_name n False acc\') acc ns\\n -- If you use \'signum\' from Num, then the user may well have\\n -- imported Num(signum). We don\'t want to complain that\\n -- Num is not itself mentioned. Hence the two cases in add_unused_with.\\n\\n add_unused_wildcard :: NamespaceSpecifier GhcRn -> [Name] -> UnusedNames -> UnusedNames\\n add_unused_wildcard ns_spec names acc@(UnusedNames acc_ns acc_wcs acc_fs)\\n | any_used = acc\\n | otherwise = UnusedNames acc_ns (ns_spec : acc_wcs) acc_fs\\n where\\n -- A wildcard `type ..` or `data ..` is used if at least one of\\n -- the names it expands to is used\\n any_used = any (isJust . lookupGRE_Name used_gre_env) names\\n\\n\\n-- | An accumulator for unused names in an import list.\\n--\\n-- See Note [Reporting unused imported duplicate record fields].\\ndata UnusedNames =\\n UnusedNames\\n { unused_names :: NameSet\\n -- ^ Unused \'Name\'s in an import list, not including record fields\\n -- that are plain \'IEVar\' imports (tracked by \'rec_fld_uses\')\\n -- or wildcard imports (tracked by \'unused_wildcards\').\\n , unused_wildcards :: [NamespaceSpecifier GhcRn]\\n -- ^ Unused wildcards @type ..@ or @data ..@ in an import list.\\n , rec_fld_uses :: FastStringEnv (NameSet, Any)\\n -- ^ Record fields imported without a parent (i.e. an \'IEVar\' import).\\n --\\n -- The \'Any\' value records whether any of the record fields\\n -- sharing the same underlying \'FastString\' have been used.\\n }\\n\\nemptyUnusedNames :: UnusedNames\\nemptyUnusedNames = UnusedNames emptyNameSet [] emptyFsEnv\\n\\ninstance Outputable UnusedNames where\\n ppr (UnusedNames nms wcs flds) =\\n text \\"UnusedNames\\" <+>\\n braces (ppr nms <+> ppr wcs <+> ppr (fmap (second getAny) flds))\\n\\n-- | Collect all unused names from a \'UnusedNames\' value.\\ncollectUnusedNames :: UnusedNames -> NameSet\\ncollectUnusedNames (UnusedNames { unused_names = nms, rec_fld_uses = flds })\\n = nms S.<> unused_flds\\n where\\n unused_flds = nonDetFoldFsEnv collect_unused emptyNameSet flds\\n collect_unused :: (NameSet, Any) -> NameSet -> NameSet\\n collect_unused (nms, Any at_least_one_name_is_used) acc\\n | at_least_one_name_is_used = acc\\n | otherwise = unionNameSet nms acc\\n\\ncollectUnusedWildcards :: UnusedNames -> [NamespaceSpecifier GhcRn]\\ncollectUnusedWildcards = unused_wildcards\\n\\n{- Note [Reporting unused imported duplicate record fields]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have (#24035):\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M1 (R1(..), R2(..)) where\\n data R1 = MkR1 { fld :: Int }\\n data R2 = MkR2 { fld :: Int }\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module M2 where\\n import M1 (R1(MkR1), R2, fld)\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nIn the import of \'M1\' in \'M2\', the \'fld\' import resolves to two separate GREs,\\nnamely R1(fld) and R2(fld). From the perspective of the renamer, and in particular\\nthe \'findImportUsage\' function, it\'s as if the user had imported the two names\\nseparately (even though no source syntax allows that).\\n\\nThis means that we need to be careful when reporting unused imports: the R2(fld)\\nimport is indeed unused, but because R1(fld) is used, we should not report\\nfld as unused altogether.\\n\\nTo achieve this, we keep track of record field imports without a parent (i.e.\\nusing the IEVar constructor) separately from other import items, using the\\nUnusedNames datatype.\\nOnce we have accumulated usages, we emit warnings for unused record fields\\nwithout parents one whole group (of record fields sharing the same textual name)\\nat a time, and only if *all* of the record fields in the group are unused;\\nsee \'collectUnusedNames\'.\\n\\nNote that this only applies to record fields imported without a parent. If we\\nhad:\\n\\n import M1 (R1(MkR1, fld), R2(fld))\\n f :: R1 -> Int\\n f (MkR1 { fld = x }) = x\\n g :: R2 -> Int\\n g _ = 3\\n\\nthen of course we should report the second \'fld\' as unused.\\n-}\\n\\n\\n{- Note [The ImportMap]\\n~~~~~~~~~~~~~~~~~~~~~~~\\nThe ImportMap is a short-lived intermediate data structure records, for\\neach import declaration, what stuff brought into scope by that\\ndeclaration is actually used in the module.\\n\\nThe [GlobalRdrElt] are the things imported from that decl.\\n-}\\n\\ndata ImportMap = ImportMap\\n { im_imports :: Map RealSrcSpan [GlobalRdrElt]\\n -- ^ See [The ImportMap]\\n -- If loc :-> gres, then\\n -- \'loc\' = the end loc of the bestImport of each GRE in \'gres\'\\n , im_generatedImports :: Map ModuleName [GlobalRdrElt]\\n }\\n\\nmkImportMap :: [GlobalRdrElt] -> ImportMap\\n-- For each of a list of used GREs, find all the import decls that brought\\n-- it into scope; choose one of them (bestImport), and record\\n-- the RdrName in that import decl\'s entry in the ImportMap\\nmkImportMap = foldr insertImportMap $ ImportMap Map.empty Map.empty\\n\\ninsertImportMap :: GlobalRdrElt -> ImportMap -> ImportMap\\ninsertImportMap gre@(GRE { gre_imp = imp_specs }) importMap\\n | RealSrcSpan importSpan _ <- is_dloc best_imp_spec =\\n importMap{im_imports = insertElem importSpan gre $ im_imports importMap}\\n | GeneratedSrcSpan{} <- is_dloc best_imp_spec =\\n importMap{im_generatedImports = insertElem (moduleName $ is_mod best_imp_spec) gre $ im_generatedImports importMap}\\n | otherwise = importMap\\n where\\n best_imp_spec =\\n case bagToList imp_specs of\\n [] -> pprPanic \\"mkImportMap: GRE with no ImportSpecs\\" (ppr gre)\\n is:iss -> is_decl $ bestImport (is NE.:| iss)\\n\\n -- https://github.com/haskell/containers/issues/784\\n insertElem :: Ord k => k -> v -> Map k [v] -> Map k [v]\\n insertElem k v = flip Map.alter k $ \\\\case\\n Just vs -> Just (v : vs)\\n Nothing -> Just [v]\\n\\nlookupImportMap :: LImportDecl GhcRn -> ImportMap -> [GlobalRdrElt]\\nlookupImportMap (L srcSpan ImportDecl{ideclName = L _ modName}) importMap =\\n fromMaybe [] $\\n -- should match logic in insertImportMap\\n case locA srcSpan of\\n RealSrcSpan realSrcSpan _ -> realSrcSpan `Map.lookup` im_imports importMap\\n GeneratedSrcSpan{} -> modName `Map.lookup` im_generatedImports importMap\\n _ -> Nothing\\n\\nlieNames :: LIE (GhcPass p) -> [Located (IdP (GhcPass p))]\\nlieNames = _\\n\\nwarnUnusedImport :: GlobalRdrEnv -> ImportDeclUsage -> RnM ()\\nwarnUnusedImport rdr_env (L loc decl, used, unused, unused_wcs)\\n\\n -- Do not warn for \'import M()\'\\n -- See (UI1) in Note [Unused imports]\\n | Just (Exactly, _) <- ideclImportList decl\\n , null unused && null unused_wcs\\n = return ()\\n\\n -- Note [Do not warn about Prelude hiding]\\n | Just (EverythingBut, hides) <- ideclImportList decl\\n , not (null hides)\\n , pRELUDE_NAME == unLoc (ideclName decl)\\n = return ()\\n\\n -- Do not warn about import X as Rebindable\\n -- See (UI2) in Note [Unused imports]\\n | Just (L _ mod) <- ideclAs decl\\n , mod == rEBINDABLE_MOD_NAME\\n = return ()\\n\\n -- Nothing used; drop entire declaration\\n | null used\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl UnusedImportNone)\\n\\n -- Everything imported is used; nop\\n | null unused && null unused_wcs\\n = return ()\\n\\n -- Some imports are unused: make the `SrcSpan` cover only the unused\\n -- items instead of the whole import statement\\n | Just (_, imports) <- ideclImportList decl\\n , let unused_locs = [ locA loc | L loc ie <- imports\\n , name <- ieNames ie\\n , name `elem` unused ]\\n , loc1 : locs <- unused_locs\\n , let span = foldr1 combineSrcSpans ( loc1 NE.:| locs )\\n = addDiagnosticAt span (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n -- Some imports are unused\\n | otherwise\\n = addDiagnosticAt (locA loc) (TcRnUnusedImport decl (UnusedImportSome sort_unused))\\n\\n where\\n -- In warning message, pretty-print identifiers unqualified unconditionally\\n -- to improve the consistent for ambiguous/unambiguous identifiers.\\n -- See #14881.\\n possible_field n =\\n case lookupGRE_Name rdr_env n of\\n Just (GRE { gre_par = par, gre_info = IAmRecField info }) ->\\n let fld_occ :: OccName\\n fld_occ = nameOccName $ flSelector $ recFieldLabel info\\n in UnusedImportNameRecField par fld_occ\\n _ -> UnusedImportNameRegular n\\n\\n -- Print unused names in a deterministic (lexicographic) order\\n sort_unused :: [UnusedImportName]\\n sort_unused =\\n [ UnusedImportWildcard wc | wc <- unused_wcs ] ++\\n [ possible_field nm | nm <- sortBy (comparing nameOccName) unused ]\\n\\ngetMinimalImports :: [ImportDeclUsage] -> RnM [LImportDecl GhcRn]\\ngetMinimalImports ie_decls\\n = do { rdr_env <- getGlobalRdrEnv\\n ; fmap combine $ mapM (mk_minimal rdr_env) ie_decls }\\n where\\n mk_minimal rdr_env (L l decl, used_gres, unused, unused_wcs)\\n | null unused && null unused_wcs\\n , Just (Exactly, _) <- ideclImportList decl\\n = return (L l decl)\\n | otherwise\\n = do { let ImportDecl { ideclName = L _ mod_name\\n , ideclSource = is_boot\\n , ideclPkgQual = pkg_qual\\n , ideclExt = XImportDeclPass { ideclOrigin = origin } } = decl\\n ; iface <- loadSrcInterface doc (importDeclLookupScope origin)\\n mod_name is_boot pkg_qual\\n ; let used_avails = gresToAvailInfo used_gres\\n ; lies <- map (L l) <$> concatMapM (to_ie rdr_env iface) used_avails\\n ; return (L l (decl { ideclImportList = Just (Exactly, lies) })) }\\n where\\n doc = text \\"Compute minimal imports for\\" <+> ppr decl\\n\\n to_ie :: GlobalRdrEnv -> ModIface -> AvailInfo -> RnM [IE GhcRn]\\n -- The main trick here is that if we\'re importing all the constructors\\n -- we want to say \\"T(..)\\", but if we\'re importing only a subset we want\\n -- to say \\"T(A,B,C)\\". So we have to find out what the module exports.\\n to_ie rdr_env _ (Avail c) -- Note [Overloaded field import]\\n = do { let\\n gre = expectJust $ lookupGRE_Name rdr_env c\\n ; return $ [IEVar Nothing (to_ie_post_rn $ noLocA $ greName gre) Nothing] }\\n to_ie _ _ avail@(AvailTC n [_]) -- Exporting the main decl and nothing else\\n | availExportsDecl avail\\n = return [IEThingAbs Nothing (to_ie_post_rn $ noLocA n) Nothing]\\n to_ie rdr_env iface (AvailTC n cs) =\\n case [ xs | avail@(AvailTC x xs) <- mi_exports iface\\n , x == n\\n , availExportsDecl avail -- Note [Partial export]\\n ] of\\n [xs]\\n | all_used xs\\n -> return [IEThingAll (IEThingAllExt Nothing noAnn noAnn noAnn)\\n (NoNamespaceSpecifier noExtField)\\n (to_ie_post_rn $ noLocA n)\\n Nothing]\\n | otherwise\\n -> do { let ns_gres = map (expectJust . lookupGRE_Name rdr_env) cs\\n ns = map greName ns_gres\\n ; return [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n -- Note [Overloaded field import]\\n _other\\n -> do { let infos = map (expectJust . lookupGRE_Name rdr_env) cs\\n (ns_gres,fs_gres) = classifyGREs infos\\n ns = map greName (ns_gres ++ fs_gres)\\n fs = map fieldGREInfo fs_gres\\n ; return $\\n if all_non_overloaded fs\\n then map (\\\\nm -> IEVar Nothing (to_ie_post_rn_var $ noLocA nm) Nothing) ns\\n else [IEThingWith (Nothing, noAnn) (to_ie_post_rn $ noLocA n) NoIEWildcard\\n (map (to_ie_post_rn . noLocA) (filter (/= n) ns)) Nothing] }\\n where\\n\\n all_used avail_cs = all (`elem` cs) avail_cs\\n\\n all_non_overloaded = all (not . flIsOverloaded . recFieldLabel)\\n\\n combine :: [LImportDecl GhcRn] -> [LImportDecl GhcRn]\\n combine = map merge . NE.groupAllWith getKey\\n\\n getKey :: LImportDecl GhcRn -> (Bool, Maybe ModuleName, ModuleName)\\n getKey decl =\\n ( isImportDeclQualified . ideclQualified $ idecl -- is this qualified? (important that this be first)\\n , unLoc <$> ideclAs idecl -- what is the qualifier (inside Maybe monad)\\n , unLoc . ideclName $ idecl -- Module Name\\n )\\n where\\n idecl :: ImportDecl GhcRn\\n idecl = unLoc decl\\n\\n merge :: NonEmpty (LImportDecl GhcRn) -> LImportDecl GhcRn\\n merge decls@((L l decl) :| _) = L l (decl { ideclImportList = Just (Exactly, lies) })\\n where lies = concatMap snd $ mapMaybe (ideclImportList . unLoc) $ NE.toList decls\\n\\nclassifyGREs :: [GlobalRdrElt] -> ([GlobalRdrElt], [FieldGlobalRdrElt])\\nclassifyGREs = partition (not . isRecFldGRE)\\n\\nprintMinimalImports :: HscSource -> [ImportDeclUsage] -> RnM ()\\n-- See Note [Printing minimal imports]\\nprintMinimalImports hsc_src imports_w_usage\\n = do { imports\' <- excludeGenerated <$> getMinimalImports imports_w_usage\\n ; this_mod <- getModule\\n ; dflags <- getDynFlags\\n ; liftIO $ withFile (mkFilename dflags this_mod) WriteMode $ \\\\h ->\\n printForUser dflags h neverQualify AllTheWay (vcat (map ppr imports\'))\\n -- The neverQualify is important. We are printing Names\\n -- but they are in the context of an \'import\' decl, and\\n -- we never qualify things inside there\\n -- E.g. import Blag( f, b )\\n -- not import Blag( Blag.f, Blag.g )!\\n }\\n where\\n mkFilename dflags this_mod\\n | Just d <- dumpDir dflags = d basefn\\n | otherwise = basefn\\n where\\n suffix = case hsc_src of\\n HsBootFile -> \\".imports-boot\\"\\n HsSrcFile -> \\".imports\\"\\n HsigFile -> \\".imports\\"\\n basefn = moduleNameString (moduleName this_mod) ++ suffix\\n\\n\\nto_ie_post_rn_var :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn_var (L l n)\\n | isDataOcc $ occName n = L l (IEPattern noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n\\n\\nto_ie_post_rn :: LocatedA (IdP GhcRn) -> LIEWrappedName GhcRn\\nto_ie_post_rn (L l n)\\n | isTcOcc occ && isSymOcc occ = L l (IEType noAnn (L (l2l l) n))\\n | otherwise = L l (IEName noExtField (L (l2l l) n))\\n where occ = occName n\\n\\n{- Note [Do not warn about Prelude hiding]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nWe do not warn about\\n import Prelude hiding( x, y )\\nbecause even if nothing else from Prelude is used, it may be essential to hide\\nx,y to avoid name-shadowing warnings. Example (#9061)\\n import Prelude hiding( log )\\n f x = log where log = ()\\n\\nNote [Unused imports]\\n~~~~~~~~~~~~~~~~~~~~~\\nIn `warnUnusedImport`, if we see an import with an explicit list imports, thus\\n import M( a, b )\\nand neither `a` nor `b` is used, we report the entire import decl as unused. We\\ncheck this by looking at the names that it brings into scope scope; if there are\\nno ununused names, don\'t report.\\n\\n(UI1) We don\'t want to complain about `import M()`, because that is often used to bring\\n M\'s /instances/ into scope. That is neatly dealt with by the \\"no unused\\n names\\" (nor unused wildcard imports) criterion.\\n\\n(UI2) We don\'t report a decl as unused if it has an `as Rebindable` qualifier.\\n See (KN1) in Note [Overview of known entities] in GHC.Builtin\\n\\n\\nNote [Printing minimal imports]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nTo print the minimal imports we walk over all import decls (both user-supplied\\nand generated), trim their import lists, then filter out generated decls.\\n\\nNB that\\n\\n * We do *not* change the \'qualified\' or \'as\' parts!\\n\\n * We do not discard a decl altogether; we might need instances\\n from it. Instead we just trim to an empty import list\\n\\nNote [Partial export]\\n~~~~~~~~~~~~~~~~~~~~~\\nSuppose we have\\n\\n module A( op ) where\\n class C a where\\n op :: a -> a\\n\\n module B where\\n import A\\n f = ..op...\\n\\nThen the minimal import for module B is\\n import A( op )\\nnot\\n import A( C( op ) )\\nwhich we would usually generate if C was exported from B. Hence\\nthe availExportsDecl test when deciding what to generate.\\n\\n\\nNote [Overloaded field import]\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\nOn the other hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n data T = MkT { foo :: Int }\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( T(foo) )\\nbecause when DuplicateRecordFields is enabled, field selectors are\\nnot in scope without their enclosing datatype.\\n\\nOn the third hand, if we have\\n\\n {-# LANGUAGE DuplicateRecordFields #-}\\n module A where\\n pattern MkT { foo } = Just foo\\n\\n module B where\\n import A\\n f = ...foo...\\n\\nthen the minimal import for module B must be\\n import A ( foo )\\nbecause foo doesn\'t have a parent. This might actually be ambiguous if A\\nexports another field called foo, but there is no good answer to return and this\\nis a very obscure corner, so it seems to be the best we can do. See\\nDRFPatSynExport for a test of this.\\n\\n\\n************************************************************************\\n* *\\n\\\\subsection{Errors}\\n* *\\n************************************************************************\\n-}\\n\\nbadImportItemErr\\n :: ModIface -> ImpDeclSpec -> IE GhcPs\\n -> IsSubordinateError\\n -> [AvailInfo]\\n -> TcRn (NonEmpty ImportLookupReason)\\nbadImportItemErr iface decl_spec ie sub avails = do\\n exts <- importLookupExtensions\\n let import_lookup_bad :: BadImportKind -> ImportLookupReason\\n import_lookup_bad k = ImportLookupBad k iface decl_spec ie exts\\n dflags <- getDynFlags\\n hsc_env <- getTopEnv\\n let rdr_env = mkGlobalRdrEnv\\n $ gresFromAvails hsc_env (Just imp_spec) all_avails\\n pure $ fmap import_lookup_bad (importErrorKind dflags rdr_env)\\n where\\n importErrorKind :: DynFlags -> GlobalRdrEnv -> NonEmpty BadImportKind\\n importErrorKind dflags rdr_env\\n | any checkIfTyCon avails = case sub of\\n IsNotSubordinate -> NE.singleton BadImportAvailTyCon\\n IsSubordinateError { subordinate_err_parent = gre\\n , subordinate_err_unavailable = unavailable\\n , subordinate_err_nontype = nontype\\n , subordinate_err_nondata = nondata }\\n -> NE.fromList $ catMaybes $\\n [ fmap (BadImportNotExportedSubordinates gre) (NE.nonEmpty unavailable)\\n , fmap (BadImportNonTypeSubordinates gre) (NE.nonEmpty nontype)\\n , fmap (BadImportNonDataSubordinates gre) (NE.nonEmpty nondata) ]\\n | any checkIfVarName avails = NE.singleton BadImportAvailVar\\n | Just con <- find checkIfDataCon avails = NE.singleton (BadImportAvailDataCon (availOccName con))\\n | otherwise = NE.singleton (BadImportNotExported suggs)\\n where\\n suggs = similar_suggs ++ fieldSelectorSuggestions rdr_env rdr\\n what_look = case sub of\\n IsNotSubordinate -> WL_TyCon_or_TermVar\\n IsSubordinateError { subordinate_err_parent = gre } ->\\n case greInfo gre of\\n IAmTyCon ClassFlavour\\n -> WL_TyCon_or_TermVar\\n _ -> WL_Term\\n similar_names =\\n similarNameSuggestions (Unbound.LF what_look WL_Global)\\n dflags rdr_env emptyLocalRdrEnv rdr\\n similar_suggs =\\n case NE.nonEmpty $ mapMaybe imported_item $ similar_names of\\n Just similar -> [ SuggestSimilarNames rdr similar ]\\n Nothing -> [ ]\\n\\n -- Only keep imported items, and set the \\"HowInScope\\" to\\n -- \\"Nothing\\" to avoid printing \\"imported from...\\" in the suggestion\\n -- error message.\\n imported_item (SimilarRdrName rdr_name gre (Just (ImportedBy {})))\\n = Just (SimilarRdrName rdr_name gre Nothing)\\n imported_item _ = Nothing\\n\\n checkIfDataCon = checkIfAvailMatches isDataConName\\n checkIfTyCon = checkIfAvailMatches isTyConName\\n checkIfVarName =\\n \\\\case\\n AvailTC{} -> False\\n Avail n -> importedFS == occNameFS (occName n)\\n && (isVarOcc <||> isFieldOcc) (occName n)\\n checkIfAvailMatches namePred =\\n \\\\case\\n AvailTC _ ns ->\\n case find (\\\\n -> importedFS == occNameFS (occName n)) ns of\\n Just n -> namePred n\\n Nothing -> False\\n Avail{} -> False\\n availOccName = occName . availName\\n rdr = ieName ie\\n importedFS = occNameFS $ rdrNameOcc rdr\\n imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }\\n all_avails = mi_exports iface\\n\\nimportLookupExtensions :: TcRn ImportLookupExtensions\\nimportLookupExtensions = do\\n ile_pattern_synonyms <- xoptM LangExt.PatternSynonyms\\n ile_explicit_namespaces <- xoptM LangExt.ExplicitNamespaces\\n return ImportLookupExtensions{ile_pattern_synonyms, ile_explicit_namespaces}\\n\\naddDupDeclErr :: NonEmpty GlobalRdrElt -> TcRn ()\\naddDupDeclErr gres@(gre :| _)\\n -- Report the error at the later location\\n = addErrAt (getSrcSpan (NE.last sorted_names)) $ (TcRnDuplicateDecls (greOccName gre) sorted_names)\\n where\\n sorted_names =\\n NE.sortBy (SrcLoc.leftmost_smallest `on` nameSrcSpan)\\n (fmap greName gres)\\n\\n-- This data decl will parse OK\\n-- data T = a Int\\n-- treating \\"a\\" as the constructor.\\n-- It is really hard to make the parser spot this malformation.\\n-- So the renamer has to check that the constructor is legal\\n--\\n-- We can get an operator as the constructor, even in the prefix form:\\n-- data T = :% Int Int\\n-- from interface files, which always print in prefix form\\n--\\n-- We also allow type constructor names, which are defined by \\"type data\\"\\n-- declarations. See Note [Type data declarations] in GHC.Rename.Module.\\n\\ncheckConName :: RdrName -> TcRn ()\\ncheckConName name\\n = checkErr (isRdrDataCon name || isRdrTc name) (TcRnIllegalDataCon name)\\n", "filetypes": ["haskell"]}}, "event_name": "BufferUnload"}' 2026-10-16 14:49:27,331 - DEBUG - POST b'http://127.0.0.1:37093/shutdown' {'content-type': 'application/json', 'x-ycm-hmac': b'7FOu0yYI61RFV6SkxVainKesN52YgWAXReVMKTtw3fo='} b''