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