Skip to content

Commit 104f430

Browse files
committed
Auto merge of #108934 - matthiaskrgr:rollup-vm414p5, r=matthiaskrgr
Rollup of 8 pull requests Successful merges: - #106915 (Only load one CSS theme by default) - #108294 (Place binder correctly for arbitrary trait bound suggestion) - #108778 (x fmt: Don't print all modified files if there's more than 10) - #108854 (feat/refactor: improve errors in case of ident with number at start) - #108870 (Fix invalid inlining of reexport of reexport of private item) - #108917 (Consider target_family as pal) - #108922 (Add auto notification for changes to stable mir) - #108929 (Fix typo in span_map.rs) Failed merges: r? `@ghost` `@rustbot` modify labels: rollup
2 parents f37f854 + 5b3f84d commit 104f430

25 files changed

+345
-153
lines changed

compiler/rustc_middle/src/ty/diagnostics.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ pub fn suggest_arbitrary_trait_bound<'tcx>(
117117
}
118118

119119
let param_name = trait_pred.skip_binder().self_ty().to_string();
120-
let mut constraint = trait_pred.print_modifiers_and_trait_path().to_string();
120+
let mut constraint = trait_pred.to_string();
121121

122122
if let Some((name, term)) = associated_ty {
123123
// FIXME: this case overlaps with code in TyCtxt::note_and_explain_type_err.
@@ -144,7 +144,7 @@ pub fn suggest_arbitrary_trait_bound<'tcx>(
144144
this requirement",
145145
if generics.where_clause_span.is_empty() { "introducing a" } else { "extending the" },
146146
),
147-
format!("{} {}: {}", generics.add_where_or_trailing_comma(), param_name, constraint),
147+
format!("{} {constraint}", generics.add_where_or_trailing_comma()),
148148
Applicability::MaybeIncorrect,
149149
);
150150
true

compiler/rustc_parse/locales/en-US.ftl

+1-2
Original file line numberDiff line numberDiff line change
@@ -412,8 +412,7 @@ parse_fn_ptr_with_generics = function pointer types may not have generic paramet
412412
*[false] a
413413
} `for` parameter list
414414
415-
parse_invalid_identifier_with_leading_number = expected identifier, found number literal
416-
.label = identifiers cannot start with a number
415+
parse_invalid_identifier_with_leading_number = identifiers cannot start with a number
417416
418417
parse_maybe_fn_typo_with_impl = you might have meant to write `impl` instead of `fn`
419418
.suggestion = replace `fn` with `impl` here

compiler/rustc_parse/src/errors.rs

+9-8
Original file line numberDiff line numberDiff line change
@@ -939,6 +939,7 @@ pub(crate) struct ExpectedIdentifier {
939939
pub token: Token,
940940
pub suggest_raw: Option<SuggEscapeToUseAsIdentifier>,
941941
pub suggest_remove_comma: Option<SuggRemoveComma>,
942+
pub help_cannot_start_number: Option<HelpIdentifierStartsWithNumber>,
942943
}
943944

944945
impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for ExpectedIdentifier {
@@ -975,10 +976,18 @@ impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for ExpectedIdentifier {
975976
sugg.add_to_diagnostic(&mut diag);
976977
}
977978

979+
if let Some(help) = self.help_cannot_start_number {
980+
help.add_to_diagnostic(&mut diag);
981+
}
982+
978983
diag
979984
}
980985
}
981986

987+
#[derive(Subdiagnostic)]
988+
#[help(parse_invalid_identifier_with_leading_number)]
989+
pub(crate) struct HelpIdentifierStartsWithNumber;
990+
982991
pub(crate) struct ExpectedSemi {
983992
pub span: Span,
984993
pub token: Token,
@@ -1207,14 +1216,6 @@ pub(crate) struct SelfParamNotFirst {
12071216
pub span: Span,
12081217
}
12091218

1210-
#[derive(Diagnostic)]
1211-
#[diag(parse_invalid_identifier_with_leading_number)]
1212-
pub(crate) struct InvalidIdentiferStartsWithNumber {
1213-
#[primary_span]
1214-
#[label]
1215-
pub span: Span,
1216-
}
1217-
12181219
#[derive(Diagnostic)]
12191220
#[diag(parse_const_generic_without_braces)]
12201221
pub(crate) struct ConstGenericWithoutBraces {

compiler/rustc_parse/src/parser/diagnostics.rs

+27-14
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,14 @@ use crate::errors::{
88
ComparisonOperatorsCannotBeChained, ComparisonOperatorsCannotBeChainedSugg,
99
ConstGenericWithoutBraces, ConstGenericWithoutBracesSugg, DocCommentOnParamType,
1010
DoubleColonInBound, ExpectedIdentifier, ExpectedSemi, ExpectedSemiSugg,
11-
GenericParamsWithoutAngleBrackets, GenericParamsWithoutAngleBracketsSugg, InInTypo,
12-
IncorrectAwait, IncorrectSemicolon, IncorrectUseOfAwait, ParenthesesInForHead,
13-
ParenthesesInForHeadSugg, PatternMethodParamWithoutBody, QuestionMarkInType,
14-
QuestionMarkInTypeSugg, SelfParamNotFirst, StructLiteralBodyWithoutPath,
15-
StructLiteralBodyWithoutPathSugg, StructLiteralNeedingParens, StructLiteralNeedingParensSugg,
16-
SuggEscapeToUseAsIdentifier, SuggRemoveComma, UnexpectedConstInGenericParam,
17-
UnexpectedConstParamDeclaration, UnexpectedConstParamDeclarationSugg, UnmatchedAngleBrackets,
18-
UseEqInstead,
11+
GenericParamsWithoutAngleBrackets, GenericParamsWithoutAngleBracketsSugg,
12+
HelpIdentifierStartsWithNumber, InInTypo, IncorrectAwait, IncorrectSemicolon,
13+
IncorrectUseOfAwait, ParenthesesInForHead, ParenthesesInForHeadSugg,
14+
PatternMethodParamWithoutBody, QuestionMarkInType, QuestionMarkInTypeSugg, SelfParamNotFirst,
15+
StructLiteralBodyWithoutPath, StructLiteralBodyWithoutPathSugg, StructLiteralNeedingParens,
16+
StructLiteralNeedingParensSugg, SuggEscapeToUseAsIdentifier, SuggRemoveComma,
17+
UnexpectedConstInGenericParam, UnexpectedConstParamDeclaration,
18+
UnexpectedConstParamDeclarationSugg, UnmatchedAngleBrackets, UseEqInstead,
1919
};
2020

2121
use crate::fluent_generated as fluent;
@@ -280,6 +280,7 @@ impl<'a> Parser<'a> {
280280
TokenKind::CloseDelim(Delimiter::Brace),
281281
TokenKind::CloseDelim(Delimiter::Parenthesis),
282282
];
283+
283284
let suggest_raw = match self.token.ident() {
284285
Some((ident, false))
285286
if ident.is_raw_guess()
@@ -295,18 +296,19 @@ impl<'a> Parser<'a> {
295296
_ => None,
296297
};
297298

298-
let suggest_remove_comma =
299-
if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
300-
Some(SuggRemoveComma { span: self.token.span })
301-
} else {
302-
None
303-
};
299+
let suggest_remove_comma = (self.token == token::Comma
300+
&& self.look_ahead(1, |t| t.is_ident()))
301+
.then_some(SuggRemoveComma { span: self.token.span });
302+
303+
let help_cannot_start_number =
304+
self.is_lit_bad_ident().then_some(HelpIdentifierStartsWithNumber);
304305

305306
let err = ExpectedIdentifier {
306307
span: self.token.span,
307308
token: self.token.clone(),
308309
suggest_raw,
309310
suggest_remove_comma,
311+
help_cannot_start_number,
310312
};
311313
let mut err = err.into_diagnostic(&self.sess.span_diagnostic);
312314

@@ -365,6 +367,17 @@ impl<'a> Parser<'a> {
365367
err
366368
}
367369

370+
/// Checks if the current token is a integer or float literal and looks like
371+
/// it could be a invalid identifier with digits at the start.
372+
pub(super) fn is_lit_bad_ident(&mut self) -> bool {
373+
matches!(self.token.uninterpolate().kind, token::Literal(Lit { kind: token::LitKind::Integer | token::LitKind::Float, .. })
374+
// ensure that the integer literal is followed by a *invalid*
375+
// suffix: this is how we know that it is a identifier with an
376+
// invalid beginning.
377+
if rustc_ast::MetaItemLit::from_token(&self.token).is_none()
378+
)
379+
}
380+
368381
pub(super) fn expected_one_of_not_found(
369382
&mut self,
370383
edible: &[TokenKind],

compiler/rustc_parse/src/parser/pat.rs

+4
Original file line numberDiff line numberDiff line change
@@ -348,6 +348,10 @@ impl<'a> Parser<'a> {
348348
lo = self.token.span;
349349
}
350350

351+
if self.is_lit_bad_ident() {
352+
return Err(self.expected_ident_found());
353+
}
354+
351355
let pat = if self.check(&token::BinOp(token::And)) || self.token.kind == token::AndAnd {
352356
self.parse_pat_deref(expected)?
353357
} else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) {

compiler/rustc_parse/src/parser/stmt.rs

-12
Original file line numberDiff line numberDiff line change
@@ -273,7 +273,6 @@ impl<'a> Parser<'a> {
273273
self.bump();
274274
}
275275

276-
self.report_invalid_identifier_error()?;
277276
let (pat, colon) =
278277
self.parse_pat_before_ty(None, RecoverComma::Yes, PatternLocation::LetBinding)?;
279278

@@ -366,17 +365,6 @@ impl<'a> Parser<'a> {
366365
Ok(P(ast::Local { ty, pat, kind, id: DUMMY_NODE_ID, span: lo.to(hi), attrs, tokens: None }))
367366
}
368367

369-
/// report error for `let 1x = 123`
370-
pub fn report_invalid_identifier_error(&mut self) -> PResult<'a, ()> {
371-
if let token::Literal(lit) = self.token.uninterpolate().kind &&
372-
rustc_ast::MetaItemLit::from_token(&self.token).is_none() &&
373-
(lit.kind == token::LitKind::Integer || lit.kind == token::LitKind::Float) &&
374-
self.look_ahead(1, |t| matches!(t.kind, token::Eq) || matches!(t.kind, token::Colon ) ) {
375-
return Err(self.sess.create_err(errors::InvalidIdentiferStartsWithNumber { span: self.token.span }));
376-
}
377-
Ok(())
378-
}
379-
380368
fn check_let_else_init_bool_expr(&self, init: &ast::Expr) {
381369
if let ast::ExprKind::Binary(op, ..) = init.kind {
382370
if op.node.lazy() {

src/bootstrap/format.rs

+7-1
Original file line numberDiff line numberDiff line change
@@ -165,8 +165,14 @@ pub fn format(build: &Builder<'_>, check: bool, paths: &[PathBuf]) {
165165
if !CiEnv::is_ci() && paths.is_empty() {
166166
match get_modified_rs_files(build) {
167167
Ok(Some(files)) => {
168+
if files.len() <= 10 {
169+
for file in &files {
170+
println!("formatting modified file {file}");
171+
}
172+
} else {
173+
println!("formatting {} modified files", files.len());
174+
}
168175
for file in files {
169-
println!("formatting modified file {file}");
170176
ignore_fmt.add(&format!("/{file}")).expect(&file);
171177
}
172178
}

src/librustdoc/clean/mod.rs

+66-42
Original file line numberDiff line numberDiff line change
@@ -2065,23 +2065,81 @@ fn clean_bare_fn_ty<'tcx>(
20652065
BareFunctionDecl { unsafety: bare_fn.unsafety, abi: bare_fn.abi, decl, generic_params }
20662066
}
20672067

2068-
/// This visitor is used to go through only the "top level" of a item and not enter any sub
2069-
/// item while looking for a given `Ident` which is stored into `item` if found.
2070-
struct OneLevelVisitor<'hir> {
2068+
/// Get DefId of of an item's user-visible parent.
2069+
///
2070+
/// "User-visible" should account for re-exporting and inlining, which is why this function isn't
2071+
/// just `tcx.parent(def_id)`. If the provided `path` has more than one path element, the `DefId`
2072+
/// of the second-to-last will be given.
2073+
///
2074+
/// ```text
2075+
/// use crate::foo::Bar;
2076+
/// ^^^ DefId of this item will be returned
2077+
/// ```
2078+
///
2079+
/// If the provided path has only one item, `tcx.parent(def_id)` will be returned instead.
2080+
fn get_path_parent_def_id(
2081+
tcx: TyCtxt<'_>,
2082+
def_id: DefId,
2083+
path: &hir::UsePath<'_>,
2084+
) -> Option<DefId> {
2085+
if let [.., parent_segment, _] = &path.segments {
2086+
match parent_segment.res {
2087+
hir::def::Res::Def(_, parent_def_id) => Some(parent_def_id),
2088+
_ if parent_segment.ident.name == kw::Crate => {
2089+
// In case the "parent" is the crate, it'll give `Res::Err` so we need to
2090+
// circumvent it this way.
2091+
Some(tcx.parent(def_id))
2092+
}
2093+
_ => None,
2094+
}
2095+
} else {
2096+
// If the path doesn't have a parent, then the parent is the current module.
2097+
Some(tcx.parent(def_id))
2098+
}
2099+
}
2100+
2101+
/// This visitor is used to find an HIR Item based on its `use` path. This doesn't use the ordinary
2102+
/// name resolver because it does not walk all the way through a chain of re-exports.
2103+
pub(crate) struct OneLevelVisitor<'hir> {
20712104
map: rustc_middle::hir::map::Map<'hir>,
2072-
item: Option<&'hir hir::Item<'hir>>,
2105+
pub(crate) item: Option<&'hir hir::Item<'hir>>,
20732106
looking_for: Ident,
20742107
target_def_id: LocalDefId,
20752108
}
20762109

20772110
impl<'hir> OneLevelVisitor<'hir> {
2078-
fn new(map: rustc_middle::hir::map::Map<'hir>, target_def_id: LocalDefId) -> Self {
2111+
pub(crate) fn new(map: rustc_middle::hir::map::Map<'hir>, target_def_id: LocalDefId) -> Self {
20792112
Self { map, item: None, looking_for: Ident::empty(), target_def_id }
20802113
}
20812114

2082-
fn reset(&mut self, looking_for: Ident) {
2083-
self.looking_for = looking_for;
2115+
pub(crate) fn find_target(
2116+
&mut self,
2117+
tcx: TyCtxt<'_>,
2118+
def_id: DefId,
2119+
path: &hir::UsePath<'_>,
2120+
) -> Option<&'hir hir::Item<'hir>> {
2121+
let parent_def_id = get_path_parent_def_id(tcx, def_id, path)?;
2122+
let parent = self.map.get_if_local(parent_def_id)?;
2123+
2124+
// We get the `Ident` we will be looking for into `item`.
2125+
self.looking_for = path.segments[path.segments.len() - 1].ident;
2126+
// We reset the `item`.
20842127
self.item = None;
2128+
2129+
match parent {
2130+
hir::Node::Item(parent_item) => {
2131+
hir::intravisit::walk_item(self, parent_item);
2132+
}
2133+
hir::Node::Crate(m) => {
2134+
hir::intravisit::walk_mod(
2135+
self,
2136+
m,
2137+
tcx.local_def_id_to_hir_id(parent_def_id.as_local().unwrap()),
2138+
);
2139+
}
2140+
_ => return None,
2141+
}
2142+
self.item
20852143
}
20862144
}
20872145

@@ -2129,41 +2187,7 @@ fn get_all_import_attributes<'hir>(
21292187
add_without_unwanted_attributes(attributes, hir_map.attrs(item.hir_id()), is_inline);
21302188
}
21312189

2132-
let def_id = if let [.., parent_segment, _] = &path.segments {
2133-
match parent_segment.res {
2134-
hir::def::Res::Def(_, def_id) => def_id,
2135-
_ if parent_segment.ident.name == kw::Crate => {
2136-
// In case the "parent" is the crate, it'll give `Res::Err` so we need to
2137-
// circumvent it this way.
2138-
tcx.parent(item.owner_id.def_id.to_def_id())
2139-
}
2140-
_ => break,
2141-
}
2142-
} else {
2143-
// If the path doesn't have a parent, then the parent is the current module.
2144-
tcx.parent(item.owner_id.def_id.to_def_id())
2145-
};
2146-
2147-
let Some(parent) = hir_map.get_if_local(def_id) else { break };
2148-
2149-
// We get the `Ident` we will be looking for into `item`.
2150-
let looking_for = path.segments[path.segments.len() - 1].ident;
2151-
visitor.reset(looking_for);
2152-
2153-
match parent {
2154-
hir::Node::Item(parent_item) => {
2155-
hir::intravisit::walk_item(&mut visitor, parent_item);
2156-
}
2157-
hir::Node::Crate(m) => {
2158-
hir::intravisit::walk_mod(
2159-
&mut visitor,
2160-
m,
2161-
tcx.local_def_id_to_hir_id(def_id.as_local().unwrap()),
2162-
);
2163-
}
2164-
_ => break,
2165-
}
2166-
if let Some(i) = visitor.item {
2190+
if let Some(i) = visitor.find_target(tcx, item.owner_id.def_id.to_def_id(), path) {
21672191
item = i;
21682192
} else {
21692193
break;

src/librustdoc/html/render/context.rs

+26-2
Original file line numberDiff line numberDiff line change
@@ -647,11 +647,35 @@ impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> {
647647
</noscript>\
648648
<link rel=\"stylesheet\" \
649649
href=\"{static_root_path}{settings_css}\">\
650-
<script defer src=\"{static_root_path}{settings_js}\"></script>",
650+
<script defer src=\"{static_root_path}{settings_js}\"></script>\
651+
<link rel=\"preload\" href=\"{static_root_path}{theme_light_css}\" \
652+
as=\"style\">\
653+
<link rel=\"preload\" href=\"{static_root_path}{theme_dark_css}\" \
654+
as=\"style\">\
655+
<link rel=\"preload\" href=\"{static_root_path}{theme_ayu_css}\" \
656+
as=\"style\">",
651657
static_root_path = page.get_static_root_path(),
652658
settings_css = static_files::STATIC_FILES.settings_css,
653659
settings_js = static_files::STATIC_FILES.settings_js,
654-
)
660+
theme_light_css = static_files::STATIC_FILES.theme_light_css,
661+
theme_dark_css = static_files::STATIC_FILES.theme_dark_css,
662+
theme_ayu_css = static_files::STATIC_FILES.theme_ayu_css,
663+
);
664+
// Pre-load all theme CSS files, so that switching feels seamless.
665+
//
666+
// When loading settings.html as a popover, the equivalent HTML is
667+
// generated in main.js.
668+
for file in &shared.style_files {
669+
if let Ok(theme) = file.basename() {
670+
write!(
671+
buf,
672+
"<link rel=\"preload\" href=\"{root_path}{theme}{suffix}.css\" \
673+
as=\"style\">",
674+
root_path = page.static_root_path.unwrap_or(""),
675+
suffix = page.resource_suffix,
676+
);
677+
}
678+
}
655679
},
656680
&shared.style_files,
657681
);

src/librustdoc/html/render/span_map.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,12 @@ pub(crate) enum LinkFromSrc {
2929

3030
/// This function will do at most two things:
3131
///
32-
/// 1. Generate a `span` correspondance map which links an item `span` to its definition `span`.
32+
/// 1. Generate a `span` correspondence map which links an item `span` to its definition `span`.
3333
/// 2. Collect the source code files.
3434
///
35-
/// It returns the `krate`, the source code files and the `span` correspondance map.
35+
/// It returns the `krate`, the source code files and the `span` correspondence map.
3636
///
37-
/// Note about the `span` correspondance map: the keys are actually `(lo, hi)` of `span`s. We don't
37+
/// Note about the `span` correspondence map: the keys are actually `(lo, hi)` of `span`s. We don't
3838
/// need the `span` context later on, only their position, so instead of keep a whole `Span`, we
3939
/// only keep the `lo` and `hi`.
4040
pub(crate) fn collect_spans_and_sources(

0 commit comments

Comments
 (0)