1 //! Contains utility functions to generate suggestions.
2 #![deny(clippy::missing_docs_in_private_items)]
4 use crate::utils::{higher, snippet, snippet_opt, 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;
11 use rustc_lint::{EarlyContext, LateContext, LintContext};
12 use rustc_span::source_map::{CharPos, Span};
13 use rustc_span::{BytePos, Pos};
15 use std::convert::TryInto;
16 use std::fmt::Display;
18 pub use crate::literal_representation::format_numeric_literal;
20 /// A helper type to build suggestion correctly handling parenthesis.
22 /// An expression that never needs parenthesis 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
28 BinOp(AssocOp, Cow<'a, str>),
31 /// Literal constant `1`, for convenience.
32 pub const ONE: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("1"));
34 impl Display for Sugg<'_> {
35 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
37 Sugg::NonParen(ref s) | Sugg::MaybeParen(ref s) | Sugg::BinOp(_, ref s) => s.fmt(f),
42 #[allow(clippy::wrong_self_convention)] // ok, because of the function `as_ty` method
44 /// Prepare a suggestion from an expression.
45 pub fn hir_opt(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>) -> Option<Self> {
46 snippet_opt(cx, expr.span).map(|snippet| {
47 let snippet = Cow::Owned(snippet);
48 Self::hir_from_snippet(cx, expr, snippet)
52 /// Convenience function around `hir_opt` for suggestions with a default
54 pub fn hir(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, default: &'a str) -> Self {
55 Self::hir_opt(cx, expr).unwrap_or_else(|| Sugg::NonParen(Cow::Borrowed(default)))
58 /// Same as `hir`, but it adapts the applicability level by following rules:
60 /// - Applicability level `Unspecified` will never be changed.
61 /// - If the span is inside a macro, change the applicability level to `MaybeIncorrect`.
62 /// - If the default value is used and the applicability level is `MachineApplicable`, change it
65 pub fn hir_with_applicability(
66 cx: &LateContext<'_, '_>,
69 applicability: &mut Applicability,
71 if *applicability != Applicability::Unspecified && expr.span.from_expansion() {
72 *applicability = Applicability::MaybeIncorrect;
74 Self::hir_opt(cx, expr).unwrap_or_else(|| {
75 if *applicability == Applicability::MachineApplicable {
76 *applicability = Applicability::HasPlaceholders;
78 Sugg::NonParen(Cow::Borrowed(default))
82 /// Same as `hir`, but will use the pre expansion span if the `expr` was in a macro.
83 pub fn hir_with_macro_callsite(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, default: &'a str) -> Self {
84 let snippet = snippet_with_macro_callsite(cx, expr.span, default);
86 Self::hir_from_snippet(cx, expr, snippet)
89 /// Generate a suggestion for an expression with the given snippet. This is used by the `hir_*`
90 /// function variants of `Sugg`, since these use different snippet functions.
91 fn hir_from_snippet(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, snippet: Cow<'a, str>) -> Self {
92 if let Some(range) = higher::range(cx, expr) {
93 let op = match range.limits {
94 ast::RangeLimits::HalfOpen => AssocOp::DotDot,
95 ast::RangeLimits::Closed => AssocOp::DotDotEq,
97 return Sugg::BinOp(op, snippet);
101 hir::ExprKind::AddrOf(..)
102 | hir::ExprKind::Box(..)
103 | hir::ExprKind::Closure(..)
104 | hir::ExprKind::Unary(..)
105 | hir::ExprKind::Match(..) => Sugg::MaybeParen(snippet),
106 hir::ExprKind::Continue(..)
107 | hir::ExprKind::Yield(..)
108 | hir::ExprKind::Array(..)
109 | hir::ExprKind::Block(..)
110 | hir::ExprKind::Break(..)
111 | hir::ExprKind::Call(..)
112 | hir::ExprKind::Field(..)
113 | hir::ExprKind::Index(..)
114 | hir::ExprKind::InlineAsm(..)
115 | hir::ExprKind::Lit(..)
116 | hir::ExprKind::Loop(..)
117 | hir::ExprKind::MethodCall(..)
118 | hir::ExprKind::Path(..)
119 | hir::ExprKind::Repeat(..)
120 | hir::ExprKind::Ret(..)
121 | hir::ExprKind::Struct(..)
122 | hir::ExprKind::Tup(..)
123 | hir::ExprKind::DropTemps(_)
124 | hir::ExprKind::Err => Sugg::NonParen(snippet),
125 hir::ExprKind::Assign(..) => Sugg::BinOp(AssocOp::Assign, snippet),
126 hir::ExprKind::AssignOp(op, ..) => Sugg::BinOp(hirbinop2assignop(op), snippet),
127 hir::ExprKind::Binary(op, ..) => Sugg::BinOp(AssocOp::from_ast_binop(higher::binop(op.node)), snippet),
128 hir::ExprKind::Cast(..) => Sugg::BinOp(AssocOp::As, snippet),
129 hir::ExprKind::Type(..) => Sugg::BinOp(AssocOp::Colon, snippet),
133 /// Prepare a suggestion from an expression.
134 pub fn ast(cx: &EarlyContext<'_>, expr: &ast::Expr, default: &'a str) -> Self {
135 use rustc_ast::ast::RangeLimits;
137 let snippet = snippet(cx, expr.span, default);
140 ast::ExprKind::AddrOf(..)
141 | ast::ExprKind::Box(..)
142 | ast::ExprKind::Closure(..)
143 | ast::ExprKind::If(..)
144 | ast::ExprKind::Let(..)
145 | ast::ExprKind::Unary(..)
146 | ast::ExprKind::Match(..) => Sugg::MaybeParen(snippet),
147 ast::ExprKind::Async(..)
148 | ast::ExprKind::Block(..)
149 | ast::ExprKind::Break(..)
150 | ast::ExprKind::Call(..)
151 | ast::ExprKind::Continue(..)
152 | ast::ExprKind::Yield(..)
153 | ast::ExprKind::Field(..)
154 | ast::ExprKind::ForLoop(..)
155 | ast::ExprKind::Index(..)
156 | ast::ExprKind::InlineAsm(..)
157 | ast::ExprKind::Lit(..)
158 | ast::ExprKind::Loop(..)
159 | ast::ExprKind::Mac(..)
160 | ast::ExprKind::MethodCall(..)
161 | ast::ExprKind::Paren(..)
162 | ast::ExprKind::Path(..)
163 | ast::ExprKind::Repeat(..)
164 | ast::ExprKind::Ret(..)
165 | ast::ExprKind::Struct(..)
166 | ast::ExprKind::Try(..)
167 | ast::ExprKind::TryBlock(..)
168 | ast::ExprKind::Tup(..)
169 | ast::ExprKind::Array(..)
170 | ast::ExprKind::While(..)
171 | ast::ExprKind::Await(..)
172 | ast::ExprKind::Err => Sugg::NonParen(snippet),
173 ast::ExprKind::Range(.., RangeLimits::HalfOpen) => Sugg::BinOp(AssocOp::DotDot, snippet),
174 ast::ExprKind::Range(.., RangeLimits::Closed) => Sugg::BinOp(AssocOp::DotDotEq, snippet),
175 ast::ExprKind::Assign(..) => Sugg::BinOp(AssocOp::Assign, snippet),
176 ast::ExprKind::AssignOp(op, ..) => Sugg::BinOp(astbinop2assignop(op), snippet),
177 ast::ExprKind::Binary(op, ..) => Sugg::BinOp(AssocOp::from_ast_binop(op.node), snippet),
178 ast::ExprKind::Cast(..) => Sugg::BinOp(AssocOp::As, snippet),
179 ast::ExprKind::Type(..) => Sugg::BinOp(AssocOp::Colon, snippet),
183 /// Convenience method to create the `<lhs> && <rhs>` suggestion.
184 pub fn and(self, rhs: &Self) -> Sugg<'static> {
185 make_binop(ast::BinOpKind::And, &self, rhs)
188 /// Convenience method to create the `<lhs> & <rhs>` suggestion.
189 pub fn bit_and(self, rhs: &Self) -> Sugg<'static> {
190 make_binop(ast::BinOpKind::BitAnd, &self, rhs)
193 /// Convenience method to create the `<lhs> as <rhs>` suggestion.
194 pub fn as_ty<R: Display>(self, rhs: R) -> Sugg<'static> {
195 make_assoc(AssocOp::As, &self, &Sugg::NonParen(rhs.to_string().into()))
198 /// Convenience method to create the `&<expr>` suggestion.
199 pub fn addr(self) -> Sugg<'static> {
203 /// Convenience method to create the `&mut <expr>` suggestion.
204 pub fn mut_addr(self) -> Sugg<'static> {
205 make_unop("&mut ", self)
208 /// Convenience method to create the `*<expr>` suggestion.
209 pub fn deref(self) -> Sugg<'static> {
213 /// Convenience method to create the `&*<expr>` suggestion. Currently this
214 /// is needed because `sugg.deref().addr()` produces an unnecessary set of
215 /// parentheses around the deref.
216 pub fn addr_deref(self) -> Sugg<'static> {
217 make_unop("&*", self)
220 /// Convenience method to create the `&mut *<expr>` suggestion. Currently
221 /// this is needed because `sugg.deref().mut_addr()` produces an unnecessary
222 /// set of parentheses around the deref.
223 pub fn mut_addr_deref(self) -> Sugg<'static> {
224 make_unop("&mut *", self)
227 /// Convenience method to transform suggestion into a return call
228 pub fn make_return(self) -> Sugg<'static> {
229 Sugg::NonParen(Cow::Owned(format!("return {}", self)))
232 /// Convenience method to transform suggestion into a block
233 /// where the suggestion is a trailing expression
234 pub fn blockify(self) -> Sugg<'static> {
235 Sugg::NonParen(Cow::Owned(format!("{{ {} }}", self)))
238 /// Convenience method to create the `<lhs>..<rhs>` or `<lhs>...<rhs>`
241 pub fn range(self, end: &Self, limit: ast::RangeLimits) -> Sugg<'static> {
243 ast::RangeLimits::HalfOpen => make_assoc(AssocOp::DotDot, &self, end),
244 ast::RangeLimits::Closed => make_assoc(AssocOp::DotDotEq, &self, end),
248 /// Adds parenthesis to any expression that might need them. Suitable to the
249 /// `self` argument of a method call
250 /// (e.g., to build `bar.foo()` or `(1 + 2).foo()`).
251 pub fn maybe_par(self) -> Self {
253 Sugg::NonParen(..) => self,
254 // `(x)` and `(x).y()` both don't need additional parens.
255 Sugg::MaybeParen(sugg) => {
256 if sugg.starts_with('(') && sugg.ends_with(')') {
257 Sugg::MaybeParen(sugg)
259 Sugg::NonParen(format!("({})", sugg).into())
262 Sugg::BinOp(_, sugg) => Sugg::NonParen(format!("({})", sugg).into()),
267 impl<'a, 'b> std::ops::Add<Sugg<'b>> for Sugg<'a> {
268 type Output = Sugg<'static>;
269 fn add(self, rhs: Sugg<'b>) -> Sugg<'static> {
270 make_binop(ast::BinOpKind::Add, &self, &rhs)
274 impl<'a, 'b> std::ops::Sub<Sugg<'b>> for Sugg<'a> {
275 type Output = Sugg<'static>;
276 fn sub(self, rhs: Sugg<'b>) -> Sugg<'static> {
277 make_binop(ast::BinOpKind::Sub, &self, &rhs)
281 impl<'a> std::ops::Not for Sugg<'a> {
282 type Output = Sugg<'static>;
283 fn not(self) -> Sugg<'static> {
288 /// Helper type to display either `foo` or `(foo)`.
289 struct ParenHelper<T> {
290 /// `true` if parentheses are needed.
292 /// The main thing to display.
296 impl<T> ParenHelper<T> {
297 /// Builds a `ParenHelper`.
298 fn new(paren: bool, wrapped: T) -> Self {
299 Self { paren, wrapped }
303 impl<T: Display> Display for ParenHelper<T> {
304 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
306 write!(f, "({})", self.wrapped)
313 /// Builds the string for `<op><expr>` adding parenthesis when necessary.
315 /// For convenience, the operator is taken as a string because all unary
316 /// operators have the same
318 pub fn make_unop(op: &str, expr: Sugg<'_>) -> Sugg<'static> {
319 Sugg::MaybeParen(format!("{}{}", op, expr.maybe_par()).into())
322 /// Builds the string for `<lhs> <op> <rhs>` adding parenthesis when necessary.
324 /// Precedence of shift operator relative to other arithmetic operation is
325 /// often confusing so
326 /// parenthesis will always be added for a mix of these.
327 pub fn make_assoc(op: AssocOp, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
328 /// Returns `true` if the operator is a shift operator `<<` or `>>`.
329 fn is_shift(op: &AssocOp) -> bool {
330 matches!(*op, AssocOp::ShiftLeft | AssocOp::ShiftRight)
333 /// Returns `true` if the operator is a arithmetic operator
334 /// (i.e., `+`, `-`, `*`, `/`, `%`).
335 fn is_arith(op: &AssocOp) -> bool {
338 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide | AssocOp::Modulus
342 /// Returns `true` if the operator `op` needs parenthesis with the operator
343 /// `other` in the direction `dir`.
344 fn needs_paren(op: &AssocOp, other: &AssocOp, dir: Associativity) -> bool {
345 other.precedence() < op.precedence()
346 || (other.precedence() == op.precedence()
347 && ((op != other && associativity(op) != dir)
348 || (op == other && associativity(op) != Associativity::Both)))
349 || is_shift(op) && is_arith(other)
350 || is_shift(other) && is_arith(op)
353 let lhs_paren = if let Sugg::BinOp(ref lop, _) = *lhs {
354 needs_paren(&op, lop, Associativity::Left)
359 let rhs_paren = if let Sugg::BinOp(ref rop, _) = *rhs {
360 needs_paren(&op, rop, Associativity::Right)
365 let lhs = ParenHelper::new(lhs_paren, lhs);
366 let rhs = ParenHelper::new(rhs_paren, rhs);
367 let sugg = match op {
375 | AssocOp::GreaterEqual
384 | AssocOp::ShiftRight
385 | AssocOp::Subtract => format!(
388 op.to_ast_binop().expect("Those are AST ops").to_string(),
391 AssocOp::Assign => format!("{} = {}", lhs, rhs),
392 AssocOp::AssignOp(op) => format!("{} {}= {}", lhs, token_kind_to_string(&token::BinOp(op)), rhs),
393 AssocOp::As => format!("{} as {}", lhs, rhs),
394 AssocOp::DotDot => format!("{}..{}", lhs, rhs),
395 AssocOp::DotDotEq => format!("{}..={}", lhs, rhs),
396 AssocOp::Colon => format!("{}: {}", lhs, rhs),
399 Sugg::BinOp(op, sugg.into())
402 /// Convenience wrapper around `make_assoc` and `AssocOp::from_ast_binop`.
403 pub fn make_binop(op: ast::BinOpKind, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
404 make_assoc(AssocOp::from_ast_binop(op), lhs, rhs)
407 #[derive(PartialEq, Eq, Clone, Copy)]
408 /// Operator associativity.
410 /// The operator is both left-associative and right-associative.
412 /// The operator is left-associative.
414 /// The operator is not associative.
416 /// The operator is right-associative.
420 /// Returns the associativity/fixity of an operator. The difference with
421 /// `AssocOp::fixity` is that an operator can be both left and right associative
422 /// (such as `+`: `a + b + c == (a + b) + c == a + (b + c)`.
424 /// Chained `as` and explicit `:` type coercion never need inner parenthesis so
425 /// they are considered
428 fn associativity(op: &AssocOp) -> Associativity {
429 use rustc_ast::util::parser::AssocOp::{
430 Add, As, Assign, AssignOp, BitAnd, BitOr, BitXor, Colon, Divide, DotDot, DotDotEq, Equal, Greater,
431 GreaterEqual, LAnd, LOr, Less, LessEqual, Modulus, Multiply, NotEqual, ShiftLeft, ShiftRight, Subtract,
435 Assign | AssignOp(_) => Associativity::Right,
436 Add | BitAnd | BitOr | BitXor | LAnd | LOr | Multiply | As | Colon => Associativity::Both,
437 Divide | Equal | Greater | GreaterEqual | Less | LessEqual | Modulus | NotEqual | ShiftLeft | ShiftRight
438 | Subtract => Associativity::Left,
439 DotDot | DotDotEq => Associativity::None,
443 /// Converts a `hir::BinOp` to the corresponding assigning binary operator.
444 fn hirbinop2assignop(op: hir::BinOp) -> AssocOp {
445 use rustc_ast::token::BinOpToken::{And, Caret, Minus, Or, Percent, Plus, Shl, Shr, Slash, Star};
447 AssocOp::AssignOp(match op.node {
448 hir::BinOpKind::Add => Plus,
449 hir::BinOpKind::BitAnd => And,
450 hir::BinOpKind::BitOr => Or,
451 hir::BinOpKind::BitXor => Caret,
452 hir::BinOpKind::Div => Slash,
453 hir::BinOpKind::Mul => Star,
454 hir::BinOpKind::Rem => Percent,
455 hir::BinOpKind::Shl => Shl,
456 hir::BinOpKind::Shr => Shr,
457 hir::BinOpKind::Sub => Minus,
466 | hir::BinOpKind::Or => panic!("This operator does not exist"),
470 /// Converts an `ast::BinOp` to the corresponding assigning binary operator.
471 fn astbinop2assignop(op: ast::BinOp) -> AssocOp {
472 use rustc_ast::ast::BinOpKind::{
473 Add, And, BitAnd, BitOr, BitXor, Div, Eq, Ge, Gt, Le, Lt, Mul, Ne, Or, Rem, Shl, Shr, Sub,
475 use rustc_ast::token::BinOpToken;
477 AssocOp::AssignOp(match op.node {
478 Add => BinOpToken::Plus,
479 BitAnd => BinOpToken::And,
480 BitOr => BinOpToken::Or,
481 BitXor => BinOpToken::Caret,
482 Div => BinOpToken::Slash,
483 Mul => BinOpToken::Star,
484 Rem => BinOpToken::Percent,
485 Shl => BinOpToken::Shl,
486 Shr => BinOpToken::Shr,
487 Sub => BinOpToken::Minus,
488 And | Eq | Ge | Gt | Le | Lt | Ne | Or => panic!("This operator does not exist"),
492 /// Returns the indentation before `span` if there are nothing but `[ \t]`
493 /// before it on its line.
494 fn indentation<T: LintContext>(cx: &T, span: Span) -> Option<String> {
495 let lo = cx.sess().source_map().lookup_char_pos(span.lo());
496 if let Some(line) = lo.file.get_line(lo.line - 1 /* line numbers in `Loc` are 1-based */) {
497 if let Some((pos, _)) = line.char_indices().find(|&(_, c)| c != ' ' && c != '\t') {
498 // We can mix char and byte positions here because we only consider `[ \t]`.
499 if lo.col == CharPos(pos) {
500 Some(line[..pos].into())
512 /// Convenience extension trait for `DiagnosticBuilder`.
513 pub trait DiagnosticBuilderExt<'a, T: LintContext> {
514 /// Suggests to add an attribute to an item.
516 /// Correctly handles indentation of the attribute and item.
521 /// db.suggest_item_with_attr(cx, item, "#[derive(Default)]");
523 fn suggest_item_with_attr<D: Display + ?Sized>(
529 applicability: Applicability,
532 /// Suggest to add an item before another.
534 /// The item should not be indented (expect for inner indentation).
539 /// db.suggest_prepend_item(cx, item,
544 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability);
546 /// Suggest to completely remove an item.
548 /// This will remove an item and all following whitespace until the next non-whitespace
549 /// character. This should work correctly if item is on the same indentation level as the
555 /// db.suggest_remove_item(cx, item, "remove this")
557 fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability);
560 impl<'a, 'b, 'c, T: LintContext> DiagnosticBuilderExt<'c, T> for rustc_errors::DiagnosticBuilder<'b> {
561 fn suggest_item_with_attr<D: Display + ?Sized>(
567 applicability: Applicability,
569 if let Some(indent) = indentation(cx, item) {
570 let span = item.with_hi(item.lo());
572 self.span_suggestion(span, msg, format!("{}\n{}", attr, indent), applicability);
576 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability) {
577 if let Some(indent) = indentation(cx, item) {
578 let span = item.with_hi(item.lo());
580 let mut first = true;
581 let new_item = new_item
588 format!("{}{}\n", indent, l)
591 .collect::<String>();
593 self.span_suggestion(span, msg, format!("{}\n{}", new_item, indent), applicability);
597 fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability) {
598 let mut remove_span = item;
599 let hi = cx.sess().source_map().next_point(remove_span).hi();
600 let fmpos = cx.sess().source_map().lookup_byte_offset(hi);
602 if let Some(ref src) = fmpos.sf.src {
603 let non_whitespace_offset = src[fmpos.pos.to_usize()..].find(|c| c != ' ' && c != '\t' && c != '\n');
605 if let Some(non_whitespace_offset) = non_whitespace_offset {
606 remove_span = remove_span
607 .with_hi(remove_span.hi() + BytePos(non_whitespace_offset.try_into().expect("offset too large")))
611 self.span_suggestion(remove_span, msg, String::new(), applicability);
618 use std::borrow::Cow;
620 const SUGGESTION: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("function_call()"));
623 fn make_return_transform_sugg_into_a_return_call() {
624 assert_eq!("return function_call()", SUGGESTION.make_return().to_string());
628 fn blockify_transforms_sugg_into_a_block() {
629 assert_eq!("{ function_call() }", SUGGESTION.blockify().to_string());