]> git.lizzy.rs Git - rust.git/blob - clippy_utils/src/sugg.rs
Merge commit '3ae8faff4d46ad92f194c2a4b941c3152a701b31' into clippyup
[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::higher;
5 use crate::source::{snippet, snippet_opt, snippet_with_context, snippet_with_macro_callsite};
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_lint::{EarlyContext, LateContext, LintContext};
12 use rustc_span::source_map::{CharPos, Span};
13 use rustc_span::{BytePos, Pos, SyntaxContext};
14 use std::borrow::Cow;
15 use std::convert::TryInto;
16 use std::fmt::Display;
17 use std::ops::{Add, Neg, Not, Sub};
18
19 /// A helper type to build suggestion correctly handling parenthesis.
20 #[derive(Clone, PartialEq)]
21 pub enum Sugg<'a> {
22     /// An expression that never needs parenthesis such as `1337` or `[0; 42]`.
23     NonParen(Cow<'a, str>),
24     /// An expression that does not fit in other variants.
25     MaybeParen(Cow<'a, str>),
26     /// A binary operator expression, including `as`-casts and explicit type
27     /// coercion.
28     BinOp(AssocOp, Cow<'a, str>),
29 }
30
31 /// Literal constant `0`, for convenience.
32 pub const ZERO: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("0"));
33 /// Literal constant `1`, for convenience.
34 pub const ONE: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("1"));
35 /// a constant represents an empty string, for convenience.
36 pub const EMPTY: Sugg<'static> = Sugg::NonParen(Cow::Borrowed(""));
37
38 impl Display for Sugg<'_> {
39     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
40         match *self {
41             Sugg::NonParen(ref s) | Sugg::MaybeParen(ref s) | Sugg::BinOp(_, ref s) => s.fmt(f),
42         }
43     }
44 }
45
46 #[allow(clippy::wrong_self_convention)] // ok, because of the function `as_ty` method
47 impl<'a> Sugg<'a> {
48     /// Prepare a suggestion from an expression.
49     pub fn hir_opt(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option<Self> {
50         snippet_opt(cx, expr.span).map(|snippet| {
51             let snippet = Cow::Owned(snippet);
52             Self::hir_from_snippet(expr, snippet)
53         })
54     }
55
56     /// Convenience function around `hir_opt` for suggestions with a default
57     /// text.
58     pub fn hir(cx: &LateContext<'_>, expr: &hir::Expr<'_>, default: &'a str) -> Self {
59         Self::hir_opt(cx, expr).unwrap_or(Sugg::NonParen(Cow::Borrowed(default)))
60     }
61
62     /// Same as `hir`, but it adapts the applicability level by following rules:
63     ///
64     /// - Applicability level `Unspecified` will never be changed.
65     /// - If the span is inside a macro, change the applicability level to `MaybeIncorrect`.
66     /// - If the default value is used and the applicability level is `MachineApplicable`, change it
67     ///   to
68     /// `HasPlaceholders`
69     pub fn hir_with_applicability(
70         cx: &LateContext<'_>,
71         expr: &hir::Expr<'_>,
72         default: &'a str,
73         applicability: &mut Applicability,
74     ) -> Self {
75         if *applicability != Applicability::Unspecified && expr.span.from_expansion() {
76             *applicability = Applicability::MaybeIncorrect;
77         }
78         Self::hir_opt(cx, expr).unwrap_or_else(|| {
79             if *applicability == Applicability::MachineApplicable {
80                 *applicability = Applicability::HasPlaceholders;
81             }
82             Sugg::NonParen(Cow::Borrowed(default))
83         })
84     }
85
86     /// Same as `hir`, but will use the pre expansion span if the `expr` was in a macro.
87     pub fn hir_with_macro_callsite(cx: &LateContext<'_>, expr: &hir::Expr<'_>, default: &'a str) -> Self {
88         let snippet = snippet_with_macro_callsite(cx, expr.span, default);
89
90         Self::hir_from_snippet(expr, snippet)
91     }
92
93     /// Same as `hir`, but first walks the span up to the given context. This will result in the
94     /// macro call, rather then the expansion, if the span is from a child context. If the span is
95     /// not from a child context, it will be used directly instead.
96     ///
97     /// e.g. Given the expression `&vec![]`, getting a snippet from the span for `vec![]` as a HIR
98     /// node would result in `box []`. If given the context of the address of expression, this
99     /// function will correctly get a snippet of `vec![]`.
100     pub fn hir_with_context(
101         cx: &LateContext<'_>,
102         expr: &hir::Expr<'_>,
103         ctxt: SyntaxContext,
104         default: &'a str,
105         applicability: &mut Applicability,
106     ) -> Self {
107         let (snippet, in_macro) = snippet_with_context(cx, expr.span, ctxt, default, applicability);
108
109         if in_macro {
110             Sugg::NonParen(snippet)
111         } else {
112             Self::hir_from_snippet(expr, snippet)
113         }
114     }
115
116     /// Generate a suggestion for an expression with the given snippet. This is used by the `hir_*`
117     /// function variants of `Sugg`, since these use different snippet functions.
118     fn hir_from_snippet(expr: &hir::Expr<'_>, snippet: Cow<'a, str>) -> Self {
119         if let Some(range) = higher::range(expr) {
120             let op = match range.limits {
121                 ast::RangeLimits::HalfOpen => AssocOp::DotDot,
122                 ast::RangeLimits::Closed => AssocOp::DotDotEq,
123             };
124             return Sugg::BinOp(op, snippet);
125         }
126
127         match expr.kind {
128             hir::ExprKind::AddrOf(..)
129             | hir::ExprKind::Box(..)
130             | hir::ExprKind::If(..)
131             | hir::ExprKind::Closure(..)
132             | hir::ExprKind::Unary(..)
133             | hir::ExprKind::Match(..) => Sugg::MaybeParen(snippet),
134             hir::ExprKind::Continue(..)
135             | hir::ExprKind::Yield(..)
136             | hir::ExprKind::Array(..)
137             | hir::ExprKind::Block(..)
138             | hir::ExprKind::Break(..)
139             | hir::ExprKind::Call(..)
140             | hir::ExprKind::Field(..)
141             | hir::ExprKind::Index(..)
142             | hir::ExprKind::InlineAsm(..)
143             | hir::ExprKind::LlvmInlineAsm(..)
144             | hir::ExprKind::ConstBlock(..)
145             | hir::ExprKind::Lit(..)
146             | hir::ExprKind::Loop(..)
147             | hir::ExprKind::MethodCall(..)
148             | hir::ExprKind::Path(..)
149             | hir::ExprKind::Repeat(..)
150             | hir::ExprKind::Ret(..)
151             | hir::ExprKind::Struct(..)
152             | hir::ExprKind::Tup(..)
153             | hir::ExprKind::DropTemps(_)
154             | hir::ExprKind::Err => Sugg::NonParen(snippet),
155             hir::ExprKind::Assign(..) => Sugg::BinOp(AssocOp::Assign, snippet),
156             hir::ExprKind::AssignOp(op, ..) => Sugg::BinOp(hirbinop2assignop(op), snippet),
157             hir::ExprKind::Binary(op, ..) => Sugg::BinOp(AssocOp::from_ast_binop(higher::binop(op.node)), snippet),
158             hir::ExprKind::Cast(..) => Sugg::BinOp(AssocOp::As, snippet),
159             hir::ExprKind::Type(..) => Sugg::BinOp(AssocOp::Colon, snippet),
160         }
161     }
162
163     /// Prepare a suggestion from an expression.
164     pub fn ast(cx: &EarlyContext<'_>, expr: &ast::Expr, default: &'a str) -> Self {
165         use rustc_ast::ast::RangeLimits;
166
167         let snippet = if expr.span.from_expansion() {
168             snippet_with_macro_callsite(cx, expr.span, default)
169         } else {
170             snippet(cx, expr.span, default)
171         };
172
173         match expr.kind {
174             ast::ExprKind::AddrOf(..)
175             | ast::ExprKind::Box(..)
176             | ast::ExprKind::Closure(..)
177             | ast::ExprKind::If(..)
178             | ast::ExprKind::Let(..)
179             | ast::ExprKind::Unary(..)
180             | ast::ExprKind::Match(..) => Sugg::MaybeParen(snippet),
181             ast::ExprKind::Async(..)
182             | ast::ExprKind::Block(..)
183             | ast::ExprKind::Break(..)
184             | ast::ExprKind::Call(..)
185             | ast::ExprKind::Continue(..)
186             | ast::ExprKind::Yield(..)
187             | ast::ExprKind::Field(..)
188             | ast::ExprKind::ForLoop(..)
189             | ast::ExprKind::Index(..)
190             | ast::ExprKind::InlineAsm(..)
191             | ast::ExprKind::LlvmInlineAsm(..)
192             | ast::ExprKind::ConstBlock(..)
193             | ast::ExprKind::Lit(..)
194             | ast::ExprKind::Loop(..)
195             | ast::ExprKind::MacCall(..)
196             | ast::ExprKind::MethodCall(..)
197             | ast::ExprKind::Paren(..)
198             | ast::ExprKind::Underscore
199             | ast::ExprKind::Path(..)
200             | ast::ExprKind::Repeat(..)
201             | ast::ExprKind::Ret(..)
202             | ast::ExprKind::Struct(..)
203             | ast::ExprKind::Try(..)
204             | ast::ExprKind::TryBlock(..)
205             | ast::ExprKind::Tup(..)
206             | ast::ExprKind::Array(..)
207             | ast::ExprKind::While(..)
208             | ast::ExprKind::Await(..)
209             | ast::ExprKind::Err => Sugg::NonParen(snippet),
210             ast::ExprKind::Range(.., RangeLimits::HalfOpen) => Sugg::BinOp(AssocOp::DotDot, snippet),
211             ast::ExprKind::Range(.., RangeLimits::Closed) => Sugg::BinOp(AssocOp::DotDotEq, snippet),
212             ast::ExprKind::Assign(..) => Sugg::BinOp(AssocOp::Assign, snippet),
213             ast::ExprKind::AssignOp(op, ..) => Sugg::BinOp(astbinop2assignop(op), snippet),
214             ast::ExprKind::Binary(op, ..) => Sugg::BinOp(AssocOp::from_ast_binop(op.node), snippet),
215             ast::ExprKind::Cast(..) => Sugg::BinOp(AssocOp::As, snippet),
216             ast::ExprKind::Type(..) => Sugg::BinOp(AssocOp::Colon, snippet),
217         }
218     }
219
220     /// Convenience method to create the `<lhs> && <rhs>` suggestion.
221     pub fn and(self, rhs: &Self) -> Sugg<'static> {
222         make_binop(ast::BinOpKind::And, &self, rhs)
223     }
224
225     /// Convenience method to create the `<lhs> & <rhs>` suggestion.
226     pub fn bit_and(self, rhs: &Self) -> Sugg<'static> {
227         make_binop(ast::BinOpKind::BitAnd, &self, rhs)
228     }
229
230     /// Convenience method to create the `<lhs> as <rhs>` suggestion.
231     pub fn as_ty<R: Display>(self, rhs: R) -> Sugg<'static> {
232         make_assoc(AssocOp::As, &self, &Sugg::NonParen(rhs.to_string().into()))
233     }
234
235     /// Convenience method to create the `&<expr>` suggestion.
236     pub fn addr(self) -> Sugg<'static> {
237         make_unop("&", self)
238     }
239
240     /// Convenience method to create the `&mut <expr>` suggestion.
241     pub fn mut_addr(self) -> Sugg<'static> {
242         make_unop("&mut ", self)
243     }
244
245     /// Convenience method to create the `*<expr>` suggestion.
246     pub fn deref(self) -> Sugg<'static> {
247         make_unop("*", self)
248     }
249
250     /// Convenience method to create the `&*<expr>` suggestion. Currently this
251     /// is needed because `sugg.deref().addr()` produces an unnecessary set of
252     /// parentheses around the deref.
253     pub fn addr_deref(self) -> Sugg<'static> {
254         make_unop("&*", self)
255     }
256
257     /// Convenience method to create the `&mut *<expr>` suggestion. Currently
258     /// this is needed because `sugg.deref().mut_addr()` produces an unnecessary
259     /// set of parentheses around the deref.
260     pub fn mut_addr_deref(self) -> Sugg<'static> {
261         make_unop("&mut *", self)
262     }
263
264     /// Convenience method to transform suggestion into a return call
265     pub fn make_return(self) -> Sugg<'static> {
266         Sugg::NonParen(Cow::Owned(format!("return {}", self)))
267     }
268
269     /// Convenience method to transform suggestion into a block
270     /// where the suggestion is a trailing expression
271     pub fn blockify(self) -> Sugg<'static> {
272         Sugg::NonParen(Cow::Owned(format!("{{ {} }}", self)))
273     }
274
275     /// Convenience method to create the `<lhs>..<rhs>` or `<lhs>...<rhs>`
276     /// suggestion.
277     #[allow(dead_code)]
278     pub fn range(self, end: &Self, limit: ast::RangeLimits) -> Sugg<'static> {
279         match limit {
280             ast::RangeLimits::HalfOpen => make_assoc(AssocOp::DotDot, &self, end),
281             ast::RangeLimits::Closed => make_assoc(AssocOp::DotDotEq, &self, end),
282         }
283     }
284
285     /// Adds parenthesis to any expression that might need them. Suitable to the
286     /// `self` argument of a method call
287     /// (e.g., to build `bar.foo()` or `(1 + 2).foo()`).
288     pub fn maybe_par(self) -> Self {
289         match self {
290             Sugg::NonParen(..) => self,
291             // `(x)` and `(x).y()` both don't need additional parens.
292             Sugg::MaybeParen(sugg) => {
293                 if has_enclosing_paren(&sugg) {
294                     Sugg::MaybeParen(sugg)
295                 } else {
296                     Sugg::NonParen(format!("({})", sugg).into())
297                 }
298             },
299             Sugg::BinOp(_, sugg) => {
300                 if has_enclosing_paren(&sugg) {
301                     Sugg::NonParen(sugg)
302                 } else {
303                     Sugg::NonParen(format!("({})", sugg).into())
304                 }
305             },
306         }
307     }
308 }
309
310 /// Return `true` if `sugg` is enclosed in parenthesis.
311 fn has_enclosing_paren(sugg: impl AsRef<str>) -> bool {
312     let mut chars = sugg.as_ref().chars();
313     if let Some('(') = chars.next() {
314         let mut depth = 1;
315         for c in &mut chars {
316             if c == '(' {
317                 depth += 1;
318             } else if c == ')' {
319                 depth -= 1;
320             }
321             if depth == 0 {
322                 break;
323             }
324         }
325         chars.next().is_none()
326     } else {
327         false
328     }
329 }
330
331 // Copied from the rust standart library, and then edited
332 macro_rules! forward_binop_impls_to_ref {
333     (impl $imp:ident, $method:ident for $t:ty, type Output = $o:ty) => {
334         impl $imp<$t> for &$t {
335             type Output = $o;
336
337             fn $method(self, other: $t) -> $o {
338                 $imp::$method(self, &other)
339             }
340         }
341
342         impl $imp<&$t> for $t {
343             type Output = $o;
344
345             fn $method(self, other: &$t) -> $o {
346                 $imp::$method(&self, other)
347             }
348         }
349
350         impl $imp for $t {
351             type Output = $o;
352
353             fn $method(self, other: $t) -> $o {
354                 $imp::$method(&self, &other)
355             }
356         }
357     };
358 }
359
360 impl Add for &Sugg<'_> {
361     type Output = Sugg<'static>;
362     fn add(self, rhs: &Sugg<'_>) -> Sugg<'static> {
363         make_binop(ast::BinOpKind::Add, self, rhs)
364     }
365 }
366
367 impl Sub for &Sugg<'_> {
368     type Output = Sugg<'static>;
369     fn sub(self, rhs: &Sugg<'_>) -> Sugg<'static> {
370         make_binop(ast::BinOpKind::Sub, self, rhs)
371     }
372 }
373
374 forward_binop_impls_to_ref!(impl Add, add for Sugg<'_>, type Output = Sugg<'static>);
375 forward_binop_impls_to_ref!(impl Sub, sub for Sugg<'_>, type Output = Sugg<'static>);
376
377 impl Neg for Sugg<'_> {
378     type Output = Sugg<'static>;
379     fn neg(self) -> Sugg<'static> {
380         make_unop("-", self)
381     }
382 }
383
384 impl Not for Sugg<'_> {
385     type Output = Sugg<'static>;
386     fn not(self) -> Sugg<'static> {
387         make_unop("!", self)
388     }
389 }
390
391 /// Helper type to display either `foo` or `(foo)`.
392 struct ParenHelper<T> {
393     /// `true` if parentheses are needed.
394     paren: bool,
395     /// The main thing to display.
396     wrapped: T,
397 }
398
399 impl<T> ParenHelper<T> {
400     /// Builds a `ParenHelper`.
401     fn new(paren: bool, wrapped: T) -> Self {
402         Self { paren, wrapped }
403     }
404 }
405
406 impl<T: Display> Display for ParenHelper<T> {
407     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
408         if self.paren {
409             write!(f, "({})", self.wrapped)
410         } else {
411             self.wrapped.fmt(f)
412         }
413     }
414 }
415
416 /// Builds the string for `<op><expr>` adding parenthesis when necessary.
417 ///
418 /// For convenience, the operator is taken as a string because all unary
419 /// operators have the same
420 /// precedence.
421 pub fn make_unop(op: &str, expr: Sugg<'_>) -> Sugg<'static> {
422     Sugg::MaybeParen(format!("{}{}", op, expr.maybe_par()).into())
423 }
424
425 /// Builds the string for `<lhs> <op> <rhs>` adding parenthesis when necessary.
426 ///
427 /// Precedence of shift operator relative to other arithmetic operation is
428 /// often confusing so
429 /// parenthesis will always be added for a mix of these.
430 pub fn make_assoc(op: AssocOp, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
431     /// Returns `true` if the operator is a shift operator `<<` or `>>`.
432     fn is_shift(op: AssocOp) -> bool {
433         matches!(op, AssocOp::ShiftLeft | AssocOp::ShiftRight)
434     }
435
436     /// Returns `true` if the operator is a arithmetic operator
437     /// (i.e., `+`, `-`, `*`, `/`, `%`).
438     fn is_arith(op: AssocOp) -> bool {
439         matches!(
440             op,
441             AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide | AssocOp::Modulus
442         )
443     }
444
445     /// Returns `true` if the operator `op` needs parenthesis with the operator
446     /// `other` in the direction `dir`.
447     fn needs_paren(op: AssocOp, other: AssocOp, dir: Associativity) -> bool {
448         other.precedence() < op.precedence()
449             || (other.precedence() == op.precedence()
450                 && ((op != other && associativity(op) != dir)
451                     || (op == other && associativity(op) != Associativity::Both)))
452             || is_shift(op) && is_arith(other)
453             || is_shift(other) && is_arith(op)
454     }
455
456     let lhs_paren = if let Sugg::BinOp(lop, _) = *lhs {
457         needs_paren(op, lop, Associativity::Left)
458     } else {
459         false
460     };
461
462     let rhs_paren = if let Sugg::BinOp(rop, _) = *rhs {
463         needs_paren(op, rop, Associativity::Right)
464     } else {
465         false
466     };
467
468     let lhs = ParenHelper::new(lhs_paren, lhs);
469     let rhs = ParenHelper::new(rhs_paren, rhs);
470     let sugg = match op {
471         AssocOp::Add
472         | AssocOp::BitAnd
473         | AssocOp::BitOr
474         | AssocOp::BitXor
475         | AssocOp::Divide
476         | AssocOp::Equal
477         | AssocOp::Greater
478         | AssocOp::GreaterEqual
479         | AssocOp::LAnd
480         | AssocOp::LOr
481         | AssocOp::Less
482         | AssocOp::LessEqual
483         | AssocOp::Modulus
484         | AssocOp::Multiply
485         | AssocOp::NotEqual
486         | AssocOp::ShiftLeft
487         | AssocOp::ShiftRight
488         | AssocOp::Subtract => format!(
489             "{} {} {}",
490             lhs,
491             op.to_ast_binop().expect("Those are AST ops").to_string(),
492             rhs
493         ),
494         AssocOp::Assign => format!("{} = {}", lhs, rhs),
495         AssocOp::AssignOp(op) => format!("{} {}= {}", lhs, token_kind_to_string(&token::BinOp(op)), rhs),
496         AssocOp::As => format!("{} as {}", lhs, rhs),
497         AssocOp::DotDot => format!("{}..{}", lhs, rhs),
498         AssocOp::DotDotEq => format!("{}..={}", lhs, rhs),
499         AssocOp::Colon => format!("{}: {}", lhs, rhs),
500     };
501
502     Sugg::BinOp(op, sugg.into())
503 }
504
505 /// Convenience wrapper around `make_assoc` and `AssocOp::from_ast_binop`.
506 pub fn make_binop(op: ast::BinOpKind, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
507     make_assoc(AssocOp::from_ast_binop(op), lhs, rhs)
508 }
509
510 #[derive(PartialEq, Eq, Clone, Copy)]
511 /// Operator associativity.
512 enum Associativity {
513     /// The operator is both left-associative and right-associative.
514     Both,
515     /// The operator is left-associative.
516     Left,
517     /// The operator is not associative.
518     None,
519     /// The operator is right-associative.
520     Right,
521 }
522
523 /// Returns the associativity/fixity of an operator. The difference with
524 /// `AssocOp::fixity` is that an operator can be both left and right associative
525 /// (such as `+`: `a + b + c == (a + b) + c == a + (b + c)`.
526 ///
527 /// Chained `as` and explicit `:` type coercion never need inner parenthesis so
528 /// they are considered
529 /// associative.
530 #[must_use]
531 fn associativity(op: AssocOp) -> Associativity {
532     use rustc_ast::util::parser::AssocOp::{
533         Add, As, Assign, AssignOp, BitAnd, BitOr, BitXor, Colon, Divide, DotDot, DotDotEq, Equal, Greater,
534         GreaterEqual, LAnd, LOr, Less, LessEqual, Modulus, Multiply, NotEqual, ShiftLeft, ShiftRight, Subtract,
535     };
536
537     match op {
538         Assign | AssignOp(_) => Associativity::Right,
539         Add | BitAnd | BitOr | BitXor | LAnd | LOr | Multiply | As | Colon => Associativity::Both,
540         Divide | Equal | Greater | GreaterEqual | Less | LessEqual | Modulus | NotEqual | ShiftLeft | ShiftRight
541         | Subtract => Associativity::Left,
542         DotDot | DotDotEq => Associativity::None,
543     }
544 }
545
546 /// Converts a `hir::BinOp` to the corresponding assigning binary operator.
547 fn hirbinop2assignop(op: hir::BinOp) -> AssocOp {
548     use rustc_ast::token::BinOpToken::{And, Caret, Minus, Or, Percent, Plus, Shl, Shr, Slash, Star};
549
550     AssocOp::AssignOp(match op.node {
551         hir::BinOpKind::Add => Plus,
552         hir::BinOpKind::BitAnd => And,
553         hir::BinOpKind::BitOr => Or,
554         hir::BinOpKind::BitXor => Caret,
555         hir::BinOpKind::Div => Slash,
556         hir::BinOpKind::Mul => Star,
557         hir::BinOpKind::Rem => Percent,
558         hir::BinOpKind::Shl => Shl,
559         hir::BinOpKind::Shr => Shr,
560         hir::BinOpKind::Sub => Minus,
561
562         hir::BinOpKind::And
563         | hir::BinOpKind::Eq
564         | hir::BinOpKind::Ge
565         | hir::BinOpKind::Gt
566         | hir::BinOpKind::Le
567         | hir::BinOpKind::Lt
568         | hir::BinOpKind::Ne
569         | hir::BinOpKind::Or => panic!("This operator does not exist"),
570     })
571 }
572
573 /// Converts an `ast::BinOp` to the corresponding assigning binary operator.
574 fn astbinop2assignop(op: ast::BinOp) -> AssocOp {
575     use rustc_ast::ast::BinOpKind::{
576         Add, And, BitAnd, BitOr, BitXor, Div, Eq, Ge, Gt, Le, Lt, Mul, Ne, Or, Rem, Shl, Shr, Sub,
577     };
578     use rustc_ast::token::BinOpToken;
579
580     AssocOp::AssignOp(match op.node {
581         Add => BinOpToken::Plus,
582         BitAnd => BinOpToken::And,
583         BitOr => BinOpToken::Or,
584         BitXor => BinOpToken::Caret,
585         Div => BinOpToken::Slash,
586         Mul => BinOpToken::Star,
587         Rem => BinOpToken::Percent,
588         Shl => BinOpToken::Shl,
589         Shr => BinOpToken::Shr,
590         Sub => BinOpToken::Minus,
591         And | Eq | Ge | Gt | Le | Lt | Ne | Or => panic!("This operator does not exist"),
592     })
593 }
594
595 /// Returns the indentation before `span` if there are nothing but `[ \t]`
596 /// before it on its line.
597 fn indentation<T: LintContext>(cx: &T, span: Span) -> Option<String> {
598     let lo = cx.sess().source_map().lookup_char_pos(span.lo());
599     lo.file
600         .get_line(lo.line - 1 /* line numbers in `Loc` are 1-based */)
601         .and_then(|line| {
602             if let Some((pos, _)) = line.char_indices().find(|&(_, c)| c != ' ' && c != '\t') {
603                 // We can mix char and byte positions here because we only consider `[ \t]`.
604                 if lo.col == CharPos(pos) {
605                     Some(line[..pos].into())
606                 } else {
607                     None
608                 }
609             } else {
610                 None
611             }
612         })
613 }
614
615 /// Convenience extension trait for `DiagnosticBuilder`.
616 pub trait DiagnosticBuilderExt<T: LintContext> {
617     /// Suggests to add an attribute to an item.
618     ///
619     /// Correctly handles indentation of the attribute and item.
620     ///
621     /// # Example
622     ///
623     /// ```rust,ignore
624     /// diag.suggest_item_with_attr(cx, item, "#[derive(Default)]");
625     /// ```
626     fn suggest_item_with_attr<D: Display + ?Sized>(
627         &mut self,
628         cx: &T,
629         item: Span,
630         msg: &str,
631         attr: &D,
632         applicability: Applicability,
633     );
634
635     /// Suggest to add an item before another.
636     ///
637     /// The item should not be indented (except for inner indentation).
638     ///
639     /// # Example
640     ///
641     /// ```rust,ignore
642     /// diag.suggest_prepend_item(cx, item,
643     /// "fn foo() {
644     ///     bar();
645     /// }");
646     /// ```
647     fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability);
648
649     /// Suggest to completely remove an item.
650     ///
651     /// This will remove an item and all following whitespace until the next non-whitespace
652     /// character. This should work correctly if item is on the same indentation level as the
653     /// following item.
654     ///
655     /// # Example
656     ///
657     /// ```rust,ignore
658     /// diag.suggest_remove_item(cx, item, "remove this")
659     /// ```
660     fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability);
661 }
662
663 impl<T: LintContext> DiagnosticBuilderExt<T> for rustc_errors::DiagnosticBuilder<'_> {
664     fn suggest_item_with_attr<D: Display + ?Sized>(
665         &mut self,
666         cx: &T,
667         item: Span,
668         msg: &str,
669         attr: &D,
670         applicability: Applicability,
671     ) {
672         if let Some(indent) = indentation(cx, item) {
673             let span = item.with_hi(item.lo());
674
675             self.span_suggestion(span, msg, format!("{}\n{}", attr, indent), applicability);
676         }
677     }
678
679     fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability) {
680         if let Some(indent) = indentation(cx, item) {
681             let span = item.with_hi(item.lo());
682
683             let mut first = true;
684             let new_item = new_item
685                 .lines()
686                 .map(|l| {
687                     if first {
688                         first = false;
689                         format!("{}\n", l)
690                     } else {
691                         format!("{}{}\n", indent, l)
692                     }
693                 })
694                 .collect::<String>();
695
696             self.span_suggestion(span, msg, format!("{}\n{}", new_item, indent), applicability);
697         }
698     }
699
700     fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability) {
701         let mut remove_span = item;
702         let hi = cx.sess().source_map().next_point(remove_span).hi();
703         let fmpos = cx.sess().source_map().lookup_byte_offset(hi);
704
705         if let Some(ref src) = fmpos.sf.src {
706             let non_whitespace_offset = src[fmpos.pos.to_usize()..].find(|c| c != ' ' && c != '\t' && c != '\n');
707
708             if let Some(non_whitespace_offset) = non_whitespace_offset {
709                 remove_span = remove_span
710                     .with_hi(remove_span.hi() + BytePos(non_whitespace_offset.try_into().expect("offset too large")));
711             }
712         }
713
714         self.span_suggestion(remove_span, msg, String::new(), applicability);
715     }
716 }
717
718 #[cfg(test)]
719 mod test {
720     use super::Sugg;
721
722     use rustc_ast::util::parser::AssocOp;
723     use std::borrow::Cow;
724
725     const SUGGESTION: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("function_call()"));
726
727     #[test]
728     fn make_return_transform_sugg_into_a_return_call() {
729         assert_eq!("return function_call()", SUGGESTION.make_return().to_string());
730     }
731
732     #[test]
733     fn blockify_transforms_sugg_into_a_block() {
734         assert_eq!("{ function_call() }", SUGGESTION.blockify().to_string());
735     }
736
737     #[test]
738     fn binop_maybe_par() {
739         let sugg = Sugg::BinOp(AssocOp::Add, "(1 + 1)".into());
740         assert_eq!("(1 + 1)", sugg.maybe_par().to_string());
741
742         let sugg = Sugg::BinOp(AssocOp::Add, "(1 + 1) + (1 + 1)".into());
743         assert_eq!("((1 + 1) + (1 + 1))", sugg.maybe_par().to_string());
744     }
745 }