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