Skip to main content

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