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