1 //! Contains utility functions to generate suggestions.
2 #![deny(clippy::missing_docs_in_private_items)]
4 use crate::utils::{higher, in_macro, snippet, snippet_opt, snippet_with_macro_callsite};
7 use rustc::lint::{EarlyContext, LateContext, LintContext};
9 use rustc_errors::Applicability;
12 use std::convert::TryInto;
13 use std::fmt::Display;
15 use syntax::parse::token;
16 use syntax::print::pprust::token_to_string;
17 use syntax::source_map::{CharPos, Span};
18 use syntax::util::parser::AssocOp;
19 use syntax_pos::{BytePos, Pos};
21 /// A helper type to build suggestion correctly handling parenthesis.
23 /// An expression that never needs parenthesis such as `1337` or `[0; 42]`.
24 NonParen(Cow<'a, str>),
25 /// An expression that does not fit in other variants.
26 MaybeParen(Cow<'a, str>),
27 /// A binary operator expression, including `as`-casts and explicit type
29 BinOp(AssocOp, Cow<'a, str>),
32 /// Literal constant `1`, for convenience.
33 pub const ONE: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("1"));
35 impl Display for Sugg<'_> {
36 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
38 Sugg::NonParen(ref s) | Sugg::MaybeParen(ref s) | Sugg::BinOp(_, ref s) => s.fmt(f),
43 #[allow(clippy::wrong_self_convention)] // ok, because of the function `as_ty` method
45 /// Prepare a suggestion from an expression.
46 pub fn hir_opt(cx: &LateContext<'_, '_>, expr: &hir::Expr) -> Option<Self> {
47 snippet_opt(cx, expr.span).map(|snippet| {
48 let snippet = Cow::Owned(snippet);
49 Self::hir_from_snippet(expr, snippet)
53 /// Convenience function around `hir_opt` for suggestions with a default
55 pub fn hir(cx: &LateContext<'_, '_>, expr: &hir::Expr, default: &'a str) -> Self {
56 Self::hir_opt(cx, expr).unwrap_or_else(|| Sugg::NonParen(Cow::Borrowed(default)))
59 /// Same as `hir`, but it adapts the applicability level by following rules:
61 /// - Applicability level `Unspecified` will never be changed.
62 /// - If the span is inside a macro, change the applicability level to `MaybeIncorrect`.
63 /// - If the default value is used and the applicability level is `MachineApplicable`, change it
66 pub fn hir_with_applicability(
67 cx: &LateContext<'_, '_>,
70 applicability: &mut Applicability,
72 if *applicability != Applicability::Unspecified && in_macro(expr.span) {
73 *applicability = Applicability::MaybeIncorrect;
75 Self::hir_opt(cx, expr).unwrap_or_else(|| {
76 if *applicability == Applicability::MachineApplicable {
77 *applicability = Applicability::HasPlaceholders;
79 Sugg::NonParen(Cow::Borrowed(default))
83 /// Same as `hir`, but will use the pre expansion span if the `expr` was in a macro.
84 pub fn hir_with_macro_callsite(cx: &LateContext<'_, '_>, expr: &hir::Expr, default: &'a str) -> Self {
85 let snippet = snippet_with_macro_callsite(cx, expr.span, default);
87 Self::hir_from_snippet(expr, snippet)
90 /// Generate a suggestion for an expression with the given snippet. This is used by the `hir_*`
91 /// function variants of `Sugg`, since these use different snippet functions.
92 fn hir_from_snippet(expr: &hir::Expr, snippet: Cow<'a, str>) -> Self {
94 hir::ExprKind::AddrOf(..)
95 | hir::ExprKind::Box(..)
96 | hir::ExprKind::Closure(.., _)
97 | hir::ExprKind::If(..)
98 | hir::ExprKind::Unary(..)
99 | hir::ExprKind::Match(..) => Sugg::MaybeParen(snippet),
100 hir::ExprKind::Continue(..)
101 | hir::ExprKind::Yield(..)
102 | hir::ExprKind::Array(..)
103 | hir::ExprKind::Block(..)
104 | hir::ExprKind::Break(..)
105 | hir::ExprKind::Call(..)
106 | hir::ExprKind::Field(..)
107 | hir::ExprKind::Index(..)
108 | hir::ExprKind::InlineAsm(..)
109 | hir::ExprKind::Lit(..)
110 | hir::ExprKind::Loop(..)
111 | hir::ExprKind::MethodCall(..)
112 | hir::ExprKind::Path(..)
113 | hir::ExprKind::Repeat(..)
114 | hir::ExprKind::Ret(..)
115 | hir::ExprKind::Struct(..)
116 | hir::ExprKind::Tup(..)
117 | hir::ExprKind::While(..)
118 | hir::ExprKind::Use(_)
119 | hir::ExprKind::Err => Sugg::NonParen(snippet),
120 hir::ExprKind::Assign(..) => Sugg::BinOp(AssocOp::Assign, snippet),
121 hir::ExprKind::AssignOp(op, ..) => Sugg::BinOp(hirbinop2assignop(op), snippet),
122 hir::ExprKind::Binary(op, ..) => Sugg::BinOp(AssocOp::from_ast_binop(higher::binop(op.node)), snippet),
123 hir::ExprKind::Cast(..) => Sugg::BinOp(AssocOp::As, snippet),
124 hir::ExprKind::Type(..) => Sugg::BinOp(AssocOp::Colon, snippet),
128 /// Prepare a suggestion from an expression.
129 pub fn ast(cx: &EarlyContext<'_>, expr: &ast::Expr, default: &'a str) -> Self {
130 use syntax::ast::RangeLimits;
132 let snippet = snippet(cx, expr.span, default);
135 ast::ExprKind::AddrOf(..)
136 | ast::ExprKind::Box(..)
137 | ast::ExprKind::Closure(..)
138 | ast::ExprKind::If(..)
139 | ast::ExprKind::IfLet(..)
140 | ast::ExprKind::ObsoleteInPlace(..)
141 | ast::ExprKind::Unary(..)
142 | ast::ExprKind::Match(..) => Sugg::MaybeParen(snippet),
143 ast::ExprKind::Async(..)
144 | ast::ExprKind::Block(..)
145 | ast::ExprKind::Break(..)
146 | ast::ExprKind::Call(..)
147 | ast::ExprKind::Continue(..)
148 | ast::ExprKind::Yield(..)
149 | ast::ExprKind::Field(..)
150 | ast::ExprKind::ForLoop(..)
151 | ast::ExprKind::Index(..)
152 | ast::ExprKind::InlineAsm(..)
153 | ast::ExprKind::Lit(..)
154 | ast::ExprKind::Loop(..)
155 | ast::ExprKind::Mac(..)
156 | ast::ExprKind::MethodCall(..)
157 | ast::ExprKind::Paren(..)
158 | ast::ExprKind::Path(..)
159 | ast::ExprKind::Repeat(..)
160 | ast::ExprKind::Ret(..)
161 | ast::ExprKind::Struct(..)
162 | ast::ExprKind::Try(..)
163 | ast::ExprKind::TryBlock(..)
164 | ast::ExprKind::Tup(..)
165 | ast::ExprKind::Array(..)
166 | ast::ExprKind::While(..)
167 | ast::ExprKind::WhileLet(..)
168 | ast::ExprKind::Err => Sugg::NonParen(snippet),
169 ast::ExprKind::Range(.., RangeLimits::HalfOpen) => Sugg::BinOp(AssocOp::DotDot, snippet),
170 ast::ExprKind::Range(.., RangeLimits::Closed) => Sugg::BinOp(AssocOp::DotDotEq, snippet),
171 ast::ExprKind::Assign(..) => Sugg::BinOp(AssocOp::Assign, snippet),
172 ast::ExprKind::AssignOp(op, ..) => Sugg::BinOp(astbinop2assignop(op), snippet),
173 ast::ExprKind::Binary(op, ..) => Sugg::BinOp(AssocOp::from_ast_binop(op.node), snippet),
174 ast::ExprKind::Cast(..) => Sugg::BinOp(AssocOp::As, snippet),
175 ast::ExprKind::Type(..) => Sugg::BinOp(AssocOp::Colon, snippet),
179 /// Convenience method to create the `<lhs> && <rhs>` suggestion.
180 pub fn and(self, rhs: &Self) -> Sugg<'static> {
181 make_binop(ast::BinOpKind::And, &self, rhs)
184 /// Convenience method to create the `<lhs> & <rhs>` suggestion.
185 pub fn bit_and(self, rhs: &Self) -> Sugg<'static> {
186 make_binop(ast::BinOpKind::BitAnd, &self, rhs)
189 /// Convenience method to create the `<lhs> as <rhs>` suggestion.
190 pub fn as_ty<R: Display>(self, rhs: R) -> Sugg<'static> {
191 make_assoc(AssocOp::As, &self, &Sugg::NonParen(rhs.to_string().into()))
194 /// Convenience method to create the `&<expr>` suggestion.
195 pub fn addr(self) -> Sugg<'static> {
199 /// Convenience method to create the `&mut <expr>` suggestion.
200 pub fn mut_addr(self) -> Sugg<'static> {
201 make_unop("&mut ", self)
204 /// Convenience method to create the `*<expr>` suggestion.
205 pub fn deref(self) -> Sugg<'static> {
209 /// Convenience method to create the `&*<expr>` suggestion. Currently this
210 /// is needed because `sugg.deref().addr()` produces an unnecessary set of
211 /// parentheses around the deref.
212 pub fn addr_deref(self) -> Sugg<'static> {
213 make_unop("&*", self)
216 /// Convenience method to create the `&mut *<expr>` suggestion. Currently
217 /// this is needed because `sugg.deref().mut_addr()` produces an unnecessary
218 /// set of parentheses around the deref.
219 pub fn mut_addr_deref(self) -> Sugg<'static> {
220 make_unop("&mut *", self)
223 /// Convenience method to transform suggestion into a return call
224 pub fn make_return(self) -> Sugg<'static> {
225 Sugg::NonParen(Cow::Owned(format!("return {}", self)))
228 /// Convenience method to transform suggestion into a block
229 /// where the suggestion is a trailing expression
230 pub fn blockify(self) -> Sugg<'static> {
231 Sugg::NonParen(Cow::Owned(format!("{{ {} }}", self)))
234 /// Convenience method to create the `<lhs>..<rhs>` or `<lhs>...<rhs>`
237 pub fn range(self, end: &Self, limit: ast::RangeLimits) -> Sugg<'static> {
239 ast::RangeLimits::HalfOpen => make_assoc(AssocOp::DotDot, &self, end),
240 ast::RangeLimits::Closed => make_assoc(AssocOp::DotDotEq, &self, end),
244 /// Adds parenthesis to any expression that might need them. Suitable to the
245 /// `self` argument of a method call
246 /// (e.g., to build `bar.foo()` or `(1 + 2).foo()`).
247 pub fn maybe_par(self) -> Self {
249 Sugg::NonParen(..) => self,
250 // `(x)` and `(x).y()` both don't need additional parens.
251 Sugg::MaybeParen(sugg) => {
252 if sugg.starts_with('(') && sugg.ends_with(')') {
253 Sugg::MaybeParen(sugg)
255 Sugg::NonParen(format!("({})", sugg).into())
258 Sugg::BinOp(_, sugg) => Sugg::NonParen(format!("({})", sugg).into()),
263 impl<'a, 'b> std::ops::Add<Sugg<'b>> for Sugg<'a> {
264 type Output = Sugg<'static>;
265 fn add(self, rhs: Sugg<'b>) -> Sugg<'static> {
266 make_binop(ast::BinOpKind::Add, &self, &rhs)
270 impl<'a, 'b> std::ops::Sub<Sugg<'b>> for Sugg<'a> {
271 type Output = Sugg<'static>;
272 fn sub(self, rhs: Sugg<'b>) -> Sugg<'static> {
273 make_binop(ast::BinOpKind::Sub, &self, &rhs)
277 impl<'a> std::ops::Not for Sugg<'a> {
278 type Output = Sugg<'static>;
279 fn not(self) -> Sugg<'static> {
284 /// Helper type to display either `foo` or `(foo)`.
285 struct ParenHelper<T> {
286 /// `true` if parentheses are needed.
288 /// The main thing to display.
292 impl<T> ParenHelper<T> {
293 /// Builds a `ParenHelper`.
294 fn new(paren: bool, wrapped: T) -> Self {
295 Self { paren, wrapped }
299 impl<T: Display> Display for ParenHelper<T> {
300 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
302 write!(f, "({})", self.wrapped)
309 /// Builds the string for `<op><expr>` adding parenthesis when necessary.
311 /// For convenience, the operator is taken as a string because all unary
312 /// operators have the same
314 pub fn make_unop(op: &str, expr: Sugg<'_>) -> Sugg<'static> {
315 Sugg::MaybeParen(format!("{}{}", op, expr.maybe_par()).into())
318 /// Builds the string for `<lhs> <op> <rhs>` adding parenthesis when necessary.
320 /// Precedence of shift operator relative to other arithmetic operation is
321 /// often confusing so
322 /// parenthesis will always be added for a mix of these.
323 pub fn make_assoc(op: AssocOp, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
324 /// Returns `true` if the operator is a shift operator `<<` or `>>`.
325 fn is_shift(op: &AssocOp) -> bool {
326 matches!(*op, AssocOp::ShiftLeft | AssocOp::ShiftRight)
329 /// Returns `true` if the operator is a arithmetic operator
330 /// (i.e., `+`, `-`, `*`, `/`, `%`).
331 fn is_arith(op: &AssocOp) -> bool {
334 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide | AssocOp::Modulus
338 /// Returns `true` if the operator `op` needs parenthesis with the operator
339 /// `other` in the direction `dir`.
340 fn needs_paren(op: &AssocOp, other: &AssocOp, dir: Associativity) -> bool {
341 other.precedence() < op.precedence()
342 || (other.precedence() == op.precedence()
343 && ((op != other && associativity(op) != dir)
344 || (op == other && associativity(op) != Associativity::Both)))
345 || is_shift(op) && is_arith(other)
346 || is_shift(other) && is_arith(op)
349 let lhs_paren = if let Sugg::BinOp(ref lop, _) = *lhs {
350 needs_paren(&op, lop, Associativity::Left)
355 let rhs_paren = if let Sugg::BinOp(ref rop, _) = *rhs {
356 needs_paren(&op, rop, Associativity::Right)
361 let lhs = ParenHelper::new(lhs_paren, lhs);
362 let rhs = ParenHelper::new(rhs_paren, rhs);
363 let sugg = match op {
371 | AssocOp::GreaterEqual
380 | AssocOp::ShiftRight
381 | AssocOp::Subtract => format!(
384 op.to_ast_binop().expect("Those are AST ops").to_string(),
387 AssocOp::Assign => format!("{} = {}", lhs, rhs),
388 AssocOp::ObsoleteInPlace => format!("in ({}) {}", lhs, rhs),
389 AssocOp::AssignOp(op) => format!("{} {}= {}", lhs, token_to_string(&token::BinOp(op)), rhs),
390 AssocOp::As => format!("{} as {}", lhs, rhs),
391 AssocOp::DotDot => format!("{}..{}", lhs, rhs),
392 AssocOp::DotDotEq => format!("{}..={}", lhs, rhs),
393 AssocOp::Colon => format!("{}: {}", lhs, rhs),
396 Sugg::BinOp(op, sugg.into())
399 /// Convenience wrapper around `make_assoc` and `AssocOp::from_ast_binop`.
400 pub fn make_binop(op: ast::BinOpKind, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
401 make_assoc(AssocOp::from_ast_binop(op), lhs, rhs)
404 #[derive(PartialEq, Eq, Clone, Copy)]
405 /// Operator associativity.
407 /// The operator is both left-associative and right-associative.
409 /// The operator is left-associative.
411 /// The operator is not associative.
413 /// The operator is right-associative.
417 /// Returns the associativity/fixity of an operator. The difference with
418 /// `AssocOp::fixity` is that an operator can be both left and right associative
419 /// (such as `+`: `a + b + c == (a + b) + c == a + (b + c)`.
421 /// Chained `as` and explicit `:` type coercion never need inner parenthesis so
422 /// they are considered
424 fn associativity(op: &AssocOp) -> Associativity {
425 use syntax::util::parser::AssocOp::*;
428 ObsoleteInPlace | Assign | AssignOp(_) => Associativity::Right,
429 Add | BitAnd | BitOr | BitXor | LAnd | LOr | Multiply | As | Colon => Associativity::Both,
430 Divide | Equal | Greater | GreaterEqual | Less | LessEqual | Modulus | NotEqual | ShiftLeft | ShiftRight
431 | Subtract => Associativity::Left,
432 DotDot | DotDotEq => Associativity::None,
436 /// Converts a `hir::BinOp` to the corresponding assigning binary operator.
437 fn hirbinop2assignop(op: hir::BinOp) -> AssocOp {
438 use syntax::parse::token::BinOpToken::*;
440 AssocOp::AssignOp(match op.node {
441 hir::BinOpKind::Add => Plus,
442 hir::BinOpKind::BitAnd => And,
443 hir::BinOpKind::BitOr => Or,
444 hir::BinOpKind::BitXor => Caret,
445 hir::BinOpKind::Div => Slash,
446 hir::BinOpKind::Mul => Star,
447 hir::BinOpKind::Rem => Percent,
448 hir::BinOpKind::Shl => Shl,
449 hir::BinOpKind::Shr => Shr,
450 hir::BinOpKind::Sub => Minus,
459 | hir::BinOpKind::Or => panic!("This operator does not exist"),
463 /// Converts an `ast::BinOp` to the corresponding assigning binary operator.
464 fn astbinop2assignop(op: ast::BinOp) -> AssocOp {
465 use syntax::ast::BinOpKind::*;
466 use syntax::parse::token::BinOpToken;
468 AssocOp::AssignOp(match op.node {
469 Add => BinOpToken::Plus,
470 BitAnd => BinOpToken::And,
471 BitOr => BinOpToken::Or,
472 BitXor => BinOpToken::Caret,
473 Div => BinOpToken::Slash,
474 Mul => BinOpToken::Star,
475 Rem => BinOpToken::Percent,
476 Shl => BinOpToken::Shl,
477 Shr => BinOpToken::Shr,
478 Sub => BinOpToken::Minus,
479 And | Eq | Ge | Gt | Le | Lt | Ne | Or => panic!("This operator does not exist"),
483 /// Returns the indentation before `span` if there are nothing but `[ \t]`
484 /// before it on its line.
485 fn indentation<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Option<String> {
486 let lo = cx.sess().source_map().lookup_char_pos(span.lo());
487 if let Some(line) = lo.file.get_line(lo.line - 1 /* line numbers in `Loc` are 1-based */) {
488 if let Some((pos, _)) = line.char_indices().find(|&(_, c)| c != ' ' && c != '\t') {
489 // We can mix char and byte positions here because we only consider `[ \t]`.
490 if lo.col == CharPos(pos) {
491 Some(line[..pos].into())
503 /// Convenience extension trait for `DiagnosticBuilder`.
504 pub trait DiagnosticBuilderExt<'a, T: LintContext<'a>> {
505 /// Suggests to add an attribute to an item.
507 /// Correctly handles indentation of the attribute and item.
512 /// db.suggest_item_with_attr(cx, item, "#[derive(Default)]");
514 fn suggest_item_with_attr<D: Display + ?Sized>(
520 applicability: Applicability,
523 /// Suggest to add an item before another.
525 /// The item should not be indented (expect for inner indentation).
530 /// db.suggest_prepend_item(cx, item,
535 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability);
537 /// Suggest to completely remove an item.
539 /// This will remove an item and all following whitespace until the next non-whitespace
540 /// character. This should work correctly if item is on the same indentation level as the
546 /// db.suggest_remove_item(cx, item, "remove this")
548 fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability);
551 impl<'a, 'b, 'c, T: LintContext<'c>> DiagnosticBuilderExt<'c, T> for rustc_errors::DiagnosticBuilder<'b> {
552 fn suggest_item_with_attr<D: Display + ?Sized>(
558 applicability: Applicability,
560 if let Some(indent) = indentation(cx, item) {
561 let span = item.with_hi(item.lo());
563 self.span_suggestion(span, msg, format!("{}\n{}", attr, indent), applicability);
567 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability) {
568 if let Some(indent) = indentation(cx, item) {
569 let span = item.with_hi(item.lo());
571 let mut first = true;
572 let new_item = new_item
579 format!("{}{}\n", indent, l)
582 .collect::<String>();
584 self.span_suggestion(span, msg, format!("{}\n{}", new_item, indent), applicability);
588 fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability) {
589 let mut remove_span = item;
590 let hi = cx.sess().source_map().next_point(remove_span).hi();
591 let fmpos = cx.sess().source_map().lookup_byte_offset(hi);
593 if let Some(ref src) = fmpos.sf.src {
594 let non_whitespace_offset = src[fmpos.pos.to_usize()..].find(|c| c != ' ' && c != '\t' && c != '\n');
596 if let Some(non_whitespace_offset) = non_whitespace_offset {
597 remove_span = remove_span
598 .with_hi(remove_span.hi() + BytePos(non_whitespace_offset.try_into().expect("offset too large")))
602 self.span_suggestion(remove_span, msg, String::new(), applicability);
609 use std::borrow::Cow;
611 const SUGGESTION: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("function_call()"));
614 fn make_return_transform_sugg_into_a_return_call() {
615 assert_eq!("return function_call()", SUGGESTION.make_return().to_string());
619 fn blockify_transforms_sugg_into_a_block() {
620 assert_eq!("{ function_call() }", SUGGESTION.blockify().to_string());