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