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