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