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