clippy_utils/
sugg.rs

1//! Contains utility functions to generate suggestions.
2#![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/// A helper type to build suggestion correctly handling parentheses.
23#[derive(Clone, Debug, PartialEq)]
24pub enum Sugg<'a> {
25    /// An expression that never needs parentheses such as `1337` or `[0; 42]`.
26    NonParen(Cow<'a, str>),
27    /// An expression that does not fit in other variants.
28    MaybeParen(Cow<'a, str>),
29    /// A binary operator expression, including `as`-casts and explicit type
30    /// coercion.
31    BinOp(AssocOp, Cow<'a, str>, Cow<'a, str>),
32    /// A unary operator expression. This is used to sometimes represent `!`
33    /// or `-`, but only if the type with and without the operator is kept identical.
34    /// It means that doubling the operator can be used to remove it instead, in
35    /// order to provide better suggestions.
36    UnOp(UnOp, Box<Self>),
37}
38
39/// Literal constant `0`, for convenience.
40pub const ZERO: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("0"));
41/// Literal constant `1`, for convenience.
42pub const ONE: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("1"));
43/// a constant represents an empty string, for convenience.
44pub 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)] // ok, because of the function `as_ty` method
57impl<'a> Sugg<'a> {
58    /// Prepare a suggestion from an expression.
59    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    /// Convenience function around `hir_opt` for suggestions with a default
66    /// text.
67    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    /// Same as `hir`, but it adapts the applicability level by following rules:
72    ///
73    /// - Applicability level `Unspecified` will never be changed.
74    /// - If the span is inside a macro, change the applicability level to `MaybeIncorrect`.
75    /// - If the default value is used and the applicability level is `MachineApplicable`, change it
76    ///   to `HasPlaceholders`
77    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    /// Same as `hir`, but first walks the span up to the given context. This will result in the
95    /// macro call, rather than the expansion, if the span is from a child context. If the span is
96    /// not from a child context, it will be used directly instead.
97    ///
98    /// e.g. Given the expression `&vec![]`, getting a snippet from the span for `vec![]` as a HIR
99    /// node would result in `box []`. If given the context of the address of expression, this
100    /// function will correctly get a snippet of `vec![]`.
101    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    /// Generate a suggestion for an expression with the given snippet. This is used by the `hir_*`
129    /// function variants of `Sugg`, since these use different snippet functions.
130    fn hir_from_snippet(
131        cx: &LateContext<'_>,
132        expr: &hir::Expr<'_>,
133        mut get_snippet: impl FnMut(Span) -> Cow<'a, str>,
134    ) -> Self {
135        if let Some(range) = higher::Range::hir(cx, expr) {
136            let op = AssocOp::Range(range.limits);
137            let start = range.start.map_or("".into(), |expr| get_snippet(expr.span));
138            let end = range.end.map_or("".into(), |expr| get_snippet(expr.span));
139
140            return Sugg::BinOp(op, start, end);
141        }
142
143        match expr.kind {
144            ExprKind::AddrOf(..)
145            | ExprKind::If(..)
146            | ExprKind::Let(..)
147            | ExprKind::Closure { .. }
148            | ExprKind::Unary(..)
149            | ExprKind::Match(..) => Sugg::MaybeParen(get_snippet(expr.span)),
150            ExprKind::Continue(..)
151            | ExprKind::Yield(..)
152            | ExprKind::Array(..)
153            | ExprKind::Block(..)
154            | ExprKind::Break(..)
155            | ExprKind::Call(..)
156            | ExprKind::Field(..)
157            | ExprKind::Index(..)
158            | ExprKind::InlineAsm(..)
159            | ExprKind::OffsetOf(..)
160            | ExprKind::ConstBlock(..)
161            | ExprKind::Lit(..)
162            | ExprKind::Loop(..)
163            | ExprKind::MethodCall(..)
164            | ExprKind::Path(..)
165            | ExprKind::Repeat(..)
166            | ExprKind::Ret(..)
167            | ExprKind::Become(..)
168            | ExprKind::Struct(..)
169            | ExprKind::Tup(..)
170            | ExprKind::Use(..)
171            | ExprKind::Err(_)
172            | ExprKind::UnsafeBinderCast(..) => Sugg::NonParen(get_snippet(expr.span)),
173            ExprKind::DropTemps(inner) => Self::hir_from_snippet(cx, inner, get_snippet),
174            ExprKind::Assign(lhs, rhs, _) => {
175                Sugg::BinOp(AssocOp::Assign, get_snippet(lhs.span), get_snippet(rhs.span))
176            },
177            ExprKind::AssignOp(op, lhs, rhs) => {
178                Sugg::BinOp(AssocOp::AssignOp(op.node), get_snippet(lhs.span), get_snippet(rhs.span))
179            },
180            ExprKind::Binary(op, lhs, rhs) => Sugg::BinOp(
181                AssocOp::Binary(op.node),
182                get_snippet(lhs.span),
183                get_snippet(rhs.span),
184            ),
185            ExprKind::Cast(lhs, ty) |
186            //FIXME(chenyukang), remove this after type ascription is removed from AST
187            ExprKind::Type(lhs, ty) => Sugg::BinOp(AssocOp::Cast, get_snippet(lhs.span), get_snippet(ty.span)),
188        }
189    }
190
191    /// Prepare a suggestion from an expression.
192    pub fn ast(
193        cx: &EarlyContext<'_>,
194        expr: &ast::Expr,
195        default: &'a str,
196        ctxt: SyntaxContext,
197        app: &mut Applicability,
198    ) -> Self {
199        let mut snippet = |span: Span| snippet_with_context(cx, span, ctxt, default, app).0;
200
201        match expr.kind {
202            _ if expr.span.ctxt() != ctxt => Sugg::NonParen(snippet(expr.span)),
203            ast::ExprKind::AddrOf(..)
204            | ast::ExprKind::Closure { .. }
205            | ast::ExprKind::If(..)
206            | ast::ExprKind::Let(..)
207            | ast::ExprKind::Unary(..)
208            | ast::ExprKind::Match(..) => match snippet_with_context(cx, expr.span, ctxt, default, app) {
209                (snip, false) => Sugg::MaybeParen(snip),
210                (snip, true) => Sugg::NonParen(snip),
211            },
212            ast::ExprKind::Gen(..)
213            | ast::ExprKind::Block(..)
214            | ast::ExprKind::Break(..)
215            | ast::ExprKind::Call(..)
216            | ast::ExprKind::Continue(..)
217            | ast::ExprKind::Yield(..)
218            | ast::ExprKind::Field(..)
219            | ast::ExprKind::ForLoop { .. }
220            | ast::ExprKind::Index(..)
221            | ast::ExprKind::InlineAsm(..)
222            | ast::ExprKind::OffsetOf(..)
223            | ast::ExprKind::ConstBlock(..)
224            | ast::ExprKind::Lit(..)
225            | ast::ExprKind::IncludedBytes(..)
226            | ast::ExprKind::Loop(..)
227            | ast::ExprKind::MacCall(..)
228            | ast::ExprKind::MethodCall(..)
229            | ast::ExprKind::Paren(..)
230            | ast::ExprKind::Underscore
231            | ast::ExprKind::Path(..)
232            | ast::ExprKind::Repeat(..)
233            | ast::ExprKind::Ret(..)
234            | ast::ExprKind::Become(..)
235            | ast::ExprKind::Yeet(..)
236            | ast::ExprKind::FormatArgs(..)
237            | ast::ExprKind::Struct(..)
238            | ast::ExprKind::Try(..)
239            | ast::ExprKind::TryBlock(..)
240            | ast::ExprKind::Tup(..)
241            | ast::ExprKind::Use(..)
242            | ast::ExprKind::Array(..)
243            | ast::ExprKind::While(..)
244            | ast::ExprKind::Await(..)
245            | ast::ExprKind::Err(_)
246            | ast::ExprKind::Dummy
247            | ast::ExprKind::UnsafeBinderCast(..) => Sugg::NonParen(snippet(expr.span)),
248            ast::ExprKind::Range(ref lhs, ref rhs, limits) => Sugg::BinOp(
249                AssocOp::Range(limits),
250                lhs.as_ref().map_or("".into(), |lhs| snippet(lhs.span)),
251                rhs.as_ref().map_or("".into(), |rhs| snippet(rhs.span)),
252            ),
253            ast::ExprKind::Assign(ref lhs, ref rhs, _) => Sugg::BinOp(
254                AssocOp::Assign,
255                snippet(lhs.span),
256                snippet(rhs.span),
257            ),
258            ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => Sugg::BinOp(
259                AssocOp::AssignOp(op.node),
260                snippet(lhs.span),
261                snippet(rhs.span),
262            ),
263            ast::ExprKind::Binary(op, ref lhs, ref rhs) => Sugg::BinOp(
264                AssocOp::Binary(op.node),
265                snippet(lhs.span),
266                snippet(rhs.span),
267            ),
268            ast::ExprKind::Cast(ref lhs, ref ty) |
269            //FIXME(chenyukang), remove this after type ascription is removed from AST
270            ast::ExprKind::Type(ref lhs, ref ty) => Sugg::BinOp(
271                AssocOp::Cast,
272                snippet(lhs.span),
273                snippet(ty.span),
274            ),
275        }
276    }
277
278    /// Convenience method to create the `<lhs> && <rhs>` suggestion.
279    pub fn and(self, rhs: &Self) -> Sugg<'static> {
280        make_binop(ast::BinOpKind::And, &self, rhs)
281    }
282
283    /// Convenience method to create the `<lhs> & <rhs>` suggestion.
284    pub fn bit_and(self, rhs: &Self) -> Sugg<'static> {
285        make_binop(ast::BinOpKind::BitAnd, &self, rhs)
286    }
287
288    /// Convenience method to create the `<lhs> as <rhs>` suggestion.
289    pub fn as_ty<R: Display>(self, rhs: R) -> Sugg<'static> {
290        make_assoc(AssocOp::Cast, &self, &Sugg::NonParen(rhs.to_string().into()))
291    }
292
293    /// Convenience method to create the `&<expr>` suggestion.
294    pub fn addr(self) -> Sugg<'static> {
295        make_unop("&", self)
296    }
297
298    /// Convenience method to create the `&mut <expr>` suggestion.
299    pub fn mut_addr(self) -> Sugg<'static> {
300        make_unop("&mut ", self)
301    }
302
303    /// Convenience method to create the `*<expr>` suggestion.
304    pub fn deref(self) -> Sugg<'static> {
305        make_unop("*", self)
306    }
307
308    /// Convenience method to create the `&*<expr>` suggestion. Currently this
309    /// is needed because `sugg.deref().addr()` produces an unnecessary set of
310    /// parentheses around the deref.
311    pub fn addr_deref(self) -> Sugg<'static> {
312        make_unop("&*", self)
313    }
314
315    /// Convenience method to create the `&mut *<expr>` suggestion. Currently
316    /// this is needed because `sugg.deref().mut_addr()` produces an unnecessary
317    /// set of parentheses around the deref.
318    pub fn mut_addr_deref(self) -> Sugg<'static> {
319        make_unop("&mut *", self)
320    }
321
322    /// Convenience method to transform suggestion into a return call
323    pub fn make_return(self) -> Sugg<'static> {
324        Sugg::NonParen(Cow::Owned(format!("return {self}")))
325    }
326
327    /// Convenience method to transform suggestion into a block
328    /// where the suggestion is a trailing expression
329    pub fn blockify(self) -> Sugg<'static> {
330        Sugg::NonParen(Cow::Owned(format!("{{ {self} }}")))
331    }
332
333    /// Convenience method to prefix the expression with the `async` keyword.
334    /// Can be used after `blockify` to create an async block.
335    pub fn asyncify(self) -> Sugg<'static> {
336        Sugg::NonParen(Cow::Owned(format!("async {self}")))
337    }
338
339    /// Convenience method to create the `<lhs>..<rhs>` or `<lhs>...<rhs>`
340    /// suggestion.
341    pub fn range(self, end: &Self, limits: ast::RangeLimits) -> Sugg<'static> {
342        make_assoc(AssocOp::Range(limits), &self, end)
343    }
344
345    /// Adds parentheses to any expression that might need them. Suitable to the
346    /// `self` argument of a method call
347    /// (e.g., to build `bar.foo()` or `(1 + 2).foo()`).
348    #[must_use]
349    pub fn maybe_paren(self) -> Self {
350        match self {
351            Sugg::NonParen(..) => self,
352            // `(x)` and `(x).y()` both don't need additional parens.
353            Sugg::MaybeParen(sugg) => {
354                if has_enclosing_paren(&sugg) {
355                    Sugg::MaybeParen(sugg)
356                } else {
357                    Sugg::NonParen(format!("({sugg})").into())
358                }
359            },
360            Sugg::BinOp(op, lhs, rhs) => {
361                let sugg = binop_to_string(op, &lhs, &rhs);
362                Sugg::NonParen(format!("({sugg})").into())
363            },
364            Sugg::UnOp(op, inner) => Sugg::NonParen(format!("({}{})", op.as_str(), inner.maybe_inner_paren()).into()),
365        }
366    }
367
368    pub fn into_string(self) -> String {
369        match self {
370            Sugg::NonParen(p) | Sugg::MaybeParen(p) => p.into_owned(),
371            Sugg::BinOp(b, l, r) => binop_to_string(b, &l, &r),
372            Sugg::UnOp(op, inner) => format!("{}{}", op.as_str(), inner.maybe_inner_paren()),
373        }
374    }
375
376    /// Checks if `self` starts with a unary operator.
377    fn starts_with_unary_op(&self) -> bool {
378        match self {
379            Sugg::UnOp(..) => true,
380            Sugg::BinOp(..) => false,
381            Sugg::MaybeParen(s) | Sugg::NonParen(s) => s.starts_with(['*', '!', '-', '&']),
382        }
383    }
384
385    /// Call `maybe_paren` on `self` if it doesn't start with a unary operator,
386    /// don't touch it otherwise.
387    fn maybe_inner_paren(self) -> Self {
388        if self.starts_with_unary_op() {
389            self
390        } else {
391            self.maybe_paren()
392        }
393    }
394}
395
396/// Generates a string from the operator and both sides.
397fn binop_to_string(op: AssocOp, lhs: &str, rhs: &str) -> String {
398    match op {
399        AssocOp::Binary(op) => format!("{lhs} {} {rhs}", op.as_str()),
400        AssocOp::Assign => format!("{lhs} = {rhs}"),
401        AssocOp::AssignOp(op) => format!("{lhs} {} {rhs}", op.as_str()),
402        AssocOp::Cast => format!("{lhs} as {rhs}"),
403        AssocOp::Range(limits) => format!("{lhs}{}{rhs}", limits.as_str()),
404    }
405}
406
407/// Returns `true` if `sugg` is enclosed in parenthesis.
408pub fn has_enclosing_paren(sugg: impl AsRef<str>) -> bool {
409    let mut chars = sugg.as_ref().chars();
410    if chars.next() == Some('(') {
411        let mut depth = 1;
412        for c in &mut chars {
413            if c == '(' {
414                depth += 1;
415            } else if c == ')' {
416                depth -= 1;
417            }
418            if depth == 0 {
419                break;
420            }
421        }
422        chars.next().is_none()
423    } else {
424        false
425    }
426}
427
428/// Copied from the rust standard library, and then edited
429macro_rules! forward_binop_impls_to_ref {
430    (impl $imp:ident, $method:ident for $t:ty, type Output = $o:ty) => {
431        impl $imp<$t> for &$t {
432            type Output = $o;
433
434            fn $method(self, other: $t) -> $o {
435                $imp::$method(self, &other)
436            }
437        }
438
439        impl $imp<&$t> for $t {
440            type Output = $o;
441
442            fn $method(self, other: &$t) -> $o {
443                $imp::$method(&self, other)
444            }
445        }
446
447        impl $imp for $t {
448            type Output = $o;
449
450            fn $method(self, other: $t) -> $o {
451                $imp::$method(&self, &other)
452            }
453        }
454    };
455}
456
457impl Add for &Sugg<'_> {
458    type Output = Sugg<'static>;
459    fn add(self, rhs: &Sugg<'_>) -> Sugg<'static> {
460        make_binop(ast::BinOpKind::Add, self, rhs)
461    }
462}
463
464impl Sub for &Sugg<'_> {
465    type Output = Sugg<'static>;
466    fn sub(self, rhs: &Sugg<'_>) -> Sugg<'static> {
467        make_binop(ast::BinOpKind::Sub, self, rhs)
468    }
469}
470
471forward_binop_impls_to_ref!(impl Add, add for Sugg<'_>, type Output = Sugg<'static>);
472forward_binop_impls_to_ref!(impl Sub, sub for Sugg<'_>, type Output = Sugg<'static>);
473
474impl<'a> Neg for Sugg<'a> {
475    type Output = Sugg<'a>;
476    fn neg(self) -> Self::Output {
477        match self {
478            Self::UnOp(UnOp::Neg, sugg) => *sugg,
479            Self::BinOp(AssocOp::Cast, ..) => Sugg::MaybeParen(format!("-({self})").into()),
480            _ => make_unop("-", self),
481        }
482    }
483}
484
485impl<'a> Not for Sugg<'a> {
486    type Output = Sugg<'a>;
487    fn not(self) -> Sugg<'a> {
488        use AssocOp::Binary;
489        use ast::BinOpKind::{Eq, Ge, Gt, Le, Lt, Ne};
490
491        match self {
492            Sugg::BinOp(op, lhs, rhs) => {
493                let to_op = match op {
494                    Binary(Eq) => Binary(Ne),
495                    Binary(Ne) => Binary(Eq),
496                    Binary(Lt) => Binary(Ge),
497                    Binary(Ge) => Binary(Lt),
498                    Binary(Gt) => Binary(Le),
499                    Binary(Le) => Binary(Gt),
500                    _ => return make_unop("!", Sugg::BinOp(op, lhs, rhs)),
501                };
502                Sugg::BinOp(to_op, lhs, rhs)
503            },
504            Sugg::UnOp(UnOp::Not, expr) => *expr,
505            _ => make_unop("!", self),
506        }
507    }
508}
509
510/// Helper type to display either `foo` or `(foo)`.
511struct ParenHelper<T> {
512    /// `true` if parentheses are needed.
513    paren: bool,
514    /// The main thing to display.
515    wrapped: T,
516}
517
518impl<T> ParenHelper<T> {
519    /// Builds a `ParenHelper`.
520    fn new(paren: bool, wrapped: T) -> Self {
521        Self { paren, wrapped }
522    }
523}
524
525impl<T: Display> Display for ParenHelper<T> {
526    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
527        if self.paren {
528            write!(f, "({})", self.wrapped)
529        } else {
530            self.wrapped.fmt(f)
531        }
532    }
533}
534
535/// Builds the string for `<op><expr>` adding parenthesis when necessary.
536///
537/// For convenience, the operator is taken as a string because all unary
538/// operators have the same precedence.
539pub fn make_unop(op: &str, expr: Sugg<'_>) -> Sugg<'static> {
540    // If the `expr` starts with a unary operator already, do not wrap it in
541    // parentheses.
542    Sugg::MaybeParen(format!("{op}{}", expr.maybe_inner_paren()).into())
543}
544
545/// Builds the string for `<lhs> <op> <rhs>` adding parenthesis when necessary.
546///
547/// Precedence of shift operator relative to other arithmetic operation is
548/// often confusing so
549/// parenthesis will always be added for a mix of these.
550pub fn make_assoc(op: AssocOp, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
551    /// Returns `true` if the operator is a shift operator `<<` or `>>`.
552    fn is_shift(op: AssocOp) -> bool {
553        matches!(op, AssocOp::Binary(ast::BinOpKind::Shl | ast::BinOpKind::Shr))
554    }
555
556    /// Returns `true` if the operator is an arithmetic operator
557    /// (i.e., `+`, `-`, `*`, `/`, `%`).
558    fn is_arith(op: AssocOp) -> bool {
559        matches!(
560            op,
561            AssocOp::Binary(
562                ast::BinOpKind::Add
563                    | ast::BinOpKind::Sub
564                    | ast::BinOpKind::Mul
565                    | ast::BinOpKind::Div
566                    | ast::BinOpKind::Rem
567            )
568        )
569    }
570
571    /// Returns `true` if the operator `op` needs parenthesis with the operator
572    /// `other` in the direction `dir`.
573    fn needs_paren(op: AssocOp, other: AssocOp, dir: Associativity) -> bool {
574        other.precedence() < op.precedence()
575            || (other.precedence() == op.precedence()
576                && ((op != other && associativity(op) != dir)
577                    || (op == other && associativity(op) != Associativity::Both)))
578            || is_shift(op) && is_arith(other)
579            || is_shift(other) && is_arith(op)
580    }
581
582    let lhs_paren = if let Sugg::BinOp(lop, _, _) = *lhs {
583        needs_paren(op, lop, Associativity::Left)
584    } else {
585        false
586    };
587
588    let rhs_paren = if let Sugg::BinOp(rop, _, _) = *rhs {
589        needs_paren(op, rop, Associativity::Right)
590    } else {
591        false
592    };
593
594    let lhs = ParenHelper::new(lhs_paren, lhs).to_string();
595    let rhs = ParenHelper::new(rhs_paren, rhs).to_string();
596    Sugg::BinOp(op, lhs.into(), rhs.into())
597}
598
599/// Convenience wrapper around `make_assoc` and `AssocOp::Binary`.
600pub fn make_binop(op: ast::BinOpKind, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
601    make_assoc(AssocOp::Binary(op), lhs, rhs)
602}
603
604#[derive(PartialEq, Eq, Clone, Copy)]
605/// Operator associativity.
606enum Associativity {
607    /// The operator is both left-associative and right-associative.
608    Both,
609    /// The operator is left-associative.
610    Left,
611    /// The operator is not associative.
612    None,
613    /// The operator is right-associative.
614    Right,
615}
616
617/// Returns the associativity/fixity of an operator. The difference with
618/// `AssocOp::fixity` is that an operator can be both left and right associative
619/// (such as `+`: `a + b + c == (a + b) + c == a + (b + c)`.
620///
621/// Chained `as` and explicit `:` type coercion never need inner parenthesis so
622/// they are considered
623/// associative.
624#[must_use]
625fn associativity(op: AssocOp) -> Associativity {
626    use ast::BinOpKind::{Add, And, BitAnd, BitOr, BitXor, Div, Eq, Ge, Gt, Le, Lt, Mul, Ne, Or, Rem, Shl, Shr, Sub};
627    use rustc_ast::util::parser::AssocOp::{Assign, AssignOp, Binary, Cast, Range};
628
629    match op {
630        Assign | AssignOp(_) => Associativity::Right,
631        Binary(Add | BitAnd | BitOr | BitXor | And | Or | Mul) | Cast => Associativity::Both,
632        Binary(Div | Eq | Gt | Ge | Lt | Le | Rem | Ne | Shl | Shr | Sub) => Associativity::Left,
633        Range(_) => Associativity::None,
634    }
635}
636
637/// Returns the indentation before `span` if there are nothing but `[ \t]`
638/// before it on its line.
639fn indentation<T: LintContext>(cx: &T, span: Span) -> Option<String> {
640    let lo = cx.sess().source_map().lookup_char_pos(span.lo());
641    lo.file
642        .get_line(lo.line - 1 /* line numbers in `Loc` are 1-based */)
643        .and_then(|line| {
644            if let Some((pos, _)) = line.char_indices().find(|&(_, c)| c != ' ' && c != '\t') {
645                // We can mix char and byte positions here because we only consider `[ \t]`.
646                if lo.col == CharPos(pos) {
647                    Some(line[..pos].into())
648                } else {
649                    None
650                }
651            } else {
652                None
653            }
654        })
655}
656
657/// Convenience extension trait for `Diag`.
658pub trait DiagExt<T: LintContext> {
659    /// Suggests to add an attribute to an item.
660    ///
661    /// Correctly handles indentation of the attribute and item.
662    ///
663    /// # Example
664    ///
665    /// ```rust,ignore
666    /// diag.suggest_item_with_attr(cx, item, "#[derive(Default)]");
667    /// ```
668    fn suggest_item_with_attr<D: Display + ?Sized>(
669        &mut self,
670        cx: &T,
671        item: Span,
672        msg: &str,
673        attr: &D,
674        applicability: Applicability,
675    );
676
677    /// Suggest to add an item before another.
678    ///
679    /// The item should not be indented (except for inner indentation).
680    ///
681    /// # Example
682    ///
683    /// ```rust,ignore
684    /// diag.suggest_prepend_item(cx, item,
685    /// "fn foo() {
686    ///     bar();
687    /// }");
688    /// ```
689    fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability);
690
691    /// Suggest to completely remove an item.
692    ///
693    /// This will remove an item and all following whitespace until the next non-whitespace
694    /// character. This should work correctly if item is on the same indentation level as the
695    /// following item.
696    ///
697    /// # Example
698    ///
699    /// ```rust,ignore
700    /// diag.suggest_remove_item(cx, item, "remove this")
701    /// ```
702    fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability);
703}
704
705impl<T: LintContext> DiagExt<T> for rustc_errors::Diag<'_, ()> {
706    fn suggest_item_with_attr<D: Display + ?Sized>(
707        &mut self,
708        cx: &T,
709        item: Span,
710        msg: &str,
711        attr: &D,
712        applicability: Applicability,
713    ) {
714        if let Some(indent) = indentation(cx, item) {
715            let span = item.with_hi(item.lo());
716
717            self.span_suggestion(span, msg.to_string(), format!("{attr}\n{indent}"), applicability);
718        }
719    }
720
721    fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability) {
722        if let Some(indent) = indentation(cx, item) {
723            let span = item.with_hi(item.lo());
724
725            let mut first = true;
726            let new_item = new_item
727                .lines()
728                .map(|l| {
729                    if first {
730                        first = false;
731                        format!("{l}\n")
732                    } else {
733                        format!("{indent}{l}\n")
734                    }
735                })
736                .collect::<String>();
737
738            self.span_suggestion(span, msg.to_string(), format!("{new_item}\n{indent}"), applicability);
739        }
740    }
741
742    fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability) {
743        let mut remove_span = item;
744        let fmpos = cx.sess().source_map().lookup_byte_offset(remove_span.hi());
745
746        if let Some(ref src) = fmpos.sf.src {
747            let non_whitespace_offset = src[fmpos.pos.to_usize()..].find(|c| c != ' ' && c != '\t' && c != '\n');
748
749            if let Some(non_whitespace_offset) = non_whitespace_offset {
750                remove_span = remove_span
751                    .with_hi(remove_span.hi() + BytePos(non_whitespace_offset.try_into().expect("offset too large")));
752            }
753        }
754
755        self.span_suggestion(remove_span, msg.to_string(), "", applicability);
756    }
757}
758
759/// Suggestion results for handling closure
760/// args dereferencing and borrowing
761pub struct DerefClosure {
762    /// confidence on the built suggestion
763    pub applicability: Applicability,
764    /// gradually built suggestion
765    pub suggestion: String,
766}
767
768/// Build suggestion gradually by handling closure arg specific usages,
769/// such as explicit deref and borrowing cases.
770/// Returns `None` if no such use cases have been triggered in closure body
771///
772/// note: This only works on immutable closures with exactly one input parameter.
773pub fn deref_closure_args(cx: &LateContext<'_>, closure: &hir::Expr<'_>) -> Option<DerefClosure> {
774    if let ExprKind::Closure(&Closure {
775        fn_decl, def_id, body, ..
776    }) = closure.kind
777    {
778        let closure_body = cx.tcx.hir_body(body);
779        // is closure arg a type annotated double reference (i.e.: `|x: &&i32| ...`)
780        // a type annotation is present if param `kind` is different from `TyKind::Infer`
781        let closure_arg_is_type_annotated_double_ref = if let TyKind::Ref(_, MutTy { ty, .. }) = fn_decl.inputs[0].kind
782        {
783            matches!(ty.kind, TyKind::Ref(_, MutTy { .. }))
784        } else {
785            false
786        };
787
788        let mut visitor = DerefDelegate {
789            cx,
790            closure_span: closure.span,
791            closure_arg_id: closure_body.params[0].pat.hir_id,
792            closure_arg_is_type_annotated_double_ref,
793            next_pos: closure.span.lo(),
794            checked_borrows: FxHashSet::default(),
795            suggestion_start: String::new(),
796            applicability: Applicability::MachineApplicable,
797        };
798
799        ExprUseVisitor::for_clippy(cx, def_id, &mut visitor)
800            .consume_body(closure_body)
801            .into_ok();
802
803        if !visitor.suggestion_start.is_empty() {
804            return Some(DerefClosure {
805                applicability: visitor.applicability,
806                suggestion: visitor.finish(),
807            });
808        }
809    }
810    None
811}
812
813/// Visitor struct used for tracking down
814/// dereferencing and borrowing of closure's args
815struct DerefDelegate<'a, 'tcx> {
816    /// The late context of the lint
817    cx: &'a LateContext<'tcx>,
818    /// The span of the input closure to adapt
819    closure_span: Span,
820    /// The `hir_id` of the closure argument being checked
821    closure_arg_id: HirId,
822    /// Indicates if the arg of the closure is a type annotated double reference
823    closure_arg_is_type_annotated_double_ref: bool,
824    /// last position of the span to gradually build the suggestion
825    next_pos: BytePos,
826    /// `hir_id`s that has been checked. This is used to avoid checking the same `hir_id` multiple
827    /// times when inside macro expansions.
828    checked_borrows: FxHashSet<HirId>,
829    /// starting part of the gradually built suggestion
830    suggestion_start: String,
831    /// confidence on the built suggestion
832    applicability: Applicability,
833}
834
835impl<'tcx> DerefDelegate<'_, 'tcx> {
836    /// build final suggestion:
837    /// - create the ending part of suggestion
838    /// - concatenate starting and ending parts
839    /// - potentially remove needless borrowing
840    pub fn finish(&mut self) -> String {
841        let end_span = Span::new(self.next_pos, self.closure_span.hi(), self.closure_span.ctxt(), None);
842        let end_snip = snippet_with_applicability(self.cx, end_span, "..", &mut self.applicability);
843        let sugg = format!("{}{end_snip}", self.suggestion_start);
844        if self.closure_arg_is_type_annotated_double_ref {
845            sugg.replacen('&', "", 1)
846        } else {
847            sugg
848        }
849    }
850
851    /// indicates whether the function from `parent_expr` takes its args by double reference
852    fn func_takes_arg_by_double_ref(&self, parent_expr: &'tcx hir::Expr<'_>, cmt_hir_id: HirId) -> bool {
853        let ty = match parent_expr.kind {
854            ExprKind::MethodCall(_, receiver, call_args, _) => {
855                if let Some(sig) = self
856                    .cx
857                    .typeck_results()
858                    .type_dependent_def_id(parent_expr.hir_id)
859                    .map(|did| self.cx.tcx.fn_sig(did).instantiate_identity().skip_binder())
860                {
861                    std::iter::once(receiver)
862                        .chain(call_args.iter())
863                        .position(|arg| arg.hir_id == cmt_hir_id)
864                        .map(|i| sig.inputs()[i])
865                } else {
866                    return false;
867                }
868            },
869            ExprKind::Call(func, call_args) => {
870                if let Some(sig) = expr_sig(self.cx, func) {
871                    call_args
872                        .iter()
873                        .position(|arg| arg.hir_id == cmt_hir_id)
874                        .and_then(|i| sig.input(i))
875                        .map(ty::Binder::skip_binder)
876                } else {
877                    return false;
878                }
879            },
880            _ => return false,
881        };
882
883        ty.is_some_and(|ty| matches!(ty.kind(), ty::Ref(_, inner, _) if inner.is_ref()))
884    }
885}
886
887impl<'tcx> Delegate<'tcx> for DerefDelegate<'_, 'tcx> {
888    fn consume(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
889
890    fn use_cloned(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
891
892    #[expect(clippy::too_many_lines)]
893    fn borrow(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId, _: ty::BorrowKind) {
894        if let PlaceBase::Local(id) = cmt.place.base {
895            let span = self.cx.tcx.hir_span(cmt.hir_id);
896            if !self.checked_borrows.insert(cmt.hir_id) {
897                // already checked this span and hir_id, skip
898                return;
899            }
900
901            let start_span = Span::new(self.next_pos, span.lo(), span.ctxt(), None);
902            let mut start_snip = snippet_with_applicability(self.cx, start_span, "..", &mut self.applicability);
903
904            // identifier referring to the variable currently triggered (i.e.: `fp`)
905            let ident_str = self.cx.tcx.hir_name(id).to_string();
906            // full identifier that includes projection (i.e.: `fp.field`)
907            let ident_str_with_proj = snippet(self.cx, span, "..").to_string();
908
909            // Make sure to get in all projections if we're on a `matches!`
910            if let Node::Pat(pat) = self.cx.tcx.hir_node(id)
911                && pat.hir_id != self.closure_arg_id
912            {
913                let _ = write!(self.suggestion_start, "{start_snip}{ident_str_with_proj}");
914            } else if cmt.place.projections.is_empty() {
915                // handle item without any projection, that needs an explicit borrowing
916                // i.e.: suggest `&x` instead of `x`
917                let _: fmt::Result = write!(self.suggestion_start, "{start_snip}&{ident_str}");
918            } else {
919                // cases where a parent `Call` or `MethodCall` is using the item
920                // i.e.: suggest `.contains(&x)` for `.find(|x| [1, 2, 3].contains(x)).is_none()`
921                //
922                // Note about method calls:
923                // - compiler automatically dereference references if the target type is a reference (works also for
924                //   function call)
925                // - `self` arguments in the case of `x.is_something()` are also automatically (de)referenced, and
926                //   no projection should be suggested
927                if let Some(parent_expr) = get_parent_expr_for_hir(self.cx, cmt.hir_id) {
928                    match &parent_expr.kind {
929                        // given expression is the self argument and will be handled completely by the compiler
930                        // i.e.: `|x| x.is_something()`
931                        ExprKind::MethodCall(_, self_expr, ..) if self_expr.hir_id == cmt.hir_id => {
932                            let _: fmt::Result = write!(self.suggestion_start, "{start_snip}{ident_str_with_proj}");
933                            self.next_pos = span.hi();
934                            return;
935                        },
936                        // item is used in a call
937                        // i.e.: `Call`: `|x| please(x)` or `MethodCall`: `|x| [1, 2, 3].contains(x)`
938                        ExprKind::Call(_, call_args) | ExprKind::MethodCall(_, _, call_args, _) => {
939                            let expr = self.cx.tcx.hir_expect_expr(cmt.hir_id);
940                            let arg_ty_kind = self.cx.typeck_results().expr_ty(expr).kind();
941
942                            if matches!(arg_ty_kind, ty::Ref(_, _, Mutability::Not)) {
943                                // suggest ampersand if call function is taking args by double reference
944                                let takes_arg_by_double_ref =
945                                    self.func_takes_arg_by_double_ref(parent_expr, cmt.hir_id);
946
947                                // compiler will automatically dereference field or index projection, so no need
948                                // to suggest ampersand, but full identifier that includes projection is required
949                                let has_field_or_index_projection =
950                                    cmt.place.projections.iter().any(|proj| {
951                                        matches!(proj.kind, ProjectionKind::Field(..) | ProjectionKind::Index)
952                                    });
953
954                                // no need to bind again if the function doesn't take arg by double ref
955                                // and if the item is already a double ref
956                                let ident_sugg = if !call_args.is_empty()
957                                    && !takes_arg_by_double_ref
958                                    && (self.closure_arg_is_type_annotated_double_ref || has_field_or_index_projection)
959                                {
960                                    let ident = if has_field_or_index_projection {
961                                        ident_str_with_proj
962                                    } else {
963                                        ident_str
964                                    };
965                                    format!("{start_snip}{ident}")
966                                } else {
967                                    format!("{start_snip}&{ident_str}")
968                                };
969                                self.suggestion_start.push_str(&ident_sugg);
970                                self.next_pos = span.hi();
971                                return;
972                            }
973
974                            self.applicability = Applicability::Unspecified;
975                        },
976                        _ => (),
977                    }
978                }
979
980                let mut replacement_str = ident_str;
981                let mut projections_handled = false;
982                cmt.place.projections.iter().enumerate().for_each(|(i, proj)| {
983                    match proj.kind {
984                        // Field projection like `|v| v.foo`
985                        // no adjustment needed here, as field projections are handled by the compiler
986                        ProjectionKind::Field(..) => match cmt.place.ty_before_projection(i).kind() {
987                            ty::Adt(..) | ty::Tuple(_) => {
988                                replacement_str.clone_from(&ident_str_with_proj);
989                                projections_handled = true;
990                            },
991                            _ => (),
992                        },
993                        // Index projection like `|x| foo[x]`
994                        // the index is dropped so we can't get it to build the suggestion,
995                        // so the span is set-up again to get more code, using `span.hi()` (i.e.: `foo[x]`)
996                        // instead of `span.lo()` (i.e.: `foo`)
997                        ProjectionKind::Index => {
998                            let start_span = Span::new(self.next_pos, span.hi(), span.ctxt(), None);
999                            start_snip = snippet_with_applicability(self.cx, start_span, "..", &mut self.applicability);
1000                            replacement_str.clear();
1001                            projections_handled = true;
1002                        },
1003                        // note: unable to trigger `Subslice` kind in tests
1004                        ProjectionKind::Subslice |
1005                        // Doesn't have surface syntax. Only occurs in patterns.
1006                        ProjectionKind::OpaqueCast |
1007                        // Only occurs in closure captures.
1008                        ProjectionKind::UnwrapUnsafeBinder => (),
1009                        ProjectionKind::Deref => {
1010                            // Explicit derefs are typically handled later on, but
1011                            // some items do not need explicit deref, such as array accesses,
1012                            // so we mark them as already processed
1013                            // i.e.: don't suggest `*sub[1..4].len()` for `|sub| sub[1..4].len() == 3`
1014                            if let ty::Ref(_, inner, _) = cmt.place.ty_before_projection(i).kind()
1015                                && matches!(inner.kind(), ty::Ref(_, innermost, _) if innermost.is_array()) {
1016                                projections_handled = true;
1017                            }
1018                        },
1019                    }
1020                });
1021
1022                // handle `ProjectionKind::Deref` by removing one explicit deref
1023                // if no special case was detected (i.e.: suggest `*x` instead of `**x`)
1024                if !projections_handled {
1025                    let last_deref = cmt
1026                        .place
1027                        .projections
1028                        .iter()
1029                        .rposition(|proj| proj.kind == ProjectionKind::Deref);
1030
1031                    if let Some(pos) = last_deref {
1032                        let mut projections = cmt.place.projections.clone();
1033                        projections.truncate(pos);
1034
1035                        for item in projections {
1036                            if item.kind == ProjectionKind::Deref {
1037                                replacement_str = format!("*{replacement_str}");
1038                            }
1039                        }
1040                    }
1041                }
1042
1043                let _: fmt::Result = write!(self.suggestion_start, "{start_snip}{replacement_str}");
1044            }
1045            self.next_pos = span.hi();
1046        }
1047    }
1048
1049    fn mutate(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
1050
1051    fn fake_read(&mut self, _: &PlaceWithHirId<'tcx>, _: FakeReadCause, _: HirId) {}
1052}
1053
1054#[cfg(test)]
1055mod test {
1056    use super::Sugg;
1057
1058    use rustc_ast as ast;
1059    use rustc_ast::util::parser::AssocOp;
1060    use std::borrow::Cow;
1061
1062    const SUGGESTION: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("function_call()"));
1063
1064    #[test]
1065    fn make_return_transform_sugg_into_a_return_call() {
1066        assert_eq!("return function_call()", SUGGESTION.make_return().to_string());
1067    }
1068
1069    #[test]
1070    fn blockify_transforms_sugg_into_a_block() {
1071        assert_eq!("{ function_call() }", SUGGESTION.blockify().to_string());
1072    }
1073
1074    #[test]
1075    fn binop_maybe_paren() {
1076        let sugg = Sugg::BinOp(AssocOp::Binary(ast::BinOpKind::Add), "1".into(), "1".into());
1077        assert_eq!("(1 + 1)", sugg.maybe_paren().to_string());
1078
1079        let sugg = Sugg::BinOp(AssocOp::Binary(ast::BinOpKind::Add), "(1 + 1)".into(), "(1 + 1)".into());
1080        assert_eq!("((1 + 1) + (1 + 1))", sugg.maybe_paren().to_string());
1081    }
1082
1083    #[test]
1084    fn unop_parenthesize() {
1085        let sugg = Sugg::NonParen("x".into()).mut_addr();
1086        assert_eq!("&mut x", sugg.to_string());
1087        let sugg = sugg.mut_addr();
1088        assert_eq!("&mut &mut x", sugg.to_string());
1089        assert_eq!("(&mut &mut x)", sugg.maybe_paren().to_string());
1090    }
1091
1092    #[test]
1093    fn not_op() {
1094        use ast::BinOpKind::{Add, And, Eq, Ge, Gt, Le, Lt, Ne, Or};
1095
1096        fn test_not(op: AssocOp, correct: &str) {
1097            let sugg = Sugg::BinOp(op, "x".into(), "y".into());
1098            assert_eq!((!sugg).to_string(), correct);
1099        }
1100
1101        // Invert the comparison operator.
1102        test_not(AssocOp::Binary(Eq), "x != y");
1103        test_not(AssocOp::Binary(Ne), "x == y");
1104        test_not(AssocOp::Binary(Lt), "x >= y");
1105        test_not(AssocOp::Binary(Le), "x > y");
1106        test_not(AssocOp::Binary(Gt), "x <= y");
1107        test_not(AssocOp::Binary(Ge), "x < y");
1108
1109        // Other operators are inverted like !(..).
1110        test_not(AssocOp::Binary(Add), "!(x + y)");
1111        test_not(AssocOp::Binary(And), "!(x && y)");
1112        test_not(AssocOp::Binary(Or), "!(x || y)");
1113    }
1114}