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.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::Paren(..)
235 | ast::ExprKind::Underscore
236 | ast::ExprKind::Path(..)
237 | ast::ExprKind::Repeat(..)
238 | ast::ExprKind::Ret(..)
239 | ast::ExprKind::Become(..)
240 | ast::ExprKind::Yeet(..)
241 | ast::ExprKind::FormatArgs(..)
242 | ast::ExprKind::Struct(..)
243 | ast::ExprKind::Try(..)
244 | ast::ExprKind::TryBlock(..)
245 | ast::ExprKind::Tup(..)
246 | ast::ExprKind::Use(..)
247 | ast::ExprKind::Array(..)
248 | ast::ExprKind::While(..)
249 | ast::ExprKind::Await(..)
250 | ast::ExprKind::Err(_)
251 | ast::ExprKind::Dummy
252 | ast::ExprKind::UnsafeBinderCast(..) => Sugg::NonParen(snippet(expr.span)),
253 ast::ExprKind::Range(ref lhs, ref rhs, limits) => Sugg::BinOp(
254 AssocOp::Range(limits),
255 lhs.as_ref().map_or("".into(), |lhs| snippet(lhs.span)),
256 rhs.as_ref().map_or("".into(), |rhs| snippet(rhs.span)),
257 ),
258 ast::ExprKind::Assign(ref lhs, ref rhs, _) => Sugg::BinOp(
259 AssocOp::Assign,
260 snippet(lhs.span),
261 snippet(rhs.span),
262 ),
263 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => Sugg::BinOp(
264 AssocOp::AssignOp(op.node),
265 snippet(lhs.span),
266 snippet(rhs.span),
267 ),
268 ast::ExprKind::Binary(op, ref lhs, ref rhs) => Sugg::BinOp(
269 AssocOp::Binary(op.node),
270 snippet(lhs.span),
271 snippet(rhs.span),
272 ),
273 ast::ExprKind::Cast(ref lhs, ref ty) |
274 ast::ExprKind::Type(ref lhs, ref ty) => Sugg::BinOp(
276 AssocOp::Cast,
277 snippet(lhs.span),
278 snippet(ty.span),
279 ),
280 }
281 }
282
283 pub fn and(self, rhs: &Self) -> Sugg<'static> {
285 make_binop(ast::BinOpKind::And, &self, rhs)
286 }
287
288 pub fn bit_and(self, rhs: &Self) -> Sugg<'static> {
290 make_binop(ast::BinOpKind::BitAnd, &self, rhs)
291 }
292
293 pub fn as_ty<R: Display>(self, rhs: R) -> Sugg<'static> {
295 make_assoc(AssocOp::Cast, &self, &Sugg::NonParen(rhs.to_string().into()))
296 }
297
298 pub fn addr(self) -> Sugg<'static> {
300 make_unop("&", self)
301 }
302
303 pub fn mut_addr(self) -> Sugg<'static> {
305 make_unop("&mut ", self)
306 }
307
308 pub fn deref(self) -> Sugg<'static> {
310 make_unop("*", self)
311 }
312
313 pub fn addr_deref(self) -> Sugg<'static> {
317 make_unop("&*", self)
318 }
319
320 pub fn mut_addr_deref(self) -> Sugg<'static> {
324 make_unop("&mut *", self)
325 }
326
327 pub fn make_return(self) -> Sugg<'static> {
329 Sugg::NonParen(Cow::Owned(format!("return {self}")))
330 }
331
332 pub fn blockify(self) -> Sugg<'static> {
335 Sugg::NonParen(Cow::Owned(format!("{{ {self} }}")))
336 }
337
338 pub fn unsafeify(self) -> Sugg<'static> {
340 Sugg::NonParen(Cow::Owned(format!("unsafe {{ {self} }}")))
341 }
342
343 pub fn asyncify(self) -> Sugg<'static> {
346 Sugg::NonParen(Cow::Owned(format!("async {self}")))
347 }
348
349 pub fn range(self, end: &Self, limits: ast::RangeLimits) -> Sugg<'static> {
352 make_assoc(AssocOp::Range(limits), &self, end)
353 }
354
355 #[must_use]
359 pub fn maybe_paren(self) -> Self {
360 match self {
361 Sugg::NonParen(..) => self,
362 Sugg::MaybeParen(sugg) => {
364 if has_enclosing_paren(&sugg) {
365 Sugg::MaybeParen(sugg)
366 } else {
367 Sugg::NonParen(format!("({sugg})").into())
368 }
369 },
370 Sugg::BinOp(op, lhs, rhs) => {
371 let sugg = binop_to_string(op, &lhs, &rhs);
372 Sugg::NonParen(format!("({sugg})").into())
373 },
374 Sugg::UnOp(op, inner) => Sugg::NonParen(format!("({}{})", op.as_str(), inner.maybe_inner_paren()).into()),
375 }
376 }
377
378 #[must_use]
385 pub fn strip_paren(self) -> Self {
386 match self {
387 Sugg::NonParen(s) | Sugg::MaybeParen(s) => Sugg::NonParen(strip_enclosing_paren(s)),
388 sugg => sugg,
389 }
390 }
391
392 pub fn into_string(self) -> String {
393 match self {
394 Sugg::NonParen(p) | Sugg::MaybeParen(p) => p.into_owned(),
395 Sugg::BinOp(b, l, r) => binop_to_string(b, &l, &r),
396 Sugg::UnOp(op, inner) => format!("{}{}", op.as_str(), inner.maybe_inner_paren()),
397 }
398 }
399
400 fn starts_with_unary_op(&self) -> bool {
402 match self {
403 Sugg::UnOp(..) => true,
404 Sugg::BinOp(..) => false,
405 Sugg::MaybeParen(s) | Sugg::NonParen(s) => s.starts_with(['*', '!', '-', '&']),
406 }
407 }
408
409 fn maybe_inner_paren(self) -> Self {
412 if self.starts_with_unary_op() {
413 self
414 } else {
415 self.maybe_paren()
416 }
417 }
418}
419
420fn binop_to_string(op: AssocOp, lhs: &str, rhs: &str) -> String {
422 match op {
423 AssocOp::Binary(op) => format!("{lhs} {} {rhs}", op.as_str()),
424 AssocOp::Assign => format!("{lhs} = {rhs}"),
425 AssocOp::AssignOp(op) => format!("{lhs} {} {rhs}", op.as_str()),
426 AssocOp::Cast => format!("{lhs} as {rhs}"),
427 AssocOp::Range(limits) => format!("{lhs}{}{rhs}", limits.as_str()),
428 }
429}
430
431pub fn has_enclosing_paren(sugg: impl AsRef<str>) -> bool {
433 let mut chars = sugg.as_ref().chars();
434 if chars.next() == Some('(') {
435 let mut depth = 1;
436 for c in &mut chars {
437 if c == '(' {
438 depth += 1;
439 } else if c == ')' {
440 depth -= 1;
441 }
442 if depth == 0 {
443 break;
444 }
445 }
446 chars.next().is_none()
447 } else {
448 false
449 }
450}
451
452fn strip_enclosing_paren(snippet: Cow<'_, str>) -> Cow<'_, str> {
454 if has_enclosing_paren(&snippet) {
455 match snippet {
456 Cow::Borrowed(s) => Cow::Borrowed(&s[1..s.len() - 1]),
457 Cow::Owned(mut s) => {
458 s.pop();
459 s.remove(0);
460 Cow::Owned(s)
461 },
462 }
463 } else {
464 snippet
465 }
466}
467
468macro_rules! forward_binop_impls_to_ref {
470 (impl $imp:ident, $method:ident for $t:ty, type Output = $o:ty) => {
471 impl $imp<$t> for &$t {
472 type Output = $o;
473
474 fn $method(self, other: $t) -> $o {
475 $imp::$method(self, &other)
476 }
477 }
478
479 impl $imp<&$t> for $t {
480 type Output = $o;
481
482 fn $method(self, other: &$t) -> $o {
483 $imp::$method(&self, other)
484 }
485 }
486
487 impl $imp for $t {
488 type Output = $o;
489
490 fn $method(self, other: $t) -> $o {
491 $imp::$method(&self, &other)
492 }
493 }
494 };
495}
496
497impl Add for &Sugg<'_> {
498 type Output = Sugg<'static>;
499 fn add(self, rhs: &Sugg<'_>) -> Sugg<'static> {
500 make_binop(ast::BinOpKind::Add, self, rhs)
501 }
502}
503
504impl Sub for &Sugg<'_> {
505 type Output = Sugg<'static>;
506 fn sub(self, rhs: &Sugg<'_>) -> Sugg<'static> {
507 make_binop(ast::BinOpKind::Sub, self, rhs)
508 }
509}
510
511forward_binop_impls_to_ref!(impl Add, add for Sugg<'_>, type Output = Sugg<'static>);
512forward_binop_impls_to_ref!(impl Sub, sub for Sugg<'_>, type Output = Sugg<'static>);
513
514impl<'a> Neg for Sugg<'a> {
515 type Output = Sugg<'a>;
516 fn neg(self) -> Self::Output {
517 match self {
518 Self::UnOp(UnOp::Neg, sugg) => *sugg,
519 Self::BinOp(AssocOp::Cast, ..) => Sugg::MaybeParen(format!("-({self})").into()),
520 _ => make_unop("-", self),
521 }
522 }
523}
524
525impl<'a> Not for Sugg<'a> {
526 type Output = Sugg<'a>;
527 fn not(self) -> Sugg<'a> {
528 use AssocOp::Binary;
529 use ast::BinOpKind::{Eq, Ge, Gt, Le, Lt, Ne};
530
531 match self {
532 Sugg::BinOp(op, lhs, rhs) => {
533 let to_op = match op {
534 Binary(Eq) => Binary(Ne),
535 Binary(Ne) => Binary(Eq),
536 Binary(Lt) => Binary(Ge),
537 Binary(Ge) => Binary(Lt),
538 Binary(Gt) => Binary(Le),
539 Binary(Le) => Binary(Gt),
540 _ => return make_unop("!", Sugg::BinOp(op, lhs, rhs)),
541 };
542 Sugg::BinOp(to_op, lhs, rhs)
543 },
544 Sugg::UnOp(UnOp::Not, expr) => *expr,
545 _ => make_unop("!", self),
546 }
547 }
548}
549
550struct ParenHelper<T> {
552 paren: bool,
554 wrapped: T,
556}
557
558impl<T> ParenHelper<T> {
559 fn new(paren: bool, wrapped: T) -> Self {
561 Self { paren, wrapped }
562 }
563}
564
565impl<T: Display> Display for ParenHelper<T> {
566 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
567 if self.paren {
568 write!(f, "({})", self.wrapped)
569 } else {
570 self.wrapped.fmt(f)
571 }
572 }
573}
574
575pub fn make_unop(op: &str, expr: Sugg<'_>) -> Sugg<'static> {
580 Sugg::MaybeParen(format!("{op}{}", expr.maybe_inner_paren()).into())
583}
584
585pub fn make_assoc(op: AssocOp, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
591 fn is_shift(op: AssocOp) -> bool {
593 matches!(op, AssocOp::Binary(ast::BinOpKind::Shl | ast::BinOpKind::Shr))
594 }
595
596 fn is_arith(op: AssocOp) -> bool {
599 matches!(
600 op,
601 AssocOp::Binary(
602 ast::BinOpKind::Add
603 | ast::BinOpKind::Sub
604 | ast::BinOpKind::Mul
605 | ast::BinOpKind::Div
606 | ast::BinOpKind::Rem
607 )
608 )
609 }
610
611 fn needs_paren(op: AssocOp, other: AssocOp, dir: Associativity) -> bool {
614 other.precedence() < op.precedence()
615 || (other.precedence() == op.precedence()
616 && ((op != other && associativity(op) != dir)
617 || (op == other && associativity(op) != Associativity::Both)))
618 || is_shift(op) && is_arith(other)
619 || is_shift(other) && is_arith(op)
620 }
621
622 let lhs_paren = if let Sugg::BinOp(lop, _, _) = *lhs {
623 needs_paren(op, lop, Associativity::Left)
624 } else {
625 false
626 };
627
628 let rhs_paren = if let Sugg::BinOp(rop, _, _) = *rhs {
629 needs_paren(op, rop, Associativity::Right)
630 } else {
631 false
632 };
633
634 let lhs = ParenHelper::new(lhs_paren, lhs).to_string();
635 let rhs = ParenHelper::new(rhs_paren, rhs).to_string();
636 Sugg::BinOp(op, lhs.into(), rhs.into())
637}
638
639pub fn make_binop(op: ast::BinOpKind, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
641 make_assoc(AssocOp::Binary(op), lhs, rhs)
642}
643
644#[derive(PartialEq, Eq, Clone, Copy)]
645enum Associativity {
647 Both,
649 Left,
651 None,
653 Right,
655}
656
657#[must_use]
665fn associativity(op: AssocOp) -> Associativity {
666 use ast::BinOpKind::{Add, And, BitAnd, BitOr, BitXor, Div, Eq, Ge, Gt, Le, Lt, Mul, Ne, Or, Rem, Shl, Shr, Sub};
667 use rustc_ast::util::parser::AssocOp::{Assign, AssignOp, Binary, Cast, Range};
668
669 match op {
670 Assign | AssignOp(_) => Associativity::Right,
671 Binary(Add | BitAnd | BitOr | BitXor | And | Or | Mul) | Cast => Associativity::Both,
672 Binary(Div | Eq | Gt | Ge | Lt | Le | Rem | Ne | Shl | Shr | Sub) => Associativity::Left,
673 Range(_) => Associativity::None,
674 }
675}
676
677fn indentation<T: LintContext>(cx: &T, span: Span) -> Option<String> {
680 let lo = cx.sess().source_map().lookup_char_pos(span.lo());
681 lo.file
682 .get_line(lo.line - 1 )
683 .and_then(|line| {
684 if let Some((pos, _)) = line.char_indices().find(|&(_, c)| c != ' ' && c != '\t') {
685 if lo.col == CharPos(pos) {
687 Some(line[..pos].into())
688 } else {
689 None
690 }
691 } else {
692 None
693 }
694 })
695}
696
697pub trait DiagExt<T: LintContext> {
699 fn suggest_item_with_attr<D: Display + ?Sized>(
709 &mut self,
710 cx: &T,
711 item: Span,
712 msg: &str,
713 attr: &D,
714 applicability: Applicability,
715 );
716
717 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability);
730
731 fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability);
743}
744
745impl<T: LintContext> DiagExt<T> for rustc_errors::Diag<'_, ()> {
746 fn suggest_item_with_attr<D: Display + ?Sized>(
747 &mut self,
748 cx: &T,
749 item: Span,
750 msg: &str,
751 attr: &D,
752 applicability: Applicability,
753 ) {
754 if let Some(indent) = indentation(cx, item) {
755 let span = item.with_hi(item.lo());
756
757 self.span_suggestion(span, msg.to_string(), format!("{attr}\n{indent}"), applicability);
758 }
759 }
760
761 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability) {
762 if let Some(indent) = indentation(cx, item) {
763 let span = item.with_hi(item.lo());
764
765 let mut first = true;
766 let new_item = new_item
767 .lines()
768 .map(|l| {
769 if first {
770 first = false;
771 format!("{l}\n")
772 } else {
773 format!("{indent}{l}\n")
774 }
775 })
776 .collect::<String>();
777
778 self.span_suggestion(span, msg.to_string(), format!("{new_item}\n{indent}"), applicability);
779 }
780 }
781
782 fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability) {
783 let mut remove_span = item;
784 let fmpos = cx.sess().source_map().lookup_byte_offset(remove_span.hi());
785
786 if let Some(ref src) = fmpos.sf.src {
787 let non_whitespace_offset = src[fmpos.pos.to_usize()..].find(|c| c != ' ' && c != '\t' && c != '\n');
788
789 if let Some(non_whitespace_offset) = non_whitespace_offset {
790 remove_span = remove_span
791 .with_hi(remove_span.hi() + BytePos(non_whitespace_offset.try_into().expect("offset too large")));
792 }
793 }
794
795 self.span_suggestion(remove_span, msg.to_string(), "", applicability);
796 }
797}
798
799pub struct DerefClosure {
802 pub applicability: Applicability,
804 pub suggestion: String,
806}
807
808pub fn deref_closure_args(cx: &LateContext<'_>, closure: &hir::Expr<'_>) -> Option<DerefClosure> {
814 if let ExprKind::Closure(&Closure {
815 fn_decl, def_id, body, ..
816 }) = closure.kind
817 {
818 let closure_body = cx.tcx.hir_body(body);
819 let closure_arg_is_type_annotated_double_ref = if let TyKind::Ref(_, MutTy { ty, .. }) = fn_decl.inputs[0].kind
822 {
823 matches!(ty.kind, TyKind::Ref(_, MutTy { .. }))
824 } else {
825 false
826 };
827
828 let mut visitor = DerefDelegate {
829 cx,
830 closure_span: closure.span,
831 closure_arg_id: closure_body.params[0].pat.hir_id,
832 closure_arg_is_type_annotated_double_ref,
833 next_pos: closure.span.lo(),
834 checked_borrows: FxHashSet::default(),
835 suggestion_start: String::new(),
836 applicability: Applicability::MachineApplicable,
837 };
838
839 ExprUseVisitor::for_clippy(cx, def_id, &mut visitor)
840 .consume_body(closure_body)
841 .into_ok();
842
843 if !visitor.suggestion_start.is_empty() {
844 return Some(DerefClosure {
845 applicability: visitor.applicability,
846 suggestion: visitor.finish(),
847 });
848 }
849 }
850 None
851}
852
853struct DerefDelegate<'a, 'tcx> {
856 cx: &'a LateContext<'tcx>,
858 closure_span: Span,
860 closure_arg_id: HirId,
862 closure_arg_is_type_annotated_double_ref: bool,
864 next_pos: BytePos,
866 checked_borrows: FxHashSet<HirId>,
869 suggestion_start: String,
871 applicability: Applicability,
873}
874
875impl<'tcx> DerefDelegate<'_, 'tcx> {
876 pub fn finish(&mut self) -> String {
881 let end_span = Span::new(self.next_pos, self.closure_span.hi(), self.closure_span.ctxt(), None);
882 let end_snip = snippet_with_applicability(self.cx, end_span, "..", &mut self.applicability);
883 let sugg = format!("{}{end_snip}", self.suggestion_start);
884 if self.closure_arg_is_type_annotated_double_ref {
885 sugg.replacen('&', "", 1)
886 } else {
887 sugg
888 }
889 }
890
891 fn func_takes_arg_by_double_ref(&self, parent_expr: &'tcx hir::Expr<'_>, cmt_hir_id: HirId) -> bool {
893 let ty = match parent_expr.kind {
894 ExprKind::MethodCall(_, receiver, call_args, _) => {
895 if let Some(sig) = self
896 .cx
897 .typeck_results()
898 .type_dependent_def_id(parent_expr.hir_id)
899 .map(|did| self.cx.tcx.fn_sig(did).instantiate_identity().skip_binder())
900 {
901 std::iter::once(receiver)
902 .chain(call_args.iter())
903 .position(|arg| arg.hir_id == cmt_hir_id)
904 .map(|i| sig.inputs()[i])
905 } else {
906 return false;
907 }
908 },
909 ExprKind::Call(func, call_args) => {
910 if let Some(sig) = expr_sig(self.cx, func) {
911 call_args
912 .iter()
913 .position(|arg| arg.hir_id == cmt_hir_id)
914 .and_then(|i| sig.input(i))
915 .map(ty::Binder::skip_binder)
916 } else {
917 return false;
918 }
919 },
920 _ => return false,
921 };
922
923 ty.is_some_and(|ty| matches!(ty.kind(), ty::Ref(_, inner, _) if inner.is_ref()))
924 }
925}
926
927impl<'tcx> Delegate<'tcx> for DerefDelegate<'_, 'tcx> {
928 fn consume(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
929
930 fn use_cloned(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
931
932 #[expect(clippy::too_many_lines)]
933 fn borrow(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId, _: ty::BorrowKind) {
934 if let PlaceBase::Local(id) = cmt.place.base {
935 let span = self.cx.tcx.hir_span(cmt.hir_id);
936 if !self.checked_borrows.insert(cmt.hir_id) {
937 return;
939 }
940
941 let start_span = Span::new(self.next_pos, span.lo(), span.ctxt(), None);
942 let mut start_snip = snippet_with_applicability(self.cx, start_span, "..", &mut self.applicability);
943
944 let ident_str = self.cx.tcx.hir_name(id).to_string();
946 let ident_str_with_proj = snippet(self.cx, span, "..").to_string();
948
949 if let Node::Pat(pat) = self.cx.tcx.hir_node(id)
951 && pat.hir_id != self.closure_arg_id
952 {
953 let _ = write!(self.suggestion_start, "{start_snip}{ident_str_with_proj}");
954 } else if cmt.place.projections.is_empty() {
955 let _: fmt::Result = write!(self.suggestion_start, "{start_snip}&{ident_str}");
958 } else {
959 if let Some(parent_expr) = get_parent_expr_for_hir(self.cx, cmt.hir_id) {
968 match &parent_expr.kind {
969 ExprKind::MethodCall(_, self_expr, ..) if self_expr.hir_id == cmt.hir_id => {
972 let _: fmt::Result = write!(self.suggestion_start, "{start_snip}{ident_str_with_proj}");
973 self.next_pos = span.hi();
974 return;
975 },
976 ExprKind::Call(_, call_args) | ExprKind::MethodCall(_, _, call_args, _) => {
979 let expr = self.cx.tcx.hir_expect_expr(cmt.hir_id);
980 let arg_ty_kind = self.cx.typeck_results().expr_ty(expr).kind();
981
982 if matches!(arg_ty_kind, ty::Ref(_, _, Mutability::Not)) {
983 let takes_arg_by_double_ref =
985 self.func_takes_arg_by_double_ref(parent_expr, cmt.hir_id);
986
987 let has_field_or_index_projection =
990 cmt.place.projections.iter().any(|proj| {
991 matches!(proj.kind, ProjectionKind::Field(..) | ProjectionKind::Index)
992 });
993
994 let ident_sugg = if !call_args.is_empty()
997 && !takes_arg_by_double_ref
998 && (self.closure_arg_is_type_annotated_double_ref || has_field_or_index_projection)
999 {
1000 let ident = if has_field_or_index_projection {
1001 ident_str_with_proj
1002 } else {
1003 ident_str
1004 };
1005 format!("{start_snip}{ident}")
1006 } else {
1007 format!("{start_snip}&{ident_str}")
1008 };
1009 self.suggestion_start.push_str(&ident_sugg);
1010 self.next_pos = span.hi();
1011 return;
1012 }
1013
1014 self.applicability = Applicability::Unspecified;
1015 },
1016 _ => (),
1017 }
1018 }
1019
1020 let mut replacement_str = ident_str;
1021 let mut projections_handled = false;
1022 cmt.place.projections.iter().enumerate().for_each(|(i, proj)| {
1023 match proj.kind {
1024 ProjectionKind::Field(..) => match cmt.place.ty_before_projection(i).kind() {
1027 ty::Adt(..) | ty::Tuple(_) => {
1028 replacement_str.clone_from(&ident_str_with_proj);
1029 projections_handled = true;
1030 },
1031 _ => (),
1032 },
1033 ProjectionKind::Index => {
1038 let start_span = Span::new(self.next_pos, span.hi(), span.ctxt(), None);
1039 start_snip = snippet_with_applicability(self.cx, start_span, "..", &mut self.applicability);
1040 replacement_str.clear();
1041 projections_handled = true;
1042 },
1043 ProjectionKind::Subslice |
1045 ProjectionKind::OpaqueCast |
1047 ProjectionKind::UnwrapUnsafeBinder => (),
1049 ProjectionKind::Deref => {
1050 if let ty::Ref(_, inner, _) = cmt.place.ty_before_projection(i).kind()
1055 && matches!(inner.kind(), ty::Ref(_, innermost, _) if innermost.is_array()) {
1056 projections_handled = true;
1057 }
1058 },
1059 }
1060 });
1061
1062 if !projections_handled {
1065 let last_deref = cmt
1066 .place
1067 .projections
1068 .iter()
1069 .rposition(|proj| proj.kind == ProjectionKind::Deref);
1070
1071 if let Some(pos) = last_deref {
1072 let mut projections = cmt.place.projections.clone();
1073 projections.truncate(pos);
1074
1075 for item in projections {
1076 if item.kind == ProjectionKind::Deref {
1077 replacement_str = format!("*{replacement_str}");
1078 }
1079 }
1080 }
1081 }
1082
1083 let _: fmt::Result = write!(self.suggestion_start, "{start_snip}{replacement_str}");
1084 }
1085 self.next_pos = span.hi();
1086 }
1087 }
1088
1089 fn mutate(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
1090
1091 fn fake_read(&mut self, _: &PlaceWithHirId<'tcx>, _: FakeReadCause, _: HirId) {}
1092}
1093
1094#[cfg(test)]
1095mod test {
1096 use super::Sugg;
1097
1098 use rustc_ast as ast;
1099 use rustc_ast::util::parser::AssocOp;
1100 use std::borrow::Cow;
1101
1102 const SUGGESTION: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("function_call()"));
1103
1104 #[test]
1105 fn make_return_transform_sugg_into_a_return_call() {
1106 assert_eq!("return function_call()", SUGGESTION.make_return().to_string());
1107 }
1108
1109 #[test]
1110 fn blockify_transforms_sugg_into_a_block() {
1111 assert_eq!("{ function_call() }", SUGGESTION.blockify().to_string());
1112 }
1113
1114 #[test]
1115 fn binop_maybe_paren() {
1116 let sugg = Sugg::BinOp(AssocOp::Binary(ast::BinOpKind::Add), "1".into(), "1".into());
1117 assert_eq!("(1 + 1)", sugg.maybe_paren().to_string());
1118
1119 let sugg = Sugg::BinOp(AssocOp::Binary(ast::BinOpKind::Add), "(1 + 1)".into(), "(1 + 1)".into());
1120 assert_eq!("((1 + 1) + (1 + 1))", sugg.maybe_paren().to_string());
1121 }
1122
1123 #[test]
1124 fn unop_parenthesize() {
1125 let sugg = Sugg::NonParen("x".into()).mut_addr();
1126 assert_eq!("&mut x", sugg.to_string());
1127 let sugg = sugg.mut_addr();
1128 assert_eq!("&mut &mut x", sugg.to_string());
1129 assert_eq!("(&mut &mut x)", sugg.maybe_paren().to_string());
1130 }
1131
1132 #[test]
1133 fn not_op() {
1134 use ast::BinOpKind::{Add, And, Eq, Ge, Gt, Le, Lt, Ne, Or};
1135
1136 fn test_not(op: AssocOp, correct: &str) {
1137 let sugg = Sugg::BinOp(op, "x".into(), "y".into());
1138 assert_eq!((!sugg).to_string(), correct);
1139 }
1140
1141 test_not(AssocOp::Binary(Eq), "x != y");
1143 test_not(AssocOp::Binary(Ne), "x == y");
1144 test_not(AssocOp::Binary(Lt), "x >= y");
1145 test_not(AssocOp::Binary(Le), "x > y");
1146 test_not(AssocOp::Binary(Gt), "x <= y");
1147 test_not(AssocOp::Binary(Ge), "x < y");
1148
1149 test_not(AssocOp::Binary(Add), "!(x + y)");
1151 test_not(AssocOp::Binary(And), "!(x && y)");
1152 test_not(AssocOp::Binary(Or), "!(x || y)");
1153 }
1154}