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