Skip to content

Commit c9d9448

Browse files
committed
Revert "Rollup merge of #154074 - dianne:dbg-temp-scopes, r=Mark-Simulacrum"
This reverts commit 2a18b88, reversing changes made to cd14b73.
1 parent 73931c4 commit c9d9448

13 files changed

Lines changed: 177 additions & 181 deletions

File tree

compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs

Lines changed: 15 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -580,6 +580,8 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
580580
}
581581

582582
// for dbg!(x) which may take ownership, suggest dbg!(&x) instead
583+
// but here we actually do not check whether the macro name is `dbg!`
584+
// so that we may extend the scope a bit larger to cover more cases
583585
fn suggest_ref_for_dbg_args(
584586
&self,
585587
body: &hir::Expr<'_>,
@@ -593,41 +595,29 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
593595
});
594596
let Some(var_info) = var_info else { return };
595597
let arg_name = var_info.name;
596-
struct MatchArgFinder<'tcx> {
597-
tcx: TyCtxt<'tcx>,
598-
move_span: Span,
598+
struct MatchArgFinder {
599+
expr_span: Span,
600+
match_arg_span: Option<Span>,
599601
arg_name: Symbol,
600-
match_arg_span: Option<Span> = None,
601602
}
602-
impl Visitor<'_> for MatchArgFinder<'_> {
603+
impl Visitor<'_> for MatchArgFinder {
603604
fn visit_expr(&mut self, e: &hir::Expr<'_>) {
604605
// dbg! is expanded into a match pattern, we need to find the right argument span
605-
if let hir::ExprKind::Match(scrutinee, ..) = &e.kind
606-
&& let hir::ExprKind::Tup(args) = scrutinee.kind
607-
&& e.span.macro_backtrace().any(|expn| {
608-
expn.macro_def_id.is_some_and(|macro_def_id| {
609-
self.tcx.is_diagnostic_item(sym::dbg_macro, macro_def_id)
610-
})
611-
})
606+
if let hir::ExprKind::Match(expr, ..) = &e.kind
607+
&& let hir::ExprKind::Path(hir::QPath::Resolved(
608+
_,
609+
path @ Path { segments: [seg], .. },
610+
)) = &expr.kind
611+
&& seg.ident.name == self.arg_name
612+
&& self.expr_span.source_callsite().contains(expr.span)
612613
{
613-
for arg in args {
614-
if let hir::ExprKind::Path(hir::QPath::Resolved(
615-
_,
616-
path @ Path { segments: [seg], .. },
617-
)) = &arg.kind
618-
&& seg.ident.name == self.arg_name
619-
&& self.move_span.source_equal(arg.span)
620-
{
621-
self.match_arg_span = Some(path.span);
622-
return;
623-
}
624-
}
614+
self.match_arg_span = Some(path.span);
625615
}
626616
hir::intravisit::walk_expr(self, e);
627617
}
628618
}
629619

630-
let mut finder = MatchArgFinder { tcx: self.infcx.tcx, move_span, arg_name, .. };
620+
let mut finder = MatchArgFinder { expr_span: move_span, match_arg_span: None, arg_name };
631621
finder.visit_expr(body);
632622
if let Some(macro_arg_span) = finder.match_arg_span {
633623
err.span_suggestion_verbose(

compiler/rustc_span/src/symbol.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -752,7 +752,6 @@ symbols! {
752752
custom_mir,
753753
custom_test_frameworks,
754754
d32,
755-
dbg_macro,
756755
dead_code,
757756
dead_code_pub_in_binary,
758757
dealloc,

library/std/src/macros.rs

Lines changed: 39 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,6 @@
55
//! library.
66
// ignore-tidy-dbg
77

8-
#[cfg(test)]
9-
mod tests;
10-
118
#[doc = include_str!("../../core/src/macros/panic.md")]
129
#[macro_export]
1310
#[rustc_builtin_macro(std_panic)]
@@ -362,16 +359,19 @@ macro_rules! dbg {
362359
};
363360
}
364361

365-
/// Internal macro that processes a list of expressions, binds their results
366-
/// with `match`, calls `eprint!` with the collected information, and returns
367-
/// all the evaluated expressions in a tuple.
362+
/// Internal macro that processes a list of expressions and produces a chain of
363+
/// nested `match`es, one for each expression, before finally calling `eprint!`
364+
/// with the collected information and returning all the evaluated expressions
365+
/// in a tuple.
368366
///
369367
/// E.g. `dbg_internal!(() () (1, 2))` expands into
370368
/// ```rust, ignore
371-
/// match (1, 2) {
372-
/// (tmp_1, tmp_2) => {
373-
/// eprint!("...", &tmp_1, &tmp_2, /* some other arguments */);
374-
/// (tmp_1, tmp_2)
369+
/// match 1 {
370+
/// tmp_1 => match 2 {
371+
/// tmp_2 => {
372+
/// eprint!("...", &tmp_1, &tmp_2, /* some other arguments */);
373+
/// (tmp_1, tmp_2)
374+
/// }
375375
/// }
376376
/// }
377377
/// ```
@@ -380,43 +380,39 @@ macro_rules! dbg {
380380
#[doc(hidden)]
381381
#[rustc_macro_transparency = "semiopaque"]
382382
pub macro dbg_internal {
383-
(($($piece:literal),+) ($($processed:expr => $bound:ident),+) ()) => {
383+
(($($piece:literal),+) ($($processed:expr => $bound:expr),+) ()) => {{
384+
$crate::eprint!(
385+
$crate::concat!($($piece),+),
386+
$(
387+
$crate::stringify!($processed),
388+
// The `&T: Debug` check happens here (not in the format literal desugaring)
389+
// to avoid format literal related messages and suggestions.
390+
&&$bound as &dyn $crate::fmt::Debug
391+
),+,
392+
// The location returned here is that of the macro invocation, so
393+
// it will be the same for all expressions. Thus, label these
394+
// arguments so that they can be reused in every piece of the
395+
// formatting template.
396+
file=$crate::file!(),
397+
line=$crate::line!(),
398+
column=$crate::column!()
399+
);
400+
// Comma separate the variables only when necessary so that this will
401+
// not yield a tuple for a single expression, but rather just parenthesize
402+
// the expression.
403+
($($bound),+)
404+
}},
405+
(($($piece:literal),*) ($($processed:expr => $bound:expr),*) ($val:expr $(,$rest:expr)*)) => {
384406
// Use of `match` here is intentional because it affects the lifetimes
385407
// of temporaries - https://stackoverflow.com/a/48732525/1063961
386-
// Always put the arguments in a tuple to avoid an unused parens lint on the pattern.
387-
match ($($processed,)+) {
388-
($($bound,)+) => {
389-
$crate::eprint!(
390-
$crate::concat!($($piece),+),
391-
$(
392-
$crate::stringify!($processed),
393-
// The `&T: Debug` check happens here (not in the format literal desugaring)
394-
// to avoid format literal related messages and suggestions.
395-
&&$bound as &dyn $crate::fmt::Debug
396-
),+,
397-
// The location returned here is that of the macro invocation, so
398-
// it will be the same for all expressions. Thus, label these
399-
// arguments so that they can be reused in every piece of the
400-
// formatting template.
401-
file=$crate::file!(),
402-
line=$crate::line!(),
403-
column=$crate::column!()
404-
);
405-
// Comma separate the variables only when necessary so that this will
406-
// not yield a tuple for a single expression, but rather just parenthesize
407-
// the expression.
408-
($($bound),+)
409-
410-
}
408+
match $val {
409+
tmp => $crate::macros::dbg_internal!(
410+
($($piece,)* "[{file}:{line}:{column}] {} = {:#?}\n")
411+
($($processed => $bound,)* $val => tmp)
412+
($($rest),*)
413+
),
411414
}
412415
},
413-
(($($piece:literal),*) ($($processed:expr => $bound:ident),*) ($val:expr $(,$rest:expr)*)) => {
414-
$crate::macros::dbg_internal!(
415-
($($piece,)* "[{file}:{line}:{column}] {} = {:#?}\n")
416-
($($processed => $bound,)* $val => tmp)
417-
($($rest),*)
418-
)
419-
},
420416
}
421417

422418
#[doc(hidden)]

library/std/src/macros/tests.rs

Lines changed: 0 additions & 13 deletions
This file was deleted.

src/tools/clippy/clippy_lints/src/dbg_macro.rs

Lines changed: 42 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use clippy_utils::source::snippet_with_applicability;
55
use clippy_utils::{is_in_test, sym};
66
use rustc_data_structures::fx::FxHashSet;
77
use rustc_errors::Applicability;
8-
use rustc_hir::{Closure, ClosureKind, CoroutineKind, Expr, ExprKind, LetStmt, LocalSource, Node, Stmt, StmtKind};
8+
use rustc_hir::{Arm, Closure, ClosureKind, CoroutineKind, Expr, ExprKind, LetStmt, LocalSource, Node, Stmt, StmtKind};
99
use rustc_lint::{LateContext, LateLintPass, LintContext};
1010
use rustc_session::impl_lint_pass;
1111
use rustc_span::{Span, SyntaxContext};
@@ -92,15 +92,16 @@ impl LateLintPass<'_> for DbgMacro {
9292
(macro_call.span, String::from("()"))
9393
}
9494
},
95-
ExprKind::Match(args, _, _) => {
96-
let suggestion = match args.kind {
95+
ExprKind::Match(first, arms, _) => {
96+
let vals = collect_vals(first, arms);
97+
let suggestion = match *vals.as_slice() {
9798
// dbg!(1) => 1
98-
ExprKind::Tup([val]) => {
99+
[val] => {
99100
snippet_with_applicability(cx, val.span.source_callsite(), "..", &mut applicability)
100101
.to_string()
101102
},
102103
// dbg!(2, 3) => (2, 3)
103-
ExprKind::Tup([first, .., last]) => {
104+
[first, .., last] => {
104105
let snippet = snippet_with_applicability(
105106
cx,
106107
first.span.source_callsite().to(last.span.source_callsite()),
@@ -164,3 +165,39 @@ fn is_async_move_desugar<'tcx>(expr: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx
164165
fn first_dbg_macro_in_expansion(cx: &LateContext<'_>, span: Span) -> Option<MacroCall> {
165166
macro_backtrace(span).find(|mc| cx.tcx.is_diagnostic_item(sym::dbg_macro, mc.def_id))
166167
}
168+
169+
/// Extracts all value expressions from the `match`-tree generated by `dbg!`.
170+
///
171+
/// E.g. from
172+
/// ```rust, ignore
173+
/// match 1 {
174+
/// tmp_1 => match 2 {
175+
/// tmp_2 => {
176+
/// /* printing */
177+
/// (tmp_1, tmp_2)
178+
/// }
179+
/// }
180+
/// }
181+
/// ```
182+
/// this extracts `1` and `2`.
183+
fn collect_vals<'hir>(first: &'hir Expr<'hir>, mut arms: &'hir [Arm<'hir>]) -> Vec<&'hir Expr<'hir>> {
184+
let mut vals = vec![first];
185+
loop {
186+
let [arm] = arms else {
187+
unreachable!("dbg! macro expansion only has single-arm matches")
188+
};
189+
190+
match is_async_move_desugar(arm.body)
191+
.unwrap_or(arm.body)
192+
.peel_drop_temps()
193+
.kind
194+
{
195+
ExprKind::Block(..) => return vals,
196+
ExprKind::Match(val, a, _) => {
197+
vals.push(val);
198+
arms = a;
199+
},
200+
_ => unreachable!("dbg! macro expansion only results in block or match expressions"),
201+
}
202+
}
203+
}

src/tools/clippy/clippy_utils/src/sym.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,7 @@ generate! {
202202
cx,
203203
cycle,
204204
cyclomatic_complexity,
205+
dbg_macro,
205206
de,
206207
debug_struct,
207208
deprecated_in_future,

src/tools/miri/tests/fail/dangling_pointers/dangling_primitive.stderr

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ error: Undefined Behavior: memory access failed: ALLOC has been freed, so this p
22
--> tests/fail/dangling_pointers/dangling_primitive.rs:LL:CC
33
|
44
LL | dbg!(*ptr);
5-
| ^^^^ Undefined Behavior occurred here
5+
| ^^^^^^^^^^ Undefined Behavior occurred here
66
|
77
= help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
88
= help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information

src/tools/miri/tests/fail/function_calls/return_pointer_on_unwind.stderr

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ error: Undefined Behavior: reading memory at ALLOC[0x0..0x4], but memory is unin
77
--> tests/fail/function_calls/return_pointer_on_unwind.rs:LL:CC
88
|
99
LL | dbg!(x.0);
10-
| ^^^ Undefined Behavior occurred here
10+
| ^^^^^^^^^ Undefined Behavior occurred here
1111
|
1212
= help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
1313
= help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information

tests/ui/borrowck/dbg-issue-120327.rs

Lines changed: 38 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,67 @@
1-
//! Diagnostic test for <https://github.com/rust-lang/rust/issues/120327>: suggest borrowing
2-
//! variables passed to `dbg!` that are later used.
3-
//@ dont-require-annotations: HELP
4-
51
fn s() -> String {
62
let a = String::new();
7-
dbg!(a); //~ HELP consider borrowing instead of transferring ownership
3+
dbg!(a);
84
return a; //~ ERROR use of moved value:
95
}
106

117
fn m() -> String {
128
let a = String::new();
13-
dbg!(1, 2, a, 1, 2); //~ HELP consider borrowing instead of transferring ownership
9+
dbg!(1, 2, a, 1, 2);
1410
return a; //~ ERROR use of moved value:
1511
}
1612

1713
fn t(a: String) -> String {
1814
let b: String = "".to_string();
19-
dbg!(a, b); //~ HELP consider borrowing instead of transferring ownership
15+
dbg!(a, b);
2016
return b; //~ ERROR use of moved value:
2117
}
2218

2319
fn x(a: String) -> String {
2420
let b: String = "".to_string();
25-
dbg!(a, b); //~ HELP consider borrowing instead of transferring ownership
21+
dbg!(a, b);
2622
return a; //~ ERROR use of moved value:
2723
}
2824

29-
fn two_of_them(a: String) -> String {
30-
dbg!(a, a); //~ ERROR use of moved value
31-
//~| HELP consider borrowing instead of transferring ownership
32-
//~| HELP consider borrowing instead of transferring ownership
33-
return a; //~ ERROR use of moved value
25+
macro_rules! my_dbg {
26+
() => {
27+
eprintln!("[{}:{}:{}]", file!(), line!(), column!())
28+
};
29+
($val:expr $(,)?) => {
30+
match $val {
31+
tmp => {
32+
eprintln!("[{}:{}:{}] {} = {:#?}",
33+
file!(), line!(), column!(), stringify!($val), &tmp);
34+
tmp
35+
}
36+
}
37+
};
38+
($($val:expr),+ $(,)?) => {
39+
($(my_dbg!($val)),+,)
40+
};
41+
}
42+
43+
fn test_my_dbg() -> String {
44+
let b: String = "".to_string();
45+
my_dbg!(b, 1);
46+
return b; //~ ERROR use of moved value:
47+
}
48+
49+
fn test_not_macro() -> String {
50+
let a = String::new();
51+
let _b = match a {
52+
tmp => {
53+
eprintln!("dbg: {}", tmp);
54+
tmp
55+
}
56+
};
57+
return a; //~ ERROR use of moved value:
3458
}
3559

3660
fn get_expr(_s: String) {}
3761

38-
// The suggestion is purely syntactic; applying it here will result in a type error.
3962
fn test() {
4063
let a: String = "".to_string();
41-
let _res = get_expr(dbg!(a)); //~ HELP consider borrowing instead of transferring ownership
64+
let _res = get_expr(dbg!(a));
4265
let _l = a.len(); //~ ERROR borrow of moved value
4366
}
4467

0 commit comments

Comments
 (0)