Skip to content

Commit 21ee03e

Browse files
committed
Auto merge of #105667 - matthiaskrgr:rollup-fexlc0b, r=matthiaskrgr
Rollup of 7 pull requests Successful merges: - #105147 (Allow unsafe through inline const) - #105438 (Move some codegen-y methods from `rustc_hir_analysis::collect` -> `rustc_codegen_ssa`) - #105464 (Support #[track_caller] on async closures) - #105476 (Change pattern borrowing suggestions to be verbose and remove invalid suggestion) - #105500 (Make some diagnostics not depend on the source of what they reference being available) - #105628 (Small doc fixes) - #105659 (Don't require owned data in `MaybeStorageLive`) Failed merges: r? `@ghost` `@rustbot` modify labels: rollup
2 parents 0f529f0 + e0e9f3a commit 21ee03e

File tree

354 files changed

+3398
-3397
lines changed

Some content is hidden

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

354 files changed

+3398
-3397
lines changed

compiler/rustc_ast_lowering/src/expr.rs

+48-37
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,44 @@ impl<'hir> LoweringContext<'_, 'hir> {
3131

3232
pub(super) fn lower_expr_mut(&mut self, e: &Expr) -> hir::Expr<'hir> {
3333
ensure_sufficient_stack(|| {
34+
match &e.kind {
35+
// Paranthesis expression does not have a HirId and is handled specially.
36+
ExprKind::Paren(ex) => {
37+
let mut ex = self.lower_expr_mut(ex);
38+
// Include parens in span, but only if it is a super-span.
39+
if e.span.contains(ex.span) {
40+
ex.span = self.lower_span(e.span);
41+
}
42+
// Merge attributes into the inner expression.
43+
if !e.attrs.is_empty() {
44+
let old_attrs =
45+
self.attrs.get(&ex.hir_id.local_id).map(|la| *la).unwrap_or(&[]);
46+
self.attrs.insert(
47+
ex.hir_id.local_id,
48+
&*self.arena.alloc_from_iter(
49+
e.attrs
50+
.iter()
51+
.map(|a| self.lower_attr(a))
52+
.chain(old_attrs.iter().cloned()),
53+
),
54+
);
55+
}
56+
return ex;
57+
}
58+
// Desugar `ExprForLoop`
59+
// from: `[opt_ident]: for <pat> in <head> <body>`
60+
//
61+
// This also needs special handling because the HirId of the returned `hir::Expr` will not
62+
// correspond to the `e.id`, so `lower_expr_for` handles attribute lowering itself.
63+
ExprKind::ForLoop(pat, head, body, opt_label) => {
64+
return self.lower_expr_for(e, pat, head, body, *opt_label);
65+
}
66+
_ => (),
67+
}
68+
69+
let hir_id = self.lower_node_id(e.id);
70+
self.lower_attrs(hir_id, &e.attrs);
71+
3472
let kind = match &e.kind {
3573
ExprKind::Box(inner) => hir::ExprKind::Box(self.lower_expr(inner)),
3674
ExprKind::Array(exprs) => hir::ExprKind::Array(self.lower_exprs(exprs)),
@@ -48,7 +86,6 @@ impl<'hir> LoweringContext<'_, 'hir> {
4886
if e.attrs.get(0).map_or(false, |a| a.has_name(sym::rustc_box)) {
4987
if let [inner] = &args[..] && e.attrs.len() == 1 {
5088
let kind = hir::ExprKind::Box(self.lower_expr(&inner));
51-
let hir_id = self.lower_node_id(e.id);
5289
return hir::Expr { hir_id, kind, span: self.lower_span(e.span) };
5390
} else {
5491
self.tcx.sess.emit_err(RustcBoxAttributeError { span: e.span });
@@ -147,7 +184,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
147184
),
148185
ExprKind::Async(capture_clause, closure_node_id, block) => self.make_async_expr(
149186
*capture_clause,
150-
None,
187+
hir_id,
151188
*closure_node_id,
152189
None,
153190
e.span,
@@ -184,6 +221,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
184221
binder,
185222
*capture_clause,
186223
e.id,
224+
hir_id,
187225
*closure_id,
188226
fn_decl,
189227
body,
@@ -279,39 +317,12 @@ impl<'hir> LoweringContext<'_, 'hir> {
279317
ExprKind::Yield(opt_expr) => self.lower_expr_yield(e.span, opt_expr.as_deref()),
280318
ExprKind::Err => hir::ExprKind::Err,
281319
ExprKind::Try(sub_expr) => self.lower_expr_try(e.span, sub_expr),
282-
ExprKind::Paren(ex) => {
283-
let mut ex = self.lower_expr_mut(ex);
284-
// Include parens in span, but only if it is a super-span.
285-
if e.span.contains(ex.span) {
286-
ex.span = self.lower_span(e.span);
287-
}
288-
// Merge attributes into the inner expression.
289-
if !e.attrs.is_empty() {
290-
let old_attrs =
291-
self.attrs.get(&ex.hir_id.local_id).map(|la| *la).unwrap_or(&[]);
292-
self.attrs.insert(
293-
ex.hir_id.local_id,
294-
&*self.arena.alloc_from_iter(
295-
e.attrs
296-
.iter()
297-
.map(|a| self.lower_attr(a))
298-
.chain(old_attrs.iter().cloned()),
299-
),
300-
);
301-
}
302-
return ex;
303-
}
304320

305-
// Desugar `ExprForLoop`
306-
// from: `[opt_ident]: for <pat> in <head> <body>`
307-
ExprKind::ForLoop(pat, head, body, opt_label) => {
308-
return self.lower_expr_for(e, pat, head, body, *opt_label);
309-
}
321+
ExprKind::Paren(_) | ExprKind::ForLoop(..) => unreachable!("already handled"),
322+
310323
ExprKind::MacCall(_) => panic!("{:?} shouldn't exist here", e.span),
311324
};
312325

313-
let hir_id = self.lower_node_id(e.id);
314-
self.lower_attrs(hir_id, &e.attrs);
315326
hir::Expr { hir_id, kind, span: self.lower_span(e.span) }
316327
})
317328
}
@@ -576,7 +587,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
576587
pub(super) fn make_async_expr(
577588
&mut self,
578589
capture_clause: CaptureBy,
579-
outer_hir_id: Option<hir::HirId>,
590+
outer_hir_id: hir::HirId,
580591
closure_node_id: NodeId,
581592
ret_ty: Option<hir::FnRetTy<'hir>>,
582593
span: Span,
@@ -669,8 +680,9 @@ impl<'hir> LoweringContext<'_, 'hir> {
669680
hir::ExprKind::Closure(c)
670681
};
671682

672-
let track_caller = outer_hir_id
673-
.and_then(|id| self.attrs.get(&id.local_id))
683+
let track_caller = self
684+
.attrs
685+
.get(&outer_hir_id.local_id)
674686
.map_or(false, |attrs| attrs.into_iter().any(|attr| attr.has_name(sym::track_caller)));
675687

676688
let hir_id = self.lower_node_id(closure_node_id);
@@ -985,6 +997,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
985997
binder: &ClosureBinder,
986998
capture_clause: CaptureBy,
987999
closure_id: NodeId,
1000+
closure_hir_id: hir::HirId,
9881001
inner_closure_id: NodeId,
9891002
decl: &FnDecl,
9901003
body: &Expr,
@@ -1018,9 +1031,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
10181031

10191032
let async_body = this.make_async_expr(
10201033
capture_clause,
1021-
// FIXME(nbdd0121): This should also use a proper HIR id so `#[track_caller]`
1022-
// can be applied on async closures as well.
1023-
None,
1034+
closure_hir_id,
10241035
inner_closure_id,
10251036
async_ret_ty,
10261037
body.span,

compiler/rustc_ast_lowering/src/item.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1139,7 +1139,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
11391139

11401140
let async_expr = this.make_async_expr(
11411141
CaptureBy::Value,
1142-
Some(fn_id),
1142+
fn_id,
11431143
closure_id,
11441144
None,
11451145
body.span,

compiler/rustc_borrowck/src/diagnostics/mod.rs

+16-8
Original file line numberDiff line numberDiff line change
@@ -1059,17 +1059,12 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
10591059
);
10601060
if self.fn_self_span_reported.insert(fn_span) {
10611061
err.span_note(
1062-
// Check whether the source is accessible
1063-
if self.infcx.tcx.sess.source_map().is_span_accessible(self_arg.span) {
1064-
self_arg.span
1065-
} else {
1066-
fn_call_span
1067-
},
1062+
self_arg.span,
10681063
"calling this operator moves the left-hand side",
10691064
);
10701065
}
10711066
}
1072-
CallKind::Normal { self_arg, desugaring, is_option_or_result } => {
1067+
CallKind::Normal { self_arg, desugaring, method_did } => {
10731068
let self_arg = self_arg.unwrap();
10741069
if let Some((CallDesugaringKind::ForLoopIntoIter, _)) = desugaring {
10751070
let ty = moved_place.ty(self.body, self.infcx.tcx).ty;
@@ -1139,14 +1134,27 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
11391134
),
11401135
);
11411136
}
1137+
let tcx = self.infcx.tcx;
11421138
// Avoid pointing to the same function in multiple different
11431139
// error messages.
11441140
if span != DUMMY_SP && self.fn_self_span_reported.insert(self_arg.span) {
1141+
let func = tcx.def_path_str(method_did);
11451142
err.span_note(
11461143
self_arg.span,
1147-
&format!("this function takes ownership of the receiver `self`, which moves {}", place_name)
1144+
&format!("`{func}` takes ownership of the receiver `self`, which moves {place_name}")
11481145
);
11491146
}
1147+
let parent_did = tcx.parent(method_did);
1148+
let parent_self_ty = (tcx.def_kind(parent_did)
1149+
== rustc_hir::def::DefKind::Impl)
1150+
.then_some(parent_did)
1151+
.and_then(|did| match tcx.type_of(did).kind() {
1152+
ty::Adt(def, ..) => Some(def.did()),
1153+
_ => None,
1154+
});
1155+
let is_option_or_result = parent_self_ty.map_or(false, |def_id| {
1156+
matches!(tcx.get_diagnostic_name(def_id), Some(sym::Option | sym::Result))
1157+
});
11501158
if is_option_or_result && maybe_reinitialized_locations_is_empty {
11511159
err.span_label(
11521160
var_span,

compiler/rustc_borrowck/src/diagnostics/move_errors.rs

+64-36
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use rustc_middle::ty;
44
use rustc_mir_dataflow::move_paths::{
55
IllegalMoveOrigin, IllegalMoveOriginKind, LookupResult, MoveError, MovePathIndex,
66
};
7-
use rustc_span::Span;
7+
use rustc_span::{BytePos, Span};
88

99
use crate::diagnostics::{DescribePlaceOpt, UseSpans};
1010
use crate::prefixes::PrefixSet;
@@ -148,7 +148,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
148148
match_span: Span,
149149
statement_span: Span,
150150
) {
151-
debug!("append_binding_error(match_place={:?}, match_span={:?})", match_place, match_span);
151+
debug!(?match_place, ?match_span, "append_binding_error");
152152

153153
let from_simple_let = match_place.is_none();
154154
let match_place = match_place.unwrap_or(move_from);
@@ -160,7 +160,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
160160
if let GroupedMoveError::MovesFromPlace { span, binds_to, .. } = ge
161161
&& match_span == *span
162162
{
163-
debug!("appending local({:?}) to list", bind_to);
163+
debug!("appending local({bind_to:?}) to list");
164164
if !binds_to.is_empty() {
165165
binds_to.push(bind_to);
166166
}
@@ -198,7 +198,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
198198
} = ge
199199
{
200200
if match_span == *span && mpi == *other_mpi {
201-
debug!("appending local({:?}) to list", bind_to);
201+
debug!("appending local({bind_to:?}) to list");
202202
binds_to.push(bind_to);
203203
return;
204204
}
@@ -410,15 +410,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
410410
fn add_move_hints(&self, error: GroupedMoveError<'tcx>, err: &mut Diagnostic, span: Span) {
411411
match error {
412412
GroupedMoveError::MovesFromPlace { mut binds_to, move_from, .. } => {
413-
if let Ok(snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(span) {
414-
err.span_suggestion(
415-
span,
416-
"consider borrowing here",
417-
format!("&{snippet}"),
418-
Applicability::Unspecified,
419-
);
420-
}
421-
413+
self.add_borrow_suggestions(err, span);
422414
if binds_to.is_empty() {
423415
let place_ty = move_from.ty(self.body, self.infcx.tcx).ty;
424416
let place_desc = match self.describe_place(move_from.as_ref()) {
@@ -461,39 +453,75 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
461453
}
462454
}
463455

456+
fn add_borrow_suggestions(&self, err: &mut Diagnostic, span: Span) {
457+
match self.infcx.tcx.sess.source_map().span_to_snippet(span) {
458+
Ok(snippet) if snippet.starts_with('*') => {
459+
err.span_suggestion_verbose(
460+
span.with_hi(span.lo() + BytePos(1)),
461+
"consider removing the dereference here",
462+
String::new(),
463+
Applicability::MaybeIncorrect,
464+
);
465+
}
466+
_ => {
467+
err.span_suggestion_verbose(
468+
span.shrink_to_lo(),
469+
"consider borrowing here",
470+
"&".to_string(),
471+
Applicability::MaybeIncorrect,
472+
);
473+
}
474+
}
475+
}
476+
464477
fn add_move_error_suggestions(&self, err: &mut Diagnostic, binds_to: &[Local]) {
465-
let mut suggestions: Vec<(Span, &str, String)> = Vec::new();
478+
let mut suggestions: Vec<(Span, String, String)> = Vec::new();
466479
for local in binds_to {
467480
let bind_to = &self.body.local_decls[*local];
468481
if let Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
469482
VarBindingForm { pat_span, .. },
470483
)))) = bind_to.local_info
471484
{
472-
if let Ok(pat_snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(pat_span)
485+
let Ok(pat_snippet) =
486+
self.infcx.tcx.sess.source_map().span_to_snippet(pat_span) else { continue; };
487+
let Some(stripped) = pat_snippet.strip_prefix('&') else {
488+
suggestions.push((
489+
bind_to.source_info.span.shrink_to_lo(),
490+
"consider borrowing the pattern binding".to_string(),
491+
"ref ".to_string(),
492+
));
493+
continue;
494+
};
495+
let inner_pat_snippet = stripped.trim_start();
496+
let (pat_span, suggestion, to_remove) = if inner_pat_snippet.starts_with("mut")
497+
&& inner_pat_snippet["mut".len()..].starts_with(rustc_lexer::is_whitespace)
473498
{
474-
if let Some(stripped) = pat_snippet.strip_prefix('&') {
475-
let pat_snippet = stripped.trim_start();
476-
let (suggestion, to_remove) = if pat_snippet.starts_with("mut")
477-
&& pat_snippet["mut".len()..].starts_with(rustc_lexer::is_whitespace)
478-
{
479-
(pat_snippet["mut".len()..].trim_start(), "&mut")
480-
} else {
481-
(pat_snippet, "&")
482-
};
483-
suggestions.push((pat_span, to_remove, suggestion.to_owned()));
484-
}
485-
}
499+
let inner_pat_snippet = inner_pat_snippet["mut".len()..].trim_start();
500+
let pat_span = pat_span.with_hi(
501+
pat_span.lo()
502+
+ BytePos((pat_snippet.len() - inner_pat_snippet.len()) as u32),
503+
);
504+
(pat_span, String::new(), "mutable borrow")
505+
} else {
506+
let pat_span = pat_span.with_hi(
507+
pat_span.lo()
508+
+ BytePos(
509+
(pat_snippet.len() - inner_pat_snippet.trim_start().len()) as u32,
510+
),
511+
);
512+
(pat_span, String::new(), "borrow")
513+
};
514+
suggestions.push((
515+
pat_span,
516+
format!("consider removing the {to_remove}"),
517+
suggestion.to_string(),
518+
));
486519
}
487520
}
488521
suggestions.sort_unstable_by_key(|&(span, _, _)| span);
489522
suggestions.dedup_by_key(|&mut (span, _, _)| span);
490-
for (span, to_remove, suggestion) in suggestions {
491-
err.span_suggestion(
492-
span,
493-
&format!("consider removing the `{to_remove}`"),
494-
suggestion,
495-
Applicability::MachineApplicable,
496-
);
523+
for (span, msg, suggestion) in suggestions {
524+
err.span_suggestion_verbose(span, &msg, suggestion, Applicability::MachineApplicable);
497525
}
498526
}
499527

@@ -521,8 +549,8 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
521549

522550
if binds_to.len() > 1 {
523551
err.note(
524-
"move occurs because these variables have types that \
525-
don't implement the `Copy` trait",
552+
"move occurs because these variables have types that don't implement the `Copy` \
553+
trait",
526554
);
527555
}
528556
}

0 commit comments

Comments
 (0)