1#![deny(clippy::missing_docs_in_private_items)]
3
4use crate::source::{snippet, snippet_opt, snippet_with_applicability, snippet_with_context};
5use crate::ty::expr_sig;
6use crate::{get_parent_expr_for_hir, higher};
7use rustc_ast::util::parser::AssocOp;
8use rustc_ast::{UnOp, ast};
9use rustc_data_structures::fx::FxHashSet;
10use rustc_errors::Applicability;
11use rustc_hir::{self as hir, Closure, ExprKind, HirId, MutTy, Node, TyKind};
12use rustc_hir_typeck::expr_use_visitor::{Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId};
13use rustc_lint::{EarlyContext, LateContext, LintContext};
14use rustc_middle::hir::place::ProjectionKind;
15use rustc_middle::mir::{FakeReadCause, Mutability};
16use rustc_middle::ty;
17use rustc_span::{BytePos, CharPos, Pos, Span, SyntaxContext};
18use std::borrow::Cow;
19use std::fmt::{self, Display, Write as _};
20use std::ops::{Add, Neg, Not, Sub};
21
22#[derive(Clone, Debug, PartialEq)]
24pub enum Sugg<'a> {
25 NonParen(Cow<'a, str>),
27 MaybeParen(Cow<'a, str>),
29 BinOp(AssocOp, Cow<'a, str>, Cow<'a, str>),
32 UnOp(UnOp, Box<Self>),
37}
38
39pub const ZERO: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("0"));
41pub const ONE: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("1"));
43pub const EMPTY: Sugg<'static> = Sugg::NonParen(Cow::Borrowed(""));
45
46impl Display for Sugg<'_> {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
48 match self {
49 Sugg::NonParen(s) | Sugg::MaybeParen(s) => s.fmt(f),
50 Sugg::BinOp(op, lhs, rhs) => binop_to_string(*op, lhs, rhs).fmt(f),
51 Sugg::UnOp(op, inner) => write!(f, "{}{}", op.as_str(), inner.clone().maybe_inner_paren()),
52 }
53 }
54}
55
56#[expect(clippy::wrong_self_convention)] impl<'a> Sugg<'a> {
58 pub fn hir_opt(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option<Self> {
60 let ctxt = expr.span.ctxt();
61 let get_snippet = |span| snippet_with_context(cx, span, ctxt, "", &mut Applicability::Unspecified).0;
62 snippet_opt(cx, expr.span).map(|_| Self::hir_from_snippet(cx, expr, get_snippet))
63 }
64
65 pub fn hir(cx: &LateContext<'_>, expr: &hir::Expr<'_>, default: &'a str) -> Self {
68 Self::hir_opt(cx, expr).unwrap_or(Sugg::NonParen(Cow::Borrowed(default)))
69 }
70
71 pub fn hir_with_applicability(
78 cx: &LateContext<'_>,
79 expr: &hir::Expr<'_>,
80 default: &'a str,
81 applicability: &mut Applicability,
82 ) -> Self {
83 if *applicability != Applicability::Unspecified && expr.span.from_expansion() {
84 *applicability = Applicability::MaybeIncorrect;
85 }
86 Self::hir_opt(cx, expr).unwrap_or_else(|| {
87 if *applicability == Applicability::MachineApplicable {
88 *applicability = Applicability::HasPlaceholders;
89 }
90 Sugg::NonParen(Cow::Borrowed(default))
91 })
92 }
93
94 pub fn hir_with_context(
102 cx: &LateContext<'_>,
103 expr: &hir::Expr<'_>,
104 ctxt: SyntaxContext,
105 default: &'a str,
106 applicability: &mut Applicability,
107 ) -> Self {
108 if expr.span.ctxt() == ctxt {
109 if let ExprKind::Unary(op, inner) = expr.kind
110 && matches!(op, UnOp::Neg | UnOp::Not)
111 && cx.typeck_results().expr_ty(expr) == cx.typeck_results().expr_ty(inner)
112 {
113 Sugg::UnOp(
114 op,
115 Box::new(Self::hir_with_context(cx, inner, ctxt, default, applicability)),
116 )
117 } else {
118 Self::hir_from_snippet(cx, expr, |span| {
119 snippet_with_context(cx, span, ctxt, default, applicability).0
120 })
121 }
122 } else {
123 let (snip, _) = snippet_with_context(cx, expr.span, ctxt, default, applicability);
124 Sugg::NonParen(snip)
125 }
126 }
127
128 fn hir_from_snippet(
131 cx: &LateContext<'_>,
132 expr: &hir::Expr<'_>,
133 mut get_snippet: impl FnMut(Span) -> Cow<'a, str>,
134 ) -> Self {
135 if let Some(range) = higher::Range::hir(cx, expr) {
136 let op = AssocOp::Range(range.limits);
137 let start = range.start.map_or("".into(), |expr| get_snippet(expr.span));
138 let end = range.end.map_or("".into(), |expr| get_snippet(expr.span));
139
140 return Sugg::BinOp(op, start, end);
141 }
142
143 match expr.kind {
144 ExprKind::AddrOf(..)
145 | ExprKind::If(..)
146 | ExprKind::Let(..)
147 | ExprKind::Closure { .. }
148 | ExprKind::Unary(..)
149 | ExprKind::Match(..) => Sugg::MaybeParen(get_snippet(expr.span)),
150 ExprKind::Continue(..)
151 | ExprKind::Yield(..)
152 | ExprKind::Array(..)
153 | ExprKind::Block(..)
154 | ExprKind::Break(..)
155 | ExprKind::Call(..)
156 | ExprKind::Field(..)
157 | ExprKind::Index(..)
158 | ExprKind::InlineAsm(..)
159 | ExprKind::OffsetOf(..)
160 | ExprKind::ConstBlock(..)
161 | ExprKind::Lit(..)
162 | ExprKind::Loop(..)
163 | ExprKind::MethodCall(..)
164 | ExprKind::Path(..)
165 | ExprKind::Repeat(..)
166 | ExprKind::Ret(..)
167 | ExprKind::Become(..)
168 | ExprKind::Struct(..)
169 | ExprKind::Tup(..)
170 | ExprKind::Use(..)
171 | ExprKind::Err(_)
172 | ExprKind::UnsafeBinderCast(..) => Sugg::NonParen(get_snippet(expr.span)),
173 ExprKind::DropTemps(inner) => Self::hir_from_snippet(cx, inner, get_snippet),
174 ExprKind::Assign(lhs, rhs, _) => {
175 Sugg::BinOp(AssocOp::Assign, get_snippet(lhs.span), get_snippet(rhs.span))
176 },
177 ExprKind::AssignOp(op, lhs, rhs) => {
178 Sugg::BinOp(AssocOp::AssignOp(op.node), get_snippet(lhs.span), get_snippet(rhs.span))
179 },
180 ExprKind::Binary(op, lhs, rhs) => Sugg::BinOp(
181 AssocOp::Binary(op.node),
182 get_snippet(lhs.span),
183 get_snippet(rhs.span),
184 ),
185 ExprKind::Cast(lhs, ty) |
186 ExprKind::Type(lhs, ty) => Sugg::BinOp(AssocOp::Cast, get_snippet(lhs.span), get_snippet(ty.span)),
188 }
189 }
190
191 pub fn ast(
193 cx: &EarlyContext<'_>,
194 expr: &ast::Expr,
195 default: &'a str,
196 ctxt: SyntaxContext,
197 app: &mut Applicability,
198 ) -> Self {
199 let mut snippet = |span: Span| snippet_with_context(cx, span, ctxt, default, app).0;
200
201 match expr.kind {
202 _ if expr.span.ctxt() != ctxt => Sugg::NonParen(snippet(expr.span)),
203 ast::ExprKind::AddrOf(..)
204 | ast::ExprKind::Closure { .. }
205 | ast::ExprKind::If(..)
206 | ast::ExprKind::Let(..)
207 | ast::ExprKind::Unary(..)
208 | ast::ExprKind::Match(..) => match snippet_with_context(cx, expr.span, ctxt, default, app) {
209 (snip, false) => Sugg::MaybeParen(snip),
210 (snip, true) => Sugg::NonParen(snip),
211 },
212 ast::ExprKind::Gen(..)
213 | ast::ExprKind::Block(..)
214 | ast::ExprKind::Break(..)
215 | ast::ExprKind::Call(..)
216 | ast::ExprKind::Continue(..)
217 | ast::ExprKind::Yield(..)
218 | ast::ExprKind::Field(..)
219 | ast::ExprKind::ForLoop { .. }
220 | ast::ExprKind::Index(..)
221 | ast::ExprKind::InlineAsm(..)
222 | ast::ExprKind::OffsetOf(..)
223 | ast::ExprKind::ConstBlock(..)
224 | ast::ExprKind::Lit(..)
225 | ast::ExprKind::IncludedBytes(..)
226 | ast::ExprKind::Loop(..)
227 | ast::ExprKind::MacCall(..)
228 | ast::ExprKind::MethodCall(..)
229 | ast::ExprKind::Paren(..)
230 | ast::ExprKind::Underscore
231 | ast::ExprKind::Path(..)
232 | ast::ExprKind::Repeat(..)
233 | ast::ExprKind::Ret(..)
234 | ast::ExprKind::Become(..)
235 | ast::ExprKind::Yeet(..)
236 | ast::ExprKind::FormatArgs(..)
237 | ast::ExprKind::Struct(..)
238 | ast::ExprKind::Try(..)
239 | ast::ExprKind::TryBlock(..)
240 | ast::ExprKind::Tup(..)
241 | ast::ExprKind::Use(..)
242 | ast::ExprKind::Array(..)
243 | ast::ExprKind::While(..)
244 | ast::ExprKind::Await(..)
245 | ast::ExprKind::Err(_)
246 | ast::ExprKind::Dummy
247 | ast::ExprKind::UnsafeBinderCast(..) => Sugg::NonParen(snippet(expr.span)),
248 ast::ExprKind::Range(ref lhs, ref rhs, limits) => Sugg::BinOp(
249 AssocOp::Range(limits),
250 lhs.as_ref().map_or("".into(), |lhs| snippet(lhs.span)),
251 rhs.as_ref().map_or("".into(), |rhs| snippet(rhs.span)),
252 ),
253 ast::ExprKind::Assign(ref lhs, ref rhs, _) => Sugg::BinOp(
254 AssocOp::Assign,
255 snippet(lhs.span),
256 snippet(rhs.span),
257 ),
258 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => Sugg::BinOp(
259 AssocOp::AssignOp(op.node),
260 snippet(lhs.span),
261 snippet(rhs.span),
262 ),
263 ast::ExprKind::Binary(op, ref lhs, ref rhs) => Sugg::BinOp(
264 AssocOp::Binary(op.node),
265 snippet(lhs.span),
266 snippet(rhs.span),
267 ),
268 ast::ExprKind::Cast(ref lhs, ref ty) |
269 ast::ExprKind::Type(ref lhs, ref ty) => Sugg::BinOp(
271 AssocOp::Cast,
272 snippet(lhs.span),
273 snippet(ty.span),
274 ),
275 }
276 }
277
278 pub fn and(self, rhs: &Self) -> Sugg<'static> {
280 make_binop(ast::BinOpKind::And, &self, rhs)
281 }
282
283 pub fn bit_and(self, rhs: &Self) -> Sugg<'static> {
285 make_binop(ast::BinOpKind::BitAnd, &self, rhs)
286 }
287
288 pub fn as_ty<R: Display>(self, rhs: R) -> Sugg<'static> {
290 make_assoc(AssocOp::Cast, &self, &Sugg::NonParen(rhs.to_string().into()))
291 }
292
293 pub fn addr(self) -> Sugg<'static> {
295 make_unop("&", self)
296 }
297
298 pub fn mut_addr(self) -> Sugg<'static> {
300 make_unop("&mut ", self)
301 }
302
303 pub fn deref(self) -> Sugg<'static> {
305 make_unop("*", self)
306 }
307
308 pub fn addr_deref(self) -> Sugg<'static> {
312 make_unop("&*", self)
313 }
314
315 pub fn mut_addr_deref(self) -> Sugg<'static> {
319 make_unop("&mut *", self)
320 }
321
322 pub fn make_return(self) -> Sugg<'static> {
324 Sugg::NonParen(Cow::Owned(format!("return {self}")))
325 }
326
327 pub fn blockify(self) -> Sugg<'static> {
330 Sugg::NonParen(Cow::Owned(format!("{{ {self} }}")))
331 }
332
333 pub fn asyncify(self) -> Sugg<'static> {
336 Sugg::NonParen(Cow::Owned(format!("async {self}")))
337 }
338
339 pub fn range(self, end: &Self, limits: ast::RangeLimits) -> Sugg<'static> {
342 make_assoc(AssocOp::Range(limits), &self, end)
343 }
344
345 #[must_use]
349 pub fn maybe_paren(self) -> Self {
350 match self {
351 Sugg::NonParen(..) => self,
352 Sugg::MaybeParen(sugg) => {
354 if has_enclosing_paren(&sugg) {
355 Sugg::MaybeParen(sugg)
356 } else {
357 Sugg::NonParen(format!("({sugg})").into())
358 }
359 },
360 Sugg::BinOp(op, lhs, rhs) => {
361 let sugg = binop_to_string(op, &lhs, &rhs);
362 Sugg::NonParen(format!("({sugg})").into())
363 },
364 Sugg::UnOp(op, inner) => Sugg::NonParen(format!("({}{})", op.as_str(), inner.maybe_inner_paren()).into()),
365 }
366 }
367
368 pub fn into_string(self) -> String {
369 match self {
370 Sugg::NonParen(p) | Sugg::MaybeParen(p) => p.into_owned(),
371 Sugg::BinOp(b, l, r) => binop_to_string(b, &l, &r),
372 Sugg::UnOp(op, inner) => format!("{}{}", op.as_str(), inner.maybe_inner_paren()),
373 }
374 }
375
376 fn starts_with_unary_op(&self) -> bool {
378 match self {
379 Sugg::UnOp(..) => true,
380 Sugg::BinOp(..) => false,
381 Sugg::MaybeParen(s) | Sugg::NonParen(s) => s.starts_with(['*', '!', '-', '&']),
382 }
383 }
384
385 fn maybe_inner_paren(self) -> Self {
388 if self.starts_with_unary_op() {
389 self
390 } else {
391 self.maybe_paren()
392 }
393 }
394}
395
396fn binop_to_string(op: AssocOp, lhs: &str, rhs: &str) -> String {
398 match op {
399 AssocOp::Binary(op) => format!("{lhs} {} {rhs}", op.as_str()),
400 AssocOp::Assign => format!("{lhs} = {rhs}"),
401 AssocOp::AssignOp(op) => format!("{lhs} {} {rhs}", op.as_str()),
402 AssocOp::Cast => format!("{lhs} as {rhs}"),
403 AssocOp::Range(limits) => format!("{lhs}{}{rhs}", limits.as_str()),
404 }
405}
406
407pub fn has_enclosing_paren(sugg: impl AsRef<str>) -> bool {
409 let mut chars = sugg.as_ref().chars();
410 if chars.next() == Some('(') {
411 let mut depth = 1;
412 for c in &mut chars {
413 if c == '(' {
414 depth += 1;
415 } else if c == ')' {
416 depth -= 1;
417 }
418 if depth == 0 {
419 break;
420 }
421 }
422 chars.next().is_none()
423 } else {
424 false
425 }
426}
427
428macro_rules! forward_binop_impls_to_ref {
430 (impl $imp:ident, $method:ident for $t:ty, type Output = $o:ty) => {
431 impl $imp<$t> for &$t {
432 type Output = $o;
433
434 fn $method(self, other: $t) -> $o {
435 $imp::$method(self, &other)
436 }
437 }
438
439 impl $imp<&$t> for $t {
440 type Output = $o;
441
442 fn $method(self, other: &$t) -> $o {
443 $imp::$method(&self, other)
444 }
445 }
446
447 impl $imp for $t {
448 type Output = $o;
449
450 fn $method(self, other: $t) -> $o {
451 $imp::$method(&self, &other)
452 }
453 }
454 };
455}
456
457impl Add for &Sugg<'_> {
458 type Output = Sugg<'static>;
459 fn add(self, rhs: &Sugg<'_>) -> Sugg<'static> {
460 make_binop(ast::BinOpKind::Add, self, rhs)
461 }
462}
463
464impl Sub for &Sugg<'_> {
465 type Output = Sugg<'static>;
466 fn sub(self, rhs: &Sugg<'_>) -> Sugg<'static> {
467 make_binop(ast::BinOpKind::Sub, self, rhs)
468 }
469}
470
471forward_binop_impls_to_ref!(impl Add, add for Sugg<'_>, type Output = Sugg<'static>);
472forward_binop_impls_to_ref!(impl Sub, sub for Sugg<'_>, type Output = Sugg<'static>);
473
474impl<'a> Neg for Sugg<'a> {
475 type Output = Sugg<'a>;
476 fn neg(self) -> Self::Output {
477 match self {
478 Self::UnOp(UnOp::Neg, sugg) => *sugg,
479 Self::BinOp(AssocOp::Cast, ..) => Sugg::MaybeParen(format!("-({self})").into()),
480 _ => make_unop("-", self),
481 }
482 }
483}
484
485impl<'a> Not for Sugg<'a> {
486 type Output = Sugg<'a>;
487 fn not(self) -> Sugg<'a> {
488 use AssocOp::Binary;
489 use ast::BinOpKind::{Eq, Ge, Gt, Le, Lt, Ne};
490
491 match self {
492 Sugg::BinOp(op, lhs, rhs) => {
493 let to_op = match op {
494 Binary(Eq) => Binary(Ne),
495 Binary(Ne) => Binary(Eq),
496 Binary(Lt) => Binary(Ge),
497 Binary(Ge) => Binary(Lt),
498 Binary(Gt) => Binary(Le),
499 Binary(Le) => Binary(Gt),
500 _ => return make_unop("!", Sugg::BinOp(op, lhs, rhs)),
501 };
502 Sugg::BinOp(to_op, lhs, rhs)
503 },
504 Sugg::UnOp(UnOp::Not, expr) => *expr,
505 _ => make_unop("!", self),
506 }
507 }
508}
509
510struct ParenHelper<T> {
512 paren: bool,
514 wrapped: T,
516}
517
518impl<T> ParenHelper<T> {
519 fn new(paren: bool, wrapped: T) -> Self {
521 Self { paren, wrapped }
522 }
523}
524
525impl<T: Display> Display for ParenHelper<T> {
526 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
527 if self.paren {
528 write!(f, "({})", self.wrapped)
529 } else {
530 self.wrapped.fmt(f)
531 }
532 }
533}
534
535pub fn make_unop(op: &str, expr: Sugg<'_>) -> Sugg<'static> {
540 Sugg::MaybeParen(format!("{op}{}", expr.maybe_inner_paren()).into())
543}
544
545pub fn make_assoc(op: AssocOp, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
551 fn is_shift(op: AssocOp) -> bool {
553 matches!(op, AssocOp::Binary(ast::BinOpKind::Shl | ast::BinOpKind::Shr))
554 }
555
556 fn is_arith(op: AssocOp) -> bool {
559 matches!(
560 op,
561 AssocOp::Binary(
562 ast::BinOpKind::Add
563 | ast::BinOpKind::Sub
564 | ast::BinOpKind::Mul
565 | ast::BinOpKind::Div
566 | ast::BinOpKind::Rem
567 )
568 )
569 }
570
571 fn needs_paren(op: AssocOp, other: AssocOp, dir: Associativity) -> bool {
574 other.precedence() < op.precedence()
575 || (other.precedence() == op.precedence()
576 && ((op != other && associativity(op) != dir)
577 || (op == other && associativity(op) != Associativity::Both)))
578 || is_shift(op) && is_arith(other)
579 || is_shift(other) && is_arith(op)
580 }
581
582 let lhs_paren = if let Sugg::BinOp(lop, _, _) = *lhs {
583 needs_paren(op, lop, Associativity::Left)
584 } else {
585 false
586 };
587
588 let rhs_paren = if let Sugg::BinOp(rop, _, _) = *rhs {
589 needs_paren(op, rop, Associativity::Right)
590 } else {
591 false
592 };
593
594 let lhs = ParenHelper::new(lhs_paren, lhs).to_string();
595 let rhs = ParenHelper::new(rhs_paren, rhs).to_string();
596 Sugg::BinOp(op, lhs.into(), rhs.into())
597}
598
599pub fn make_binop(op: ast::BinOpKind, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
601 make_assoc(AssocOp::Binary(op), lhs, rhs)
602}
603
604#[derive(PartialEq, Eq, Clone, Copy)]
605enum Associativity {
607 Both,
609 Left,
611 None,
613 Right,
615}
616
617#[must_use]
625fn associativity(op: AssocOp) -> Associativity {
626 use ast::BinOpKind::{Add, And, BitAnd, BitOr, BitXor, Div, Eq, Ge, Gt, Le, Lt, Mul, Ne, Or, Rem, Shl, Shr, Sub};
627 use rustc_ast::util::parser::AssocOp::{Assign, AssignOp, Binary, Cast, Range};
628
629 match op {
630 Assign | AssignOp(_) => Associativity::Right,
631 Binary(Add | BitAnd | BitOr | BitXor | And | Or | Mul) | Cast => Associativity::Both,
632 Binary(Div | Eq | Gt | Ge | Lt | Le | Rem | Ne | Shl | Shr | Sub) => Associativity::Left,
633 Range(_) => Associativity::None,
634 }
635}
636
637fn indentation<T: LintContext>(cx: &T, span: Span) -> Option<String> {
640 let lo = cx.sess().source_map().lookup_char_pos(span.lo());
641 lo.file
642 .get_line(lo.line - 1 )
643 .and_then(|line| {
644 if let Some((pos, _)) = line.char_indices().find(|&(_, c)| c != ' ' && c != '\t') {
645 if lo.col == CharPos(pos) {
647 Some(line[..pos].into())
648 } else {
649 None
650 }
651 } else {
652 None
653 }
654 })
655}
656
657pub trait DiagExt<T: LintContext> {
659 fn suggest_item_with_attr<D: Display + ?Sized>(
669 &mut self,
670 cx: &T,
671 item: Span,
672 msg: &str,
673 attr: &D,
674 applicability: Applicability,
675 );
676
677 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability);
690
691 fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability);
703}
704
705impl<T: LintContext> DiagExt<T> for rustc_errors::Diag<'_, ()> {
706 fn suggest_item_with_attr<D: Display + ?Sized>(
707 &mut self,
708 cx: &T,
709 item: Span,
710 msg: &str,
711 attr: &D,
712 applicability: Applicability,
713 ) {
714 if let Some(indent) = indentation(cx, item) {
715 let span = item.with_hi(item.lo());
716
717 self.span_suggestion(span, msg.to_string(), format!("{attr}\n{indent}"), applicability);
718 }
719 }
720
721 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability) {
722 if let Some(indent) = indentation(cx, item) {
723 let span = item.with_hi(item.lo());
724
725 let mut first = true;
726 let new_item = new_item
727 .lines()
728 .map(|l| {
729 if first {
730 first = false;
731 format!("{l}\n")
732 } else {
733 format!("{indent}{l}\n")
734 }
735 })
736 .collect::<String>();
737
738 self.span_suggestion(span, msg.to_string(), format!("{new_item}\n{indent}"), applicability);
739 }
740 }
741
742 fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability) {
743 let mut remove_span = item;
744 let fmpos = cx.sess().source_map().lookup_byte_offset(remove_span.hi());
745
746 if let Some(ref src) = fmpos.sf.src {
747 let non_whitespace_offset = src[fmpos.pos.to_usize()..].find(|c| c != ' ' && c != '\t' && c != '\n');
748
749 if let Some(non_whitespace_offset) = non_whitespace_offset {
750 remove_span = remove_span
751 .with_hi(remove_span.hi() + BytePos(non_whitespace_offset.try_into().expect("offset too large")));
752 }
753 }
754
755 self.span_suggestion(remove_span, msg.to_string(), "", applicability);
756 }
757}
758
759pub struct DerefClosure {
762 pub applicability: Applicability,
764 pub suggestion: String,
766}
767
768pub fn deref_closure_args(cx: &LateContext<'_>, closure: &hir::Expr<'_>) -> Option<DerefClosure> {
774 if let ExprKind::Closure(&Closure {
775 fn_decl, def_id, body, ..
776 }) = closure.kind
777 {
778 let closure_body = cx.tcx.hir_body(body);
779 let closure_arg_is_type_annotated_double_ref = if let TyKind::Ref(_, MutTy { ty, .. }) = fn_decl.inputs[0].kind
782 {
783 matches!(ty.kind, TyKind::Ref(_, MutTy { .. }))
784 } else {
785 false
786 };
787
788 let mut visitor = DerefDelegate {
789 cx,
790 closure_span: closure.span,
791 closure_arg_id: closure_body.params[0].pat.hir_id,
792 closure_arg_is_type_annotated_double_ref,
793 next_pos: closure.span.lo(),
794 checked_borrows: FxHashSet::default(),
795 suggestion_start: String::new(),
796 applicability: Applicability::MachineApplicable,
797 };
798
799 ExprUseVisitor::for_clippy(cx, def_id, &mut visitor)
800 .consume_body(closure_body)
801 .into_ok();
802
803 if !visitor.suggestion_start.is_empty() {
804 return Some(DerefClosure {
805 applicability: visitor.applicability,
806 suggestion: visitor.finish(),
807 });
808 }
809 }
810 None
811}
812
813struct DerefDelegate<'a, 'tcx> {
816 cx: &'a LateContext<'tcx>,
818 closure_span: Span,
820 closure_arg_id: HirId,
822 closure_arg_is_type_annotated_double_ref: bool,
824 next_pos: BytePos,
826 checked_borrows: FxHashSet<HirId>,
829 suggestion_start: String,
831 applicability: Applicability,
833}
834
835impl<'tcx> DerefDelegate<'_, 'tcx> {
836 pub fn finish(&mut self) -> String {
841 let end_span = Span::new(self.next_pos, self.closure_span.hi(), self.closure_span.ctxt(), None);
842 let end_snip = snippet_with_applicability(self.cx, end_span, "..", &mut self.applicability);
843 let sugg = format!("{}{end_snip}", self.suggestion_start);
844 if self.closure_arg_is_type_annotated_double_ref {
845 sugg.replacen('&', "", 1)
846 } else {
847 sugg
848 }
849 }
850
851 fn func_takes_arg_by_double_ref(&self, parent_expr: &'tcx hir::Expr<'_>, cmt_hir_id: HirId) -> bool {
853 let ty = match parent_expr.kind {
854 ExprKind::MethodCall(_, receiver, call_args, _) => {
855 if let Some(sig) = self
856 .cx
857 .typeck_results()
858 .type_dependent_def_id(parent_expr.hir_id)
859 .map(|did| self.cx.tcx.fn_sig(did).instantiate_identity().skip_binder())
860 {
861 std::iter::once(receiver)
862 .chain(call_args.iter())
863 .position(|arg| arg.hir_id == cmt_hir_id)
864 .map(|i| sig.inputs()[i])
865 } else {
866 return false;
867 }
868 },
869 ExprKind::Call(func, call_args) => {
870 if let Some(sig) = expr_sig(self.cx, func) {
871 call_args
872 .iter()
873 .position(|arg| arg.hir_id == cmt_hir_id)
874 .and_then(|i| sig.input(i))
875 .map(ty::Binder::skip_binder)
876 } else {
877 return false;
878 }
879 },
880 _ => return false,
881 };
882
883 ty.is_some_and(|ty| matches!(ty.kind(), ty::Ref(_, inner, _) if inner.is_ref()))
884 }
885}
886
887impl<'tcx> Delegate<'tcx> for DerefDelegate<'_, 'tcx> {
888 fn consume(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
889
890 fn use_cloned(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
891
892 #[expect(clippy::too_many_lines)]
893 fn borrow(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId, _: ty::BorrowKind) {
894 if let PlaceBase::Local(id) = cmt.place.base {
895 let span = self.cx.tcx.hir_span(cmt.hir_id);
896 if !self.checked_borrows.insert(cmt.hir_id) {
897 return;
899 }
900
901 let start_span = Span::new(self.next_pos, span.lo(), span.ctxt(), None);
902 let mut start_snip = snippet_with_applicability(self.cx, start_span, "..", &mut self.applicability);
903
904 let ident_str = self.cx.tcx.hir_name(id).to_string();
906 let ident_str_with_proj = snippet(self.cx, span, "..").to_string();
908
909 if let Node::Pat(pat) = self.cx.tcx.hir_node(id)
911 && pat.hir_id != self.closure_arg_id
912 {
913 let _ = write!(self.suggestion_start, "{start_snip}{ident_str_with_proj}");
914 } else if cmt.place.projections.is_empty() {
915 let _: fmt::Result = write!(self.suggestion_start, "{start_snip}&{ident_str}");
918 } else {
919 if let Some(parent_expr) = get_parent_expr_for_hir(self.cx, cmt.hir_id) {
928 match &parent_expr.kind {
929 ExprKind::MethodCall(_, self_expr, ..) if self_expr.hir_id == cmt.hir_id => {
932 let _: fmt::Result = write!(self.suggestion_start, "{start_snip}{ident_str_with_proj}");
933 self.next_pos = span.hi();
934 return;
935 },
936 ExprKind::Call(_, call_args) | ExprKind::MethodCall(_, _, call_args, _) => {
939 let expr = self.cx.tcx.hir_expect_expr(cmt.hir_id);
940 let arg_ty_kind = self.cx.typeck_results().expr_ty(expr).kind();
941
942 if matches!(arg_ty_kind, ty::Ref(_, _, Mutability::Not)) {
943 let takes_arg_by_double_ref =
945 self.func_takes_arg_by_double_ref(parent_expr, cmt.hir_id);
946
947 let has_field_or_index_projection =
950 cmt.place.projections.iter().any(|proj| {
951 matches!(proj.kind, ProjectionKind::Field(..) | ProjectionKind::Index)
952 });
953
954 let ident_sugg = if !call_args.is_empty()
957 && !takes_arg_by_double_ref
958 && (self.closure_arg_is_type_annotated_double_ref || has_field_or_index_projection)
959 {
960 let ident = if has_field_or_index_projection {
961 ident_str_with_proj
962 } else {
963 ident_str
964 };
965 format!("{start_snip}{ident}")
966 } else {
967 format!("{start_snip}&{ident_str}")
968 };
969 self.suggestion_start.push_str(&ident_sugg);
970 self.next_pos = span.hi();
971 return;
972 }
973
974 self.applicability = Applicability::Unspecified;
975 },
976 _ => (),
977 }
978 }
979
980 let mut replacement_str = ident_str;
981 let mut projections_handled = false;
982 cmt.place.projections.iter().enumerate().for_each(|(i, proj)| {
983 match proj.kind {
984 ProjectionKind::Field(..) => match cmt.place.ty_before_projection(i).kind() {
987 ty::Adt(..) | ty::Tuple(_) => {
988 replacement_str.clone_from(&ident_str_with_proj);
989 projections_handled = true;
990 },
991 _ => (),
992 },
993 ProjectionKind::Index => {
998 let start_span = Span::new(self.next_pos, span.hi(), span.ctxt(), None);
999 start_snip = snippet_with_applicability(self.cx, start_span, "..", &mut self.applicability);
1000 replacement_str.clear();
1001 projections_handled = true;
1002 },
1003 ProjectionKind::Subslice |
1005 ProjectionKind::OpaqueCast |
1007 ProjectionKind::UnwrapUnsafeBinder => (),
1009 ProjectionKind::Deref => {
1010 if let ty::Ref(_, inner, _) = cmt.place.ty_before_projection(i).kind()
1015 && matches!(inner.kind(), ty::Ref(_, innermost, _) if innermost.is_array()) {
1016 projections_handled = true;
1017 }
1018 },
1019 }
1020 });
1021
1022 if !projections_handled {
1025 let last_deref = cmt
1026 .place
1027 .projections
1028 .iter()
1029 .rposition(|proj| proj.kind == ProjectionKind::Deref);
1030
1031 if let Some(pos) = last_deref {
1032 let mut projections = cmt.place.projections.clone();
1033 projections.truncate(pos);
1034
1035 for item in projections {
1036 if item.kind == ProjectionKind::Deref {
1037 replacement_str = format!("*{replacement_str}");
1038 }
1039 }
1040 }
1041 }
1042
1043 let _: fmt::Result = write!(self.suggestion_start, "{start_snip}{replacement_str}");
1044 }
1045 self.next_pos = span.hi();
1046 }
1047 }
1048
1049 fn mutate(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
1050
1051 fn fake_read(&mut self, _: &PlaceWithHirId<'tcx>, _: FakeReadCause, _: HirId) {}
1052}
1053
1054#[cfg(test)]
1055mod test {
1056 use super::Sugg;
1057
1058 use rustc_ast as ast;
1059 use rustc_ast::util::parser::AssocOp;
1060 use std::borrow::Cow;
1061
1062 const SUGGESTION: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("function_call()"));
1063
1064 #[test]
1065 fn make_return_transform_sugg_into_a_return_call() {
1066 assert_eq!("return function_call()", SUGGESTION.make_return().to_string());
1067 }
1068
1069 #[test]
1070 fn blockify_transforms_sugg_into_a_block() {
1071 assert_eq!("{ function_call() }", SUGGESTION.blockify().to_string());
1072 }
1073
1074 #[test]
1075 fn binop_maybe_paren() {
1076 let sugg = Sugg::BinOp(AssocOp::Binary(ast::BinOpKind::Add), "1".into(), "1".into());
1077 assert_eq!("(1 + 1)", sugg.maybe_paren().to_string());
1078
1079 let sugg = Sugg::BinOp(AssocOp::Binary(ast::BinOpKind::Add), "(1 + 1)".into(), "(1 + 1)".into());
1080 assert_eq!("((1 + 1) + (1 + 1))", sugg.maybe_paren().to_string());
1081 }
1082
1083 #[test]
1084 fn unop_parenthesize() {
1085 let sugg = Sugg::NonParen("x".into()).mut_addr();
1086 assert_eq!("&mut x", sugg.to_string());
1087 let sugg = sugg.mut_addr();
1088 assert_eq!("&mut &mut x", sugg.to_string());
1089 assert_eq!("(&mut &mut x)", sugg.maybe_paren().to_string());
1090 }
1091
1092 #[test]
1093 fn not_op() {
1094 use ast::BinOpKind::{Add, And, Eq, Ge, Gt, Le, Lt, Ne, Or};
1095
1096 fn test_not(op: AssocOp, correct: &str) {
1097 let sugg = Sugg::BinOp(op, "x".into(), "y".into());
1098 assert_eq!((!sugg).to_string(), correct);
1099 }
1100
1101 test_not(AssocOp::Binary(Eq), "x != y");
1103 test_not(AssocOp::Binary(Ne), "x == y");
1104 test_not(AssocOp::Binary(Lt), "x >= y");
1105 test_not(AssocOp::Binary(Le), "x > y");
1106 test_not(AssocOp::Binary(Gt), "x <= y");
1107 test_not(AssocOp::Binary(Ge), "x < y");
1108
1109 test_not(AssocOp::Binary(Add), "!(x + y)");
1111 test_not(AssocOp::Binary(And), "!(x && y)");
1112 test_not(AssocOp::Binary(Or), "!(x || y)");
1113 }
1114}