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