Skip to content

Commit 15c701f

Browse files
committed
Auto merge of #142794 - tgross35:rollup-iae7okj, r=tgross35
Rollup of 9 pull requests Successful merges: - #142331 (Add `trim_prefix` and `trim_suffix` methods for both `slice` and `str` types.) - #142491 (Rework #[cold] attribute parser) - #142494 (Fix missing docs in `rustc_attr_parsing`) - #142495 (Better template for `#[repr]` attributes) - #142497 (Fix random failure when JS code is executed when the whole file was not read yet) - #142575 (Ensure copy* intrinsics also perform the static self-init checks) - #142650 (Refactor Translator) - #142713 (mbe: Refactor transcription) - #142755 (rustdoc: Remove `FormatRenderer::cache`) r? `@ghost` `@rustbot` modify labels: rollup
2 parents 5526a2f + 61f4918 commit 15c701f

File tree

46 files changed

+997
-757
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

46 files changed

+997
-757
lines changed

compiler/rustc_attr_data_structures/src/attributes.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,9 @@ pub enum AttributeKind {
202202
span: Span,
203203
},
204204

205+
/// Represents `#[cold]`.
206+
Cold(Span),
207+
205208
/// Represents `#[rustc_confusables]`.
206209
Confusables {
207210
symbols: ThinVec<Symbol>,

compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,3 +38,21 @@ impl<S: Stage> SingleAttributeParser<S> for OptimizeParser {
3838
Some(AttributeKind::Optimize(res, cx.attr_span))
3939
}
4040
}
41+
42+
pub(crate) struct ColdParser;
43+
44+
impl<S: Stage> SingleAttributeParser<S> for ColdParser {
45+
const PATH: &[rustc_span::Symbol] = &[sym::cold];
46+
const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepLast;
47+
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Warn;
48+
const TEMPLATE: AttributeTemplate = template!(Word);
49+
50+
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser<'_>) -> Option<AttributeKind> {
51+
if !args.no_args() {
52+
cx.expected_no_args(args.span().unwrap_or(cx.attr_span));
53+
return None;
54+
};
55+
56+
Some(AttributeKind::Cold(cx.attr_span))
57+
}
58+
}

compiler/rustc_attr_parsing/src/attributes/mod.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,8 +87,19 @@ pub(crate) trait AttributeParser<S: Stage>: Default + 'static {
8787
/// [`SingleAttributeParser`] can only convert attributes one-to-one, and cannot combine multiple
8888
/// attributes together like is necessary for `#[stable()]` and `#[unstable()]` for example.
8989
pub(crate) trait SingleAttributeParser<S: Stage>: 'static {
90+
/// The single path of the attribute this parser accepts.
91+
///
92+
/// If you need the parser to accept more than one path, use [`AttributeParser`] instead
9093
const PATH: &[Symbol];
94+
95+
/// Configures the precedence of attributes with the same `PATH` on a syntax node.
9196
const ATTRIBUTE_ORDER: AttributeOrder;
97+
98+
/// Configures what to do when when the same attribute is
99+
/// applied more than once on the same syntax node.
100+
///
101+
/// [`ATTRIBUTE_ORDER`](Self::ATTRIBUTE_ORDER) specified which one is assumed to be correct,
102+
/// and this specified whether to, for example, warn or error on the other one.
92103
const ON_DUPLICATE: OnDuplicate<S>;
93104

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

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

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

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

262+
/// Use in combination with [`CombineAttributeParser`].
263+
/// `Combine<T: CombineAttributeParser>` implements [`AttributeParser`].
245264
pub(crate) struct Combine<T: CombineAttributeParser<S>, S: Stage>(
246265
PhantomData<(S, T)>,
247266
ThinVec<<T as CombineAttributeParser<S>>::Item>,

compiler/rustc_attr_parsing/src/attributes/repr.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@ impl<S: Stage> CombineAttributeParser<S> for ReprParser {
2525
const PATH: &[Symbol] = &[sym::repr];
2626
const CONVERT: ConvertFn<Self::Item> = AttributeKind::Repr;
2727
// FIXME(jdonszelmann): never used
28-
const TEMPLATE: AttributeTemplate = template!(List: "C");
28+
const TEMPLATE: AttributeTemplate =
29+
template!(List: "C | Rust | align(...) | packed(...) | <integer type> | transparent");
2930

3031
fn extend<'c>(
3132
cx: &'c mut AcceptContext<'_, '_, S>,

compiler/rustc_attr_parsing/src/context.rs

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ use rustc_session::Session;
1515
use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, Symbol, sym};
1616

1717
use crate::attributes::allow_unstable::{AllowConstFnUnstableParser, AllowInternalUnstableParser};
18-
use crate::attributes::codegen_attrs::OptimizeParser;
18+
use crate::attributes::codegen_attrs::{ColdParser, OptimizeParser};
1919
use crate::attributes::confusables::ConfusablesParser;
2020
use crate::attributes::deprecation::DeprecationParser;
2121
use crate::attributes::inline::{InlineParser, RustcForceInlineParser};
@@ -106,6 +106,7 @@ attribute_parsers!(
106106

107107
// tidy-alphabetical-start
108108
Single<AsPtrParser>,
109+
Single<ColdParser>,
109110
Single<ConstStabilityIndirectParser>,
110111
Single<DeprecationParser>,
111112
Single<InlineParser>,
@@ -234,6 +235,16 @@ impl<'f, 'sess: 'f, S: Stage> AcceptContext<'f, 'sess, S> {
234235
})
235236
}
236237

238+
pub(crate) fn expected_no_args(&self, args_span: Span) -> ErrorGuaranteed {
239+
self.emit_err(AttributeParseError {
240+
span: args_span,
241+
attr_span: self.attr_span,
242+
template: self.template.clone(),
243+
attribute: self.attr_path.clone(),
244+
reason: AttributeParseErrorReason::ExpectedNoArgs,
245+
})
246+
}
247+
237248
/// emit an error that a `name = value` pair was expected at this span. The symbol can be given for
238249
/// a nicer error message talking about the specific name that was found lacking a value.
239250
pub(crate) fn expected_name_value(&self, span: Span, name: Option<Symbol>) -> ErrorGuaranteed {

compiler/rustc_attr_parsing/src/session_diagnostics.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -474,6 +474,7 @@ pub(crate) struct UnrecognizedReprHint {
474474
}
475475

476476
pub(crate) enum AttributeParseErrorReason {
477+
ExpectedNoArgs,
477478
ExpectedStringLiteral { byte_string: Option<Span> },
478479
ExpectedSingleArgument,
479480
ExpectedList,
@@ -529,6 +530,10 @@ impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for AttributeParseError {
529530
diag.span_label(self.span, format!("didn't expect a literal here"));
530531
diag.code(E0565);
531532
}
533+
AttributeParseErrorReason::ExpectedNoArgs => {
534+
diag.span_label(self.span, format!("didn't expect any arguments here"));
535+
diag.code(E0565);
536+
}
532537
AttributeParseErrorReason::ExpectedNameValue(None) => {
533538
diag.span_label(
534539
self.span,

compiler/rustc_codegen_ssa/src/back/write.rs

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,10 @@ use rustc_data_structures::jobserver::{self, Acquired};
1414
use rustc_data_structures::memmap::Mmap;
1515
use rustc_data_structures::profiling::{SelfProfilerRef, VerboseTimingGuard};
1616
use rustc_errors::emitter::Emitter;
17-
use rustc_errors::translation::Translate;
17+
use rustc_errors::translation::Translator;
1818
use rustc_errors::{
19-
Diag, DiagArgMap, DiagCtxt, DiagMessage, ErrCode, FatalError, FluentBundle, Level, MultiSpan,
20-
Style, Suggestions,
19+
Diag, DiagArgMap, DiagCtxt, DiagMessage, ErrCode, FatalError, Level, MultiSpan, Style,
20+
Suggestions,
2121
};
2222
use rustc_fs_util::link_or_copy;
2323
use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
@@ -1889,16 +1889,6 @@ impl SharedEmitter {
18891889
}
18901890
}
18911891

1892-
impl Translate for SharedEmitter {
1893-
fn fluent_bundle(&self) -> Option<&FluentBundle> {
1894-
None
1895-
}
1896-
1897-
fn fallback_fluent_bundle(&self) -> &FluentBundle {
1898-
panic!("shared emitter attempted to translate a diagnostic");
1899-
}
1900-
}
1901-
19021892
impl Emitter for SharedEmitter {
19031893
fn emit_diagnostic(
19041894
&mut self,
@@ -1932,6 +1922,10 @@ impl Emitter for SharedEmitter {
19321922
fn source_map(&self) -> Option<&SourceMap> {
19331923
None
19341924
}
1925+
1926+
fn translator(&self) -> &Translator {
1927+
panic!("shared emitter attempted to translate a diagnostic");
1928+
}
19351929
}
19361930

19371931
impl SharedEmitterMain {

compiler/rustc_codegen_ssa/src/codegen_attrs.rs

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use rustc_abi::ExternAbi;
44
use rustc_ast::expand::autodiff_attrs::{AutoDiffAttrs, DiffActivity, DiffMode};
55
use rustc_ast::{LitKind, MetaItem, MetaItemInner, attr};
66
use rustc_attr_data_structures::{
7-
AttributeKind, InlineAttr, InstructionSetAttr, OptimizeAttr, find_attr,
7+
AttributeKind, InlineAttr, InstructionSetAttr, OptimizeAttr, ReprAttr, find_attr,
88
};
99
use rustc_hir::def::DefKind;
1010
use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
@@ -110,16 +110,27 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
110110
}
111111
};
112112

113-
if let hir::Attribute::Parsed(AttributeKind::Align { align, .. }) = attr {
114-
codegen_fn_attrs.alignment = Some(*align);
113+
if let hir::Attribute::Parsed(p) = attr {
114+
match p {
115+
AttributeKind::Repr(reprs) => {
116+
codegen_fn_attrs.alignment = reprs
117+
.iter()
118+
.filter_map(
119+
|(r, _)| if let ReprAttr::ReprAlign(x) = r { Some(*x) } else { None },
120+
)
121+
.max();
122+
}
123+
AttributeKind::Cold(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD,
124+
AttributeKind::Align { align, .. } => codegen_fn_attrs.alignment = Some(*align),
125+
_ => {}
126+
}
115127
}
116128

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

121133
match name {
122-
sym::cold => codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD,
123134
sym::rustc_allocator => codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR,
124135
sym::ffi_pure => codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_PURE,
125136
sym::ffi_const => codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_CONST,

compiler/rustc_const_eval/src/interpret/memory.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1412,8 +1412,13 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
14121412
let src_alloc = self.get_alloc_raw(src_alloc_id)?;
14131413
let src_range = alloc_range(src_offset, size);
14141414
assert!(!self.memory.validation_in_progress.get(), "we can't be copying during validation");
1415-
// For the overlapping case, it is crucial that we trigger the read hook
1415+
1416+
// Trigger read hooks.
1417+
// For the overlapping case, it is crucial that we trigger the read hooks
14161418
// before the write hook -- the aliasing model cares about the order.
1419+
if let Ok((alloc_id, ..)) = self.ptr_try_get_alloc_id(src, size.bytes() as i64) {
1420+
M::before_alloc_read(self, alloc_id)?;
1421+
}
14171422
M::before_memory_read(
14181423
tcx,
14191424
&self.machine,

compiler/rustc_driver_impl/src/lib.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ use rustc_data_structures::profiling::{
3838
};
3939
use rustc_errors::emitter::stderr_destination;
4040
use rustc_errors::registry::Registry;
41+
use rustc_errors::translation::Translator;
4142
use rustc_errors::{ColorConfig, DiagCtxt, ErrCode, FatalError, PResult, markdown};
4243
use rustc_feature::find_gated_cfg;
4344
// This avoids a false positive with `-Wunused_crate_dependencies`.
@@ -109,6 +110,10 @@ use crate::session_diagnostics::{
109110

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

113+
pub fn default_translator() -> Translator {
114+
Translator::with_fallback_bundle(DEFAULT_LOCALE_RESOURCES.to_vec(), false)
115+
}
116+
112117
pub static DEFAULT_LOCALE_RESOURCES: &[&str] = &[
113118
// tidy-alphabetical-start
114119
crate::DEFAULT_LOCALE_RESOURCE,
@@ -1413,11 +1418,10 @@ fn report_ice(
14131418
extra_info: fn(&DiagCtxt),
14141419
using_internal_features: &AtomicBool,
14151420
) {
1416-
let fallback_bundle =
1417-
rustc_errors::fallback_fluent_bundle(crate::DEFAULT_LOCALE_RESOURCES.to_vec(), false);
1421+
let translator = default_translator();
14181422
let emitter = Box::new(rustc_errors::emitter::HumanEmitter::new(
14191423
stderr_destination(rustc_errors::ColorConfig::Auto),
1420-
fallback_bundle,
1424+
translator,
14211425
));
14221426
let dcx = rustc_errors::DiagCtxt::new(emitter);
14231427
let dcx = dcx.handle();

compiler/rustc_error_messages/src/lib.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ pub use fluent_bundle::{self, FluentArgs, FluentError, FluentValue};
1818
use fluent_syntax::parser::ParserError;
1919
use icu_provider_adapters::fallback::{LocaleFallbackProvider, LocaleFallbacker};
2020
use intl_memoizer::concurrent::IntlLangMemoizer;
21-
use rustc_data_structures::sync::IntoDynSyncSend;
21+
use rustc_data_structures::sync::{DynSend, IntoDynSyncSend};
2222
use rustc_macros::{Decodable, Encodable};
2323
use rustc_span::Span;
2424
use smallvec::SmallVec;
@@ -204,16 +204,16 @@ fn register_functions(bundle: &mut FluentBundle) {
204204

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

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

219219
register_functions(&mut fallback_bundle);
@@ -228,7 +228,7 @@ pub fn fallback_fluent_bundle(
228228
}
229229

230230
fallback_bundle
231-
}))
231+
})))
232232
}
233233

234234
/// Identifier for the Fluent message/attribute corresponding to a diagnostic message.

compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs

Lines changed: 10 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -15,17 +15,15 @@ use rustc_span::source_map::SourceMap;
1515
use crate::emitter::FileWithAnnotatedLines;
1616
use crate::registry::Registry;
1717
use crate::snippet::Line;
18-
use crate::translation::{Translate, to_fluent_args};
18+
use crate::translation::{Translator, to_fluent_args};
1919
use crate::{
20-
CodeSuggestion, DiagInner, DiagMessage, Emitter, ErrCode, FluentBundle, LazyFallbackBundle,
21-
Level, MultiSpan, Style, Subdiag,
20+
CodeSuggestion, DiagInner, DiagMessage, Emitter, ErrCode, Level, MultiSpan, Style, Subdiag,
2221
};
2322

2423
/// Generates diagnostics using annotate-snippet
2524
pub struct AnnotateSnippetEmitter {
2625
source_map: Option<Arc<SourceMap>>,
27-
fluent_bundle: Option<Arc<FluentBundle>>,
28-
fallback_bundle: LazyFallbackBundle,
26+
translator: Translator,
2927

3028
/// If true, hides the longer explanation text
3129
short_message: bool,
@@ -35,16 +33,6 @@ pub struct AnnotateSnippetEmitter {
3533
macro_backtrace: bool,
3634
}
3735

38-
impl Translate for AnnotateSnippetEmitter {
39-
fn fluent_bundle(&self) -> Option<&FluentBundle> {
40-
self.fluent_bundle.as_deref()
41-
}
42-
43-
fn fallback_fluent_bundle(&self) -> &FluentBundle {
44-
&self.fallback_bundle
45-
}
46-
}
47-
4836
impl Emitter for AnnotateSnippetEmitter {
4937
/// The entry point for the diagnostics generation
5038
fn emit_diagnostic(&mut self, mut diag: DiagInner, _registry: &Registry) {
@@ -78,6 +66,10 @@ impl Emitter for AnnotateSnippetEmitter {
7866
fn should_show_explain(&self) -> bool {
7967
!self.short_message
8068
}
69+
70+
fn translator(&self) -> &Translator {
71+
&self.translator
72+
}
8173
}
8274

8375
/// Provides the source string for the given `line` of `file`
@@ -104,19 +96,11 @@ fn annotation_level_for_level(level: Level) -> annotate_snippets::Level {
10496
impl AnnotateSnippetEmitter {
10597
pub fn new(
10698
source_map: Option<Arc<SourceMap>>,
107-
fluent_bundle: Option<Arc<FluentBundle>>,
108-
fallback_bundle: LazyFallbackBundle,
99+
translator: Translator,
109100
short_message: bool,
110101
macro_backtrace: bool,
111102
) -> Self {
112-
Self {
113-
source_map,
114-
fluent_bundle,
115-
fallback_bundle,
116-
short_message,
117-
ui_testing: false,
118-
macro_backtrace,
119-
}
103+
Self { source_map, translator, short_message, ui_testing: false, macro_backtrace }
120104
}
121105

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

0 commit comments

Comments
 (0)