Skip to content

Commit c576bba

Browse files
committed
Auto merge of #144038 - matthiaskrgr:rollup-j1lmywa, r=matthiaskrgr
Rollup of 11 pull requests Successful merges: - #143595 (add `const_make_global`; err for `const_allocate` ptrs if didn't call) - #143678 (Added error for invalid char cast) - #143793 (Opaque type collection: Guard against endlessly recursing free alias types) - #143820 (Fixed a core crate compilation failure when enabling the `optimize_for_size` feature on some targets) - #143829 (Trim `BorrowedCursor` API) - #143856 (Linting public reexport of private dependencies) - #143891 (Port `#[coverage]` to the new attribute system) - #143914 (Reword mismatched-lifetime-syntaxes text based on feedback) - #143922 (Improve path segment joining) - #143926 (Remove deprecated fields in bootstrap) - #143975 (type_id_eq: check that the hash fully matches the type) r? `@ghost` `@rustbot` modify labels: rollup
2 parents 5795086 + 3140424 commit c576bba

File tree

130 files changed

+2055
-1240
lines changed

Some content is hidden

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

130 files changed

+2055
-1240
lines changed

compiler/rustc_ast/src/ast.rs

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
//! - [`Attribute`]: Metadata associated with item.
1919
//! - [`UnOp`], [`BinOp`], and [`BinOpKind`]: Unary and binary operators.
2020
21-
use std::borrow::Cow;
21+
use std::borrow::{Borrow, Cow};
2222
use std::{cmp, fmt};
2323

2424
pub use GenericArgs::*;
@@ -155,6 +155,57 @@ impl Path {
155155
}
156156
}
157157

158+
/// Joins multiple symbols with "::" into a path, e.g. "a::b::c". If the first
159+
/// segment is `kw::PathRoot` it will be printed as empty, e.g. "::b::c".
160+
///
161+
/// The generics on the `path` argument mean it can accept many forms, such as:
162+
/// - `&[Symbol]`
163+
/// - `Vec<Symbol>`
164+
/// - `Vec<&Symbol>`
165+
/// - `impl Iterator<Item = Symbol>`
166+
/// - `impl Iterator<Item = &Symbol>`
167+
///
168+
/// Panics if `path` is empty or a segment after the first is `kw::PathRoot`.
169+
pub fn join_path_syms(path: impl IntoIterator<Item = impl Borrow<Symbol>>) -> String {
170+
// This is a guess at the needed capacity that works well in practice. It is slightly faster
171+
// than (a) starting with an empty string, or (b) computing the exact capacity required.
172+
let mut iter = path.into_iter();
173+
let len_hint = iter.size_hint().1.unwrap_or(1);
174+
let mut s = String::with_capacity(len_hint * 8);
175+
176+
let first_sym = *iter.next().unwrap().borrow();
177+
if first_sym != kw::PathRoot {
178+
s.push_str(first_sym.as_str());
179+
}
180+
for sym in iter {
181+
let sym = *sym.borrow();
182+
debug_assert_ne!(sym, kw::PathRoot);
183+
s.push_str("::");
184+
s.push_str(sym.as_str());
185+
}
186+
s
187+
}
188+
189+
/// Like `join_path_syms`, but for `Ident`s. This function is necessary because
190+
/// `Ident::to_string` does more than just print the symbol in the `name` field.
191+
pub fn join_path_idents(path: impl IntoIterator<Item = impl Borrow<Ident>>) -> String {
192+
let mut iter = path.into_iter();
193+
let len_hint = iter.size_hint().1.unwrap_or(1);
194+
let mut s = String::with_capacity(len_hint * 8);
195+
196+
let first_ident = *iter.next().unwrap().borrow();
197+
if first_ident.name != kw::PathRoot {
198+
s.push_str(&first_ident.to_string());
199+
}
200+
for ident in iter {
201+
let ident = *ident.borrow();
202+
debug_assert_ne!(ident.name, kw::PathRoot);
203+
s.push_str("::");
204+
s.push_str(&ident.to_string());
205+
}
206+
s
207+
}
208+
158209
/// A segment of a path: an identifier, an optional lifetime, and a set of types.
159210
///
160211
/// E.g., `std`, `String` or `Box<T>`.

compiler/rustc_attr_data_structures/src/attributes.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,22 @@ pub enum DeprecatedSince {
110110
Err,
111111
}
112112

113+
#[derive(
114+
Copy,
115+
Debug,
116+
Eq,
117+
PartialEq,
118+
Encodable,
119+
Decodable,
120+
Clone,
121+
HashStable_Generic,
122+
PrintAttribute
123+
)]
124+
pub enum CoverageStatus {
125+
On,
126+
Off,
127+
}
128+
113129
impl Deprecation {
114130
/// Whether an item marked with #[deprecated(since = "X")] is currently
115131
/// deprecated (i.e., whether X is not greater than the current rustc
@@ -274,6 +290,9 @@ pub enum AttributeKind {
274290
/// Represents `#[const_trait]`.
275291
ConstTrait(Span),
276292

293+
/// Represents `#[coverage]`.
294+
Coverage(Span, CoverageStatus),
295+
277296
///Represents `#[rustc_deny_explicit_impl]`.
278297
DenyExplicitImpl(Span),
279298

compiler/rustc_attr_data_structures/src/encode_cross_crate.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ impl AttributeKind {
2828
ConstStability { .. } => Yes,
2929
ConstStabilityIndirect => No,
3030
ConstTrait(..) => No,
31+
Coverage(..) => No,
3132
DenyExplicitImpl(..) => No,
3233
Deprecation { .. } => Yes,
3334
DoNotImplementViaObject(..) => No,

compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use rustc_attr_data_structures::{AttributeKind, OptimizeAttr, UsedBy};
1+
use rustc_attr_data_structures::{AttributeKind, CoverageStatus, OptimizeAttr, UsedBy};
22
use rustc_feature::{AttributeTemplate, template};
33
use rustc_session::parse::feature_err;
44
use rustc_span::{Span, Symbol, sym};
@@ -52,6 +52,45 @@ impl<S: Stage> NoArgsAttributeParser<S> for ColdParser {
5252
const CREATE: fn(Span) -> AttributeKind = AttributeKind::Cold;
5353
}
5454

55+
pub(crate) struct CoverageParser;
56+
57+
impl<S: Stage> SingleAttributeParser<S> for CoverageParser {
58+
const PATH: &[Symbol] = &[sym::coverage];
59+
const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepOutermost;
60+
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
61+
const TEMPLATE: AttributeTemplate = template!(OneOf: &[sym::off, sym::on]);
62+
63+
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser<'_>) -> Option<AttributeKind> {
64+
let Some(args) = args.list() else {
65+
cx.expected_specific_argument_and_list(cx.attr_span, vec!["on", "off"]);
66+
return None;
67+
};
68+
69+
let Some(arg) = args.single() else {
70+
cx.expected_single_argument(args.span);
71+
return None;
72+
};
73+
74+
let fail_incorrect_argument = |span| cx.expected_specific_argument(span, vec!["on", "off"]);
75+
76+
let Some(arg) = arg.meta_item() else {
77+
fail_incorrect_argument(args.span);
78+
return None;
79+
};
80+
81+
let status = match arg.path().word_sym() {
82+
Some(sym::off) => CoverageStatus::Off,
83+
Some(sym::on) => CoverageStatus::On,
84+
None | Some(_) => {
85+
fail_incorrect_argument(arg.span());
86+
return None;
87+
}
88+
};
89+
90+
Some(AttributeKind::Coverage(cx.attr_span, status))
91+
}
92+
}
93+
5594
pub(crate) struct ExportNameParser;
5695

5796
impl<S: Stage> SingleAttributeParser<S> for ExportNameParser {

compiler/rustc_attr_parsing/src/context.rs

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,9 @@ use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, Symbol, sym};
1515

1616
use crate::attributes::allow_unstable::{AllowConstFnUnstableParser, AllowInternalUnstableParser};
1717
use crate::attributes::codegen_attrs::{
18-
ColdParser, ExportNameParser, NakedParser, NoMangleParser, OmitGdbPrettyPrinterSectionParser,
19-
OptimizeParser, TargetFeatureParser, TrackCallerParser, UsedParser,
18+
ColdParser, CoverageParser, ExportNameParser, NakedParser, NoMangleParser,
19+
OmitGdbPrettyPrinterSectionParser, OptimizeParser, TargetFeatureParser, TrackCallerParser,
20+
UsedParser,
2021
};
2122
use crate::attributes::confusables::ConfusablesParser;
2223
use crate::attributes::deprecation::DeprecationParser;
@@ -136,6 +137,7 @@ attribute_parsers!(
136137
// tidy-alphabetical-end
137138

138139
// tidy-alphabetical-start
140+
Single<CoverageParser>,
139141
Single<DeprecationParser>,
140142
Single<DummyParser>,
141143
Single<ExportNameParser>,
@@ -449,6 +451,25 @@ impl<'f, 'sess: 'f, S: Stage> AcceptContext<'f, 'sess, S> {
449451
reason: AttributeParseErrorReason::ExpectedSpecificArgument {
450452
possibilities,
451453
strings: false,
454+
list: false,
455+
},
456+
})
457+
}
458+
459+
pub(crate) fn expected_specific_argument_and_list(
460+
&self,
461+
span: Span,
462+
possibilities: Vec<&'static str>,
463+
) -> ErrorGuaranteed {
464+
self.emit_err(AttributeParseError {
465+
span,
466+
attr_span: self.attr_span,
467+
template: self.template.clone(),
468+
attribute: self.attr_path.clone(),
469+
reason: AttributeParseErrorReason::ExpectedSpecificArgument {
470+
possibilities,
471+
strings: false,
472+
list: true,
452473
},
453474
})
454475
}
@@ -466,6 +487,7 @@ impl<'f, 'sess: 'f, S: Stage> AcceptContext<'f, 'sess, S> {
466487
reason: AttributeParseErrorReason::ExpectedSpecificArgument {
467488
possibilities,
468489
strings: true,
490+
list: false,
469491
},
470492
})
471493
}

compiler/rustc_attr_parsing/src/session_diagnostics.rs

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -525,15 +525,22 @@ pub(crate) struct LinkOrdinalOutOfRange {
525525

526526
pub(crate) enum AttributeParseErrorReason {
527527
ExpectedNoArgs,
528-
ExpectedStringLiteral { byte_string: Option<Span> },
528+
ExpectedStringLiteral {
529+
byte_string: Option<Span>,
530+
},
529531
ExpectedIntegerLiteral,
530532
ExpectedAtLeastOneArgument,
531533
ExpectedSingleArgument,
532534
ExpectedList,
533535
UnexpectedLiteral,
534536
ExpectedNameValue(Option<Symbol>),
535537
DuplicateKey(Symbol),
536-
ExpectedSpecificArgument { possibilities: Vec<&'static str>, strings: bool },
538+
ExpectedSpecificArgument {
539+
possibilities: Vec<&'static str>,
540+
strings: bool,
541+
/// Should we tell the user to write a list when they didn't?
542+
list: bool,
543+
},
537544
}
538545

539546
pub(crate) struct AttributeParseError {
@@ -607,7 +614,11 @@ impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for AttributeParseError {
607614
format!("expected this to be of the form `{name} = \"...\"`"),
608615
);
609616
}
610-
AttributeParseErrorReason::ExpectedSpecificArgument { possibilities, strings } => {
617+
AttributeParseErrorReason::ExpectedSpecificArgument {
618+
possibilities,
619+
strings,
620+
list: false,
621+
} => {
611622
let quote = if strings { '"' } else { '`' };
612623
match possibilities.as_slice() {
613624
&[] => {}
@@ -633,6 +644,38 @@ impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for AttributeParseError {
633644
}
634645
}
635646
}
647+
AttributeParseErrorReason::ExpectedSpecificArgument {
648+
possibilities,
649+
strings,
650+
list: true,
651+
} => {
652+
let quote = if strings { '"' } else { '`' };
653+
match possibilities.as_slice() {
654+
&[] => {}
655+
&[x] => {
656+
diag.span_label(
657+
self.span,
658+
format!(
659+
"this attribute is only valid with {quote}{x}{quote} as an argument"
660+
),
661+
);
662+
}
663+
[first, second] => {
664+
diag.span_label(self.span, format!("this attribute is only valid with either {quote}{first}{quote} or {quote}{second}{quote} as an argument"));
665+
}
666+
[first @ .., second_to_last, last] => {
667+
let mut res = String::new();
668+
for i in first {
669+
res.push_str(&format!("{quote}{i}{quote}, "));
670+
}
671+
res.push_str(&format!(
672+
"{quote}{second_to_last}{quote} or {quote}{last}{quote}"
673+
));
674+
675+
diag.span_label(self.span, format!("this attribute is only valid with one of the following arguments: {res}"));
676+
}
677+
}
678+
}
636679
}
637680

638681
let suggestions = self.template.suggestions(false, &name);

compiler/rustc_builtin_macros/src/source_util.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@ use std::sync::Arc;
44

55
use rustc_ast as ast;
66
use rustc_ast::ptr::P;
7-
use rustc_ast::token;
87
use rustc_ast::tokenstream::TokenStream;
8+
use rustc_ast::{join_path_idents, token};
99
use rustc_ast_pretty::pprust;
1010
use rustc_expand::base::{
1111
DummyResult, ExpandResult, ExtCtxt, MacEager, MacResult, MacroExpanderResult, resolve_path,
@@ -100,7 +100,7 @@ pub(crate) fn expand_mod(
100100
let sp = cx.with_def_site_ctxt(sp);
101101
check_zero_tts(cx, sp, tts, "module_path!");
102102
let mod_path = &cx.current_expansion.module.mod_path;
103-
let string = mod_path.iter().map(|x| x.to_string()).collect::<Vec<String>>().join("::");
103+
let string = join_path_idents(mod_path);
104104

105105
ExpandResult::Ready(MacEager::expr(cx.expr_str(sp, Symbol::intern(&string))))
106106
}

compiler/rustc_builtin_macros/src/test.rs

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use std::assert_matches::assert_matches;
55
use std::iter;
66

77
use rustc_ast::ptr::P;
8-
use rustc_ast::{self as ast, GenericParamKind, attr};
8+
use rustc_ast::{self as ast, GenericParamKind, attr, join_path_idents};
99
use rustc_ast_pretty::pprust;
1010
use rustc_errors::{Applicability, Diag, Level};
1111
use rustc_expand::base::*;
@@ -446,12 +446,7 @@ fn get_location_info(cx: &ExtCtxt<'_>, fn_: &ast::Fn) -> (Symbol, usize, usize,
446446
}
447447

448448
fn item_path(mod_path: &[Ident], item_ident: &Ident) -> String {
449-
mod_path
450-
.iter()
451-
.chain(iter::once(item_ident))
452-
.map(|x| x.to_string())
453-
.collect::<Vec<String>>()
454-
.join("::")
449+
join_path_idents(mod_path.iter().chain(iter::once(item_ident)))
455450
}
456451

457452
enum ShouldPanic {

compiler/rustc_const_eval/messages.ftl

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,17 @@ const_eval_const_context = {$kind ->
5656
*[other] {""}
5757
}
5858
59+
const_eval_const_heap_ptr_in_final = encountered `const_allocate` pointer in final value that was not made global
60+
.note = use `const_make_global` to make allocated pointers immutable before returning
61+
62+
const_eval_const_make_global_ptr_already_made_global = attempting to call `const_make_global` twice on the same allocation {$alloc}
63+
64+
const_eval_const_make_global_ptr_is_non_heap = pointer passed to `const_make_global` does not point to a heap allocation: {$ptr}
65+
66+
const_eval_const_make_global_with_dangling_ptr = pointer passed to `const_make_global` is dangling: {$ptr}
67+
68+
const_eval_const_make_global_with_offset = making {$ptr} global which does not point to the beginning of an object
69+
5970
const_eval_copy_nonoverlapping_overlapping =
6071
`copy_nonoverlapping` called on overlapping ranges
6172

compiler/rustc_const_eval/src/const_eval/dummy_machine.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,6 @@ impl HasStaticRootDefId for DummyMachine {
4949

5050
impl<'tcx> interpret::Machine<'tcx> for DummyMachine {
5151
interpret::compile_time_machine!(<'tcx>);
52-
type MemoryKind = !;
5352
const PANIC_ON_ALLOC_FAIL: bool = true;
5453

5554
// We want to just eval random consts in the program, so `eval_mir_const` can fail.

0 commit comments

Comments
 (0)