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