Skip to content

Rollup of 9 pull requests #142794

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 24 commits into from
Jun 21, 2025
Merged
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
32cb8f1
Add trim_prefix and trim_suffix for slice and str.
deven Jun 11, 2025
6ca4639
Fix random failure when JS code is executed when the whole file was n…
GuillaumeGomez Jun 14, 2025
2eccf18
Add comment to prevent having code other than `initSearch` at the end…
GuillaumeGomez Jun 16, 2025
815f0b7
better template for repr attributes
jdonszelmann Jun 12, 2025
7f49de2
fixup missing docs in attr parsing
jdonszelmann Jun 12, 2025
496cbe1
mbe: Move `transcribe_metavar_expr` directly after `transcribe`
tgross35 Jun 19, 2025
67a9fb2
mbe: Refactor transcription
tgross35 Jun 19, 2025
07b9bb1
Extract Translator struct
camsteffen Jun 19, 2025
316f63b
Rename SilentEmitter -> FatalOnlyEmitter
camsteffen Jun 17, 2025
3388d83
Extract SilentEmitter
camsteffen Jun 19, 2025
aab941f
rustdoc: Remove `FormatRenderer::cache`
aDotInTheVoid Jun 19, 2025
e159cf0
Add regression test
oli-obk Jun 16, 2025
cfc22cf
Ensure copy* intrinsics also perform the static self-init checks
oli-obk Jun 16, 2025
de0fd27
cold
jdonszelmann Jun 12, 2025
b9107a8
expected word diagnostic test
jdonszelmann Jun 12, 2025
851fbcb
Rollup merge of #142331 - deven:trim_prefix_suffix, r=Amanieu
tgross35 Jun 20, 2025
f0374dc
Rollup merge of #142491 - jdonszelmann:cold, r=oli-obk
tgross35 Jun 20, 2025
d2a00eb
Rollup merge of #142494 - jdonszelmann:missing-attr-parsing-docs, r=o…
tgross35 Jun 20, 2025
1e2ac53
Rollup merge of #142495 - jdonszelmann:better-repr-template, r=oli-obk
tgross35 Jun 20, 2025
bad4bf5
Rollup merge of #142497 - GuillaumeGomez:fix-random-search-failure, r…
tgross35 Jun 20, 2025
5d6ecf5
Rollup merge of #142575 - oli-obk:sneaky-self-init, r=RalfJung
tgross35 Jun 20, 2025
38600a6
Rollup merge of #142650 - camsteffen:refactor-translator, r=petrochenkov
tgross35 Jun 20, 2025
e7a2c40
Rollup merge of #142713 - tgross35:mbe-transcribe-refactor, r=petroch…
tgross35 Jun 20, 2025
61f4918
Rollup merge of #142755 - aDotInTheVoid:rdj-shattrs, r=GuillaumeGomez
tgross35 Jun 20, 2025
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
3 changes: 3 additions & 0 deletions compiler/rustc_attr_data_structures/src/attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,9 @@ pub enum AttributeKind {
span: Span,
},

/// Represents `#[cold]`.
Cold(Span),

/// Represents `#[rustc_confusables]`.
Confusables {
symbols: ThinVec<Symbol>,
Expand Down
18 changes: 18 additions & 0 deletions compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,21 @@ impl<S: Stage> SingleAttributeParser<S> for OptimizeParser {
Some(AttributeKind::Optimize(res, cx.attr_span))
}
}

pub(crate) struct ColdParser;

impl<S: Stage> SingleAttributeParser<S> for ColdParser {
const PATH: &[rustc_span::Symbol] = &[sym::cold];
const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepLast;
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
const TEMPLATE: AttributeTemplate = template!(Word);

fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser<'_>) -> Option<AttributeKind> {
if !args.no_args() {
cx.expected_no_args(args.span().unwrap_or(cx.attr_span));
return None;
};

Some(AttributeKind::Cold(cx.attr_span))
}
}
19 changes: 19 additions & 0 deletions compiler/rustc_attr_parsing/src/attributes/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,19 @@ pub(crate) trait AttributeParser<S: Stage>: Default + 'static {
/// [`SingleAttributeParser`] can only convert attributes one-to-one, and cannot combine multiple
/// attributes together like is necessary for `#[stable()]` and `#[unstable()]` for example.
pub(crate) trait SingleAttributeParser<S: Stage>: 'static {
/// The single path of the attribute this parser accepts.
///
/// If you need the parser to accept more than one path, use [`AttributeParser`] instead
const PATH: &[Symbol];

/// Configures the precedence of attributes with the same `PATH` on a syntax node.
const ATTRIBUTE_ORDER: AttributeOrder;

/// Configures what to do when when the same attribute is
/// applied more than once on the same syntax node.
///
/// [`ATTRIBUTE_ORDER`](Self::ATTRIBUTE_ORDER) specified which one is assumed to be correct,
/// and this specified whether to, for example, warn or error on the other one.
const ON_DUPLICATE: OnDuplicate<S>;

/// The template this attribute parser should implement. Used for diagnostics.
Expand All @@ -98,6 +109,8 @@ pub(crate) trait SingleAttributeParser<S: Stage>: 'static {
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser<'_>) -> Option<AttributeKind>;
}

/// Use in combination with [`SingleAttributeParser`].
/// `Single<T: SingleAttributeParser>` implements [`AttributeParser`].
pub(crate) struct Single<T: SingleAttributeParser<S>, S: Stage>(
PhantomData<(S, T)>,
Option<(AttributeKind, Span)>,
Expand Down Expand Up @@ -230,6 +243,10 @@ pub(crate) trait CombineAttributeParser<S: Stage>: 'static {
const PATH: &[rustc_span::Symbol];

type Item;
/// A function that converts individual items (of type [`Item`](Self::Item)) into the final attribute.
///
/// For example, individual representations fomr `#[repr(...)]` attributes into an `AttributeKind::Repr(x)`,
/// where `x` is a vec of these individual reprs.
const CONVERT: ConvertFn<Self::Item>;

/// The template this attribute parser should implement. Used for diagnostics.
Expand All @@ -242,6 +259,8 @@ pub(crate) trait CombineAttributeParser<S: Stage>: 'static {
) -> impl IntoIterator<Item = Self::Item> + 'c;
}

/// Use in combination with [`CombineAttributeParser`].
/// `Combine<T: CombineAttributeParser>` implements [`AttributeParser`].
pub(crate) struct Combine<T: CombineAttributeParser<S>, S: Stage>(
PhantomData<(S, T)>,
ThinVec<<T as CombineAttributeParser<S>>::Item>,
Expand Down
3 changes: 2 additions & 1 deletion compiler/rustc_attr_parsing/src/attributes/repr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ impl<S: Stage> CombineAttributeParser<S> for ReprParser {
const PATH: &[Symbol] = &[sym::repr];
const CONVERT: ConvertFn<Self::Item> = AttributeKind::Repr;
// FIXME(jdonszelmann): never used
const TEMPLATE: AttributeTemplate = template!(List: "C");
const TEMPLATE: AttributeTemplate =
template!(List: "C | Rust | align(...) | packed(...) | <integer type> | transparent");

fn extend<'c>(
cx: &'c mut AcceptContext<'_, '_, S>,
Expand Down
13 changes: 12 additions & 1 deletion compiler/rustc_attr_parsing/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use rustc_session::Session;
use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, Symbol, sym};

use crate::attributes::allow_unstable::{AllowConstFnUnstableParser, AllowInternalUnstableParser};
use crate::attributes::codegen_attrs::OptimizeParser;
use crate::attributes::codegen_attrs::{ColdParser, OptimizeParser};
use crate::attributes::confusables::ConfusablesParser;
use crate::attributes::deprecation::DeprecationParser;
use crate::attributes::inline::{InlineParser, RustcForceInlineParser};
Expand Down Expand Up @@ -106,6 +106,7 @@ attribute_parsers!(

// tidy-alphabetical-start
Single<AsPtrParser>,
Single<ColdParser>,
Single<ConstStabilityIndirectParser>,
Single<DeprecationParser>,
Single<InlineParser>,
Expand Down Expand Up @@ -234,6 +235,16 @@ impl<'f, 'sess: 'f, S: Stage> AcceptContext<'f, 'sess, S> {
})
}

pub(crate) fn expected_no_args(&self, args_span: Span) -> ErrorGuaranteed {
self.emit_err(AttributeParseError {
span: args_span,
attr_span: self.attr_span,
template: self.template.clone(),
attribute: self.attr_path.clone(),
reason: AttributeParseErrorReason::ExpectedNoArgs,
})
}

/// emit an error that a `name = value` pair was expected at this span. The symbol can be given for
/// a nicer error message talking about the specific name that was found lacking a value.
pub(crate) fn expected_name_value(&self, span: Span, name: Option<Symbol>) -> ErrorGuaranteed {
Expand Down
5 changes: 5 additions & 0 deletions compiler/rustc_attr_parsing/src/session_diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,7 @@ pub(crate) struct UnrecognizedReprHint {
}

pub(crate) enum AttributeParseErrorReason {
ExpectedNoArgs,
ExpectedStringLiteral { byte_string: Option<Span> },
ExpectedSingleArgument,
ExpectedList,
Expand Down Expand Up @@ -529,6 +530,10 @@ impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for AttributeParseError {
diag.span_label(self.span, format!("didn't expect a literal here"));
diag.code(E0565);
}
AttributeParseErrorReason::ExpectedNoArgs => {
diag.span_label(self.span, format!("didn't expect any arguments here"));
diag.code(E0565);
}
AttributeParseErrorReason::ExpectedNameValue(None) => {
diag.span_label(
self.span,
Expand Down
20 changes: 7 additions & 13 deletions compiler/rustc_codegen_ssa/src/back/write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ use rustc_data_structures::jobserver::{self, Acquired};
use rustc_data_structures::memmap::Mmap;
use rustc_data_structures::profiling::{SelfProfilerRef, VerboseTimingGuard};
use rustc_errors::emitter::Emitter;
use rustc_errors::translation::Translate;
use rustc_errors::translation::Translator;
use rustc_errors::{
Diag, DiagArgMap, DiagCtxt, DiagMessage, ErrCode, FatalError, FluentBundle, Level, MultiSpan,
Style, Suggestions,
Diag, DiagArgMap, DiagCtxt, DiagMessage, ErrCode, FatalError, Level, MultiSpan, Style,
Suggestions,
};
use rustc_fs_util::link_or_copy;
use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
Expand Down Expand Up @@ -1889,16 +1889,6 @@ impl SharedEmitter {
}
}

impl Translate for SharedEmitter {
fn fluent_bundle(&self) -> Option<&FluentBundle> {
None
}

fn fallback_fluent_bundle(&self) -> &FluentBundle {
panic!("shared emitter attempted to translate a diagnostic");
}
}

impl Emitter for SharedEmitter {
fn emit_diagnostic(
&mut self,
Expand Down Expand Up @@ -1932,6 +1922,10 @@ impl Emitter for SharedEmitter {
fn source_map(&self) -> Option<&SourceMap> {
None
}

fn translator(&self) -> &Translator {
panic!("shared emitter attempted to translate a diagnostic");
}
}

impl SharedEmitterMain {
Expand Down
19 changes: 15 additions & 4 deletions compiler/rustc_codegen_ssa/src/codegen_attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use rustc_abi::ExternAbi;
use rustc_ast::expand::autodiff_attrs::{AutoDiffAttrs, DiffActivity, DiffMode};
use rustc_ast::{LitKind, MetaItem, MetaItemInner, attr};
use rustc_attr_data_structures::{
AttributeKind, InlineAttr, InstructionSetAttr, OptimizeAttr, find_attr,
AttributeKind, InlineAttr, InstructionSetAttr, OptimizeAttr, ReprAttr, find_attr,
};
use rustc_hir::def::DefKind;
use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
Expand Down Expand Up @@ -110,16 +110,27 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
}
};

if let hir::Attribute::Parsed(AttributeKind::Align { align, .. }) = attr {
codegen_fn_attrs.alignment = Some(*align);
if let hir::Attribute::Parsed(p) = attr {
match p {
AttributeKind::Repr(reprs) => {
codegen_fn_attrs.alignment = reprs
.iter()
.filter_map(
|(r, _)| if let ReprAttr::ReprAlign(x) = r { Some(*x) } else { None },
)
.max();
}
AttributeKind::Cold(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD,
AttributeKind::Align { align, .. } => codegen_fn_attrs.alignment = Some(*align),
_ => {}
}
}

let Some(Ident { name, .. }) = attr.ident() else {
continue;
};

match name {
sym::cold => codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD,
sym::rustc_allocator => codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR,
sym::ffi_pure => codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_PURE,
sym::ffi_const => codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_CONST,
Expand Down
7 changes: 6 additions & 1 deletion compiler/rustc_const_eval/src/interpret/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1412,8 +1412,13 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
let src_alloc = self.get_alloc_raw(src_alloc_id)?;
let src_range = alloc_range(src_offset, size);
assert!(!self.memory.validation_in_progress.get(), "we can't be copying during validation");
// For the overlapping case, it is crucial that we trigger the read hook

// Trigger read hooks.
// For the overlapping case, it is crucial that we trigger the read hooks
// before the write hook -- the aliasing model cares about the order.
if let Ok((alloc_id, ..)) = self.ptr_try_get_alloc_id(src, size.bytes() as i64) {
M::before_alloc_read(self, alloc_id)?;
}
M::before_memory_read(
tcx,
&self.machine,
Expand Down
10 changes: 7 additions & 3 deletions compiler/rustc_driver_impl/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ use rustc_data_structures::profiling::{
};
use rustc_errors::emitter::stderr_destination;
use rustc_errors::registry::Registry;
use rustc_errors::translation::Translator;
use rustc_errors::{ColorConfig, DiagCtxt, ErrCode, FatalError, PResult, markdown};
use rustc_feature::find_gated_cfg;
// This avoids a false positive with `-Wunused_crate_dependencies`.
Expand Down Expand Up @@ -109,6 +110,10 @@ use crate::session_diagnostics::{

rustc_fluent_macro::fluent_messages! { "../messages.ftl" }

pub fn default_translator() -> Translator {
Translator::with_fallback_bundle(DEFAULT_LOCALE_RESOURCES.to_vec(), false)
}

pub static DEFAULT_LOCALE_RESOURCES: &[&str] = &[
// tidy-alphabetical-start
crate::DEFAULT_LOCALE_RESOURCE,
Expand Down Expand Up @@ -1413,11 +1418,10 @@ fn report_ice(
extra_info: fn(&DiagCtxt),
using_internal_features: &AtomicBool,
) {
let fallback_bundle =
rustc_errors::fallback_fluent_bundle(crate::DEFAULT_LOCALE_RESOURCES.to_vec(), false);
let translator = default_translator();
let emitter = Box::new(rustc_errors::emitter::HumanEmitter::new(
stderr_destination(rustc_errors::ColorConfig::Auto),
fallback_bundle,
translator,
));
let dcx = rustc_errors::DiagCtxt::new(emitter);
let dcx = dcx.handle();
Expand Down
10 changes: 5 additions & 5 deletions compiler/rustc_error_messages/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ pub use fluent_bundle::{self, FluentArgs, FluentError, FluentValue};
use fluent_syntax::parser::ParserError;
use icu_provider_adapters::fallback::{LocaleFallbackProvider, LocaleFallbacker};
use intl_memoizer::concurrent::IntlLangMemoizer;
use rustc_data_structures::sync::IntoDynSyncSend;
use rustc_data_structures::sync::{DynSend, IntoDynSyncSend};
use rustc_macros::{Decodable, Encodable};
use rustc_span::Span;
use smallvec::SmallVec;
Expand Down Expand Up @@ -204,16 +204,16 @@ fn register_functions(bundle: &mut FluentBundle) {

/// Type alias for the result of `fallback_fluent_bundle` - a reference-counted pointer to a lazily
/// evaluated fluent bundle.
pub type LazyFallbackBundle = Arc<LazyLock<FluentBundle, impl FnOnce() -> FluentBundle>>;
pub type LazyFallbackBundle =
Arc<LazyLock<FluentBundle, Box<dyn FnOnce() -> FluentBundle + DynSend>>>;

/// Return the default `FluentBundle` with standard "en-US" diagnostic messages.
#[instrument(level = "trace", skip(resources))]
#[define_opaque(LazyFallbackBundle)]
pub fn fallback_fluent_bundle(
resources: Vec<&'static str>,
with_directionality_markers: bool,
) -> LazyFallbackBundle {
Arc::new(LazyLock::new(move || {
Arc::new(LazyLock::new(Box::new(move || {
let mut fallback_bundle = new_bundle(vec![langid!("en-US")]);

register_functions(&mut fallback_bundle);
Expand All @@ -228,7 +228,7 @@ pub fn fallback_fluent_bundle(
}

fallback_bundle
}))
})))
}

/// Identifier for the Fluent message/attribute corresponding to a diagnostic message.
Expand Down
36 changes: 10 additions & 26 deletions compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,15 @@ use rustc_span::source_map::SourceMap;
use crate::emitter::FileWithAnnotatedLines;
use crate::registry::Registry;
use crate::snippet::Line;
use crate::translation::{Translate, to_fluent_args};
use crate::translation::{Translator, to_fluent_args};
use crate::{
CodeSuggestion, DiagInner, DiagMessage, Emitter, ErrCode, FluentBundle, LazyFallbackBundle,
Level, MultiSpan, Style, Subdiag,
CodeSuggestion, DiagInner, DiagMessage, Emitter, ErrCode, Level, MultiSpan, Style, Subdiag,
};

/// Generates diagnostics using annotate-snippet
pub struct AnnotateSnippetEmitter {
source_map: Option<Arc<SourceMap>>,
fluent_bundle: Option<Arc<FluentBundle>>,
fallback_bundle: LazyFallbackBundle,
translator: Translator,

/// If true, hides the longer explanation text
short_message: bool,
Expand All @@ -35,16 +33,6 @@ pub struct AnnotateSnippetEmitter {
macro_backtrace: bool,
}

impl Translate for AnnotateSnippetEmitter {
fn fluent_bundle(&self) -> Option<&FluentBundle> {
self.fluent_bundle.as_deref()
}

fn fallback_fluent_bundle(&self) -> &FluentBundle {
&self.fallback_bundle
}
}

impl Emitter for AnnotateSnippetEmitter {
/// The entry point for the diagnostics generation
fn emit_diagnostic(&mut self, mut diag: DiagInner, _registry: &Registry) {
Expand Down Expand Up @@ -78,6 +66,10 @@ impl Emitter for AnnotateSnippetEmitter {
fn should_show_explain(&self) -> bool {
!self.short_message
}

fn translator(&self) -> &Translator {
&self.translator
}
}

/// Provides the source string for the given `line` of `file`
Expand All @@ -104,19 +96,11 @@ fn annotation_level_for_level(level: Level) -> annotate_snippets::Level {
impl AnnotateSnippetEmitter {
pub fn new(
source_map: Option<Arc<SourceMap>>,
fluent_bundle: Option<Arc<FluentBundle>>,
fallback_bundle: LazyFallbackBundle,
translator: Translator,
short_message: bool,
macro_backtrace: bool,
) -> Self {
Self {
source_map,
fluent_bundle,
fallback_bundle,
short_message,
ui_testing: false,
macro_backtrace,
}
Self { source_map, translator, short_message, ui_testing: false, macro_backtrace }
}

/// Allows to modify `Self` to enable or disable the `ui_testing` flag.
Expand All @@ -137,7 +121,7 @@ impl AnnotateSnippetEmitter {
_children: &[Subdiag],
_suggestions: &[CodeSuggestion],
) {
let message = self.translate_messages(messages, args);
let message = self.translator.translate_messages(messages, args);
if let Some(source_map) = &self.source_map {
// Make sure our primary file comes first
let primary_lo = if let Some(primary_span) = msp.primary_span().as_ref() {
Expand Down
Loading
Loading