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