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