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