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