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