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