1 //! Contains utility functions to generate suggestions.
2 #![deny(clippy::missing_docs_in_private_items)]
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;
10 use rustc_lint::{EarlyContext, LateContext, LintContext};
11 use rustc_span::source_map::{CharPos, Span};
12 use rustc_span::{BytePos, Pos};
14 use std::convert::TryInto;
15 use std::fmt::Display;
16 use std::ops::{Add, Neg, Not, Sub};
18 /// A helper type to build suggestion correctly handling parenthesis.
19 #[derive(Clone, PartialEq)]
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
27 BinOp(AssocOp, Cow<'a, str>),
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(""));
37 impl Display for Sugg<'_> {
38 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
40 Sugg::NonParen(ref s) | Sugg::MaybeParen(ref s) | Sugg::BinOp(_, ref s) => s.fmt(f),
45 #[allow(clippy::wrong_self_convention)] // ok, because of the function `as_ty` method
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)
55 /// Convenience function around `hir_opt` for suggestions with a default
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)))
61 /// Same as `hir`, but it adapts the applicability level by following rules:
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
68 pub fn hir_with_applicability(
72 applicability: &mut Applicability,
74 if *applicability != Applicability::Unspecified && expr.span.from_expansion() {
75 *applicability = Applicability::MaybeIncorrect;
77 Self::hir_opt(cx, expr).unwrap_or_else(|| {
78 if *applicability == Applicability::MachineApplicable {
79 *applicability = Applicability::HasPlaceholders;
81 Sugg::NonParen(Cow::Borrowed(default))
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);
89 Self::hir_from_snippet(expr, snippet)
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,
100 return Sugg::BinOp(op, snippet);
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),
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;
143 let snippet = if expr.span.from_expansion() {
144 snippet_with_macro_callsite(cx, expr.span, default)
146 snippet(cx, expr.span, default)
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),
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)
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)
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()))
211 /// Convenience method to create the `&<expr>` suggestion.
212 pub fn addr(self) -> Sugg<'static> {
216 /// Convenience method to create the `&mut <expr>` suggestion.
217 pub fn mut_addr(self) -> Sugg<'static> {
218 make_unop("&mut ", self)
221 /// Convenience method to create the `*<expr>` suggestion.
222 pub fn deref(self) -> Sugg<'static> {
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)
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)
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)))
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)))
251 /// Convenience method to create the `<lhs>..<rhs>` or `<lhs>...<rhs>`
254 pub fn range(self, end: &Self, limit: ast::RangeLimits) -> Sugg<'static> {
256 ast::RangeLimits::HalfOpen => make_assoc(AssocOp::DotDot, &self, end),
257 ast::RangeLimits::Closed => make_assoc(AssocOp::DotDotEq, &self, end),
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 {
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)
272 Sugg::NonParen(format!("({})", sugg).into())
275 Sugg::BinOp(_, sugg) => Sugg::NonParen(format!("({})", sugg).into()),
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 {
286 fn $method(self, other: $t) -> $o {
287 $imp::$method(self, &other)
291 impl $imp<&$t> for $t {
294 fn $method(self, other: &$t) -> $o {
295 $imp::$method(&self, other)
302 fn $method(self, other: $t) -> $o {
303 $imp::$method(&self, &other)
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)
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)
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>);
326 impl Neg for Sugg<'_> {
327 type Output = Sugg<'static>;
328 fn neg(self) -> Sugg<'static> {
333 impl Not for Sugg<'_> {
334 type Output = Sugg<'static>;
335 fn not(self) -> Sugg<'static> {
340 /// Helper type to display either `foo` or `(foo)`.
341 struct ParenHelper<T> {
342 /// `true` if parentheses are needed.
344 /// The main thing to display.
348 impl<T> ParenHelper<T> {
349 /// Builds a `ParenHelper`.
350 fn new(paren: bool, wrapped: T) -> Self {
351 Self { paren, wrapped }
355 impl<T: Display> Display for ParenHelper<T> {
356 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
358 write!(f, "({})", self.wrapped)
365 /// Builds the string for `<op><expr>` adding parenthesis when necessary.
367 /// For convenience, the operator is taken as a string because all unary
368 /// operators have the same
370 pub fn make_unop(op: &str, expr: Sugg<'_>) -> Sugg<'static> {
371 Sugg::MaybeParen(format!("{}{}", op, expr.maybe_par()).into())
374 /// Builds the string for `<lhs> <op> <rhs>` adding parenthesis when necessary.
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)
385 /// Returns `true` if the operator is a arithmetic operator
386 /// (i.e., `+`, `-`, `*`, `/`, `%`).
387 fn is_arith(op: AssocOp) -> bool {
390 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide | AssocOp::Modulus
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)
405 let lhs_paren = if let Sugg::BinOp(lop, _) = *lhs {
406 needs_paren(op, lop, Associativity::Left)
411 let rhs_paren = if let Sugg::BinOp(rop, _) = *rhs {
412 needs_paren(op, rop, Associativity::Right)
417 let lhs = ParenHelper::new(lhs_paren, lhs);
418 let rhs = ParenHelper::new(rhs_paren, rhs);
419 let sugg = match op {
427 | AssocOp::GreaterEqual
436 | AssocOp::ShiftRight
437 | AssocOp::Subtract => format!(
440 op.to_ast_binop().expect("Those are AST ops").to_string(),
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),
451 Sugg::BinOp(op, sugg.into())
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)
459 #[derive(PartialEq, Eq, Clone, Copy)]
460 /// Operator associativity.
462 /// The operator is both left-associative and right-associative.
464 /// The operator is left-associative.
466 /// The operator is not associative.
468 /// The operator is right-associative.
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)`.
476 /// Chained `as` and explicit `:` type coercion never need inner parenthesis so
477 /// they are considered
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,
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,
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};
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,
518 | hir::BinOpKind::Or => panic!("This operator does not exist"),
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,
527 use rustc_ast::token::BinOpToken;
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"),
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());
549 .get_line(lo.line - 1 /* line numbers in `Loc` are 1-based */)
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())
564 /// Convenience extension trait for `DiagnosticBuilder`.
565 pub trait DiagnosticBuilderExt<T: LintContext> {
566 /// Suggests to add an attribute to an item.
568 /// Correctly handles indentation of the attribute and item.
573 /// diag.suggest_item_with_attr(cx, item, "#[derive(Default)]");
575 fn suggest_item_with_attr<D: Display + ?Sized>(
581 applicability: Applicability,
584 /// Suggest to add an item before another.
586 /// The item should not be indented (except for inner indentation).
591 /// diag.suggest_prepend_item(cx, item,
596 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability);
598 /// Suggest to completely remove an item.
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
607 /// diag.suggest_remove_item(cx, item, "remove this")
609 fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability);
612 impl<T: LintContext> DiagnosticBuilderExt<T> for rustc_errors::DiagnosticBuilder<'_> {
613 fn suggest_item_with_attr<D: Display + ?Sized>(
619 applicability: Applicability,
621 if let Some(indent) = indentation(cx, item) {
622 let span = item.with_hi(item.lo());
624 self.span_suggestion(span, msg, format!("{}\n{}", attr, indent), applicability);
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());
632 let mut first = true;
633 let new_item = new_item
640 format!("{}{}\n", indent, l)
643 .collect::<String>();
645 self.span_suggestion(span, msg, format!("{}\n{}", new_item, indent), applicability);
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);
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');
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")))
663 self.span_suggestion(remove_span, msg, String::new(), applicability);
670 use std::borrow::Cow;
672 const SUGGESTION: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("function_call()"));
675 fn make_return_transform_sugg_into_a_return_call() {
676 assert_eq!("return function_call()", SUGGESTION.make_return().to_string());
680 fn blockify_transforms_sugg_into_a_block() {
681 assert_eq!("{ function_call() }", SUGGESTION.blockify().to_string());