1 //! Contains utility functions to generate suggestions.
2 #![deny(clippy::missing_docs_in_private_items)]
5 snippet, snippet_opt, snippet_with_applicability, snippet_with_context, snippet_with_macro_callsite,
7 use crate::{get_parent_expr_for_hir, higher};
8 use rustc_ast::util::parser::AssocOp;
9 use rustc_ast::{ast, token};
10 use rustc_ast_pretty::pprust::token_kind_to_string;
11 use rustc_errors::Applicability;
13 use rustc_hir::{ExprKind, HirId, MutTy, TyKind};
14 use rustc_infer::infer::TyCtxtInferExt;
15 use rustc_lint::{EarlyContext, LateContext, LintContext};
16 use rustc_middle::hir::place::ProjectionKind;
17 use rustc_middle::mir::{FakeReadCause, Mutability};
19 use rustc_span::source_map::{BytePos, CharPos, Pos, Span, SyntaxContext};
20 use rustc_typeck::expr_use_visitor::{Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId};
22 use std::convert::TryInto;
23 use std::fmt::Display;
25 use std::ops::{Add, Neg, Not, Sub};
27 /// A helper type to build suggestion correctly handling parentheses.
28 #[derive(Clone, PartialEq)]
30 /// An expression that never needs parentheses such as `1337` or `[0; 42]`.
31 NonParen(Cow<'a, str>),
32 /// An expression that does not fit in other variants.
33 MaybeParen(Cow<'a, str>),
34 /// A binary operator expression, including `as`-casts and explicit type
36 BinOp(AssocOp, Cow<'a, str>),
39 /// Literal constant `0`, for convenience.
40 pub const ZERO: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("0"));
41 /// Literal constant `1`, for convenience.
42 pub const ONE: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("1"));
43 /// a constant represents an empty string, for convenience.
44 pub const EMPTY: Sugg<'static> = Sugg::NonParen(Cow::Borrowed(""));
46 impl Display for Sugg<'_> {
47 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
49 Sugg::NonParen(ref s) | Sugg::MaybeParen(ref s) | Sugg::BinOp(_, ref s) => s.fmt(f),
54 #[allow(clippy::wrong_self_convention)] // ok, because of the function `as_ty` method
56 /// Prepare a suggestion from an expression.
57 pub fn hir_opt(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option<Self> {
58 snippet_opt(cx, expr.span).map(|snippet| {
59 let snippet = Cow::Owned(snippet);
60 Self::hir_from_snippet(expr, snippet)
64 /// Convenience function around `hir_opt` for suggestions with a default
66 pub fn hir(cx: &LateContext<'_>, expr: &hir::Expr<'_>, default: &'a str) -> Self {
67 Self::hir_opt(cx, expr).unwrap_or(Sugg::NonParen(Cow::Borrowed(default)))
70 /// Same as `hir`, but it adapts the applicability level by following rules:
72 /// - Applicability level `Unspecified` will never be changed.
73 /// - If the span is inside a macro, change the applicability level to `MaybeIncorrect`.
74 /// - If the default value is used and the applicability level is `MachineApplicable`, change it
77 pub fn hir_with_applicability(
81 applicability: &mut Applicability,
83 if *applicability != Applicability::Unspecified && expr.span.from_expansion() {
84 *applicability = Applicability::MaybeIncorrect;
86 Self::hir_opt(cx, expr).unwrap_or_else(|| {
87 if *applicability == Applicability::MachineApplicable {
88 *applicability = Applicability::HasPlaceholders;
90 Sugg::NonParen(Cow::Borrowed(default))
94 /// Same as `hir`, but will use the pre expansion span if the `expr` was in a macro.
95 pub fn hir_with_macro_callsite(cx: &LateContext<'_>, expr: &hir::Expr<'_>, default: &'a str) -> Self {
96 let snippet = snippet_with_macro_callsite(cx, expr.span, default);
98 Self::hir_from_snippet(expr, snippet)
101 /// Same as `hir`, but first walks the span up to the given context. This will result in the
102 /// macro call, rather then the expansion, if the span is from a child context. If the span is
103 /// not from a child context, it will be used directly instead.
105 /// e.g. Given the expression `&vec![]`, getting a snippet from the span for `vec![]` as a HIR
106 /// node would result in `box []`. If given the context of the address of expression, this
107 /// function will correctly get a snippet of `vec![]`.
108 pub fn hir_with_context(
109 cx: &LateContext<'_>,
110 expr: &hir::Expr<'_>,
113 applicability: &mut Applicability,
115 let (snippet, in_macro) = snippet_with_context(cx, expr.span, ctxt, default, applicability);
118 Sugg::NonParen(snippet)
120 Self::hir_from_snippet(expr, snippet)
124 /// Generate a suggestion for an expression with the given snippet. This is used by the `hir_*`
125 /// function variants of `Sugg`, since these use different snippet functions.
126 fn hir_from_snippet(expr: &hir::Expr<'_>, snippet: Cow<'a, str>) -> Self {
127 if let Some(range) = higher::Range::hir(expr) {
128 let op = match range.limits {
129 ast::RangeLimits::HalfOpen => AssocOp::DotDot,
130 ast::RangeLimits::Closed => AssocOp::DotDotEq,
132 return Sugg::BinOp(op, snippet);
136 hir::ExprKind::AddrOf(..)
137 | hir::ExprKind::Box(..)
138 | hir::ExprKind::If(..)
139 | hir::ExprKind::Let(..)
140 | hir::ExprKind::Closure(..)
141 | hir::ExprKind::Unary(..)
142 | hir::ExprKind::Match(..) => Sugg::MaybeParen(snippet),
143 hir::ExprKind::Continue(..)
144 | hir::ExprKind::Yield(..)
145 | hir::ExprKind::Array(..)
146 | hir::ExprKind::Block(..)
147 | hir::ExprKind::Break(..)
148 | hir::ExprKind::Call(..)
149 | hir::ExprKind::Field(..)
150 | hir::ExprKind::Index(..)
151 | hir::ExprKind::InlineAsm(..)
152 | hir::ExprKind::LlvmInlineAsm(..)
153 | hir::ExprKind::ConstBlock(..)
154 | hir::ExprKind::Lit(..)
155 | hir::ExprKind::Loop(..)
156 | hir::ExprKind::MethodCall(..)
157 | hir::ExprKind::Path(..)
158 | hir::ExprKind::Repeat(..)
159 | hir::ExprKind::Ret(..)
160 | hir::ExprKind::Struct(..)
161 | hir::ExprKind::Tup(..)
162 | hir::ExprKind::DropTemps(_)
163 | hir::ExprKind::Err => Sugg::NonParen(snippet),
164 hir::ExprKind::Assign(..) => Sugg::BinOp(AssocOp::Assign, snippet),
165 hir::ExprKind::AssignOp(op, ..) => Sugg::BinOp(hirbinop2assignop(op), snippet),
166 hir::ExprKind::Binary(op, ..) => Sugg::BinOp(AssocOp::from_ast_binop(op.node.into()), snippet),
167 hir::ExprKind::Cast(..) => Sugg::BinOp(AssocOp::As, snippet),
168 hir::ExprKind::Type(..) => Sugg::BinOp(AssocOp::Colon, snippet),
172 /// Prepare a suggestion from an expression.
173 pub fn ast(cx: &EarlyContext<'_>, expr: &ast::Expr, default: &'a str) -> Self {
174 use rustc_ast::ast::RangeLimits;
176 let snippet = if expr.span.from_expansion() {
177 snippet_with_macro_callsite(cx, expr.span, default)
179 snippet(cx, expr.span, default)
183 ast::ExprKind::AddrOf(..)
184 | ast::ExprKind::Box(..)
185 | ast::ExprKind::Closure(..)
186 | ast::ExprKind::If(..)
187 | ast::ExprKind::Let(..)
188 | ast::ExprKind::Unary(..)
189 | ast::ExprKind::Match(..) => Sugg::MaybeParen(snippet),
190 ast::ExprKind::Async(..)
191 | ast::ExprKind::Block(..)
192 | ast::ExprKind::Break(..)
193 | ast::ExprKind::Call(..)
194 | ast::ExprKind::Continue(..)
195 | ast::ExprKind::Yield(..)
196 | ast::ExprKind::Field(..)
197 | ast::ExprKind::ForLoop(..)
198 | ast::ExprKind::Index(..)
199 | ast::ExprKind::InlineAsm(..)
200 | ast::ExprKind::LlvmInlineAsm(..)
201 | ast::ExprKind::ConstBlock(..)
202 | ast::ExprKind::Lit(..)
203 | ast::ExprKind::Loop(..)
204 | ast::ExprKind::MacCall(..)
205 | ast::ExprKind::MethodCall(..)
206 | ast::ExprKind::Paren(..)
207 | ast::ExprKind::Underscore
208 | ast::ExprKind::Path(..)
209 | ast::ExprKind::Repeat(..)
210 | ast::ExprKind::Ret(..)
211 | ast::ExprKind::Struct(..)
212 | ast::ExprKind::Try(..)
213 | ast::ExprKind::TryBlock(..)
214 | ast::ExprKind::Tup(..)
215 | ast::ExprKind::Array(..)
216 | ast::ExprKind::While(..)
217 | ast::ExprKind::Await(..)
218 | ast::ExprKind::Err => Sugg::NonParen(snippet),
219 ast::ExprKind::Range(.., RangeLimits::HalfOpen) => Sugg::BinOp(AssocOp::DotDot, snippet),
220 ast::ExprKind::Range(.., RangeLimits::Closed) => Sugg::BinOp(AssocOp::DotDotEq, snippet),
221 ast::ExprKind::Assign(..) => Sugg::BinOp(AssocOp::Assign, snippet),
222 ast::ExprKind::AssignOp(op, ..) => Sugg::BinOp(astbinop2assignop(op), snippet),
223 ast::ExprKind::Binary(op, ..) => Sugg::BinOp(AssocOp::from_ast_binop(op.node), snippet),
224 ast::ExprKind::Cast(..) => Sugg::BinOp(AssocOp::As, snippet),
225 ast::ExprKind::Type(..) => Sugg::BinOp(AssocOp::Colon, snippet),
229 /// Convenience method to create the `<lhs> && <rhs>` suggestion.
230 pub fn and(self, rhs: &Self) -> Sugg<'static> {
231 make_binop(ast::BinOpKind::And, &self, rhs)
234 /// Convenience method to create the `<lhs> & <rhs>` suggestion.
235 pub fn bit_and(self, rhs: &Self) -> Sugg<'static> {
236 make_binop(ast::BinOpKind::BitAnd, &self, rhs)
239 /// Convenience method to create the `<lhs> as <rhs>` suggestion.
240 pub fn as_ty<R: Display>(self, rhs: R) -> Sugg<'static> {
241 make_assoc(AssocOp::As, &self, &Sugg::NonParen(rhs.to_string().into()))
244 /// Convenience method to create the `&<expr>` suggestion.
245 pub fn addr(self) -> Sugg<'static> {
249 /// Convenience method to create the `&mut <expr>` suggestion.
250 pub fn mut_addr(self) -> Sugg<'static> {
251 make_unop("&mut ", self)
254 /// Convenience method to create the `*<expr>` suggestion.
255 pub fn deref(self) -> Sugg<'static> {
259 /// Convenience method to create the `&*<expr>` suggestion. Currently this
260 /// is needed because `sugg.deref().addr()` produces an unnecessary set of
261 /// parentheses around the deref.
262 pub fn addr_deref(self) -> Sugg<'static> {
263 make_unop("&*", self)
266 /// Convenience method to create the `&mut *<expr>` suggestion. Currently
267 /// this is needed because `sugg.deref().mut_addr()` produces an unnecessary
268 /// set of parentheses around the deref.
269 pub fn mut_addr_deref(self) -> Sugg<'static> {
270 make_unop("&mut *", self)
273 /// Convenience method to transform suggestion into a return call
274 pub fn make_return(self) -> Sugg<'static> {
275 Sugg::NonParen(Cow::Owned(format!("return {}", self)))
278 /// Convenience method to transform suggestion into a block
279 /// where the suggestion is a trailing expression
280 pub fn blockify(self) -> Sugg<'static> {
281 Sugg::NonParen(Cow::Owned(format!("{{ {} }}", self)))
284 /// Convenience method to create the `<lhs>..<rhs>` or `<lhs>...<rhs>`
287 pub fn range(self, end: &Self, limit: ast::RangeLimits) -> Sugg<'static> {
289 ast::RangeLimits::HalfOpen => make_assoc(AssocOp::DotDot, &self, end),
290 ast::RangeLimits::Closed => make_assoc(AssocOp::DotDotEq, &self, end),
294 /// Adds parentheses to any expression that might need them. Suitable to the
295 /// `self` argument of a method call
296 /// (e.g., to build `bar.foo()` or `(1 + 2).foo()`).
298 pub fn maybe_par(self) -> Self {
300 Sugg::NonParen(..) => self,
301 // `(x)` and `(x).y()` both don't need additional parens.
302 Sugg::MaybeParen(sugg) => {
303 if has_enclosing_paren(&sugg) {
304 Sugg::MaybeParen(sugg)
306 Sugg::NonParen(format!("({})", sugg).into())
309 Sugg::BinOp(_, sugg) => {
310 if has_enclosing_paren(&sugg) {
313 Sugg::NonParen(format!("({})", sugg).into())
320 /// Return `true` if `sugg` is enclosed in parenthesis.
321 fn has_enclosing_paren(sugg: impl AsRef<str>) -> bool {
322 let mut chars = sugg.as_ref().chars();
323 if chars.next() == Some('(') {
325 for c in &mut chars {
335 chars.next().is_none()
341 /// Copied from the rust standard library, and then edited
342 macro_rules! forward_binop_impls_to_ref {
343 (impl $imp:ident, $method:ident for $t:ty, type Output = $o:ty) => {
344 impl $imp<$t> for &$t {
347 fn $method(self, other: $t) -> $o {
348 $imp::$method(self, &other)
352 impl $imp<&$t> for $t {
355 fn $method(self, other: &$t) -> $o {
356 $imp::$method(&self, other)
363 fn $method(self, other: $t) -> $o {
364 $imp::$method(&self, &other)
370 impl Add for &Sugg<'_> {
371 type Output = Sugg<'static>;
372 fn add(self, rhs: &Sugg<'_>) -> Sugg<'static> {
373 make_binop(ast::BinOpKind::Add, self, rhs)
377 impl Sub for &Sugg<'_> {
378 type Output = Sugg<'static>;
379 fn sub(self, rhs: &Sugg<'_>) -> Sugg<'static> {
380 make_binop(ast::BinOpKind::Sub, self, rhs)
384 forward_binop_impls_to_ref!(impl Add, add for Sugg<'_>, type Output = Sugg<'static>);
385 forward_binop_impls_to_ref!(impl Sub, sub for Sugg<'_>, type Output = Sugg<'static>);
387 impl Neg for Sugg<'_> {
388 type Output = Sugg<'static>;
389 fn neg(self) -> Sugg<'static> {
394 impl Not for Sugg<'_> {
395 type Output = Sugg<'static>;
396 fn not(self) -> Sugg<'static> {
397 use AssocOp::{Equal, Greater, GreaterEqual, Less, LessEqual, NotEqual};
399 /// Convert ```AssocOp``` to a string of operators.
400 fn op_as_str(op: AssocOp) -> &'static str {
401 op.to_ast_binop().unwrap().to_string()
404 /// Replace the operator in the Snippet.
405 fn replace_op(from_op: AssocOp, to_op: AssocOp, snip: Cow<'_, str>) -> Sugg<'static> {
406 let from = op_as_str(from_op);
407 let to = op_as_str(to_op);
408 let snip = snip.into_owned().replace(from, to);
409 Sugg::BinOp(to_op, Cow::Owned(snip))
412 if let Sugg::BinOp(op, snip) = self {
414 Equal => replace_op(op, NotEqual, snip),
415 NotEqual => replace_op(op, Equal, snip),
416 Less => replace_op(op, GreaterEqual, snip),
417 GreaterEqual => replace_op(op, Less, snip),
418 Greater => replace_op(op, LessEqual, snip),
419 LessEqual => replace_op(op, Greater, snip),
420 _ => make_unop("!", Sugg::BinOp(op, snip)),
428 /// Helper type to display either `foo` or `(foo)`.
429 struct ParenHelper<T> {
430 /// `true` if parentheses are needed.
432 /// The main thing to display.
436 impl<T> ParenHelper<T> {
437 /// Builds a `ParenHelper`.
438 fn new(paren: bool, wrapped: T) -> Self {
439 Self { paren, wrapped }
443 impl<T: Display> Display for ParenHelper<T> {
444 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
446 write!(f, "({})", self.wrapped)
453 /// Builds the string for `<op><expr>` adding parenthesis when necessary.
455 /// For convenience, the operator is taken as a string because all unary
456 /// operators have the same
458 pub fn make_unop(op: &str, expr: Sugg<'_>) -> Sugg<'static> {
459 Sugg::MaybeParen(format!("{}{}", op, expr.maybe_par()).into())
462 /// Builds the string for `<lhs> <op> <rhs>` adding parenthesis when necessary.
464 /// Precedence of shift operator relative to other arithmetic operation is
465 /// often confusing so
466 /// parenthesis will always be added for a mix of these.
467 pub fn make_assoc(op: AssocOp, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
468 /// Returns `true` if the operator is a shift operator `<<` or `>>`.
469 fn is_shift(op: AssocOp) -> bool {
470 matches!(op, AssocOp::ShiftLeft | AssocOp::ShiftRight)
473 /// Returns `true` if the operator is an arithmetic operator
474 /// (i.e., `+`, `-`, `*`, `/`, `%`).
475 fn is_arith(op: AssocOp) -> bool {
478 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide | AssocOp::Modulus
482 /// Returns `true` if the operator `op` needs parenthesis with the operator
483 /// `other` in the direction `dir`.
484 fn needs_paren(op: AssocOp, other: AssocOp, dir: Associativity) -> bool {
485 other.precedence() < op.precedence()
486 || (other.precedence() == op.precedence()
487 && ((op != other && associativity(op) != dir)
488 || (op == other && associativity(op) != Associativity::Both)))
489 || is_shift(op) && is_arith(other)
490 || is_shift(other) && is_arith(op)
493 let lhs_paren = if let Sugg::BinOp(lop, _) = *lhs {
494 needs_paren(op, lop, Associativity::Left)
499 let rhs_paren = if let Sugg::BinOp(rop, _) = *rhs {
500 needs_paren(op, rop, Associativity::Right)
505 let lhs = ParenHelper::new(lhs_paren, lhs);
506 let rhs = ParenHelper::new(rhs_paren, rhs);
507 let sugg = match op {
515 | AssocOp::GreaterEqual
524 | AssocOp::ShiftRight
525 | AssocOp::Subtract => format!(
528 op.to_ast_binop().expect("Those are AST ops").to_string(),
531 AssocOp::Assign => format!("{} = {}", lhs, rhs),
532 AssocOp::AssignOp(op) => format!("{} {}= {}", lhs, token_kind_to_string(&token::BinOp(op)), rhs),
533 AssocOp::As => format!("{} as {}", lhs, rhs),
534 AssocOp::DotDot => format!("{}..{}", lhs, rhs),
535 AssocOp::DotDotEq => format!("{}..={}", lhs, rhs),
536 AssocOp::Colon => format!("{}: {}", lhs, rhs),
539 Sugg::BinOp(op, sugg.into())
542 /// Convenience wrapper around `make_assoc` and `AssocOp::from_ast_binop`.
543 pub fn make_binop(op: ast::BinOpKind, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
544 make_assoc(AssocOp::from_ast_binop(op), lhs, rhs)
547 #[derive(PartialEq, Eq, Clone, Copy)]
548 /// Operator associativity.
550 /// The operator is both left-associative and right-associative.
552 /// The operator is left-associative.
554 /// The operator is not associative.
556 /// The operator is right-associative.
560 /// Returns the associativity/fixity of an operator. The difference with
561 /// `AssocOp::fixity` is that an operator can be both left and right associative
562 /// (such as `+`: `a + b + c == (a + b) + c == a + (b + c)`.
564 /// Chained `as` and explicit `:` type coercion never need inner parenthesis so
565 /// they are considered
568 fn associativity(op: AssocOp) -> Associativity {
569 use rustc_ast::util::parser::AssocOp::{
570 Add, As, Assign, AssignOp, BitAnd, BitOr, BitXor, Colon, Divide, DotDot, DotDotEq, Equal, Greater,
571 GreaterEqual, LAnd, LOr, Less, LessEqual, Modulus, Multiply, NotEqual, ShiftLeft, ShiftRight, Subtract,
575 Assign | AssignOp(_) => Associativity::Right,
576 Add | BitAnd | BitOr | BitXor | LAnd | LOr | Multiply | As | Colon => Associativity::Both,
577 Divide | Equal | Greater | GreaterEqual | Less | LessEqual | Modulus | NotEqual | ShiftLeft | ShiftRight
578 | Subtract => Associativity::Left,
579 DotDot | DotDotEq => Associativity::None,
583 /// Converts a `hir::BinOp` to the corresponding assigning binary operator.
584 fn hirbinop2assignop(op: hir::BinOp) -> AssocOp {
585 use rustc_ast::token::BinOpToken::{And, Caret, Minus, Or, Percent, Plus, Shl, Shr, Slash, Star};
587 AssocOp::AssignOp(match op.node {
588 hir::BinOpKind::Add => Plus,
589 hir::BinOpKind::BitAnd => And,
590 hir::BinOpKind::BitOr => Or,
591 hir::BinOpKind::BitXor => Caret,
592 hir::BinOpKind::Div => Slash,
593 hir::BinOpKind::Mul => Star,
594 hir::BinOpKind::Rem => Percent,
595 hir::BinOpKind::Shl => Shl,
596 hir::BinOpKind::Shr => Shr,
597 hir::BinOpKind::Sub => Minus,
606 | hir::BinOpKind::Or => panic!("This operator does not exist"),
610 /// Converts an `ast::BinOp` to the corresponding assigning binary operator.
611 fn astbinop2assignop(op: ast::BinOp) -> AssocOp {
612 use rustc_ast::ast::BinOpKind::{
613 Add, And, BitAnd, BitOr, BitXor, Div, Eq, Ge, Gt, Le, Lt, Mul, Ne, Or, Rem, Shl, Shr, Sub,
615 use rustc_ast::token::BinOpToken;
617 AssocOp::AssignOp(match op.node {
618 Add => BinOpToken::Plus,
619 BitAnd => BinOpToken::And,
620 BitOr => BinOpToken::Or,
621 BitXor => BinOpToken::Caret,
622 Div => BinOpToken::Slash,
623 Mul => BinOpToken::Star,
624 Rem => BinOpToken::Percent,
625 Shl => BinOpToken::Shl,
626 Shr => BinOpToken::Shr,
627 Sub => BinOpToken::Minus,
628 And | Eq | Ge | Gt | Le | Lt | Ne | Or => panic!("This operator does not exist"),
632 /// Returns the indentation before `span` if there are nothing but `[ \t]`
633 /// before it on its line.
634 fn indentation<T: LintContext>(cx: &T, span: Span) -> Option<String> {
635 let lo = cx.sess().source_map().lookup_char_pos(span.lo());
637 .get_line(lo.line - 1 /* line numbers in `Loc` are 1-based */)
639 if let Some((pos, _)) = line.char_indices().find(|&(_, c)| c != ' ' && c != '\t') {
640 // We can mix char and byte positions here because we only consider `[ \t]`.
641 if lo.col == CharPos(pos) {
642 Some(line[..pos].into())
652 /// Convenience extension trait for `DiagnosticBuilder`.
653 pub trait DiagnosticBuilderExt<T: LintContext> {
654 /// Suggests to add an attribute to an item.
656 /// Correctly handles indentation of the attribute and item.
661 /// diag.suggest_item_with_attr(cx, item, "#[derive(Default)]");
663 fn suggest_item_with_attr<D: Display + ?Sized>(
669 applicability: Applicability,
672 /// Suggest to add an item before another.
674 /// The item should not be indented (except for inner indentation).
679 /// diag.suggest_prepend_item(cx, item,
684 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability);
686 /// Suggest to completely remove an item.
688 /// This will remove an item and all following whitespace until the next non-whitespace
689 /// character. This should work correctly if item is on the same indentation level as the
695 /// diag.suggest_remove_item(cx, item, "remove this")
697 fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability);
700 impl<T: LintContext> DiagnosticBuilderExt<T> for rustc_errors::DiagnosticBuilder<'_> {
701 fn suggest_item_with_attr<D: Display + ?Sized>(
707 applicability: Applicability,
709 if let Some(indent) = indentation(cx, item) {
710 let span = item.with_hi(item.lo());
712 self.span_suggestion(span, msg, format!("{}\n{}", attr, indent), applicability);
716 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability) {
717 if let Some(indent) = indentation(cx, item) {
718 let span = item.with_hi(item.lo());
720 let mut first = true;
721 let new_item = new_item
728 format!("{}{}\n", indent, l)
731 .collect::<String>();
733 self.span_suggestion(span, msg, format!("{}\n{}", new_item, indent), applicability);
737 fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability) {
738 let mut remove_span = item;
739 let hi = cx.sess().source_map().next_point(remove_span).hi();
740 let fmpos = cx.sess().source_map().lookup_byte_offset(hi);
742 if let Some(ref src) = fmpos.sf.src {
743 let non_whitespace_offset = src[fmpos.pos.to_usize()..].find(|c| c != ' ' && c != '\t' && c != '\n');
745 if let Some(non_whitespace_offset) = non_whitespace_offset {
746 remove_span = remove_span
747 .with_hi(remove_span.hi() + BytePos(non_whitespace_offset.try_into().expect("offset too large")));
751 self.span_suggestion(remove_span, msg, String::new(), applicability);
755 /// Suggestion results for handling closure
756 /// args dereferencing and borrowing
757 pub struct DerefClosure {
758 /// confidence on the built suggestion
759 pub applicability: Applicability,
760 /// gradually built suggestion
761 pub suggestion: String,
764 /// Build suggestion gradually by handling closure arg specific usages,
765 /// such as explicit deref and borrowing cases.
766 /// Returns `None` if no such use cases have been triggered in closure body
768 /// note: this only works on single line immutable closures with exactly one input parameter.
769 pub fn deref_closure_args<'tcx>(cx: &LateContext<'_>, closure: &'tcx hir::Expr<'_>) -> Option<DerefClosure> {
770 if let hir::ExprKind::Closure(_, fn_decl, body_id, ..) = closure.kind {
771 let closure_body = cx.tcx.hir().body(body_id);
772 // is closure arg a type annotated double reference (i.e.: `|x: &&i32| ...`)
773 // a type annotation is present if param `kind` is different from `TyKind::Infer`
774 let closure_arg_is_type_annotated_double_ref = if let TyKind::Rptr(_, MutTy { ty, .. }) = fn_decl.inputs[0].kind
776 matches!(ty.kind, TyKind::Rptr(_, MutTy { .. }))
781 let mut visitor = DerefDelegate {
783 closure_span: closure.span,
784 closure_arg_is_type_annotated_double_ref,
785 next_pos: closure.span.lo(),
786 suggestion_start: String::new(),
787 applicability: Applicability::MaybeIncorrect,
790 let fn_def_id = cx.tcx.hir().local_def_id(closure.hir_id);
791 cx.tcx.infer_ctxt().enter(|infcx| {
792 ExprUseVisitor::new(&mut visitor, &infcx, fn_def_id, cx.param_env, cx.typeck_results())
793 .consume_body(closure_body);
796 if !visitor.suggestion_start.is_empty() {
797 return Some(DerefClosure {
798 applicability: visitor.applicability,
799 suggestion: visitor.finish(),
806 /// Visitor struct used for tracking down
807 /// dereferencing and borrowing of closure's args
808 struct DerefDelegate<'a, 'tcx> {
809 /// The late context of the lint
810 cx: &'a LateContext<'tcx>,
811 /// The span of the input closure to adapt
813 /// Indicates if the arg of the closure is a type annotated double reference
814 closure_arg_is_type_annotated_double_ref: bool,
815 /// last position of the span to gradually build the suggestion
817 /// starting part of the gradually built suggestion
818 suggestion_start: String,
819 /// confidence on the built suggestion
820 applicability: Applicability,
823 impl DerefDelegate<'_, 'tcx> {
824 /// build final suggestion:
825 /// - create the ending part of suggestion
826 /// - concatenate starting and ending parts
827 /// - potentially remove needless borrowing
828 pub fn finish(&mut self) -> String {
829 let end_span = Span::new(self.next_pos, self.closure_span.hi(), self.closure_span.ctxt(), None);
830 let end_snip = snippet_with_applicability(self.cx, end_span, "..", &mut self.applicability);
831 let sugg = format!("{}{}", self.suggestion_start, end_snip);
832 if self.closure_arg_is_type_annotated_double_ref {
833 sugg.replacen('&', "", 1)
839 /// indicates whether the function from `parent_expr` takes its args by double reference
840 fn func_takes_arg_by_double_ref(&self, parent_expr: &'tcx hir::Expr<'_>, cmt_hir_id: HirId) -> bool {
841 let (call_args, inputs) = match parent_expr.kind {
842 ExprKind::MethodCall(_, _, call_args, _) => {
843 if let Some(method_did) = self.cx.typeck_results().type_dependent_def_id(parent_expr.hir_id) {
844 (call_args, self.cx.tcx.fn_sig(method_did).skip_binder().inputs())
849 ExprKind::Call(func, call_args) => {
850 let typ = self.cx.typeck_results().expr_ty(func);
851 (call_args, typ.fn_sig(self.cx.tcx).skip_binder().inputs())
856 iter::zip(call_args, inputs)
857 .any(|(arg, ty)| arg.hir_id == cmt_hir_id && matches!(ty.kind(), ty::Ref(_, inner, _) if inner.is_ref()))
861 impl<'tcx> Delegate<'tcx> for DerefDelegate<'_, 'tcx> {
862 fn consume(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
864 #[allow(clippy::too_many_lines)]
865 fn borrow(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId, _: ty::BorrowKind) {
866 if let PlaceBase::Local(id) = cmt.place.base {
867 let map = self.cx.tcx.hir();
868 let span = map.span(cmt.hir_id);
869 let start_span = Span::new(self.next_pos, span.lo(), span.ctxt(), None);
870 let mut start_snip = snippet_with_applicability(self.cx, start_span, "..", &mut self.applicability);
872 // identifier referring to the variable currently triggered (i.e.: `fp`)
873 let ident_str = map.name(id).to_string();
874 // full identifier that includes projection (i.e.: `fp.field`)
875 let ident_str_with_proj = snippet(self.cx, span, "..").to_string();
877 if cmt.place.projections.is_empty() {
878 // handle item without any projection, that needs an explicit borrowing
879 // i.e.: suggest `&x` instead of `x`
880 self.suggestion_start.push_str(&format!("{}&{}", start_snip, ident_str));
882 // cases where a parent `Call` or `MethodCall` is using the item
883 // i.e.: suggest `.contains(&x)` for `.find(|x| [1, 2, 3].contains(x)).is_none()`
885 // Note about method calls:
886 // - compiler automatically dereference references if the target type is a reference (works also for
888 // - `self` arguments in the case of `x.is_something()` are also automatically (de)referenced, and
889 // no projection should be suggested
890 if let Some(parent_expr) = get_parent_expr_for_hir(self.cx, cmt.hir_id) {
891 match &parent_expr.kind {
892 // given expression is the self argument and will be handled completely by the compiler
893 // i.e.: `|x| x.is_something()`
894 ExprKind::MethodCall(_, _, [self_expr, ..], _) if self_expr.hir_id == cmt.hir_id => {
895 self.suggestion_start
896 .push_str(&format!("{}{}", start_snip, ident_str_with_proj));
897 self.next_pos = span.hi();
900 // item is used in a call
901 // i.e.: `Call`: `|x| please(x)` or `MethodCall`: `|x| [1, 2, 3].contains(x)`
902 ExprKind::Call(_, [call_args @ ..]) | ExprKind::MethodCall(_, _, [_, call_args @ ..], _) => {
903 let expr = self.cx.tcx.hir().expect_expr(cmt.hir_id);
904 let arg_ty_kind = self.cx.typeck_results().expr_ty(expr).kind();
906 if matches!(arg_ty_kind, ty::Ref(_, _, Mutability::Not)) {
907 // suggest ampersand if call function is taking args by double reference
908 let takes_arg_by_double_ref =
909 self.func_takes_arg_by_double_ref(parent_expr, cmt.hir_id);
911 // compiler will automatically dereference field or index projection, so no need
912 // to suggest ampersand, but full identifier that includes projection is required
913 let has_field_or_index_projection =
914 cmt.place.projections.iter().any(|proj| {
915 matches!(proj.kind, ProjectionKind::Field(..) | ProjectionKind::Index)
918 // no need to bind again if the function doesn't take arg by double ref
919 // and if the item is already a double ref
920 let ident_sugg = if !call_args.is_empty()
921 && !takes_arg_by_double_ref
922 && (self.closure_arg_is_type_annotated_double_ref || has_field_or_index_projection)
924 let ident = if has_field_or_index_projection {
929 format!("{}{}", start_snip, ident)
931 format!("{}&{}", start_snip, ident_str)
933 self.suggestion_start.push_str(&ident_sugg);
934 self.next_pos = span.hi();
938 self.applicability = Applicability::Unspecified;
944 let mut replacement_str = ident_str;
945 let mut projections_handled = false;
946 cmt.place.projections.iter().enumerate().for_each(|(i, proj)| {
948 // Field projection like `|v| v.foo`
949 // no adjustment needed here, as field projections are handled by the compiler
950 ProjectionKind::Field(..) => match cmt.place.ty_before_projection(i).kind() {
951 ty::Adt(..) | ty::Tuple(_) => {
952 replacement_str = ident_str_with_proj.clone();
953 projections_handled = true;
957 // Index projection like `|x| foo[x]`
958 // the index is dropped so we can't get it to build the suggestion,
959 // so the span is set-up again to get more code, using `span.hi()` (i.e.: `foo[x]`)
960 // instead of `span.lo()` (i.e.: `foo`)
961 ProjectionKind::Index => {
962 let start_span = Span::new(self.next_pos, span.hi(), span.ctxt(), None);
963 start_snip = snippet_with_applicability(self.cx, start_span, "..", &mut self.applicability);
964 replacement_str.clear();
965 projections_handled = true;
967 // note: unable to trigger `Subslice` kind in tests
968 ProjectionKind::Subslice => (),
969 ProjectionKind::Deref => {
970 // Explicit derefs are typically handled later on, but
971 // some items do not need explicit deref, such as array accesses,
972 // so we mark them as already processed
973 // i.e.: don't suggest `*sub[1..4].len()` for `|sub| sub[1..4].len() == 3`
974 if let ty::Ref(_, inner, _) = cmt.place.ty_before_projection(i).kind() {
975 if matches!(inner.kind(), ty::Ref(_, innermost, _) if innermost.is_array()) {
976 projections_handled = true;
983 // handle `ProjectionKind::Deref` by removing one explicit deref
984 // if no special case was detected (i.e.: suggest `*x` instead of `**x`)
985 if !projections_handled {
990 .rposition(|proj| proj.kind == ProjectionKind::Deref);
992 if let Some(pos) = last_deref {
993 let mut projections = cmt.place.projections.clone();
994 projections.truncate(pos);
996 for item in projections {
997 if item.kind == ProjectionKind::Deref {
998 replacement_str = format!("*{}", replacement_str);
1004 self.suggestion_start
1005 .push_str(&format!("{}{}", start_snip, replacement_str));
1007 self.next_pos = span.hi();
1011 fn mutate(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
1013 fn fake_read(&mut self, _: rustc_typeck::expr_use_visitor::Place<'tcx>, _: FakeReadCause, _: HirId) {}
1020 use rustc_ast::util::parser::AssocOp;
1021 use std::borrow::Cow;
1023 const SUGGESTION: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("function_call()"));
1026 fn make_return_transform_sugg_into_a_return_call() {
1027 assert_eq!("return function_call()", SUGGESTION.make_return().to_string());
1031 fn blockify_transforms_sugg_into_a_block() {
1032 assert_eq!("{ function_call() }", SUGGESTION.blockify().to_string());
1036 fn binop_maybe_par() {
1037 let sugg = Sugg::BinOp(AssocOp::Add, "(1 + 1)".into());
1038 assert_eq!("(1 + 1)", sugg.maybe_par().to_string());
1040 let sugg = Sugg::BinOp(AssocOp::Add, "(1 + 1) + (1 + 1)".into());
1041 assert_eq!("((1 + 1) + (1 + 1))", sugg.maybe_par().to_string());
1045 use AssocOp::{Add, Equal, Greater, GreaterEqual, LAnd, LOr, Less, LessEqual, NotEqual};
1047 // Invert the comparison operator.
1048 let sugg = Sugg::BinOp(Equal, "1 == 1".into());
1049 assert_eq!("1 != 1", (!sugg).to_string());
1051 let sugg = Sugg::BinOp(NotEqual, "1 != 1".into());
1052 assert_eq!("1 == 1", (!sugg).to_string());
1054 let sugg = Sugg::BinOp(Less, "1 < 1".into());
1055 assert_eq!("1 >= 1", (!sugg).to_string());
1057 let sugg = Sugg::BinOp(LessEqual, "1 <= 1".into());
1058 assert_eq!("1 > 1", (!sugg).to_string());
1060 let sugg = Sugg::BinOp(Greater, "1 > 1".into());
1061 assert_eq!("1 <= 1", (!sugg).to_string());
1063 let sugg = Sugg::BinOp(GreaterEqual, "1 >= 1".into());
1064 assert_eq!("1 < 1", (!sugg).to_string());
1066 // Other operators are inverted like !(..).
1067 let sugg = Sugg::BinOp(Add, "1 + 1".into());
1068 assert_eq!("!(1 + 1)", (!sugg).to_string());
1070 let sugg = Sugg::BinOp(LAnd, "1 && 1".into());
1071 assert_eq!("!(1 && 1)", (!sugg).to_string());
1073 let sugg = Sugg::BinOp(LOr, "1 || 1".into());
1074 assert_eq!("!(1 || 1)", (!sugg).to_string());