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