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