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