Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ pub fn inject(

let item = cx.item(
span,
thin_vec![cx.attr_word(sym::macro_use, span)],
ast::AttrVec::new(),
ast::ItemKind::ExternCrate(None, Ident::new(name, ident_span)),
);

Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_lint/src/early/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -257,8 +257,8 @@ pub fn decorate_builtin_lint(

lints::ExternCrateNotIdiomatic { span: suggestion_span, code }.decorate_lint(diag);
}
BuiltinLintDiag::AmbiguousGlobImports { diag: ambiguity } => {
lints::AmbiguousGlobImports { ambiguity }.decorate_lint(diag);
BuiltinLintDiag::AmbiguousImports { diag: ambiguity } => {
lints::AmbiguousImports { ambiguity }.decorate_lint(diag);
}
BuiltinLintDiag::AmbiguousGlobReexports {
name,
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_lint/src/lints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2863,11 +2863,11 @@ pub(crate) struct ExternCrateNotIdiomatic {
}

// FIXME: make this translatable
pub(crate) struct AmbiguousGlobImports {
pub(crate) struct AmbiguousImports {
pub ambiguity: AmbiguityErrorDiag,
}

impl<'a, G: EmissionGuarantee> LintDiagnostic<'a, G> for AmbiguousGlobImports {
impl<'a, G: EmissionGuarantee> LintDiagnostic<'a, G> for AmbiguousImports {
fn decorate_lint<'b>(self, diag: &'b mut Diag<'a, G>) {
diag.primary_message(self.ambiguity.msg.clone());
rustc_errors::report_ambiguity_error(diag, self.ambiguity);
Expand Down
38 changes: 38 additions & 0 deletions compiler/rustc_lint_defs/src/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ declare_lint_pass! {
AMBIGUOUS_ASSOCIATED_ITEMS,
AMBIGUOUS_GLOB_IMPORTS,
AMBIGUOUS_GLOB_REEXPORTS,
AMBIGUOUS_PANIC_IMPORTS,
ARITHMETIC_OVERFLOW,
ASM_SUB_REGISTER,
BAD_ASM_STYLE,
Expand Down Expand Up @@ -4438,6 +4439,43 @@ declare_lint! {
};
}

declare_lint! {
/// The `ambiguous_panic_imports` lint detects ambiguous core and std panic imports, but
/// previously didn't do that due to `#[macro_use]` prelude macro import.
///
/// ### Example
///
/// ```rust,compile_fail
/// #![deny(ambiguous_panic_imports)]
/// #![no_std]
///
/// extern crate std;
/// use std::prelude::v1::*;
///
/// fn xx() {
/// panic!(); // resolves to core::panic
/// }
/// ```
///
/// {{produces}}
///
/// ### Explanation
///
/// Future versions of Rust will no longer accept the ambiguous resolution.
///
/// This is a [future-incompatible] lint to transition this to a hard error in the future.
///
/// [future-incompatible]: ../index.md#future-incompatible-lints
pub AMBIGUOUS_PANIC_IMPORTS,
Warn,
"detects ambiguous core and std panic imports",
@future_incompatible = FutureIncompatibleInfo {
reason: FutureIncompatibilityReason::FutureReleaseError,
reference: "issue #147319 <https://github.com/rust-lang/rust/issues/147319>",
report_in_deps: true,
};
}

declare_lint! {
/// The `refining_impl_trait_reachable` lint detects `impl Trait` return
/// types in method signatures that are refined by a publically reachable
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_lint_defs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -682,7 +682,7 @@ pub enum BuiltinLintDiag {
vis_span: Span,
ident_span: Span,
},
AmbiguousGlobImports {
AmbiguousImports {
diag: AmbiguityErrorDiag,
},
AmbiguousGlobReexports {
Expand Down
20 changes: 13 additions & 7 deletions compiler/rustc_resolve/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use rustc_middle::bug;
use rustc_middle::ty::TyCtxt;
use rustc_session::Session;
use rustc_session::lint::builtin::{
ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE, AMBIGUOUS_GLOB_IMPORTS,
ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE, AMBIGUOUS_GLOB_IMPORTS, AMBIGUOUS_PANIC_IMPORTS,
MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS,
};
use rustc_session::lint::{AmbiguityErrorDiag, BuiltinLintDiag};
Expand All @@ -42,9 +42,9 @@ use crate::errors::{
use crate::imports::{Import, ImportKind};
use crate::late::{PatternSource, Rib};
use crate::{
AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, BindingError, BindingKey, Finalize,
ForwardGenericParamBanReason, HasGenericParams, LexicalScopeBinding, MacroRulesScope, Module,
ModuleKind, ModuleOrUniformRoot, NameBinding, NameBindingKind, ParentScope, PathResult,
AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, AmbiguityWarning, BindingError, BindingKey,
Finalize, ForwardGenericParamBanReason, HasGenericParams, LexicalScopeBinding, MacroRulesScope,
Module, ModuleKind, ModuleOrUniformRoot, NameBinding, NameBindingKind, ParentScope, PathResult,
PrivacyError, ResolutionError, Resolver, Scope, ScopeSet, Segment, UseError, Used,
VisResolutionError, errors as errs, path_names_to_string,
};
Expand Down Expand Up @@ -144,15 +144,21 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {

for ambiguity_error in &self.ambiguity_errors {
let diag = self.ambiguity_diagnostics(ambiguity_error);
if ambiguity_error.warning {
if let Some(ambiguity_warning) = ambiguity_error.warning {
let NameBindingKind::Import { import, .. } = ambiguity_error.b1.0.kind else {
unreachable!()
};

let lint = match ambiguity_warning {
AmbiguityWarning::GlobImport => AMBIGUOUS_GLOB_IMPORTS,
AmbiguityWarning::PanicImport => AMBIGUOUS_PANIC_IMPORTS,
};

self.lint_buffer.buffer_lint(
AMBIGUOUS_GLOB_IMPORTS,
lint,
import.root_id,
ambiguity_error.ident.span,
BuiltinLintDiag::AmbiguousGlobImports { diag },
BuiltinLintDiag::AmbiguousImports { diag },
);
} else {
let mut err = struct_span_code_err!(self.dcx(), diag.span, E0659, "{}", diag.msg);
Expand Down
43 changes: 32 additions & 11 deletions compiler/rustc_resolve/src/ident.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ use crate::imports::{Import, NameResolution};
use crate::late::{ConstantHasGenerics, NoConstantGenericsReason, PathSource, Rib, RibKind};
use crate::macros::{MacroRulesScope, sub_namespace_match};
use crate::{
AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, BindingKey, CmResolver, Determinacy,
Finalize, ImportKind, LexicalScopeBinding, Module, ModuleKind, ModuleOrUniformRoot,
NameBinding, NameBindingKind, ParentScope, PathResult, PrivacyError, Res, ResolutionError,
Resolver, Scope, ScopeSet, Segment, Stage, Used, Weak, errors,
AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, AmbiguityWarning, BindingKey, CmResolver,
Determinacy, Finalize, ImportKind, LexicalScopeBinding, Module, ModuleKind,
ModuleOrUniformRoot, NameBinding, NameBindingKind, ParentScope, PathResult, PrivacyError, Res,
ResolutionError, Resolver, Scope, ScopeSet, Segment, Stage, Used, Weak, errors,
};

#[derive(Copy, Clone)]
Expand Down Expand Up @@ -697,13 +697,34 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
// Skip ambiguity errors for extern flag bindings "overridden"
// by extern item bindings.
// FIXME: Remove with lang team approval.
let issue_145575_hack = Some(binding)
== extern_prelude_flag_binding
&& extern_prelude_item_binding.is_some()
&& extern_prelude_item_binding != Some(innermost_binding);
let is_issue_145575_hack = || {
Some(binding) == extern_prelude_flag_binding
&& extern_prelude_item_binding.is_some()
&& extern_prelude_item_binding != Some(innermost_binding)
};

if let Some(kind) = ambiguity_error_kind
&& !issue_145575_hack
&& !is_issue_145575_hack()
{
// Turn ambiguity errors for core vs std panic into warnings.
// FIXME: Remove with lang team approval.
let is_issue_147319_hack = matches!(
(binding.res(), innermost_binding.res()),
(
Res::Def(DefKind::Macro(_), def_id_core),
Res::Def(DefKind::Macro(_), def_id_std)
) if this.tcx.def_path_debug_str(def_id_core)
== "core[234c]::macros::panic"
&& this.tcx.def_path_debug_str(def_id_std)
== "std[d474]::macros::panic"
);

let warning = if is_issue_147319_hack {
Some(AmbiguityWarning::PanicImport)
} else {
None
};

let misc = |f: Flags| {
if f.contains(Flags::MISC_SUGGEST_CRATE) {
AmbiguityErrorMisc::SuggestCrate
Expand All @@ -720,7 +741,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
ident: orig_ident,
b1: innermost_binding,
b2: binding,
warning: false,
warning,
misc1: misc(innermost_flags),
misc2: misc(flags),
});
Expand Down Expand Up @@ -1064,7 +1085,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
ident,
b1: binding,
b2: shadowed_glob,
warning: false,
warning: None,
misc1: AmbiguityErrorMisc::None,
misc2: AmbiguityErrorMisc::None,
});
Expand Down
7 changes: 4 additions & 3 deletions compiler/rustc_resolve/src/imports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -957,8 +957,9 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
ImportKind::Single { bindings, .. } => bindings[TypeNS].get().binding(),
_ => None,
};
let ambiguity_errors_len =
|errors: &Vec<AmbiguityError<'_>>| errors.iter().filter(|error| !error.warning).count();
let ambiguity_errors_len = |errors: &Vec<AmbiguityError<'_>>| {
errors.iter().filter(|error| error.warning.is_none()).count()
};
let prev_ambiguity_errors_len = ambiguity_errors_len(&self.ambiguity_errors);
let finalize = Finalize::with_root_span(import.root_id, import.span, import.root_span);

Expand Down Expand Up @@ -1173,7 +1174,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
});
let res = binding.res();
let has_ambiguity_error =
this.ambiguity_errors.iter().any(|error| !error.warning);
this.ambiguity_errors.iter().any(|error| error.warning.is_none());
if res == Res::Err || has_ambiguity_error {
this.dcx()
.span_delayed_bug(import.span, "some error happened for an import");
Expand Down
10 changes: 8 additions & 2 deletions compiler/rustc_resolve/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -903,14 +903,20 @@ enum AmbiguityErrorMisc {
None,
}

#[derive(Clone, Copy, PartialEq)]
enum AmbiguityWarning {
GlobImport,
PanicImport,
}

struct AmbiguityError<'ra> {
kind: AmbiguityKind,
ident: Ident,
b1: NameBinding<'ra>,
b2: NameBinding<'ra>,
misc1: AmbiguityErrorMisc,
misc2: AmbiguityErrorMisc,
warning: bool,
warning: Option<AmbiguityWarning>,
}

impl<'ra> NameBindingData<'ra> {
Expand Down Expand Up @@ -2046,7 +2052,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
b2,
misc1: AmbiguityErrorMisc::None,
misc2: AmbiguityErrorMisc::None,
warning: warn_ambiguity,
warning: if warn_ambiguity { Some(AmbiguityWarning::GlobImport) } else { None },
};
if !self.matches_previous_ambiguity_error(&ambiguity_error) {
// avoid duplicated span information to be emit out
Expand Down
12 changes: 9 additions & 3 deletions library/alloctests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
#![feature(negative_impls)]
#![feature(never_type)]
#![feature(optimize_attribute)]
#![feature(prelude_import)]
#![feature(rustc_allow_const_fn_unstable)]
#![feature(rustc_attrs)]
#![feature(staged_api)]
Expand All @@ -65,11 +66,17 @@

// Allow testing this library
extern crate alloc as realalloc;
#[macro_use]

// This is needed to provide macros to the directly imported alloc modules below.
extern crate std;
#[prelude_import]
#[allow(unused_imports)]
use std::prelude::rust_2024::*;

#[cfg(test)]
extern crate test;
mod testing;

use realalloc::*;

// We are directly including collections, raw_vec, and wtf8 here as they use non-public
Expand All @@ -93,8 +100,7 @@ pub(crate) mod test_helpers {
let mut hasher = std::hash::RandomState::new().build_hasher();
std::panic::Location::caller().hash(&mut hasher);
let hc64 = hasher.finish();
let seed_vec =
hc64.to_le_bytes().into_iter().chain(0u8..8).collect::<crate::vec::Vec<u8>>();
let seed_vec = hc64.to_le_bytes().into_iter().chain(0u8..8).collect::<std::vec::Vec<u8>>();
let seed: [u8; 16] = seed_vec.as_slice().try_into().unwrap();
rand::SeedableRng::from_seed(seed)
}
Expand Down
47 changes: 44 additions & 3 deletions library/core/src/prelude/v1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,29 @@ pub use crate::hash::macros::Hash;

#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
#[doc(no_inline)]
#[allow(deprecated)]
pub use crate::{
assert, cfg, column, compile_error, concat, env, file, format_args,
format_args_nl, include, include_bytes, include_str, line, log_syntax, module_path, option_env,
stringify, trace_macros,
assert, assert_eq, assert_ne, cfg, column, compile_error, concat, debug_assert, debug_assert_eq, debug_assert_ne, file, format_args, include, include_bytes, include_str, line, matches, module_path, option_env, stringify, todo, r#try, unimplemented, unreachable, write, writeln,
};

// These macros needs special handling, so that we don't export it *and* the modules of the same
// name. We only want the macro in the prelude.
mod ambiguous_macro_only {
#[allow(hidden_glob_reexports)]
mod env {}
#[allow(hidden_glob_reexports)]
mod panic {}
#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
pub use crate::*;
}
#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
#[doc(no_inline)]
pub use self::ambiguous_macro_only::{env, panic};

#[unstable(feature = "cfg_select", issue = "115585")]
#[doc(no_inline)]
pub use crate::cfg_select;

#[unstable(
feature = "concat_bytes",
issue = "87555",
Expand All @@ -73,6 +90,30 @@ pub use crate::{
#[doc(no_inline)]
pub use crate::concat_bytes;

#[unstable(feature = "const_format_args", issue = "none")]
#[doc(no_inline)]
pub use crate::const_format_args;

#[unstable(
feature = "log_syntax",
issue = "29598",
reason = "`log_syntax!` is not stable enough for use and is subject to change"
)]
#[doc(no_inline)]
pub use crate::log_syntax;

#[unstable(feature = "pattern_type_macro", issue = "123646")]
#[doc(no_inline)]
pub use crate::pattern_type;

#[unstable(
feature = "trace_macros",
issue = "29598",
reason = "`trace_macros` is not stable enough for use and is subject to change"
)]
#[doc(no_inline)]
pub use crate::trace_macros;

// Do not `doc(no_inline)` so that they become doc items on their own
// (no public module for them to be re-exported from).
#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
Expand Down
7 changes: 5 additions & 2 deletions library/proc_macro/src/bridge/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,12 @@

use std::cell::RefCell;
use std::num::NonZero;
use std::str;
use std::{fmt, str};

use super::*;
// Explicit import to avoid macro namespace collision.
use super::{
DecodeMut, Encode, Mark, Marked, Reader, Unmark, Writer, arena, client, fxhash, server,
};

/// Handle for a symbol string stored within the Interner.
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
Expand Down
Loading
Loading