Skip to content

Commit 1bee814

Browse files
committed
Auto merge of #153312 - b-naber:namespaced-crate-names-pt1, r=<try>
Packages as namespaces part 1 try-job: x86_64-gnu-aux
2 parents 562dee4 + e844c24 commit 1bee814

32 files changed

+480
-54
lines changed

compiler/rustc_hir/src/def.rs

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -590,6 +590,13 @@ pub enum Res<Id = hir::HirId> {
590590
/// **Belongs to the type namespace.**
591591
ToolMod,
592592

593+
/// The resolution for an open module in a namespaced crate. E.g. `my_api`
594+
/// in the namespaced crate `my_api::utils` when `my_api` isn't part of the
595+
/// extern prelude.
596+
///
597+
/// **Belongs to the type namespace.**
598+
OpenMod(Symbol),
599+
593600
// Macro namespace
594601
/// An attribute that is *not* implemented via macro.
595602
/// E.g., `#[inline]` and `#[rustfmt::skip]`, which are essentially directives,
@@ -838,6 +845,7 @@ impl<Id> Res<Id> {
838845
| Res::SelfTyAlias { .. }
839846
| Res::SelfCtor(..)
840847
| Res::ToolMod
848+
| Res::OpenMod(..)
841849
| Res::NonMacroAttr(..)
842850
| Res::Err => None,
843851
}
@@ -869,6 +877,7 @@ impl<Id> Res<Id> {
869877
Res::Local(..) => "local variable",
870878
Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } => "self type",
871879
Res::ToolMod => "tool module",
880+
Res::OpenMod(..) => "namespaced crate",
872881
Res::NonMacroAttr(attr_kind) => attr_kind.descr(),
873882
Res::Err => "unresolved item",
874883
}
@@ -895,6 +904,7 @@ impl<Id> Res<Id> {
895904
Res::SelfTyAlias { alias_to, is_trait_impl }
896905
}
897906
Res::ToolMod => Res::ToolMod,
907+
Res::OpenMod(sym) => Res::OpenMod(sym),
898908
Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
899909
Res::Err => Res::Err,
900910
}
@@ -911,6 +921,7 @@ impl<Id> Res<Id> {
911921
Res::SelfTyAlias { alias_to, is_trait_impl }
912922
}
913923
Res::ToolMod => Res::ToolMod,
924+
Res::OpenMod(sym) => Res::OpenMod(sym),
914925
Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
915926
Res::Err => Res::Err,
916927
})
@@ -936,9 +947,11 @@ impl<Id> Res<Id> {
936947
pub fn ns(&self) -> Option<Namespace> {
937948
match self {
938949
Res::Def(kind, ..) => kind.ns(),
939-
Res::PrimTy(..) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } | Res::ToolMod => {
940-
Some(Namespace::TypeNS)
941-
}
950+
Res::PrimTy(..)
951+
| Res::SelfTyParam { .. }
952+
| Res::SelfTyAlias { .. }
953+
| Res::ToolMod
954+
| Res::OpenMod(..) => Some(Namespace::TypeNS),
942955
Res::SelfCtor(..) | Res::Local(..) => Some(Namespace::ValueNS),
943956
Res::NonMacroAttr(..) => Some(Namespace::MacroNS),
944957
Res::Err => None,

compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2830,6 +2830,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
28302830
| Res::SelfCtor(_)
28312831
| Res::Local(_)
28322832
| Res::ToolMod
2833+
| Res::OpenMod(..)
28332834
| Res::NonMacroAttr(_)
28342835
| Res::Err) => Const::new_error_with_message(
28352836
tcx,

compiler/rustc_passes/src/dead.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ impl<'tcx> MarkSymbolVisitor<'tcx> {
157157
Res::Def(_, def_id) => self.check_def_id(def_id),
158158
Res::SelfTyParam { trait_: t } => self.check_def_id(t),
159159
Res::SelfTyAlias { alias_to: i, .. } => self.check_def_id(i),
160-
Res::ToolMod | Res::NonMacroAttr(..) | Res::Err => {}
160+
Res::ToolMod | Res::NonMacroAttr(..) | Res::OpenMod(..) | Res::Err => {}
161161
}
162162
}
163163

compiler/rustc_resolve/src/build_reduced_graph.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
357357
| Res::SelfTyParam { .. }
358358
| Res::SelfTyAlias { .. }
359359
| Res::SelfCtor(..)
360+
| Res::OpenMod(..)
360361
| Res::Err => bug!("unexpected resolution: {:?}", res),
361362
}
362363
}

compiler/rustc_resolve/src/diagnostics.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1740,8 +1740,8 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
17401740
Res::Def(DefKind::Macro(kinds), _) => {
17411741
format!("{} {}", kinds.article(), kinds.descr())
17421742
}
1743-
Res::ToolMod => {
1744-
// Don't confuse the user with tool modules.
1743+
Res::ToolMod | Res::OpenMod(..) => {
1744+
// Don't confuse the user with tool modules or open modules.
17451745
continue;
17461746
}
17471747
Res::Def(DefKind::Trait, _) if macro_kind == MacroKind::Derive => {
@@ -1978,7 +1978,8 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
19781978
let (built_in, from) = match scope {
19791979
Scope::StdLibPrelude | Scope::MacroUsePrelude => ("", " from prelude"),
19801980
Scope::ExternPreludeFlags
1981-
if self.tcx.sess.opts.externs.get(ident.as_str()).is_some() =>
1981+
if self.tcx.sess.opts.externs.get(ident.as_str()).is_some()
1982+
|| matches!(res, Res::OpenMod(..)) =>
19821983
{
19831984
("", " passed with `--extern`")
19841985
}

compiler/rustc_resolve/src/ident.rs

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ use crate::{
2626
AmbiguityError, AmbiguityKind, AmbiguityWarning, BindingKey, CmResolver, Decl, DeclKind,
2727
Determinacy, Finalize, IdentKey, ImportKind, LateDecl, Module, ModuleKind, ModuleOrUniformRoot,
2828
ParentScope, PathResult, PrivacyError, Res, ResolutionError, Resolver, Scope, ScopeSet,
29-
Segment, Stage, Used, errors,
29+
Segment, Stage, Symbol, Used, errors,
3030
};
3131

3232
#[derive(Copy, Clone)]
@@ -386,7 +386,6 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
386386
}
387387

388388
/// Resolve an identifier in the specified set of scopes.
389-
#[instrument(level = "debug", skip(self))]
390389
pub(crate) fn resolve_ident_in_scope_set<'r>(
391390
self: CmResolver<'r, 'ra, 'tcx>,
392391
orig_ident: Ident,
@@ -976,6 +975,14 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
976975
ignore_import,
977976
)
978977
}
978+
ModuleOrUniformRoot::OpenModule(sym) => {
979+
let open_ns_name = format!("{}::{}", sym.as_str(), ident.name);
980+
let ns_ident = IdentKey::with_root_ctxt(Symbol::intern(&open_ns_name));
981+
match self.extern_prelude_get_flag(ns_ident, ident.span, finalize.is_some()) {
982+
Some(decl) => Ok(decl),
983+
None => Err(Determinacy::Determined),
984+
}
985+
}
979986
ModuleOrUniformRoot::ModuleAndExternPrelude(module) => self.resolve_ident_in_scope_set(
980987
ident,
981988
ScopeSet::ModuleAndExternPrelude(ns, module),
@@ -1962,7 +1969,10 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
19621969
}
19631970

19641971
let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(res);
1965-
if let Some(def_id) = binding.res().module_like_def_id() {
1972+
if let Res::OpenMod(sym) = binding.res() {
1973+
module = Some(ModuleOrUniformRoot::OpenModule(sym));
1974+
record_segment_res(self.reborrow(), finalize, res, id);
1975+
} else if let Some(def_id) = binding.res().module_like_def_id() {
19661976
if self.mods_with_parse_errors.contains(&def_id) {
19671977
module_had_parse_errors = true;
19681978
}

compiler/rustc_resolve/src/imports.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ type Res = def::Res<NodeId>;
4141

4242
/// A potential import declaration in the process of being planted into a module.
4343
/// Also used for lazily planting names from `--extern` flags to extern prelude.
44-
#[derive(Clone, Copy, Default, PartialEq)]
44+
#[derive(Clone, Copy, Default, PartialEq, Debug)]
4545
pub(crate) enum PendingDecl<'ra> {
4646
Ready(Option<Decl<'ra>>),
4747
#[default]

compiler/rustc_resolve/src/lib.rs

Lines changed: 101 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ use rustc_hir::definitions::DisambiguatorState;
6161
use rustc_hir::{PrimTy, TraitCandidate, find_attr};
6262
use rustc_index::bit_set::DenseBitSet;
6363
use rustc_metadata::creader::CStore;
64+
use rustc_middle::bug;
6465
use rustc_middle::metadata::{AmbigModChild, ModChild, Reexport};
6566
use rustc_middle::middle::privacy::EffectiveVisibilities;
6667
use rustc_middle::query::Providers;
@@ -445,6 +446,11 @@ enum ModuleOrUniformRoot<'ra> {
445446
/// Used only for resolving single-segment imports. The reason it exists is that import paths
446447
/// are always split into two parts, the first of which should be some kind of module.
447448
CurrentScope,
449+
450+
/// Virtual module for the resolution of base names of namespaced crates,
451+
/// where the base name doesn't correspond to a module in the extern prelude.
452+
/// E.g. `my_api::utils` is in the prelude, but `my_api` is not.
453+
OpenModule(Symbol),
448454
}
449455

450456
#[derive(Debug)]
@@ -1105,13 +1111,20 @@ impl<'ra> DeclData<'ra> {
11051111
}
11061112
}
11071113

1114+
#[derive(Debug)]
11081115
struct ExternPreludeEntry<'ra> {
11091116
/// Name declaration from an `extern crate` item.
11101117
/// The boolean flag is true is `item_decl` is non-redundant, happens either when
11111118
/// `flag_decl` is `None`, or when `extern crate` introducing `item_decl` used renaming.
11121119
item_decl: Option<(Decl<'ra>, Span, /* introduced by item */ bool)>,
11131120
/// Name declaration from an `--extern` flag, lazily populated on first use.
1114-
flag_decl: Option<CacheCell<(PendingDecl<'ra>, /* finalized */ bool)>>,
1121+
flag_decl: Option<
1122+
CacheCell<(
1123+
PendingDecl<'ra>,
1124+
/* finalized */ bool,
1125+
/* open flag (namespaced crate) */ bool,
1126+
)>,
1127+
>,
11151128
}
11161129

11171130
impl ExternPreludeEntry<'_> {
@@ -1122,7 +1135,14 @@ impl ExternPreludeEntry<'_> {
11221135
fn flag() -> Self {
11231136
ExternPreludeEntry {
11241137
item_decl: None,
1125-
flag_decl: Some(CacheCell::new((PendingDecl::Pending, false))),
1138+
flag_decl: Some(CacheCell::new((PendingDecl::Pending, false, false))),
1139+
}
1140+
}
1141+
1142+
fn open_flag() -> Self {
1143+
ExternPreludeEntry {
1144+
item_decl: None,
1145+
flag_decl: Some(CacheCell::new((PendingDecl::Pending, false, true))),
11261146
}
11271147
}
11281148

@@ -1643,35 +1663,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
16431663
let mut invocation_parents = FxHashMap::default();
16441664
invocation_parents.insert(LocalExpnId::ROOT, InvocationParent::ROOT);
16451665

1646-
let mut extern_prelude: FxIndexMap<_, _> = tcx
1647-
.sess
1648-
.opts
1649-
.externs
1650-
.iter()
1651-
.filter_map(|(name, entry)| {
1652-
// Make sure `self`, `super`, `_` etc do not get into extern prelude.
1653-
// FIXME: reject `--extern self` and similar in option parsing instead.
1654-
if entry.add_prelude
1655-
&& let name = Symbol::intern(name)
1656-
&& name.can_be_raw()
1657-
{
1658-
let ident = IdentKey::with_root_ctxt(name);
1659-
Some((ident, ExternPreludeEntry::flag()))
1660-
} else {
1661-
None
1662-
}
1663-
})
1664-
.collect();
1665-
1666-
if !attr::contains_name(attrs, sym::no_core) {
1667-
let ident = IdentKey::with_root_ctxt(sym::core);
1668-
extern_prelude.insert(ident, ExternPreludeEntry::flag());
1669-
if !attr::contains_name(attrs, sym::no_std) {
1670-
let ident = IdentKey::with_root_ctxt(sym::std);
1671-
extern_prelude.insert(ident, ExternPreludeEntry::flag());
1672-
}
1673-
}
1674-
1666+
let extern_prelude = build_extern_prelude(tcx, attrs);
16751667
let registered_tools = tcx.registered_tools(());
16761668
let edition = tcx.sess.edition();
16771669

@@ -2326,10 +2318,10 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
23262318
) -> Option<Decl<'ra>> {
23272319
let entry = self.extern_prelude.get(&ident);
23282320
entry.and_then(|entry| entry.flag_decl.as_ref()).and_then(|flag_decl| {
2329-
let (pending_decl, finalized) = flag_decl.get();
2321+
let (pending_decl, finalized, is_open) = flag_decl.get();
23302322
let decl = match pending_decl {
23312323
PendingDecl::Ready(decl) => {
2332-
if finalize && !finalized {
2324+
if finalize && !finalized && !is_open {
23332325
self.cstore_mut().process_path_extern(
23342326
self.tcx,
23352327
ident.name,
@@ -2340,18 +2332,28 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
23402332
}
23412333
PendingDecl::Pending => {
23422334
debug_assert!(!finalized);
2343-
let crate_id = if finalize {
2344-
self.cstore_mut().process_path_extern(self.tcx, ident.name, orig_ident_span)
2335+
if is_open {
2336+
let res = Res::OpenMod(ident.name);
2337+
Some(self.arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT))
23452338
} else {
2346-
self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name)
2347-
};
2348-
crate_id.map(|crate_id| {
2349-
let res = Res::Def(DefKind::Mod, crate_id.as_def_id());
2350-
self.arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT)
2351-
})
2339+
let crate_id = if finalize {
2340+
self.cstore_mut().process_path_extern(
2341+
self.tcx,
2342+
ident.name,
2343+
orig_ident_span,
2344+
)
2345+
} else {
2346+
self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name)
2347+
};
2348+
crate_id.map(|crate_id| {
2349+
let def_id = crate_id.as_def_id();
2350+
let res = Res::Def(DefKind::Mod, def_id);
2351+
self.arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT)
2352+
})
2353+
}
23522354
}
23532355
};
2354-
flag_decl.set((PendingDecl::Ready(decl), finalize || finalized));
2356+
flag_decl.set((PendingDecl::Ready(decl), finalize || finalized, is_open));
23552357
decl.or_else(|| finalize.then_some(self.dummy_decl))
23562358
})
23572359
}
@@ -2393,7 +2395,9 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
23932395
PathResult::Module(ModuleOrUniformRoot::ExternPrelude) | PathResult::Failed { .. } => {
23942396
None
23952397
}
2396-
PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
2398+
path_result @ (PathResult::Module(..) | PathResult::Indeterminate) => {
2399+
bug!("got invalid path_result: {path_result:?}")
2400+
}
23972401
}
23982402
}
23992403

@@ -2511,6 +2515,60 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
25112515
}
25122516
}
25132517

2518+
fn build_extern_prelude<'tcx, 'ra>(
2519+
tcx: TyCtxt<'tcx>,
2520+
attrs: &[ast::Attribute],
2521+
) -> FxIndexMap<IdentKey, ExternPreludeEntry<'ra>> {
2522+
let mut extern_prelude: FxIndexMap<IdentKey, ExternPreludeEntry<'ra>> = tcx
2523+
.sess
2524+
.opts
2525+
.externs
2526+
.iter()
2527+
.filter_map(|(name, entry)| {
2528+
// Make sure `self`, `super`, `_` etc do not get into extern prelude.
2529+
// FIXME: reject `--extern self` and similar in option parsing instead.
2530+
if entry.add_prelude
2531+
&& let sym = Symbol::intern(name)
2532+
&& sym.can_be_raw()
2533+
{
2534+
Some((IdentKey::with_root_ctxt(sym), ExternPreludeEntry::flag()))
2535+
} else {
2536+
None
2537+
}
2538+
})
2539+
.collect();
2540+
2541+
// Add open base entries for namespaced crates whose base segment
2542+
// is missing from the prelude (e.g. `foo::bar` without `foo`).
2543+
// These are necessary in order to resolve the open modules, whereas
2544+
// the namespaced names are necessary in `extern_prelude` for actually
2545+
// resolving the namespaced crates.
2546+
let missing_open_bases: Vec<IdentKey> = extern_prelude
2547+
.keys()
2548+
.filter_map(|ident| {
2549+
let (base, _) = ident.name.as_str().split_once("::")?;
2550+
let base_sym = Symbol::intern(base);
2551+
base_sym.can_be_raw().then(|| IdentKey::with_root_ctxt(base_sym))
2552+
})
2553+
.filter(|base_ident| !extern_prelude.contains_key(base_ident))
2554+
.collect();
2555+
2556+
extern_prelude.extend(
2557+
missing_open_bases.into_iter().map(|ident| (ident, ExternPreludeEntry::open_flag())),
2558+
);
2559+
2560+
// Inject `core` / `std` unless suppressed by attributes.
2561+
if !attr::contains_name(attrs, sym::no_core) {
2562+
extern_prelude.insert(IdentKey::with_root_ctxt(sym::core), ExternPreludeEntry::flag());
2563+
2564+
if !attr::contains_name(attrs, sym::no_std) {
2565+
extern_prelude.insert(IdentKey::with_root_ctxt(sym::std), ExternPreludeEntry::flag());
2566+
}
2567+
}
2568+
2569+
extern_prelude
2570+
}
2571+
25142572
fn names_to_string(names: impl Iterator<Item = Symbol>) -> String {
25152573
let mut result = String::new();
25162574
for (i, name) in names.enumerate().filter(|(_, name)| *name != kw::PathRoot) {

compiler/rustc_session/src/config/externs.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,13 @@ pub(crate) fn split_extern_opt<'a>(
4343
}
4444
};
4545

46+
// Reject paths with more than two segments.
47+
if unstable_opts.namespaced_crates && crate_name.split("::").count() > 2 {
48+
return Err(early_dcx.early_struct_fatal(format!(
49+
"crate name `{crate_name}` passed to `--extern` can have at most two segments."
50+
)));
51+
}
52+
4653
if !valid_crate_name(&crate_name, unstable_opts) {
4754
let mut error = early_dcx.early_struct_fatal(format!(
4855
"crate name `{crate_name}` passed to `--extern` is not a valid ASCII identifier"

0 commit comments

Comments
 (0)