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<Sugg<'a>>),
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(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(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(expr: &hir::Expr<'_>, mut get_snippet: impl FnMut(Span) -> Cow<'a, str>) -> Self {
131 if let Some(range) = higher::Range::hir(expr) {
132 let op = AssocOp::Range(range.limits);
133 let start = range.start.map_or("".into(), |expr| get_snippet(expr.span));
134 let end = range.end.map_or("".into(), |expr| get_snippet(expr.span));
135
136 return Sugg::BinOp(op, start, end);
137 }
138
139 match expr.kind {
140 ExprKind::AddrOf(..)
141 | ExprKind::If(..)
142 | ExprKind::Let(..)
143 | ExprKind::Closure { .. }
144 | ExprKind::Unary(..)
145 | ExprKind::Match(..) => Sugg::MaybeParen(get_snippet(expr.span)),
146 ExprKind::Continue(..)
147 | ExprKind::Yield(..)
148 | ExprKind::Array(..)
149 | ExprKind::Block(..)
150 | ExprKind::Break(..)
151 | ExprKind::Call(..)
152 | ExprKind::Field(..)
153 | ExprKind::Index(..)
154 | ExprKind::InlineAsm(..)
155 | ExprKind::OffsetOf(..)
156 | ExprKind::ConstBlock(..)
157 | ExprKind::Lit(..)
158 | ExprKind::Loop(..)
159 | ExprKind::MethodCall(..)
160 | ExprKind::Path(..)
161 | ExprKind::Repeat(..)
162 | ExprKind::Ret(..)
163 | ExprKind::Become(..)
164 | ExprKind::Struct(..)
165 | ExprKind::Tup(..)
166 | ExprKind::Use(..)
167 | ExprKind::Err(_)
168 | ExprKind::UnsafeBinderCast(..) => Sugg::NonParen(get_snippet(expr.span)),
169 ExprKind::DropTemps(inner) => Self::hir_from_snippet(inner, get_snippet),
170 ExprKind::Assign(lhs, rhs, _) => {
171 Sugg::BinOp(AssocOp::Assign, get_snippet(lhs.span), get_snippet(rhs.span))
172 },
173 ExprKind::AssignOp(op, lhs, rhs) => {
174 Sugg::BinOp(AssocOp::AssignOp(op.node), get_snippet(lhs.span), get_snippet(rhs.span))
175 },
176 ExprKind::Binary(op, lhs, rhs) => Sugg::BinOp(
177 AssocOp::Binary(op.node),
178 get_snippet(lhs.span),
179 get_snippet(rhs.span),
180 ),
181 ExprKind::Cast(lhs, ty) |
182 ExprKind::Type(lhs, ty) => Sugg::BinOp(AssocOp::Cast, get_snippet(lhs.span), get_snippet(ty.span)),
184 }
185 }
186
187 pub fn ast(
189 cx: &EarlyContext<'_>,
190 expr: &ast::Expr,
191 default: &'a str,
192 ctxt: SyntaxContext,
193 app: &mut Applicability,
194 ) -> Self {
195 let mut snippet = |span: Span| snippet_with_context(cx, span, ctxt, default, app).0;
196
197 match expr.kind {
198 _ if expr.span.ctxt() != ctxt => Sugg::NonParen(snippet(expr.span)),
199 ast::ExprKind::AddrOf(..)
200 | ast::ExprKind::Closure { .. }
201 | ast::ExprKind::If(..)
202 | ast::ExprKind::Let(..)
203 | ast::ExprKind::Unary(..)
204 | ast::ExprKind::Match(..) => match snippet_with_context(cx, expr.span, ctxt, default, app) {
205 (snip, false) => Sugg::MaybeParen(snip),
206 (snip, true) => Sugg::NonParen(snip),
207 },
208 ast::ExprKind::Gen(..)
209 | ast::ExprKind::Block(..)
210 | ast::ExprKind::Break(..)
211 | ast::ExprKind::Call(..)
212 | ast::ExprKind::Continue(..)
213 | ast::ExprKind::Yield(..)
214 | ast::ExprKind::Field(..)
215 | ast::ExprKind::ForLoop { .. }
216 | ast::ExprKind::Index(..)
217 | ast::ExprKind::InlineAsm(..)
218 | ast::ExprKind::OffsetOf(..)
219 | ast::ExprKind::ConstBlock(..)
220 | ast::ExprKind::Lit(..)
221 | ast::ExprKind::IncludedBytes(..)
222 | ast::ExprKind::Loop(..)
223 | ast::ExprKind::MacCall(..)
224 | ast::ExprKind::MethodCall(..)
225 | ast::ExprKind::Paren(..)
226 | ast::ExprKind::Underscore
227 | ast::ExprKind::Path(..)
228 | ast::ExprKind::Repeat(..)
229 | ast::ExprKind::Ret(..)
230 | ast::ExprKind::Become(..)
231 | ast::ExprKind::Yeet(..)
232 | ast::ExprKind::FormatArgs(..)
233 | ast::ExprKind::Struct(..)
234 | ast::ExprKind::Try(..)
235 | ast::ExprKind::TryBlock(..)
236 | ast::ExprKind::Tup(..)
237 | ast::ExprKind::Use(..)
238 | ast::ExprKind::Array(..)
239 | ast::ExprKind::While(..)
240 | ast::ExprKind::Await(..)
241 | ast::ExprKind::Err(_)
242 | ast::ExprKind::Dummy
243 | ast::ExprKind::UnsafeBinderCast(..) => Sugg::NonParen(snippet(expr.span)),
244 ast::ExprKind::Range(ref lhs, ref rhs, limits) => Sugg::BinOp(
245 AssocOp::Range(limits),
246 lhs.as_ref().map_or("".into(), |lhs| snippet(lhs.span)),
247 rhs.as_ref().map_or("".into(), |rhs| snippet(rhs.span)),
248 ),
249 ast::ExprKind::Assign(ref lhs, ref rhs, _) => Sugg::BinOp(
250 AssocOp::Assign,
251 snippet(lhs.span),
252 snippet(rhs.span),
253 ),
254 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => Sugg::BinOp(
255 AssocOp::AssignOp(op.node),
256 snippet(lhs.span),
257 snippet(rhs.span),
258 ),
259 ast::ExprKind::Binary(op, ref lhs, ref rhs) => Sugg::BinOp(
260 AssocOp::Binary(op.node),
261 snippet(lhs.span),
262 snippet(rhs.span),
263 ),
264 ast::ExprKind::Cast(ref lhs, ref ty) |
265 ast::ExprKind::Type(ref lhs, ref ty) => Sugg::BinOp(
267 AssocOp::Cast,
268 snippet(lhs.span),
269 snippet(ty.span),
270 ),
271 }
272 }
273
274 pub fn and(self, rhs: &Self) -> Sugg<'static> {
276 make_binop(ast::BinOpKind::And, &self, rhs)
277 }
278
279 pub fn bit_and(self, rhs: &Self) -> Sugg<'static> {
281 make_binop(ast::BinOpKind::BitAnd, &self, rhs)
282 }
283
284 pub fn as_ty<R: Display>(self, rhs: R) -> Sugg<'static> {
286 make_assoc(AssocOp::Cast, &self, &Sugg::NonParen(rhs.to_string().into()))
287 }
288
289 pub fn addr(self) -> Sugg<'static> {
291 make_unop("&", self)
292 }
293
294 pub fn mut_addr(self) -> Sugg<'static> {
296 make_unop("&mut ", self)
297 }
298
299 pub fn deref(self) -> Sugg<'static> {
301 make_unop("*", self)
302 }
303
304 pub fn addr_deref(self) -> Sugg<'static> {
308 make_unop("&*", self)
309 }
310
311 pub fn mut_addr_deref(self) -> Sugg<'static> {
315 make_unop("&mut *", self)
316 }
317
318 pub fn make_return(self) -> Sugg<'static> {
320 Sugg::NonParen(Cow::Owned(format!("return {self}")))
321 }
322
323 pub fn blockify(self) -> Sugg<'static> {
326 Sugg::NonParen(Cow::Owned(format!("{{ {self} }}")))
327 }
328
329 pub fn asyncify(self) -> Sugg<'static> {
332 Sugg::NonParen(Cow::Owned(format!("async {self}")))
333 }
334
335 pub fn range(self, end: &Self, limits: ast::RangeLimits) -> Sugg<'static> {
338 make_assoc(AssocOp::Range(limits), &self, end)
339 }
340
341 #[must_use]
345 pub fn maybe_paren(self) -> Self {
346 match self {
347 Sugg::NonParen(..) => self,
348 Sugg::MaybeParen(sugg) => {
350 if has_enclosing_paren(&sugg) {
351 Sugg::MaybeParen(sugg)
352 } else {
353 Sugg::NonParen(format!("({sugg})").into())
354 }
355 },
356 Sugg::BinOp(op, lhs, rhs) => {
357 let sugg = binop_to_string(op, &lhs, &rhs);
358 Sugg::NonParen(format!("({sugg})").into())
359 },
360 Sugg::UnOp(op, inner) => Sugg::NonParen(format!("({}{})", op.as_str(), inner.maybe_inner_paren()).into()),
361 }
362 }
363
364 pub fn into_string(self) -> String {
365 match self {
366 Sugg::NonParen(p) | Sugg::MaybeParen(p) => p.into_owned(),
367 Sugg::BinOp(b, l, r) => binop_to_string(b, &l, &r),
368 Sugg::UnOp(op, inner) => format!("{}{}", op.as_str(), inner.maybe_inner_paren()),
369 }
370 }
371
372 fn starts_with_unary_op(&self) -> bool {
374 match self {
375 Sugg::UnOp(..) => true,
376 Sugg::BinOp(..) => false,
377 Sugg::MaybeParen(s) | Sugg::NonParen(s) => s.starts_with(['*', '!', '-', '&']),
378 }
379 }
380
381 fn maybe_inner_paren(self) -> Self {
384 if self.starts_with_unary_op() {
385 self
386 } else {
387 self.maybe_paren()
388 }
389 }
390}
391
392fn binop_to_string(op: AssocOp, lhs: &str, rhs: &str) -> String {
394 match op {
395 AssocOp::Binary(op) => format!("{lhs} {} {rhs}", op.as_str()),
396 AssocOp::Assign => format!("{lhs} = {rhs}"),
397 AssocOp::AssignOp(op) => format!("{lhs} {} {rhs}", op.as_str()),
398 AssocOp::Cast => format!("{lhs} as {rhs}"),
399 AssocOp::Range(limits) => format!("{lhs}{}{rhs}", limits.as_str()),
400 }
401}
402
403pub fn has_enclosing_paren(sugg: impl AsRef<str>) -> bool {
405 let mut chars = sugg.as_ref().chars();
406 if chars.next() == Some('(') {
407 let mut depth = 1;
408 for c in &mut chars {
409 if c == '(' {
410 depth += 1;
411 } else if c == ')' {
412 depth -= 1;
413 }
414 if depth == 0 {
415 break;
416 }
417 }
418 chars.next().is_none()
419 } else {
420 false
421 }
422}
423
424macro_rules! forward_binop_impls_to_ref {
426 (impl $imp:ident, $method:ident for $t:ty, type Output = $o:ty) => {
427 impl $imp<$t> for &$t {
428 type Output = $o;
429
430 fn $method(self, other: $t) -> $o {
431 $imp::$method(self, &other)
432 }
433 }
434
435 impl $imp<&$t> for $t {
436 type Output = $o;
437
438 fn $method(self, other: &$t) -> $o {
439 $imp::$method(&self, other)
440 }
441 }
442
443 impl $imp for $t {
444 type Output = $o;
445
446 fn $method(self, other: $t) -> $o {
447 $imp::$method(&self, &other)
448 }
449 }
450 };
451}
452
453impl Add for &Sugg<'_> {
454 type Output = Sugg<'static>;
455 fn add(self, rhs: &Sugg<'_>) -> Sugg<'static> {
456 make_binop(ast::BinOpKind::Add, self, rhs)
457 }
458}
459
460impl Sub for &Sugg<'_> {
461 type Output = Sugg<'static>;
462 fn sub(self, rhs: &Sugg<'_>) -> Sugg<'static> {
463 make_binop(ast::BinOpKind::Sub, self, rhs)
464 }
465}
466
467forward_binop_impls_to_ref!(impl Add, add for Sugg<'_>, type Output = Sugg<'static>);
468forward_binop_impls_to_ref!(impl Sub, sub for Sugg<'_>, type Output = Sugg<'static>);
469
470impl<'a> Neg for Sugg<'a> {
471 type Output = Sugg<'a>;
472 fn neg(self) -> Self::Output {
473 match self {
474 Self::UnOp(UnOp::Neg, sugg) => *sugg,
475 Self::BinOp(AssocOp::Cast, ..) => Sugg::MaybeParen(format!("-({self})").into()),
476 _ => make_unop("-", self),
477 }
478 }
479}
480
481impl<'a> Not for Sugg<'a> {
482 type Output = Sugg<'a>;
483 fn not(self) -> Sugg<'a> {
484 use AssocOp::Binary;
485 use ast::BinOpKind::{Eq, Ge, Gt, Le, Lt, Ne};
486
487 match self {
488 Sugg::BinOp(op, lhs, rhs) => {
489 let to_op = match op {
490 Binary(Eq) => Binary(Ne),
491 Binary(Ne) => Binary(Eq),
492 Binary(Lt) => Binary(Ge),
493 Binary(Ge) => Binary(Lt),
494 Binary(Gt) => Binary(Le),
495 Binary(Le) => Binary(Gt),
496 _ => return make_unop("!", Sugg::BinOp(op, lhs, rhs)),
497 };
498 Sugg::BinOp(to_op, lhs, rhs)
499 },
500 Sugg::UnOp(UnOp::Not, expr) => *expr,
501 _ => make_unop("!", self),
502 }
503 }
504}
505
506struct ParenHelper<T> {
508 paren: bool,
510 wrapped: T,
512}
513
514impl<T> ParenHelper<T> {
515 fn new(paren: bool, wrapped: T) -> Self {
517 Self { paren, wrapped }
518 }
519}
520
521impl<T: Display> Display for ParenHelper<T> {
522 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
523 if self.paren {
524 write!(f, "({})", self.wrapped)
525 } else {
526 self.wrapped.fmt(f)
527 }
528 }
529}
530
531pub fn make_unop(op: &str, expr: Sugg<'_>) -> Sugg<'static> {
536 Sugg::MaybeParen(format!("{op}{}", expr.maybe_inner_paren()).into())
539}
540
541pub fn make_assoc(op: AssocOp, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
547 fn is_shift(op: AssocOp) -> bool {
549 matches!(op, AssocOp::Binary(ast::BinOpKind::Shl | ast::BinOpKind::Shr))
550 }
551
552 fn is_arith(op: AssocOp) -> bool {
555 matches!(
556 op,
557 AssocOp::Binary(
558 ast::BinOpKind::Add
559 | ast::BinOpKind::Sub
560 | ast::BinOpKind::Mul
561 | ast::BinOpKind::Div
562 | ast::BinOpKind::Rem
563 )
564 )
565 }
566
567 fn needs_paren(op: AssocOp, other: AssocOp, dir: Associativity) -> bool {
570 other.precedence() < op.precedence()
571 || (other.precedence() == op.precedence()
572 && ((op != other && associativity(op) != dir)
573 || (op == other && associativity(op) != Associativity::Both)))
574 || is_shift(op) && is_arith(other)
575 || is_shift(other) && is_arith(op)
576 }
577
578 let lhs_paren = if let Sugg::BinOp(lop, _, _) = *lhs {
579 needs_paren(op, lop, Associativity::Left)
580 } else {
581 false
582 };
583
584 let rhs_paren = if let Sugg::BinOp(rop, _, _) = *rhs {
585 needs_paren(op, rop, Associativity::Right)
586 } else {
587 false
588 };
589
590 let lhs = ParenHelper::new(lhs_paren, lhs).to_string();
591 let rhs = ParenHelper::new(rhs_paren, rhs).to_string();
592 Sugg::BinOp(op, lhs.into(), rhs.into())
593}
594
595pub fn make_binop(op: ast::BinOpKind, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
597 make_assoc(AssocOp::Binary(op), lhs, rhs)
598}
599
600#[derive(PartialEq, Eq, Clone, Copy)]
601enum Associativity {
603 Both,
605 Left,
607 None,
609 Right,
611}
612
613#[must_use]
621fn associativity(op: AssocOp) -> Associativity {
622 use ast::BinOpKind::{Add, And, BitAnd, BitOr, BitXor, Div, Eq, Ge, Gt, Le, Lt, Mul, Ne, Or, Rem, Shl, Shr, Sub};
623 use rustc_ast::util::parser::AssocOp::{Assign, AssignOp, Binary, Cast, Range};
624
625 match op {
626 Assign | AssignOp(_) => Associativity::Right,
627 Binary(Add | BitAnd | BitOr | BitXor | And | Or | Mul) | Cast => Associativity::Both,
628 Binary(Div | Eq | Gt | Ge | Lt | Le | Rem | Ne | Shl | Shr | Sub) => Associativity::Left,
629 Range(_) => Associativity::None,
630 }
631}
632
633fn indentation<T: LintContext>(cx: &T, span: Span) -> Option<String> {
636 let lo = cx.sess().source_map().lookup_char_pos(span.lo());
637 lo.file
638 .get_line(lo.line - 1 )
639 .and_then(|line| {
640 if let Some((pos, _)) = line.char_indices().find(|&(_, c)| c != ' ' && c != '\t') {
641 if lo.col == CharPos(pos) {
643 Some(line[..pos].into())
644 } else {
645 None
646 }
647 } else {
648 None
649 }
650 })
651}
652
653pub trait DiagExt<T: LintContext> {
655 fn suggest_item_with_attr<D: Display + ?Sized>(
665 &mut self,
666 cx: &T,
667 item: Span,
668 msg: &str,
669 attr: &D,
670 applicability: Applicability,
671 );
672
673 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability);
686
687 fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability);
699}
700
701impl<T: LintContext> DiagExt<T> for rustc_errors::Diag<'_, ()> {
702 fn suggest_item_with_attr<D: Display + ?Sized>(
703 &mut self,
704 cx: &T,
705 item: Span,
706 msg: &str,
707 attr: &D,
708 applicability: Applicability,
709 ) {
710 if let Some(indent) = indentation(cx, item) {
711 let span = item.with_hi(item.lo());
712
713 self.span_suggestion(span, msg.to_string(), format!("{attr}\n{indent}"), applicability);
714 }
715 }
716
717 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability) {
718 if let Some(indent) = indentation(cx, item) {
719 let span = item.with_hi(item.lo());
720
721 let mut first = true;
722 let new_item = new_item
723 .lines()
724 .map(|l| {
725 if first {
726 first = false;
727 format!("{l}\n")
728 } else {
729 format!("{indent}{l}\n")
730 }
731 })
732 .collect::<String>();
733
734 self.span_suggestion(span, msg.to_string(), format!("{new_item}\n{indent}"), applicability);
735 }
736 }
737
738 fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability) {
739 let mut remove_span = item;
740 let fmpos = cx.sess().source_map().lookup_byte_offset(remove_span.hi());
741
742 if let Some(ref src) = fmpos.sf.src {
743 let non_whitespace_offset = src[fmpos.pos.to_usize()..].find(|c| c != ' ' && c != '\t' && c != '\n');
744
745 if let Some(non_whitespace_offset) = non_whitespace_offset {
746 remove_span = remove_span
747 .with_hi(remove_span.hi() + BytePos(non_whitespace_offset.try_into().expect("offset too large")));
748 }
749 }
750
751 self.span_suggestion(remove_span, msg.to_string(), "", applicability);
752 }
753}
754
755pub struct DerefClosure {
758 pub applicability: Applicability,
760 pub suggestion: String,
762}
763
764pub fn deref_closure_args(cx: &LateContext<'_>, closure: &hir::Expr<'_>) -> Option<DerefClosure> {
770 if let ExprKind::Closure(&Closure {
771 fn_decl, def_id, body, ..
772 }) = closure.kind
773 {
774 let closure_body = cx.tcx.hir_body(body);
775 let closure_arg_is_type_annotated_double_ref = if let TyKind::Ref(_, MutTy { ty, .. }) = fn_decl.inputs[0].kind
778 {
779 matches!(ty.kind, TyKind::Ref(_, MutTy { .. }))
780 } else {
781 false
782 };
783
784 let mut visitor = DerefDelegate {
785 cx,
786 closure_span: closure.span,
787 closure_arg_id: closure_body.params[0].pat.hir_id,
788 closure_arg_is_type_annotated_double_ref,
789 next_pos: closure.span.lo(),
790 checked_borrows: FxHashSet::default(),
791 suggestion_start: String::new(),
792 applicability: Applicability::MachineApplicable,
793 };
794
795 ExprUseVisitor::for_clippy(cx, def_id, &mut visitor)
796 .consume_body(closure_body)
797 .into_ok();
798
799 if !visitor.suggestion_start.is_empty() {
800 return Some(DerefClosure {
801 applicability: visitor.applicability,
802 suggestion: visitor.finish(),
803 });
804 }
805 }
806 None
807}
808
809struct DerefDelegate<'a, 'tcx> {
812 cx: &'a LateContext<'tcx>,
814 closure_span: Span,
816 closure_arg_id: HirId,
818 closure_arg_is_type_annotated_double_ref: bool,
820 next_pos: BytePos,
822 checked_borrows: FxHashSet<HirId>,
825 suggestion_start: String,
827 applicability: Applicability,
829}
830
831impl<'tcx> DerefDelegate<'_, 'tcx> {
832 pub fn finish(&mut self) -> String {
837 let end_span = Span::new(self.next_pos, self.closure_span.hi(), self.closure_span.ctxt(), None);
838 let end_snip = snippet_with_applicability(self.cx, end_span, "..", &mut self.applicability);
839 let sugg = format!("{}{end_snip}", self.suggestion_start);
840 if self.closure_arg_is_type_annotated_double_ref {
841 sugg.replacen('&', "", 1)
842 } else {
843 sugg
844 }
845 }
846
847 fn func_takes_arg_by_double_ref(&self, parent_expr: &'tcx hir::Expr<'_>, cmt_hir_id: HirId) -> bool {
849 let ty = match parent_expr.kind {
850 ExprKind::MethodCall(_, receiver, call_args, _) => {
851 if let Some(sig) = self
852 .cx
853 .typeck_results()
854 .type_dependent_def_id(parent_expr.hir_id)
855 .map(|did| self.cx.tcx.fn_sig(did).instantiate_identity().skip_binder())
856 {
857 std::iter::once(receiver)
858 .chain(call_args.iter())
859 .position(|arg| arg.hir_id == cmt_hir_id)
860 .map(|i| sig.inputs()[i])
861 } else {
862 return false;
863 }
864 },
865 ExprKind::Call(func, call_args) => {
866 if let Some(sig) = expr_sig(self.cx, func) {
867 call_args
868 .iter()
869 .position(|arg| arg.hir_id == cmt_hir_id)
870 .and_then(|i| sig.input(i))
871 .map(ty::Binder::skip_binder)
872 } else {
873 return false;
874 }
875 },
876 _ => return false,
877 };
878
879 ty.is_some_and(|ty| matches!(ty.kind(), ty::Ref(_, inner, _) if inner.is_ref()))
880 }
881}
882
883impl<'tcx> Delegate<'tcx> for DerefDelegate<'_, 'tcx> {
884 fn consume(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
885
886 fn use_cloned(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
887
888 #[expect(clippy::too_many_lines)]
889 fn borrow(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId, _: ty::BorrowKind) {
890 if let PlaceBase::Local(id) = cmt.place.base {
891 let span = self.cx.tcx.hir_span(cmt.hir_id);
892 if !self.checked_borrows.insert(cmt.hir_id) {
893 return;
895 }
896
897 let start_span = Span::new(self.next_pos, span.lo(), span.ctxt(), None);
898 let mut start_snip = snippet_with_applicability(self.cx, start_span, "..", &mut self.applicability);
899
900 let ident_str = self.cx.tcx.hir_name(id).to_string();
902 let ident_str_with_proj = snippet(self.cx, span, "..").to_string();
904
905 if let Node::Pat(pat) = self.cx.tcx.hir_node(id)
907 && pat.hir_id != self.closure_arg_id
908 {
909 let _ = write!(self.suggestion_start, "{start_snip}{ident_str_with_proj}");
910 } else if cmt.place.projections.is_empty() {
911 let _: fmt::Result = write!(self.suggestion_start, "{start_snip}&{ident_str}");
914 } else {
915 if let Some(parent_expr) = get_parent_expr_for_hir(self.cx, cmt.hir_id) {
924 match &parent_expr.kind {
925 ExprKind::MethodCall(_, self_expr, ..) if self_expr.hir_id == cmt.hir_id => {
928 let _: fmt::Result = write!(self.suggestion_start, "{start_snip}{ident_str_with_proj}");
929 self.next_pos = span.hi();
930 return;
931 },
932 ExprKind::Call(_, call_args) | ExprKind::MethodCall(_, _, call_args, _) => {
935 let expr = self.cx.tcx.hir_expect_expr(cmt.hir_id);
936 let arg_ty_kind = self.cx.typeck_results().expr_ty(expr).kind();
937
938 if matches!(arg_ty_kind, ty::Ref(_, _, Mutability::Not)) {
939 let takes_arg_by_double_ref =
941 self.func_takes_arg_by_double_ref(parent_expr, cmt.hir_id);
942
943 let has_field_or_index_projection =
946 cmt.place.projections.iter().any(|proj| {
947 matches!(proj.kind, ProjectionKind::Field(..) | ProjectionKind::Index)
948 });
949
950 let ident_sugg = if !call_args.is_empty()
953 && !takes_arg_by_double_ref
954 && (self.closure_arg_is_type_annotated_double_ref || has_field_or_index_projection)
955 {
956 let ident = if has_field_or_index_projection {
957 ident_str_with_proj
958 } else {
959 ident_str
960 };
961 format!("{start_snip}{ident}")
962 } else {
963 format!("{start_snip}&{ident_str}")
964 };
965 self.suggestion_start.push_str(&ident_sugg);
966 self.next_pos = span.hi();
967 return;
968 }
969
970 self.applicability = Applicability::Unspecified;
971 },
972 _ => (),
973 }
974 }
975
976 let mut replacement_str = ident_str;
977 let mut projections_handled = false;
978 cmt.place.projections.iter().enumerate().for_each(|(i, proj)| {
979 match proj.kind {
980 ProjectionKind::Field(..) => match cmt.place.ty_before_projection(i).kind() {
983 ty::Adt(..) | ty::Tuple(_) => {
984 replacement_str.clone_from(&ident_str_with_proj);
985 projections_handled = true;
986 },
987 _ => (),
988 },
989 ProjectionKind::Index => {
994 let start_span = Span::new(self.next_pos, span.hi(), span.ctxt(), None);
995 start_snip = snippet_with_applicability(self.cx, start_span, "..", &mut self.applicability);
996 replacement_str.clear();
997 projections_handled = true;
998 },
999 ProjectionKind::Subslice |
1001 ProjectionKind::OpaqueCast |
1003 ProjectionKind::UnwrapUnsafeBinder => (),
1005 ProjectionKind::Deref => {
1006 if let ty::Ref(_, inner, _) = cmt.place.ty_before_projection(i).kind()
1011 && matches!(inner.kind(), ty::Ref(_, innermost, _) if innermost.is_array()) {
1012 projections_handled = true;
1013 }
1014 },
1015 }
1016 });
1017
1018 if !projections_handled {
1021 let last_deref = cmt
1022 .place
1023 .projections
1024 .iter()
1025 .rposition(|proj| proj.kind == ProjectionKind::Deref);
1026
1027 if let Some(pos) = last_deref {
1028 let mut projections = cmt.place.projections.clone();
1029 projections.truncate(pos);
1030
1031 for item in projections {
1032 if item.kind == ProjectionKind::Deref {
1033 replacement_str = format!("*{replacement_str}");
1034 }
1035 }
1036 }
1037 }
1038
1039 let _: fmt::Result = write!(self.suggestion_start, "{start_snip}{replacement_str}");
1040 }
1041 self.next_pos = span.hi();
1042 }
1043 }
1044
1045 fn mutate(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
1046
1047 fn fake_read(&mut self, _: &PlaceWithHirId<'tcx>, _: FakeReadCause, _: HirId) {}
1048}
1049
1050#[cfg(test)]
1051mod test {
1052 use super::Sugg;
1053
1054 use rustc_ast as ast;
1055 use rustc_ast::util::parser::AssocOp;
1056 use std::borrow::Cow;
1057
1058 const SUGGESTION: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("function_call()"));
1059
1060 #[test]
1061 fn make_return_transform_sugg_into_a_return_call() {
1062 assert_eq!("return function_call()", SUGGESTION.make_return().to_string());
1063 }
1064
1065 #[test]
1066 fn blockify_transforms_sugg_into_a_block() {
1067 assert_eq!("{ function_call() }", SUGGESTION.blockify().to_string());
1068 }
1069
1070 #[test]
1071 fn binop_maybe_paren() {
1072 let sugg = Sugg::BinOp(AssocOp::Binary(ast::BinOpKind::Add), "1".into(), "1".into());
1073 assert_eq!("(1 + 1)", sugg.maybe_paren().to_string());
1074
1075 let sugg = Sugg::BinOp(AssocOp::Binary(ast::BinOpKind::Add), "(1 + 1)".into(), "(1 + 1)".into());
1076 assert_eq!("((1 + 1) + (1 + 1))", sugg.maybe_paren().to_string());
1077 }
1078
1079 #[test]
1080 fn unop_parenthesize() {
1081 let sugg = Sugg::NonParen("x".into()).mut_addr();
1082 assert_eq!("&mut x", sugg.to_string());
1083 let sugg = sugg.mut_addr();
1084 assert_eq!("&mut &mut x", sugg.to_string());
1085 assert_eq!("(&mut &mut x)", sugg.maybe_paren().to_string());
1086 }
1087
1088 #[test]
1089 fn not_op() {
1090 use ast::BinOpKind::{Add, And, Eq, Ge, Gt, Le, Lt, Ne, Or};
1091
1092 fn test_not(op: AssocOp, correct: &str) {
1093 let sugg = Sugg::BinOp(op, "x".into(), "y".into());
1094 assert_eq!((!sugg).to_string(), correct);
1095 }
1096
1097 test_not(AssocOp::Binary(Eq), "x != y");
1099 test_not(AssocOp::Binary(Ne), "x == y");
1100 test_not(AssocOp::Binary(Lt), "x >= y");
1101 test_not(AssocOp::Binary(Le), "x > y");
1102 test_not(AssocOp::Binary(Gt), "x <= y");
1103 test_not(AssocOp::Binary(Ge), "x < y");
1104
1105 test_not(AssocOp::Binary(Add), "!(x + y)");
1107 test_not(AssocOp::Binary(And), "!(x && y)");
1108 test_not(AssocOp::Binary(Or), "!(x || y)");
1109 }
1110}