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