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