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