Skip to content

Commit fe5f3de

Browse files
committed
Auto merge of #143091 - GuillaumeGomez:rollup-f300qwe, r=GuillaumeGomez
Rollup of 10 pull requests Successful merges: - #142270 (Rustdoc js: even more typechecking improvements) - #142420 (Report infer ty errors during hir ty lowering) - #142671 (add #![rustc_no_implicit_bounds]) - #142721 (Add tracing to `InterpCx::layout_of()` ) - #142818 (Port `#[used]` to new attribute parsing infrastructure) - #143020 (codegen_fn_attrs: make comment more precise) - #143051 (Add tracing to `validate_operand`) - #143060 (Only args in main diag are saved and restored without removing the newly added ones) - #143065 (Improve recovery when users write `where:`) - #143084 (const-eval: error when initializing a static writes to that static) r? `@ghost` `@rustbot` modify labels: rollup
2 parents 13c46fd + 0bbeeff commit fe5f3de

File tree

127 files changed

+1009
-1122
lines changed

Some content is hidden

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

127 files changed

+1009
-1122
lines changed

compiler/rustc_ast/src/token.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -893,7 +893,7 @@ impl Token {
893893
|| self.is_qpath_start()
894894
|| matches!(self.is_metavar_seq(), Some(MetaVarKind::Path))
895895
|| self.is_path_segment_keyword()
896-
|| self.is_ident() && !self.is_reserved_ident()
896+
|| self.is_non_reserved_ident()
897897
}
898898

899899
/// Returns `true` if the token is a given keyword, `kw`.
@@ -937,6 +937,10 @@ impl Token {
937937
self.is_non_raw_ident_where(Ident::is_reserved)
938938
}
939939

940+
pub fn is_non_reserved_ident(&self) -> bool {
941+
self.ident().is_some_and(|(id, raw)| raw == IdentIsRaw::Yes || !Ident::is_reserved(id))
942+
}
943+
940944
/// Returns `true` if the token is the identifier `true` or `false`.
941945
pub fn is_bool_lit(&self) -> bool {
942946
self.is_non_raw_ident_where(|id| id.name.is_bool_lit())

compiler/rustc_ast/src/tokenstream.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -634,10 +634,8 @@ impl TokenStream {
634634
(
635635
TokenTree::Token(token_left, Spacing::Alone),
636636
TokenTree::Token(token_right, _),
637-
) if ((token_left.is_ident() && !token_left.is_reserved_ident())
638-
|| token_left.is_lit())
639-
&& ((token_right.is_ident() && !token_right.is_reserved_ident())
640-
|| token_right.is_lit()) =>
637+
) if (token_left.is_non_reserved_ident() || token_left.is_lit())
638+
&& (token_right.is_non_reserved_ident() || token_right.is_lit()) =>
641639
{
642640
token_left.span
643641
}

compiler/rustc_attr_data_structures/src/attributes.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,17 @@ impl Deprecation {
131131
}
132132
}
133133

134+
/// There are three valid forms of the attribute:
135+
/// `#[used]`, which is semantically equivalent to `#[used(linker)]` except that the latter is currently unstable.
136+
/// `#[used(compiler)]`
137+
/// `#[used(linker)]`
138+
#[derive(Encodable, Decodable, Copy, Clone, Debug, PartialEq, Eq, Hash)]
139+
#[derive(HashStable_Generic, PrintAttribute)]
140+
pub enum UsedBy {
141+
Compiler,
142+
Linker,
143+
}
144+
134145
/// Represents parsed *built-in* inert attributes.
135146
///
136147
/// ## Overview
@@ -285,5 +296,8 @@ pub enum AttributeKind {
285296

286297
/// Represents `#[track_caller]`
287298
TrackCaller(Span),
299+
300+
/// Represents `#[used]`
301+
Used { used_by: UsedBy, span: Span },
288302
// tidy-alphabetical-end
289303
}

compiler/rustc_attr_data_structures/src/encode_cross_crate.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ impl AttributeKind {
3838
PubTransparent(..) => Yes,
3939
SkipDuringMethodDispatch { .. } => No,
4040
TrackCaller(..) => Yes,
41+
Used { .. } => No,
4142
}
4243
}
4344
}

compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs

Lines changed: 82 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use rustc_attr_data_structures::{AttributeKind, OptimizeAttr};
1+
use rustc_attr_data_structures::{AttributeKind, OptimizeAttr, UsedBy};
22
use rustc_feature::{AttributeTemplate, template};
33
use rustc_session::parse::feature_err;
44
use rustc_span::{Span, Symbol, sym};
@@ -228,3 +228,84 @@ impl<S: Stage> SingleAttributeParser<S> for NoMangleParser {
228228
Some(AttributeKind::NoMangle(cx.attr_span))
229229
}
230230
}
231+
232+
#[derive(Default)]
233+
pub(crate) struct UsedParser {
234+
first_compiler: Option<Span>,
235+
first_linker: Option<Span>,
236+
}
237+
238+
// A custom `AttributeParser` is used rather than a Simple attribute parser because
239+
// - Specifying two `#[used]` attributes is a warning (but will be an error in the future)
240+
// - But specifying two conflicting attributes: `#[used(compiler)]` and `#[used(linker)]` is already an error today
241+
// We can change this to a Simple parser once the warning becomes an error
242+
impl<S: Stage> AttributeParser<S> for UsedParser {
243+
const ATTRIBUTES: AcceptMapping<Self, S> = &[(
244+
&[sym::used],
245+
template!(Word, List: "compiler|linker"),
246+
|group: &mut Self, cx, args| {
247+
let used_by = match args {
248+
ArgParser::NoArgs => UsedBy::Linker,
249+
ArgParser::List(list) => {
250+
let Some(l) = list.single() else {
251+
cx.expected_single_argument(list.span);
252+
return;
253+
};
254+
255+
match l.meta_item().and_then(|i| i.path().word_sym()) {
256+
Some(sym::compiler) => {
257+
if !cx.features().used_with_arg() {
258+
feature_err(
259+
&cx.sess(),
260+
sym::used_with_arg,
261+
cx.attr_span,
262+
"`#[used(compiler)]` is currently unstable",
263+
)
264+
.emit();
265+
}
266+
UsedBy::Compiler
267+
}
268+
Some(sym::linker) => {
269+
if !cx.features().used_with_arg() {
270+
feature_err(
271+
&cx.sess(),
272+
sym::used_with_arg,
273+
cx.attr_span,
274+
"`#[used(linker)]` is currently unstable",
275+
)
276+
.emit();
277+
}
278+
UsedBy::Linker
279+
}
280+
_ => {
281+
cx.expected_specific_argument(l.span(), vec!["compiler", "linker"]);
282+
return;
283+
}
284+
}
285+
}
286+
ArgParser::NameValue(_) => return,
287+
};
288+
289+
let target = match used_by {
290+
UsedBy::Compiler => &mut group.first_compiler,
291+
UsedBy::Linker => &mut group.first_linker,
292+
};
293+
294+
let attr_span = cx.attr_span;
295+
if let Some(prev) = *target {
296+
cx.warn_unused_duplicate(prev, attr_span);
297+
} else {
298+
*target = Some(attr_span);
299+
}
300+
},
301+
)];
302+
303+
fn finalize(self, _cx: &FinalizeContext<'_, '_, S>) -> Option<AttributeKind> {
304+
// Ratcheting behaviour, if both `linker` and `compiler` are specified, use `linker`
305+
Some(match (self.first_compiler, self.first_linker) {
306+
(_, Some(span)) => AttributeKind::Used { used_by: UsedBy::Linker, span },
307+
(Some(span), _) => AttributeKind::Used { used_by: UsedBy::Compiler, span },
308+
(None, None) => return None,
309+
})
310+
}
311+
}

compiler/rustc_attr_parsing/src/context.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, Symbol, sym};
1717
use crate::attributes::allow_unstable::{AllowConstFnUnstableParser, AllowInternalUnstableParser};
1818
use crate::attributes::codegen_attrs::{
1919
ColdParser, ExportNameParser, NakedParser, NoMangleParser, OptimizeParser, TrackCallerParser,
20+
UsedParser,
2021
};
2122
use crate::attributes::confusables::ConfusablesParser;
2223
use crate::attributes::deprecation::DeprecationParser;
@@ -103,6 +104,7 @@ attribute_parsers!(
103104
ConstStabilityParser,
104105
NakedParser,
105106
StabilityParser,
107+
UsedParser,
106108
// tidy-alphabetical-end
107109

108110
// tidy-alphabetical-start

compiler/rustc_codegen_ssa/messages.ftl

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,6 @@ codegen_ssa_error_writing_def_file =
4848
4949
codegen_ssa_expected_name_value_pair = expected name value pair
5050
51-
codegen_ssa_expected_used_symbol = expected `used`, `used(compiler)` or `used(linker)`
52-
5351
codegen_ssa_extern_funcs_not_found = some `extern` functions couldn't be found; some native libraries may need to be installed or have their path specified
5452
5553
codegen_ssa_extract_bundled_libs_archive_member = failed to get data from archive member '{$rlib}': {$error}

compiler/rustc_codegen_ssa/src/codegen_attrs.rs

Lines changed: 8 additions & 40 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, ReprAttr, find_attr,
7+
AttributeKind, InlineAttr, InstructionSetAttr, OptimizeAttr, ReprAttr, UsedBy, find_attr,
88
};
99
use rustc_hir::def::DefKind;
1010
use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
@@ -160,6 +160,10 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
160160
}
161161
codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER
162162
}
163+
AttributeKind::Used { used_by, .. } => match used_by {
164+
UsedBy::Compiler => codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_COMPILER,
165+
UsedBy::Linker => codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_LINKER,
166+
},
163167
_ => {}
164168
}
165169
}
@@ -181,44 +185,6 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
181185
sym::rustc_std_internal_symbol => {
182186
codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL
183187
}
184-
sym::used => {
185-
let inner = attr.meta_item_list();
186-
match inner.as_deref() {
187-
Some([item]) if item.has_name(sym::linker) => {
188-
if !tcx.features().used_with_arg() {
189-
feature_err(
190-
&tcx.sess,
191-
sym::used_with_arg,
192-
attr.span(),
193-
"`#[used(linker)]` is currently unstable",
194-
)
195-
.emit();
196-
}
197-
codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_LINKER;
198-
}
199-
Some([item]) if item.has_name(sym::compiler) => {
200-
if !tcx.features().used_with_arg() {
201-
feature_err(
202-
&tcx.sess,
203-
sym::used_with_arg,
204-
attr.span(),
205-
"`#[used(compiler)]` is currently unstable",
206-
)
207-
.emit();
208-
}
209-
codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_COMPILER;
210-
}
211-
Some(_) => {
212-
tcx.dcx().emit_err(errors::ExpectedUsedSymbol { span: attr.span() });
213-
}
214-
None => {
215-
// Unconditionally using `llvm.used` causes issues in handling
216-
// `.init_array` with the gold linker. Luckily gold has been
217-
// deprecated with GCC 15 and rustc now warns about using gold.
218-
codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_LINKER
219-
}
220-
}
221-
}
222188
sym::thread_local => codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL,
223189
sym::target_feature => {
224190
let Some(sig) = tcx.hir_node_by_def_id(did).fn_sig() else {
@@ -430,7 +396,9 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
430396
}
431397
}
432398

433-
// Apply the minimum function alignment here, so that individual backends don't have to.
399+
// Apply the minimum function alignment here. This ensures that a function's alignment is
400+
// determined by the `-C` flags of the crate it is defined in, not the `-C` flags of the crate
401+
// it happens to be codegen'd (or const-eval'd) in.
434402
codegen_fn_attrs.alignment =
435403
Ord::max(codegen_fn_attrs.alignment, tcx.sess.opts.unstable_opts.min_function_alignment);
436404

compiler/rustc_codegen_ssa/src/errors.rs

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -726,13 +726,6 @@ pub struct UnknownArchiveKind<'a> {
726726
pub kind: &'a str,
727727
}
728728

729-
#[derive(Diagnostic)]
730-
#[diag(codegen_ssa_expected_used_symbol)]
731-
pub(crate) struct ExpectedUsedSymbol {
732-
#[primary_span]
733-
pub span: Span,
734-
}
735-
736729
#[derive(Diagnostic)]
737730
#[diag(codegen_ssa_multiple_main_functions)]
738731
#[help]

compiler/rustc_const_eval/messages.ftl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -352,7 +352,7 @@ const_eval_realloc_or_alloc_with_offset =
352352
*[other] {""}
353353
} {$ptr} which does not point to the beginning of an object
354354
355-
const_eval_recursive_static = encountered static that tried to initialize itself with itself
355+
const_eval_recursive_static = encountered static that tried to access itself during initialization
356356
357357
const_eval_remainder_by_zero =
358358
calculating the remainder with a divisor of zero

compiler/rustc_const_eval/src/const_eval/eval_queries.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use rustc_hir::def::DefKind;
77
use rustc_middle::mir::interpret::{AllocId, ErrorHandled, InterpErrorInfo, ReportedErrorInfo};
88
use rustc_middle::mir::{self, ConstAlloc, ConstValue};
99
use rustc_middle::query::TyCtxtAt;
10-
use rustc_middle::ty::layout::{HasTypingEnv, LayoutOf};
10+
use rustc_middle::ty::layout::HasTypingEnv;
1111
use rustc_middle::ty::print::with_no_trimmed_paths;
1212
use rustc_middle::ty::{self, Ty, TyCtxt};
1313
use rustc_middle::{bug, throw_inval};

compiler/rustc_const_eval/src/const_eval/machine.rs

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ pub struct CompileTimeMachine<'tcx> {
6262

6363
/// If `Some`, we are evaluating the initializer of the static with the given `LocalDefId`,
6464
/// storing the result in the given `AllocId`.
65-
/// Used to prevent reads from a static's base allocation, as that may allow for self-initialization loops.
65+
/// Used to prevent accesses to a static's base allocation, as that may allow for self-initialization loops.
6666
pub(crate) static_root_ids: Option<(AllocId, LocalDefId)>,
6767

6868
/// A cache of "data range" computations for unions (i.e., the offsets of non-padding bytes).
@@ -705,19 +705,27 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> {
705705
interp_ok(())
706706
}
707707

708-
fn before_alloc_read(ecx: &InterpCx<'tcx, Self>, alloc_id: AllocId) -> InterpResult<'tcx> {
708+
fn before_alloc_access(
709+
tcx: TyCtxtAt<'tcx>,
710+
machine: &Self,
711+
alloc_id: AllocId,
712+
) -> InterpResult<'tcx> {
713+
if machine.stack.is_empty() {
714+
// Get out of the way for the final copy.
715+
return interp_ok(());
716+
}
709717
// Check if this is the currently evaluated static.
710-
if Some(alloc_id) == ecx.machine.static_root_ids.map(|(id, _)| id) {
718+
if Some(alloc_id) == machine.static_root_ids.map(|(id, _)| id) {
711719
return Err(ConstEvalErrKind::RecursiveStatic).into();
712720
}
713721
// If this is another static, make sure we fire off the query to detect cycles.
714722
// But only do that when checks for static recursion are enabled.
715-
if ecx.machine.static_root_ids.is_some() {
716-
if let Some(GlobalAlloc::Static(def_id)) = ecx.tcx.try_get_global_alloc(alloc_id) {
717-
if ecx.tcx.is_foreign_item(def_id) {
723+
if machine.static_root_ids.is_some() {
724+
if let Some(GlobalAlloc::Static(def_id)) = tcx.try_get_global_alloc(alloc_id) {
725+
if tcx.is_foreign_item(def_id) {
718726
throw_unsup!(ExternStatic(def_id));
719727
}
720-
ecx.ctfe_query(|tcx| tcx.eval_static_initializer(def_id))?;
728+
tcx.eval_static_initializer(def_id)?;
721729
}
722730
}
723731
interp_ok(())

compiler/rustc_const_eval/src/const_eval/mod.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
use rustc_abi::{FieldIdx, VariantIdx};
44
use rustc_middle::query::Key;
5-
use rustc_middle::ty::layout::LayoutOf;
65
use rustc_middle::ty::{self, Ty, TyCtxt};
76
use rustc_middle::{bug, mir};
87
use tracing::instrument;

compiler/rustc_const_eval/src/const_eval/valtrees.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use rustc_abi::{BackendRepr, FieldIdx, VariantIdx};
22
use rustc_data_structures::stack::ensure_sufficient_stack;
33
use rustc_middle::mir::interpret::{EvalToValTreeResult, GlobalId, ValTreeCreationError};
4-
use rustc_middle::ty::layout::{LayoutCx, LayoutOf, TyAndLayout};
4+
use rustc_middle::ty::layout::{LayoutCx, TyAndLayout};
55
use rustc_middle::ty::{self, Ty, TyCtxt};
66
use rustc_middle::{bug, mir};
77
use rustc_span::DUMMY_SP;

compiler/rustc_const_eval/src/interpret/call.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use std::borrow::Cow;
66
use either::{Left, Right};
77
use rustc_abi::{self as abi, ExternAbi, FieldIdx, Integer, VariantIdx};
88
use rustc_hir::def_id::DefId;
9-
use rustc_middle::ty::layout::{FnAbiOf, IntegerExt, LayoutOf, TyAndLayout};
9+
use rustc_middle::ty::layout::{FnAbiOf, IntegerExt, TyAndLayout};
1010
use rustc_middle::ty::{self, AdtDef, Instance, Ty, VariantDef};
1111
use rustc_middle::{bug, mir, span_bug};
1212
use rustc_span::sym;

compiler/rustc_const_eval/src/interpret/cast.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use rustc_apfloat::{Float, FloatConvert};
66
use rustc_middle::mir::CastKind;
77
use rustc_middle::mir::interpret::{InterpResult, PointerArithmetic, Scalar};
88
use rustc_middle::ty::adjustment::PointerCoercion;
9-
use rustc_middle::ty::layout::{IntegerExt, LayoutOf, TyAndLayout};
9+
use rustc_middle::ty::layout::{IntegerExt, TyAndLayout};
1010
use rustc_middle::ty::{self, FloatTy, Ty};
1111
use rustc_middle::{bug, span_bug};
1212
use tracing::trace;

compiler/rustc_const_eval/src/interpret/discriminant.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
//! Functions for reading and writing discriminants of multi-variant layouts (enums and coroutines).
22
33
use rustc_abi::{self as abi, FieldIdx, TagEncoding, VariantIdx, Variants};
4-
use rustc_middle::ty::layout::{LayoutOf, PrimitiveExt, TyAndLayout};
4+
use rustc_middle::ty::layout::{PrimitiveExt, TyAndLayout};
55
use rustc_middle::ty::{self, CoroutineArgsExt, ScalarInt, Ty};
66
use rustc_middle::{mir, span_bug};
77
use tracing::{instrument, trace};

0 commit comments

Comments
 (0)