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