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, MatchSource, 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 pub 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.ty.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(_, _,
150 MatchSource::Normal | MatchSource::Postfix | MatchSource::ForLoopDesugar
151 ) => Sugg::MaybeParen(get_snippet(expr.span)),
152 ExprKind::Continue(..)
153 | ExprKind::Yield(..)
154 | ExprKind::Array(..)
155 | ExprKind::Block(..)
156 | ExprKind::Break(..)
157 | ExprKind::Call(..)
158 | ExprKind::Field(..)
159 | ExprKind::Index(..)
160 | ExprKind::InlineAsm(..)
161 | ExprKind::OffsetOf(..)
162 | ExprKind::ConstBlock(..)
163 | ExprKind::Lit(..)
164 | ExprKind::Loop(..)
165 | ExprKind::MethodCall(..)
166 | ExprKind::Path(..)
167 | ExprKind::Repeat(..)
168 | ExprKind::Ret(..)
169 | ExprKind::Become(..)
170 | ExprKind::Struct(..)
171 | ExprKind::Tup(..)
172 | ExprKind::Use(..)
173 | ExprKind::Err(_)
174 | ExprKind::UnsafeBinderCast(..)
175 | ExprKind::Match(_, _,
176 MatchSource::AwaitDesugar | MatchSource::TryDesugar(_) | MatchSource::FormatArgs
177 ) => Sugg::NonParen(get_snippet(expr.span)),
178 ExprKind::DropTemps(inner) => Self::hir_from_snippet(cx, inner, get_snippet),
179 ExprKind::Assign(lhs, rhs, _) => {
180 Sugg::BinOp(AssocOp::Assign, get_snippet(lhs.span), get_snippet(rhs.span))
181 },
182 ExprKind::AssignOp(op, lhs, rhs) => {
183 Sugg::BinOp(AssocOp::AssignOp(op.node), get_snippet(lhs.span), get_snippet(rhs.span))
184 },
185 ExprKind::Binary(op, lhs, rhs) => Sugg::BinOp(
186 AssocOp::Binary(op.node),
187 get_snippet(lhs.span),
188 get_snippet(rhs.span),
189 ),
190 ExprKind::Cast(lhs, ty) |
191 ExprKind::Type(lhs, ty) => Sugg::BinOp(AssocOp::Cast, get_snippet(lhs.span), get_snippet(ty.span)),
193 }
194 }
195
196 pub fn ast(
198 cx: &EarlyContext<'_>,
199 expr: &ast::Expr,
200 default: &'a str,
201 ctxt: SyntaxContext,
202 app: &mut Applicability,
203 ) -> Self {
204 let mut snippet = |span: Span| snippet_with_context(cx, span, ctxt, default, app).0;
205
206 match expr.kind {
207 _ if expr.span.ctxt() != ctxt => Sugg::NonParen(snippet(expr.span)),
208 ast::ExprKind::AddrOf(..)
209 | ast::ExprKind::Closure { .. }
210 | ast::ExprKind::If(..)
211 | ast::ExprKind::Let(..)
212 | ast::ExprKind::Unary(..)
213 | ast::ExprKind::Match(..) => match snippet_with_context(cx, expr.span, ctxt, default, app) {
214 (snip, false) => Sugg::MaybeParen(snip),
215 (snip, true) => Sugg::NonParen(snip),
216 },
217 ast::ExprKind::Gen(..)
218 | ast::ExprKind::Block(..)
219 | ast::ExprKind::Break(..)
220 | ast::ExprKind::Call(..)
221 | ast::ExprKind::Continue(..)
222 | ast::ExprKind::Yield(..)
223 | ast::ExprKind::Field(..)
224 | ast::ExprKind::ForLoop { .. }
225 | ast::ExprKind::Index(..)
226 | ast::ExprKind::InlineAsm(..)
227 | ast::ExprKind::OffsetOf(..)
228 | ast::ExprKind::ConstBlock(..)
229 | ast::ExprKind::Lit(..)
230 | ast::ExprKind::IncludedBytes(..)
231 | ast::ExprKind::Loop(..)
232 | ast::ExprKind::MacCall(..)
233 | ast::ExprKind::MethodCall(..)
234 | ast::ExprKind::Move(..)
235 | ast::ExprKind::Paren(..)
236 | ast::ExprKind::Underscore
237 | ast::ExprKind::Path(..)
238 | ast::ExprKind::Repeat(..)
239 | ast::ExprKind::Ret(..)
240 | ast::ExprKind::Become(..)
241 | ast::ExprKind::Yeet(..)
242 | ast::ExprKind::FormatArgs(..)
243 | ast::ExprKind::Struct(..)
244 | ast::ExprKind::Try(..)
245 | ast::ExprKind::TryBlock(..)
246 | ast::ExprKind::Tup(..)
247 | ast::ExprKind::Use(..)
248 | ast::ExprKind::Array(..)
249 | ast::ExprKind::While(..)
250 | ast::ExprKind::Await(..)
251 | ast::ExprKind::DirectConstArg(..)
252 | ast::ExprKind::Err(_)
253 | ast::ExprKind::Dummy
254 | ast::ExprKind::UnsafeBinderCast(..) => Sugg::NonParen(snippet(expr.span)),
255 ast::ExprKind::Range(ref lhs, ref rhs, limits) => Sugg::BinOp(
256 AssocOp::Range(limits),
257 lhs.as_ref().map_or("".into(), |lhs| snippet(lhs.span)),
258 rhs.as_ref().map_or("".into(), |rhs| snippet(rhs.span)),
259 ),
260 ast::ExprKind::Assign(ref lhs, ref rhs, _) => Sugg::BinOp(
261 AssocOp::Assign,
262 snippet(lhs.span),
263 snippet(rhs.span),
264 ),
265 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => Sugg::BinOp(
266 AssocOp::AssignOp(op.node),
267 snippet(lhs.span),
268 snippet(rhs.span),
269 ),
270 ast::ExprKind::Binary(op, ref lhs, ref rhs) => Sugg::BinOp(
271 AssocOp::Binary(op.node),
272 snippet(lhs.span),
273 snippet(rhs.span),
274 ),
275 ast::ExprKind::Cast(ref lhs, ref ty) |
276 ast::ExprKind::Type(ref lhs, ref ty) => Sugg::BinOp(
278 AssocOp::Cast,
279 snippet(lhs.span),
280 snippet(ty.span),
281 ),
282 }
283 }
284
285 pub fn and(self, rhs: &Self) -> Sugg<'static> {
287 make_binop(ast::BinOpKind::And, &self, rhs)
288 }
289
290 pub fn bit_and(self, rhs: &Self) -> Sugg<'static> {
292 make_binop(ast::BinOpKind::BitAnd, &self, rhs)
293 }
294
295 pub fn as_ty<R: Display>(self, rhs: R) -> Sugg<'static> {
297 make_assoc(AssocOp::Cast, &self, &Sugg::NonParen(rhs.to_string().into()))
298 }
299
300 pub fn addr(self) -> Sugg<'static> {
302 make_unop("&", self)
303 }
304
305 pub fn mut_addr(self) -> Sugg<'static> {
307 make_unop("&mut ", self)
308 }
309
310 pub fn deref(self) -> Sugg<'static> {
312 make_unop("*", self)
313 }
314
315 pub fn addr_deref(self) -> Sugg<'static> {
319 make_unop("&*", self)
320 }
321
322 pub fn mut_addr_deref(self) -> Sugg<'static> {
326 make_unop("&mut *", self)
327 }
328
329 pub fn make_return(self) -> Sugg<'static> {
331 Sugg::NonParen(Cow::Owned(format!("return {self}")))
332 }
333
334 pub fn blockify(self) -> Sugg<'static> {
337 Sugg::NonParen(Cow::Owned(format!("{{ {self} }}")))
338 }
339
340 pub fn unsafeify(self) -> Sugg<'static> {
342 Sugg::NonParen(Cow::Owned(format!("unsafe {{ {self} }}")))
343 }
344
345 pub fn asyncify(self) -> Sugg<'static> {
348 Sugg::NonParen(Cow::Owned(format!("async {self}")))
349 }
350
351 pub fn range(self, end: &Self, limits: ast::RangeLimits) -> Sugg<'static> {
354 make_assoc(AssocOp::Range(limits), &self, end)
355 }
356
357 #[must_use]
361 pub fn maybe_paren(self) -> Self {
362 match self {
363 Sugg::NonParen(..) => self,
364 Sugg::MaybeParen(sugg) => {
366 if has_enclosing_paren(&sugg) {
367 Sugg::MaybeParen(sugg)
368 } else {
369 Sugg::NonParen(format!("({sugg})").into())
370 }
371 },
372 Sugg::BinOp(op, lhs, rhs) => {
373 let sugg = binop_to_string(op, &lhs, &rhs);
374 Sugg::NonParen(format!("({sugg})").into())
375 },
376 Sugg::UnOp(op, inner) => Sugg::NonParen(format!("({}{})", op.as_str(), inner.maybe_inner_paren()).into()),
377 }
378 }
379
380 #[must_use]
387 pub fn strip_paren(self) -> Self {
388 match self {
389 Sugg::NonParen(s) | Sugg::MaybeParen(s) => Sugg::NonParen(strip_enclosing_paren(s)),
390 sugg => sugg,
391 }
392 }
393
394 pub fn into_string(self) -> String {
395 match self {
396 Sugg::NonParen(p) | Sugg::MaybeParen(p) => p.into_owned(),
397 Sugg::BinOp(b, l, r) => binop_to_string(b, &l, &r),
398 Sugg::UnOp(op, inner) => format!("{}{}", op.as_str(), inner.maybe_inner_paren()),
399 }
400 }
401
402 fn starts_with_unary_op(&self) -> bool {
404 match self {
405 Sugg::UnOp(..) => true,
406 Sugg::BinOp(..) => false,
407 Sugg::MaybeParen(s) | Sugg::NonParen(s) => s.starts_with(['*', '!', '-', '&']),
408 }
409 }
410
411 fn maybe_inner_paren(self) -> Self {
414 if self.starts_with_unary_op() {
415 self
416 } else {
417 self.maybe_paren()
418 }
419 }
420}
421
422fn binop_to_string(op: AssocOp, lhs: &str, rhs: &str) -> String {
424 match op {
425 AssocOp::Binary(op) => format!("{lhs} {} {rhs}", op.as_str()),
426 AssocOp::Assign => format!("{lhs} = {rhs}"),
427 AssocOp::AssignOp(op) => format!("{lhs} {} {rhs}", op.as_str()),
428 AssocOp::Cast => format!("{lhs} as {rhs}"),
429 AssocOp::Range(limits) => format!("{lhs}{}{rhs}", limits.as_str()),
430 }
431}
432
433pub fn has_enclosing_paren(sugg: impl AsRef<str>) -> bool {
435 let mut chars = sugg.as_ref().chars();
436 if chars.next() == Some('(') {
437 let mut depth = 1;
438 for c in &mut chars {
439 if c == '(' {
440 depth += 1;
441 } else if c == ')' {
442 depth -= 1;
443 }
444 if depth == 0 {
445 break;
446 }
447 }
448 chars.next().is_none()
449 } else {
450 false
451 }
452}
453
454fn strip_enclosing_paren(snippet: Cow<'_, str>) -> Cow<'_, str> {
456 if has_enclosing_paren(&snippet) {
457 match snippet {
458 Cow::Borrowed(s) => Cow::Borrowed(&s[1..s.len() - 1]),
459 Cow::Owned(mut s) => {
460 s.pop();
461 s.remove(0);
462 Cow::Owned(s)
463 },
464 }
465 } else {
466 snippet
467 }
468}
469
470macro_rules! forward_binop_impls_to_ref {
472 (impl $imp:ident, $method:ident for $t:ty, type Output = $o:ty) => {
473 impl $imp<$t> for &$t {
474 type Output = $o;
475
476 fn $method(self, other: $t) -> $o {
477 $imp::$method(self, &other)
478 }
479 }
480
481 impl $imp<&$t> for $t {
482 type Output = $o;
483
484 fn $method(self, other: &$t) -> $o {
485 $imp::$method(&self, other)
486 }
487 }
488
489 impl $imp for $t {
490 type Output = $o;
491
492 fn $method(self, other: $t) -> $o {
493 $imp::$method(&self, &other)
494 }
495 }
496 };
497}
498
499impl Add for &Sugg<'_> {
500 type Output = Sugg<'static>;
501 fn add(self, rhs: &Sugg<'_>) -> Sugg<'static> {
502 make_binop(ast::BinOpKind::Add, self, rhs)
503 }
504}
505
506impl Sub for &Sugg<'_> {
507 type Output = Sugg<'static>;
508 fn sub(self, rhs: &Sugg<'_>) -> Sugg<'static> {
509 make_binop(ast::BinOpKind::Sub, self, rhs)
510 }
511}
512
513forward_binop_impls_to_ref!(impl Add, add for Sugg<'_>, type Output = Sugg<'static>);
514forward_binop_impls_to_ref!(impl Sub, sub for Sugg<'_>, type Output = Sugg<'static>);
515
516impl<'a> Neg for Sugg<'a> {
517 type Output = Sugg<'a>;
518 fn neg(self) -> Self::Output {
519 match self {
520 Self::UnOp(UnOp::Neg, sugg) => *sugg,
521 Self::BinOp(AssocOp::Cast, ..) => Sugg::MaybeParen(format!("-({self})").into()),
522 _ => make_unop("-", self),
523 }
524 }
525}
526
527impl<'a> Not for Sugg<'a> {
528 type Output = Sugg<'a>;
529 fn not(self) -> Sugg<'a> {
530 use AssocOp::Binary;
531 use ast::BinOpKind::{Eq, Ge, Gt, Le, Lt, Ne};
532
533 match self {
534 Sugg::BinOp(op, lhs, rhs) => {
535 let to_op = match op {
536 Binary(Eq) => Binary(Ne),
537 Binary(Ne) => Binary(Eq),
538 Binary(Lt) => Binary(Ge),
539 Binary(Ge) => Binary(Lt),
540 Binary(Gt) => Binary(Le),
541 Binary(Le) => Binary(Gt),
542 _ => return make_unop("!", Sugg::BinOp(op, lhs, rhs)),
543 };
544 Sugg::BinOp(to_op, lhs, rhs)
545 },
546 Sugg::UnOp(UnOp::Not, expr) => *expr,
547 _ => make_unop("!", self),
548 }
549 }
550}
551
552struct ParenHelper<T> {
554 paren: bool,
556 wrapped: T,
558}
559
560impl<T> ParenHelper<T> {
561 fn new(paren: bool, wrapped: T) -> Self {
563 Self { paren, wrapped }
564 }
565}
566
567impl<T: Display> Display for ParenHelper<T> {
568 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
569 if self.paren {
570 write!(f, "({})", self.wrapped)
571 } else {
572 self.wrapped.fmt(f)
573 }
574 }
575}
576
577pub fn make_unop(op: &str, expr: Sugg<'_>) -> Sugg<'static> {
582 Sugg::MaybeParen(format!("{op}{}", expr.maybe_inner_paren()).into())
585}
586
587pub fn make_assoc(op: AssocOp, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
593 fn is_shift(op: AssocOp) -> bool {
595 matches!(op, AssocOp::Binary(ast::BinOpKind::Shl | ast::BinOpKind::Shr))
596 }
597
598 fn is_arith(op: AssocOp) -> bool {
601 matches!(
602 op,
603 AssocOp::Binary(
604 ast::BinOpKind::Add
605 | ast::BinOpKind::Sub
606 | ast::BinOpKind::Mul
607 | ast::BinOpKind::Div
608 | ast::BinOpKind::Rem
609 )
610 )
611 }
612
613 fn needs_paren(op: AssocOp, other: AssocOp, dir: Associativity) -> bool {
616 other.precedence() < op.precedence()
617 || (other.precedence() == op.precedence()
618 && ((op != other && associativity(op) != dir)
619 || (op == other && associativity(op) != Associativity::Both)))
620 || is_shift(op) && is_arith(other)
621 || is_shift(other) && is_arith(op)
622 }
623
624 let lhs_paren = if let Sugg::BinOp(lop, _, _) = *lhs {
625 needs_paren(op, lop, Associativity::Left)
626 } else {
627 false
628 };
629
630 let rhs_paren = if let Sugg::BinOp(rop, _, _) = *rhs {
631 needs_paren(op, rop, Associativity::Right)
632 } else {
633 false
634 };
635
636 let lhs = ParenHelper::new(lhs_paren, lhs).to_string();
637 let rhs = ParenHelper::new(rhs_paren, rhs).to_string();
638 Sugg::BinOp(op, lhs.into(), rhs.into())
639}
640
641pub fn make_binop(op: ast::BinOpKind, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
643 make_assoc(AssocOp::Binary(op), lhs, rhs)
644}
645
646#[derive(PartialEq, Eq, Clone, Copy)]
647enum Associativity {
649 Both,
651 Left,
653 None,
655 Right,
657}
658
659#[must_use]
667fn associativity(op: AssocOp) -> Associativity {
668 use ast::BinOpKind::{Add, And, BitAnd, BitOr, BitXor, Div, Eq, Ge, Gt, Le, Lt, Mul, Ne, Or, Rem, Shl, Shr, Sub};
669 use rustc_ast::util::parser::AssocOp::{Assign, AssignOp, Binary, Cast, Range};
670
671 match op {
672 Assign | AssignOp(_) => Associativity::Right,
673 Binary(Add | BitAnd | BitOr | BitXor | And | Or | Mul) | Cast => Associativity::Both,
674 Binary(Div | Eq | Gt | Ge | Lt | Le | Rem | Ne | Shl | Shr | Sub) => Associativity::Left,
675 Range(_) => Associativity::None,
676 }
677}
678
679fn indentation<T: LintContext>(cx: &T, span: Span) -> Option<String> {
682 let lo = cx.sess().source_map().lookup_char_pos(span.lo());
683 lo.file
684 .get_line(lo.line - 1 )
685 .and_then(|line| {
686 if let Some((pos, _)) = line.char_indices().find(|&(_, c)| c != ' ' && c != '\t') {
687 if lo.col == CharPos(pos) {
689 Some(line[..pos].into())
690 } else {
691 None
692 }
693 } else {
694 None
695 }
696 })
697}
698
699pub trait DiagExt<T: LintContext> {
701 fn suggest_item_with_attr<D: Display + ?Sized>(
711 &mut self,
712 cx: &T,
713 item: Span,
714 msg: &str,
715 attr: &D,
716 applicability: Applicability,
717 );
718
719 fn suggest_append_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability);
732
733 fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability);
745}
746
747impl<T: LintContext> DiagExt<T> for rustc_errors::Diag<'_, ()> {
748 fn suggest_item_with_attr<D: Display + ?Sized>(
749 &mut self,
750 cx: &T,
751 item: Span,
752 msg: &str,
753 attr: &D,
754 applicability: Applicability,
755 ) {
756 if let Some(indent) = indentation(cx, item) {
757 let span = item.with_hi(item.lo());
758
759 self.span_suggestion(span, msg.to_string(), format!("{attr}\n{indent}"), applicability);
760 }
761 }
762
763 fn suggest_append_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability) {
764 if let Some(indent) = indentation(cx, item) {
765 let span = item.shrink_to_hi();
766 let mut new_item_code = String::new();
767 for l in new_item.lines() {
768 writeln!(new_item_code, "{indent}{l}").unwrap();
769 }
770 self.span_suggestion(
771 span,
772 msg.to_string(),
773 format!("\n\n{}", new_item_code.strip_suffix('\n').unwrap()),
774 applicability,
775 );
776 }
777 }
778
779 fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability) {
780 let mut remove_span = item;
781 let fmpos = cx.sess().source_map().lookup_byte_offset(remove_span.hi());
782
783 if let Some(ref src) = fmpos.sf.src {
784 let non_whitespace_offset = src[fmpos.pos.to_usize()..].find(|c| c != ' ' && c != '\t' && c != '\n');
785
786 if let Some(non_whitespace_offset) = non_whitespace_offset {
787 remove_span = remove_span
788 .with_hi(remove_span.hi() + BytePos(non_whitespace_offset.try_into().expect("offset too large")));
789 }
790 }
791
792 self.span_suggestion(remove_span, msg.to_string(), "", applicability);
793 }
794}
795
796pub struct DerefClosure {
799 pub applicability: Applicability,
801 pub suggestion: String,
803}
804
805pub fn deref_closure_args(cx: &LateContext<'_>, closure: &hir::Expr<'_>) -> Option<DerefClosure> {
811 if let ExprKind::Closure(&Closure {
812 fn_decl, def_id, body, ..
813 }) = closure.kind
814 {
815 let closure_body = cx.tcx.hir_body(body);
816 let closure_arg_is_type_annotated_double_ref = if let TyKind::Ref(_, MutTy { ty, .. }) = fn_decl.inputs[0].kind
819 {
820 matches!(ty.kind, TyKind::Ref(_, MutTy { .. }))
821 } else {
822 false
823 };
824
825 let mut visitor = DerefDelegate {
826 cx,
827 closure_span: closure.span,
828 closure_arg_id: closure_body.params[0].pat.hir_id,
829 closure_arg_is_type_annotated_double_ref,
830 next_pos: closure.span.lo(),
831 checked_borrows: FxHashSet::default(),
832 suggestion_start: String::new(),
833 applicability: Applicability::MachineApplicable,
834 };
835
836 ExprUseVisitor::for_clippy(cx, def_id, &mut visitor)
837 .consume_body(closure_body)
838 .into_ok();
839
840 if !visitor.suggestion_start.is_empty() {
841 return Some(DerefClosure {
842 applicability: visitor.applicability,
843 suggestion: visitor.finish(),
844 });
845 }
846 }
847 None
848}
849
850struct DerefDelegate<'a, 'tcx> {
853 cx: &'a LateContext<'tcx>,
855 closure_span: Span,
857 closure_arg_id: HirId,
859 closure_arg_is_type_annotated_double_ref: bool,
861 next_pos: BytePos,
863 checked_borrows: FxHashSet<HirId>,
866 suggestion_start: String,
868 applicability: Applicability,
870}
871
872impl<'tcx> DerefDelegate<'_, 'tcx> {
873 pub fn finish(&mut self) -> String {
878 let end_span = Span::new(self.next_pos, self.closure_span.hi(), self.closure_span.ctxt(), None);
879 let end_snip = snippet_with_applicability(self.cx, end_span, "..", &mut self.applicability);
880 let sugg = format!("{}{end_snip}", self.suggestion_start);
881 if self.closure_arg_is_type_annotated_double_ref {
882 sugg.replacen('&', "", 1)
883 } else {
884 sugg
885 }
886 }
887
888 fn func_takes_arg_by_double_ref(&self, parent_expr: &'tcx hir::Expr<'_>, cmt_hir_id: HirId) -> bool {
890 let ty = match parent_expr.kind {
891 ExprKind::MethodCall(_, receiver, call_args, _) => {
892 if let Some(sig) = self
893 .cx
894 .typeck_results()
895 .type_dependent_def_id(parent_expr.hir_id)
896 .map(|did| {
897 self.cx
898 .tcx
899 .fn_sig(did)
900 .instantiate_identity()
901 .skip_norm_wip()
902 .skip_binder()
903 })
904 {
905 std::iter::once(receiver)
906 .chain(call_args.iter())
907 .position(|arg| arg.hir_id == cmt_hir_id)
908 .map(|i| sig.inputs()[i])
909 } else {
910 return false;
911 }
912 },
913 ExprKind::Call(func, call_args) => {
914 if let Some(sig) = expr_sig(self.cx, func) {
915 call_args
916 .iter()
917 .position(|arg| arg.hir_id == cmt_hir_id)
918 .and_then(|i| sig.input(i))
919 .map(ty::Binder::skip_binder)
920 } else {
921 return false;
922 }
923 },
924 _ => return false,
925 };
926
927 ty.is_some_and(|ty| matches!(ty.kind(), ty::Ref(_, inner, _) if inner.is_ref()))
928 }
929}
930
931impl<'tcx> Delegate<'tcx> for DerefDelegate<'_, 'tcx> {
932 fn consume(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
933
934 fn use_cloned(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
935
936 #[expect(clippy::too_many_lines)]
937 fn borrow(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId, _: ty::BorrowKind) {
938 if let PlaceBase::Local(id) = cmt.place.base {
939 let span = self.cx.tcx.hir_span(cmt.hir_id);
940 if !self.checked_borrows.insert(cmt.hir_id) {
941 return;
943 }
944
945 let start_span = Span::new(self.next_pos, span.lo(), span.ctxt(), None);
946 let mut start_snip = snippet_with_applicability(self.cx, start_span, "..", &mut self.applicability);
947
948 let ident_str = self.cx.tcx.hir_name(id).to_string();
950 let ident_str_with_proj = snippet(self.cx, span, "..").to_string();
952
953 if let Node::Pat(pat) = self.cx.tcx.hir_node(id)
955 && pat.hir_id != self.closure_arg_id
956 {
957 let _ = write!(self.suggestion_start, "{start_snip}{ident_str_with_proj}");
958 } else if cmt.place.projections.is_empty() {
959 let _: fmt::Result = write!(self.suggestion_start, "{start_snip}&{ident_str}");
962 } else {
963 if let Some(parent_expr) = get_parent_expr_for_hir(self.cx, cmt.hir_id) {
972 match &parent_expr.kind {
973 ExprKind::MethodCall(_, self_expr, ..) if self_expr.hir_id == cmt.hir_id => {
976 let _: fmt::Result = write!(self.suggestion_start, "{start_snip}{ident_str_with_proj}");
977 self.next_pos = span.hi();
978 return;
979 },
980 ExprKind::Call(_, call_args) | ExprKind::MethodCall(_, _, call_args, _) => {
983 let expr = self.cx.tcx.hir_expect_expr(cmt.hir_id);
984 let arg_ty_kind = self.cx.typeck_results().expr_ty(expr).kind();
985
986 if matches!(arg_ty_kind, ty::Ref(_, _, Mutability::Not)) {
987 let takes_arg_by_double_ref =
989 self.func_takes_arg_by_double_ref(parent_expr, cmt.hir_id);
990
991 let has_field_or_index_projection =
994 cmt.place.projections.iter().any(|proj| {
995 matches!(proj.kind, ProjectionKind::Field(..) | ProjectionKind::Index)
996 });
997
998 let ident_sugg = if !call_args.is_empty()
1001 && !takes_arg_by_double_ref
1002 && (self.closure_arg_is_type_annotated_double_ref || has_field_or_index_projection)
1003 {
1004 let ident = if has_field_or_index_projection {
1005 ident_str_with_proj
1006 } else {
1007 ident_str
1008 };
1009 format!("{start_snip}{ident}")
1010 } else {
1011 format!("{start_snip}&{ident_str}")
1012 };
1013 self.suggestion_start.push_str(&ident_sugg);
1014 self.next_pos = span.hi();
1015 return;
1016 }
1017
1018 self.applicability = Applicability::Unspecified;
1019 },
1020 _ => (),
1021 }
1022 }
1023
1024 let mut replacement_str = ident_str;
1025 let mut projections_handled = false;
1026 cmt.place.projections.iter().enumerate().for_each(|(i, proj)| {
1027 match proj.kind {
1028 ProjectionKind::Field(..) => match cmt.place.ty_before_projection(i).kind() {
1031 ty::Adt(..) | ty::Tuple(_) => {
1032 replacement_str.clone_from(&ident_str_with_proj);
1033 projections_handled = true;
1034 },
1035 _ => (),
1036 },
1037 ProjectionKind::Index => {
1042 let start_span = Span::new(self.next_pos, span.hi(), span.ctxt(), None);
1043 start_snip = snippet_with_applicability(self.cx, start_span, "..", &mut self.applicability);
1044 replacement_str.clear();
1045 projections_handled = true;
1046 },
1047 ProjectionKind::Subslice |
1049 ProjectionKind::OpaqueCast |
1051 ProjectionKind::UnwrapUnsafeBinder => (),
1053 ProjectionKind::Deref => {
1054 if let ty::Ref(_, inner, _) = cmt.place.ty_before_projection(i).kind()
1059 && matches!(inner.kind(), ty::Ref(_, innermost, _) if innermost.is_array()) {
1060 projections_handled = true;
1061 }
1062 },
1063 }
1064 });
1065
1066 if !projections_handled {
1069 let last_deref = cmt
1070 .place
1071 .projections
1072 .iter()
1073 .rposition(|proj| proj.kind == ProjectionKind::Deref);
1074
1075 if let Some(pos) = last_deref {
1076 let mut projections = cmt.place.projections.clone();
1077 projections.truncate(pos);
1078
1079 for item in projections {
1080 if item.kind == ProjectionKind::Deref {
1081 replacement_str = format!("*{replacement_str}");
1082 }
1083 }
1084 }
1085 }
1086
1087 let _: fmt::Result = write!(self.suggestion_start, "{start_snip}{replacement_str}");
1088 }
1089 self.next_pos = span.hi();
1090 }
1091 }
1092
1093 fn mutate(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
1094
1095 fn fake_read(&mut self, _: &PlaceWithHirId<'tcx>, _: FakeReadCause, _: HirId) {}
1096}
1097
1098#[cfg(test)]
1099mod test {
1100 use super::Sugg;
1101
1102 use rustc_ast as ast;
1103 use rustc_ast::util::parser::AssocOp;
1104 use std::borrow::Cow;
1105
1106 const SUGGESTION: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("function_call()"));
1107
1108 #[test]
1109 fn make_return_transform_sugg_into_a_return_call() {
1110 assert_eq!("return function_call()", SUGGESTION.make_return().to_string());
1111 }
1112
1113 #[test]
1114 fn blockify_transforms_sugg_into_a_block() {
1115 assert_eq!("{ function_call() }", SUGGESTION.blockify().to_string());
1116 }
1117
1118 #[test]
1119 fn binop_maybe_paren() {
1120 let sugg = Sugg::BinOp(AssocOp::Binary(ast::BinOpKind::Add), "1".into(), "1".into());
1121 assert_eq!("(1 + 1)", sugg.maybe_paren().to_string());
1122
1123 let sugg = Sugg::BinOp(AssocOp::Binary(ast::BinOpKind::Add), "(1 + 1)".into(), "(1 + 1)".into());
1124 assert_eq!("((1 + 1) + (1 + 1))", sugg.maybe_paren().to_string());
1125 }
1126
1127 #[test]
1128 fn unop_parenthesize() {
1129 let sugg = Sugg::NonParen("x".into()).mut_addr();
1130 assert_eq!("&mut x", sugg.to_string());
1131 let sugg = sugg.mut_addr();
1132 assert_eq!("&mut &mut x", sugg.to_string());
1133 assert_eq!("(&mut &mut x)", sugg.maybe_paren().to_string());
1134 }
1135
1136 #[test]
1137 fn not_op() {
1138 use ast::BinOpKind::{Add, And, Eq, Ge, Gt, Le, Lt, Ne, Or};
1139
1140 fn test_not(op: AssocOp, correct: &str) {
1141 let sugg = Sugg::BinOp(op, "x".into(), "y".into());
1142 assert_eq!((!sugg).to_string(), correct);
1143 }
1144
1145 test_not(AssocOp::Binary(Eq), "x != y");
1147 test_not(AssocOp::Binary(Ne), "x == y");
1148 test_not(AssocOp::Binary(Lt), "x >= y");
1149 test_not(AssocOp::Binary(Le), "x > y");
1150 test_not(AssocOp::Binary(Gt), "x <= y");
1151 test_not(AssocOp::Binary(Ge), "x < y");
1152
1153 test_not(AssocOp::Binary(Add), "!(x + y)");
1155 test_not(AssocOp::Binary(And), "!(x && y)");
1156 test_not(AssocOp::Binary(Or), "!(x || y)");
1157 }
1158}