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