1 //! Contains utility functions to generate suggestions.
2 #![deny(clippy::missing_docs_in_private_items)]
4 use crate::source::{snippet, snippet_opt, snippet_with_applicability, snippet_with_macro_callsite};
5 use crate::ty::expr_sig;
6 use crate::{get_parent_expr_for_hir, higher};
7 use rustc_ast::util::parser::AssocOp;
8 use rustc_ast::{ast, token};
9 use rustc_ast_pretty::pprust::token_kind_to_string;
10 use rustc_errors::Applicability;
12 use rustc_hir::{Closure, ExprKind, HirId, MutTy, TyKind};
13 use rustc_hir_analysis::expr_use_visitor::{Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId};
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};
21 use std::fmt::{Display, Write as _};
22 use std::ops::{Add, Neg, Not, Sub};
24 /// A helper type to build suggestion correctly handling parentheses.
25 #[derive(Clone, Debug, PartialEq)]
27 /// An expression that never needs parentheses such as `1337` or `[0; 42]`.
28 NonParen(Cow<'a, str>),
29 /// An expression that does not fit in other variants.
30 MaybeParen(Cow<'a, str>),
31 /// A binary operator expression, including `as`-casts and explicit type
33 BinOp(AssocOp, Cow<'a, str>, Cow<'a, str>),
36 /// Literal constant `0`, for convenience.
37 pub const ZERO: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("0"));
38 /// Literal constant `1`, for convenience.
39 pub const ONE: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("1"));
40 /// a constant represents an empty string, for convenience.
41 pub const EMPTY: Sugg<'static> = Sugg::NonParen(Cow::Borrowed(""));
43 impl Display for Sugg<'_> {
44 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
46 Sugg::NonParen(ref s) | Sugg::MaybeParen(ref s) => s.fmt(f),
47 Sugg::BinOp(op, ref lhs, ref rhs) => binop_to_string(op, lhs, rhs).fmt(f),
52 #[expect(clippy::wrong_self_convention)] // ok, because of the function `as_ty` method
54 /// Prepare a suggestion from an expression.
55 pub fn hir_opt(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option<Self> {
56 let get_snippet = |span| snippet(cx, span, "");
57 snippet_opt(cx, expr.span).map(|_| Self::hir_from_snippet(expr, get_snippet))
60 /// Convenience function around `hir_opt` for suggestions with a default
62 pub fn hir(cx: &LateContext<'_>, expr: &hir::Expr<'_>, default: &'a str) -> Self {
63 Self::hir_opt(cx, expr).unwrap_or(Sugg::NonParen(Cow::Borrowed(default)))
66 /// Same as `hir`, but it adapts the applicability level by following rules:
68 /// - Applicability level `Unspecified` will never be changed.
69 /// - If the span is inside a macro, change the applicability level to `MaybeIncorrect`.
70 /// - If the default value is used and the applicability level is `MachineApplicable`, change it
73 pub fn hir_with_applicability(
77 applicability: &mut Applicability,
79 if *applicability != Applicability::Unspecified && expr.span.from_expansion() {
80 *applicability = Applicability::MaybeIncorrect;
82 Self::hir_opt(cx, expr).unwrap_or_else(|| {
83 if *applicability == Applicability::MachineApplicable {
84 *applicability = Applicability::HasPlaceholders;
86 Sugg::NonParen(Cow::Borrowed(default))
90 /// Same as `hir`, but will use the pre expansion span if the `expr` was in a macro.
91 pub fn hir_with_macro_callsite(cx: &LateContext<'_>, expr: &hir::Expr<'_>, default: &'a str) -> Self {
92 let get_snippet = |span| snippet_with_macro_callsite(cx, span, default);
93 Self::hir_from_snippet(expr, get_snippet)
96 /// Same as `hir`, but first walks the span up to the given context. This will result in the
97 /// macro call, rather then the expansion, if the span is from a child context. If the span is
98 /// not from a child context, it will be used directly instead.
100 /// e.g. Given the expression `&vec![]`, getting a snippet from the span for `vec![]` as a HIR
101 /// node would result in `box []`. If given the context of the address of expression, this
102 /// function will correctly get a snippet of `vec![]`.
103 pub fn hir_with_context(
104 cx: &LateContext<'_>,
105 expr: &hir::Expr<'_>,
108 applicability: &mut Applicability,
110 if expr.span.ctxt() == ctxt {
111 Self::hir_from_snippet(expr, |span| snippet(cx, span, default))
113 let snip = snippet_with_applicability(cx, expr.span, default, applicability);
118 /// Generate a suggestion for an expression with the given snippet. This is used by the `hir_*`
119 /// function variants of `Sugg`, since these use different snippet functions.
120 fn hir_from_snippet(expr: &hir::Expr<'_>, get_snippet: impl Fn(Span) -> Cow<'a, str>) -> Self {
121 if let Some(range) = higher::Range::hir(expr) {
122 let op = match range.limits {
123 ast::RangeLimits::HalfOpen => AssocOp::DotDot,
124 ast::RangeLimits::Closed => AssocOp::DotDotEq,
126 let start = range.start.map_or("".into(), |expr| get_snippet(expr.span));
127 let end = range.end.map_or("".into(), |expr| get_snippet(expr.span));
129 return Sugg::BinOp(op, start, end);
133 hir::ExprKind::AddrOf(..)
134 | hir::ExprKind::Box(..)
135 | hir::ExprKind::If(..)
136 | hir::ExprKind::Let(..)
137 | hir::ExprKind::Closure { .. }
138 | hir::ExprKind::Unary(..)
139 | hir::ExprKind::Match(..) => Sugg::MaybeParen(get_snippet(expr.span)),
140 hir::ExprKind::Continue(..)
141 | hir::ExprKind::Yield(..)
142 | hir::ExprKind::Array(..)
143 | hir::ExprKind::Block(..)
144 | hir::ExprKind::Break(..)
145 | hir::ExprKind::Call(..)
146 | hir::ExprKind::Field(..)
147 | hir::ExprKind::Index(..)
148 | hir::ExprKind::InlineAsm(..)
149 | hir::ExprKind::ConstBlock(..)
150 | hir::ExprKind::Lit(..)
151 | hir::ExprKind::Loop(..)
152 | hir::ExprKind::MethodCall(..)
153 | hir::ExprKind::Path(..)
154 | hir::ExprKind::Repeat(..)
155 | hir::ExprKind::Ret(..)
156 | hir::ExprKind::Struct(..)
157 | hir::ExprKind::Tup(..)
158 | hir::ExprKind::Err => Sugg::NonParen(get_snippet(expr.span)),
159 hir::ExprKind::DropTemps(inner) => Self::hir_from_snippet(inner, get_snippet),
160 hir::ExprKind::Assign(lhs, rhs, _) => {
161 Sugg::BinOp(AssocOp::Assign, get_snippet(lhs.span), get_snippet(rhs.span))
163 hir::ExprKind::AssignOp(op, lhs, rhs) => {
164 Sugg::BinOp(hirbinop2assignop(op), get_snippet(lhs.span), get_snippet(rhs.span))
166 hir::ExprKind::Binary(op, lhs, rhs) => Sugg::BinOp(
167 AssocOp::from_ast_binop(op.node.into()),
168 get_snippet(lhs.span),
169 get_snippet(rhs.span),
171 hir::ExprKind::Cast(lhs, ty) => Sugg::BinOp(AssocOp::As, get_snippet(lhs.span), get_snippet(ty.span)),
172 hir::ExprKind::Type(lhs, ty) => Sugg::BinOp(AssocOp::Colon, get_snippet(lhs.span), get_snippet(ty.span)),
176 /// Prepare a suggestion from an expression.
177 pub fn ast(cx: &EarlyContext<'_>, expr: &ast::Expr, default: &'a str) -> Self {
178 use rustc_ast::ast::RangeLimits;
180 let snippet_without_expansion = |cx, span: Span, default| {
181 if span.from_expansion() {
182 snippet_with_macro_callsite(cx, span, default)
184 snippet(cx, span, default)
189 ast::ExprKind::AddrOf(..)
190 | ast::ExprKind::Box(..)
191 | ast::ExprKind::Closure { .. }
192 | ast::ExprKind::If(..)
193 | ast::ExprKind::Let(..)
194 | ast::ExprKind::Unary(..)
195 | ast::ExprKind::Match(..) => Sugg::MaybeParen(snippet_without_expansion(cx, expr.span, default)),
196 ast::ExprKind::Async(..)
197 | ast::ExprKind::Block(..)
198 | ast::ExprKind::Break(..)
199 | ast::ExprKind::Call(..)
200 | ast::ExprKind::Continue(..)
201 | ast::ExprKind::Yield(..)
202 | ast::ExprKind::Field(..)
203 | ast::ExprKind::ForLoop(..)
204 | ast::ExprKind::Index(..)
205 | ast::ExprKind::InlineAsm(..)
206 | ast::ExprKind::ConstBlock(..)
207 | ast::ExprKind::Lit(..)
208 | ast::ExprKind::Loop(..)
209 | ast::ExprKind::MacCall(..)
210 | ast::ExprKind::MethodCall(..)
211 | ast::ExprKind::Paren(..)
212 | ast::ExprKind::Underscore
213 | ast::ExprKind::Path(..)
214 | ast::ExprKind::Repeat(..)
215 | ast::ExprKind::Ret(..)
216 | ast::ExprKind::Yeet(..)
217 | ast::ExprKind::Struct(..)
218 | ast::ExprKind::Try(..)
219 | ast::ExprKind::TryBlock(..)
220 | ast::ExprKind::Tup(..)
221 | ast::ExprKind::Array(..)
222 | ast::ExprKind::While(..)
223 | ast::ExprKind::Await(..)
224 | ast::ExprKind::Err => Sugg::NonParen(snippet_without_expansion(cx, expr.span, default)),
225 ast::ExprKind::Range(ref lhs, ref rhs, RangeLimits::HalfOpen) => Sugg::BinOp(
228 .map_or("".into(), |lhs| snippet_without_expansion(cx, lhs.span, default)),
230 .map_or("".into(), |rhs| snippet_without_expansion(cx, rhs.span, default)),
232 ast::ExprKind::Range(ref lhs, ref rhs, RangeLimits::Closed) => Sugg::BinOp(
235 .map_or("".into(), |lhs| snippet_without_expansion(cx, lhs.span, default)),
237 .map_or("".into(), |rhs| snippet_without_expansion(cx, rhs.span, default)),
239 ast::ExprKind::Assign(ref lhs, ref rhs, _) => Sugg::BinOp(
241 snippet_without_expansion(cx, lhs.span, default),
242 snippet_without_expansion(cx, rhs.span, default),
244 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => Sugg::BinOp(
245 astbinop2assignop(op),
246 snippet_without_expansion(cx, lhs.span, default),
247 snippet_without_expansion(cx, rhs.span, default),
249 ast::ExprKind::Binary(op, ref lhs, ref rhs) => Sugg::BinOp(
250 AssocOp::from_ast_binop(op.node),
251 snippet_without_expansion(cx, lhs.span, default),
252 snippet_without_expansion(cx, rhs.span, default),
254 ast::ExprKind::Cast(ref lhs, ref ty) => Sugg::BinOp(
256 snippet_without_expansion(cx, lhs.span, default),
257 snippet_without_expansion(cx, ty.span, default),
259 ast::ExprKind::Type(ref lhs, ref ty) => Sugg::BinOp(
261 snippet_without_expansion(cx, lhs.span, default),
262 snippet_without_expansion(cx, ty.span, default),
267 /// Convenience method to create the `<lhs> && <rhs>` suggestion.
268 pub fn and(self, rhs: &Self) -> Sugg<'static> {
269 make_binop(ast::BinOpKind::And, &self, rhs)
272 /// Convenience method to create the `<lhs> & <rhs>` suggestion.
273 pub fn bit_and(self, rhs: &Self) -> Sugg<'static> {
274 make_binop(ast::BinOpKind::BitAnd, &self, rhs)
277 /// Convenience method to create the `<lhs> as <rhs>` suggestion.
278 pub fn as_ty<R: Display>(self, rhs: R) -> Sugg<'static> {
279 make_assoc(AssocOp::As, &self, &Sugg::NonParen(rhs.to_string().into()))
282 /// Convenience method to create the `&<expr>` suggestion.
283 pub fn addr(self) -> Sugg<'static> {
287 /// Convenience method to create the `&mut <expr>` suggestion.
288 pub fn mut_addr(self) -> Sugg<'static> {
289 make_unop("&mut ", self)
292 /// Convenience method to create the `*<expr>` suggestion.
293 pub fn deref(self) -> Sugg<'static> {
297 /// Convenience method to create the `&*<expr>` suggestion. Currently this
298 /// is needed because `sugg.deref().addr()` produces an unnecessary set of
299 /// parentheses around the deref.
300 pub fn addr_deref(self) -> Sugg<'static> {
301 make_unop("&*", self)
304 /// Convenience method to create the `&mut *<expr>` suggestion. Currently
305 /// this is needed because `sugg.deref().mut_addr()` produces an unnecessary
306 /// set of parentheses around the deref.
307 pub fn mut_addr_deref(self) -> Sugg<'static> {
308 make_unop("&mut *", self)
311 /// Convenience method to transform suggestion into a return call
312 pub fn make_return(self) -> Sugg<'static> {
313 Sugg::NonParen(Cow::Owned(format!("return {self}")))
316 /// Convenience method to transform suggestion into a block
317 /// where the suggestion is a trailing expression
318 pub fn blockify(self) -> Sugg<'static> {
319 Sugg::NonParen(Cow::Owned(format!("{{ {self} }}")))
322 /// Convenience method to prefix the expression with the `async` keyword.
323 /// Can be used after `blockify` to create an async block.
324 pub fn asyncify(self) -> Sugg<'static> {
325 Sugg::NonParen(Cow::Owned(format!("async {self}")))
328 /// Convenience method to create the `<lhs>..<rhs>` or `<lhs>...<rhs>`
330 pub fn range(self, end: &Self, limit: ast::RangeLimits) -> Sugg<'static> {
332 ast::RangeLimits::HalfOpen => make_assoc(AssocOp::DotDot, &self, end),
333 ast::RangeLimits::Closed => make_assoc(AssocOp::DotDotEq, &self, end),
337 /// Adds parentheses to any expression that might need them. Suitable to the
338 /// `self` argument of a method call
339 /// (e.g., to build `bar.foo()` or `(1 + 2).foo()`).
341 pub fn maybe_par(self) -> Self {
343 Sugg::NonParen(..) => self,
344 // `(x)` and `(x).y()` both don't need additional parens.
345 Sugg::MaybeParen(sugg) => {
346 if has_enclosing_paren(&sugg) {
347 Sugg::MaybeParen(sugg)
349 Sugg::NonParen(format!("({sugg})").into())
352 Sugg::BinOp(op, lhs, rhs) => {
353 let sugg = binop_to_string(op, &lhs, &rhs);
354 Sugg::NonParen(format!("({sugg})").into())
360 /// Generates a string from the operator and both sides.
361 fn binop_to_string(op: AssocOp, lhs: &str, rhs: &str) -> String {
374 | AssocOp::ShiftRight
380 | AssocOp::GreaterEqual => {
383 op.to_ast_binop().expect("Those are AST ops").to_string()
386 AssocOp::Assign => format!("{lhs} = {rhs}"),
387 AssocOp::AssignOp(op) => {
388 format!("{lhs} {}= {rhs}", token_kind_to_string(&token::BinOp(op)))
390 AssocOp::As => format!("{lhs} as {rhs}"),
391 AssocOp::DotDot => format!("{lhs}..{rhs}"),
392 AssocOp::DotDotEq => format!("{lhs}..={rhs}"),
393 AssocOp::Colon => format!("{lhs}: {rhs}"),
397 /// Return `true` if `sugg` is enclosed in parenthesis.
398 pub fn has_enclosing_paren(sugg: impl AsRef<str>) -> bool {
399 let mut chars = sugg.as_ref().chars();
400 if chars.next() == Some('(') {
402 for c in &mut chars {
412 chars.next().is_none()
418 /// Copied from the rust standard library, and then edited
419 macro_rules! forward_binop_impls_to_ref {
420 (impl $imp:ident, $method:ident for $t:ty, type Output = $o:ty) => {
421 impl $imp<$t> for &$t {
424 fn $method(self, other: $t) -> $o {
425 $imp::$method(self, &other)
429 impl $imp<&$t> for $t {
432 fn $method(self, other: &$t) -> $o {
433 $imp::$method(&self, other)
440 fn $method(self, other: $t) -> $o {
441 $imp::$method(&self, &other)
447 impl Add for &Sugg<'_> {
448 type Output = Sugg<'static>;
449 fn add(self, rhs: &Sugg<'_>) -> Sugg<'static> {
450 make_binop(ast::BinOpKind::Add, self, rhs)
454 impl Sub for &Sugg<'_> {
455 type Output = Sugg<'static>;
456 fn sub(self, rhs: &Sugg<'_>) -> Sugg<'static> {
457 make_binop(ast::BinOpKind::Sub, self, rhs)
461 forward_binop_impls_to_ref!(impl Add, add for Sugg<'_>, type Output = Sugg<'static>);
462 forward_binop_impls_to_ref!(impl Sub, sub for Sugg<'_>, type Output = Sugg<'static>);
464 impl Neg for Sugg<'_> {
465 type Output = Sugg<'static>;
466 fn neg(self) -> Sugg<'static> {
471 impl<'a> Not for Sugg<'a> {
472 type Output = Sugg<'a>;
473 fn not(self) -> Sugg<'a> {
474 use AssocOp::{Equal, Greater, GreaterEqual, Less, LessEqual, NotEqual};
476 if let Sugg::BinOp(op, lhs, rhs) = self {
477 let to_op = match op {
480 Less => GreaterEqual,
481 GreaterEqual => Less,
482 Greater => LessEqual,
483 LessEqual => Greater,
484 _ => return make_unop("!", Sugg::BinOp(op, lhs, rhs)),
486 Sugg::BinOp(to_op, lhs, rhs)
493 /// Helper type to display either `foo` or `(foo)`.
494 struct ParenHelper<T> {
495 /// `true` if parentheses are needed.
497 /// The main thing to display.
501 impl<T> ParenHelper<T> {
502 /// Builds a `ParenHelper`.
503 fn new(paren: bool, wrapped: T) -> Self {
504 Self { paren, wrapped }
508 impl<T: Display> Display for ParenHelper<T> {
509 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
511 write!(f, "({})", self.wrapped)
518 /// Builds the string for `<op><expr>` adding parenthesis when necessary.
520 /// For convenience, the operator is taken as a string because all unary
521 /// operators have the same
523 pub fn make_unop(op: &str, expr: Sugg<'_>) -> Sugg<'static> {
524 Sugg::MaybeParen(format!("{op}{}", expr.maybe_par()).into())
527 /// Builds the string for `<lhs> <op> <rhs>` adding parenthesis when necessary.
529 /// Precedence of shift operator relative to other arithmetic operation is
530 /// often confusing so
531 /// parenthesis will always be added for a mix of these.
532 pub fn make_assoc(op: AssocOp, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
533 /// Returns `true` if the operator is a shift operator `<<` or `>>`.
534 fn is_shift(op: AssocOp) -> bool {
535 matches!(op, AssocOp::ShiftLeft | AssocOp::ShiftRight)
538 /// Returns `true` if the operator is an arithmetic operator
539 /// (i.e., `+`, `-`, `*`, `/`, `%`).
540 fn is_arith(op: AssocOp) -> bool {
543 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide | AssocOp::Modulus
547 /// Returns `true` if the operator `op` needs parenthesis with the operator
548 /// `other` in the direction `dir`.
549 fn needs_paren(op: AssocOp, other: AssocOp, dir: Associativity) -> bool {
550 other.precedence() < op.precedence()
551 || (other.precedence() == op.precedence()
552 && ((op != other && associativity(op) != dir)
553 || (op == other && associativity(op) != Associativity::Both)))
554 || is_shift(op) && is_arith(other)
555 || is_shift(other) && is_arith(op)
558 let lhs_paren = if let Sugg::BinOp(lop, _, _) = *lhs {
559 needs_paren(op, lop, Associativity::Left)
564 let rhs_paren = if let Sugg::BinOp(rop, _, _) = *rhs {
565 needs_paren(op, rop, Associativity::Right)
570 let lhs = ParenHelper::new(lhs_paren, lhs).to_string();
571 let rhs = ParenHelper::new(rhs_paren, rhs).to_string();
572 Sugg::BinOp(op, lhs.into(), rhs.into())
575 /// Convenience wrapper around `make_assoc` and `AssocOp::from_ast_binop`.
576 pub fn make_binop(op: ast::BinOpKind, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
577 make_assoc(AssocOp::from_ast_binop(op), lhs, rhs)
580 #[derive(PartialEq, Eq, Clone, Copy)]
581 /// Operator associativity.
583 /// The operator is both left-associative and right-associative.
585 /// The operator is left-associative.
587 /// The operator is not associative.
589 /// The operator is right-associative.
593 /// Returns the associativity/fixity of an operator. The difference with
594 /// `AssocOp::fixity` is that an operator can be both left and right associative
595 /// (such as `+`: `a + b + c == (a + b) + c == a + (b + c)`.
597 /// Chained `as` and explicit `:` type coercion never need inner parenthesis so
598 /// they are considered
601 fn associativity(op: AssocOp) -> Associativity {
602 use rustc_ast::util::parser::AssocOp::{
603 Add, As, Assign, AssignOp, BitAnd, BitOr, BitXor, Colon, Divide, DotDot, DotDotEq, Equal, Greater,
604 GreaterEqual, LAnd, LOr, Less, LessEqual, Modulus, Multiply, NotEqual, ShiftLeft, ShiftRight, Subtract,
608 Assign | AssignOp(_) => Associativity::Right,
609 Add | BitAnd | BitOr | BitXor | LAnd | LOr | Multiply | As | Colon => Associativity::Both,
610 Divide | Equal | Greater | GreaterEqual | Less | LessEqual | Modulus | NotEqual | ShiftLeft | ShiftRight
611 | Subtract => Associativity::Left,
612 DotDot | DotDotEq => Associativity::None,
616 /// Converts a `hir::BinOp` to the corresponding assigning binary operator.
617 fn hirbinop2assignop(op: hir::BinOp) -> AssocOp {
618 use rustc_ast::token::BinOpToken::{And, Caret, Minus, Or, Percent, Plus, Shl, Shr, Slash, Star};
620 AssocOp::AssignOp(match op.node {
621 hir::BinOpKind::Add => Plus,
622 hir::BinOpKind::BitAnd => And,
623 hir::BinOpKind::BitOr => Or,
624 hir::BinOpKind::BitXor => Caret,
625 hir::BinOpKind::Div => Slash,
626 hir::BinOpKind::Mul => Star,
627 hir::BinOpKind::Rem => Percent,
628 hir::BinOpKind::Shl => Shl,
629 hir::BinOpKind::Shr => Shr,
630 hir::BinOpKind::Sub => Minus,
639 | hir::BinOpKind::Or => panic!("This operator does not exist"),
643 /// Converts an `ast::BinOp` to the corresponding assigning binary operator.
644 fn astbinop2assignop(op: ast::BinOp) -> AssocOp {
645 use rustc_ast::ast::BinOpKind::{
646 Add, And, BitAnd, BitOr, BitXor, Div, Eq, Ge, Gt, Le, Lt, Mul, Ne, Or, Rem, Shl, Shr, Sub,
648 use rustc_ast::token::BinOpToken;
650 AssocOp::AssignOp(match op.node {
651 Add => BinOpToken::Plus,
652 BitAnd => BinOpToken::And,
653 BitOr => BinOpToken::Or,
654 BitXor => BinOpToken::Caret,
655 Div => BinOpToken::Slash,
656 Mul => BinOpToken::Star,
657 Rem => BinOpToken::Percent,
658 Shl => BinOpToken::Shl,
659 Shr => BinOpToken::Shr,
660 Sub => BinOpToken::Minus,
661 And | Eq | Ge | Gt | Le | Lt | Ne | Or => panic!("This operator does not exist"),
665 /// Returns the indentation before `span` if there are nothing but `[ \t]`
666 /// before it on its line.
667 fn indentation<T: LintContext>(cx: &T, span: Span) -> Option<String> {
668 let lo = cx.sess().source_map().lookup_char_pos(span.lo());
670 .get_line(lo.line - 1 /* line numbers in `Loc` are 1-based */)
672 if let Some((pos, _)) = line.char_indices().find(|&(_, c)| c != ' ' && c != '\t') {
673 // We can mix char and byte positions here because we only consider `[ \t]`.
674 if lo.col == CharPos(pos) {
675 Some(line[..pos].into())
685 /// Convenience extension trait for `Diagnostic`.
686 pub trait DiagnosticExt<T: LintContext> {
687 /// Suggests to add an attribute to an item.
689 /// Correctly handles indentation of the attribute and item.
694 /// diag.suggest_item_with_attr(cx, item, "#[derive(Default)]");
696 fn suggest_item_with_attr<D: Display + ?Sized>(
702 applicability: Applicability,
705 /// Suggest to add an item before another.
707 /// The item should not be indented (except for inner indentation).
712 /// diag.suggest_prepend_item(cx, item,
717 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability);
719 /// Suggest to completely remove an item.
721 /// This will remove an item and all following whitespace until the next non-whitespace
722 /// character. This should work correctly if item is on the same indentation level as the
728 /// diag.suggest_remove_item(cx, item, "remove this")
730 fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability);
733 impl<T: LintContext> DiagnosticExt<T> for rustc_errors::Diagnostic {
734 fn suggest_item_with_attr<D: Display + ?Sized>(
740 applicability: Applicability,
742 if let Some(indent) = indentation(cx, item) {
743 let span = item.with_hi(item.lo());
745 self.span_suggestion(span, msg, format!("{attr}\n{indent}"), applicability);
749 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability) {
750 if let Some(indent) = indentation(cx, item) {
751 let span = item.with_hi(item.lo());
753 let mut first = true;
754 let new_item = new_item
761 format!("{indent}{l}\n")
764 .collect::<String>();
766 self.span_suggestion(span, msg, format!("{new_item}\n{indent}"), applicability);
770 fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability) {
771 let mut remove_span = item;
772 let hi = cx.sess().source_map().next_point(remove_span).hi();
773 let fmpos = cx.sess().source_map().lookup_byte_offset(hi);
775 if let Some(ref src) = fmpos.sf.src {
776 let non_whitespace_offset = src[fmpos.pos.to_usize()..].find(|c| c != ' ' && c != '\t' && c != '\n');
778 if let Some(non_whitespace_offset) = non_whitespace_offset {
779 remove_span = remove_span
780 .with_hi(remove_span.hi() + BytePos(non_whitespace_offset.try_into().expect("offset too large")));
784 self.span_suggestion(remove_span, msg, "", applicability);
788 /// Suggestion results for handling closure
789 /// args dereferencing and borrowing
790 pub struct DerefClosure {
791 /// confidence on the built suggestion
792 pub applicability: Applicability,
793 /// gradually built suggestion
794 pub suggestion: String,
797 /// Build suggestion gradually by handling closure arg specific usages,
798 /// such as explicit deref and borrowing cases.
799 /// Returns `None` if no such use cases have been triggered in closure body
801 /// note: this only works on single line immutable closures with exactly one input parameter.
802 pub fn deref_closure_args<'tcx>(cx: &LateContext<'_>, closure: &'tcx hir::Expr<'_>) -> Option<DerefClosure> {
803 if let hir::ExprKind::Closure(&Closure { fn_decl, body, .. }) = closure.kind {
804 let closure_body = cx.tcx.hir().body(body);
805 // is closure arg a type annotated double reference (i.e.: `|x: &&i32| ...`)
806 // a type annotation is present if param `kind` is different from `TyKind::Infer`
807 let closure_arg_is_type_annotated_double_ref = if let TyKind::Rptr(_, MutTy { ty, .. }) = fn_decl.inputs[0].kind
809 matches!(ty.kind, TyKind::Rptr(_, MutTy { .. }))
814 let mut visitor = DerefDelegate {
816 closure_span: closure.span,
817 closure_arg_is_type_annotated_double_ref,
818 next_pos: closure.span.lo(),
819 suggestion_start: String::new(),
820 applicability: Applicability::MachineApplicable,
823 let fn_def_id = cx.tcx.hir().local_def_id(closure.hir_id);
824 let infcx = cx.tcx.infer_ctxt().build();
825 ExprUseVisitor::new(&mut visitor, &infcx, fn_def_id, cx.param_env, cx.typeck_results())
826 .consume_body(closure_body);
828 if !visitor.suggestion_start.is_empty() {
829 return Some(DerefClosure {
830 applicability: visitor.applicability,
831 suggestion: visitor.finish(),
838 /// Visitor struct used for tracking down
839 /// dereferencing and borrowing of closure's args
840 struct DerefDelegate<'a, 'tcx> {
841 /// The late context of the lint
842 cx: &'a LateContext<'tcx>,
843 /// The span of the input closure to adapt
845 /// Indicates if the arg of the closure is a type annotated double reference
846 closure_arg_is_type_annotated_double_ref: bool,
847 /// last position of the span to gradually build the suggestion
849 /// starting part of the gradually built suggestion
850 suggestion_start: String,
851 /// confidence on the built suggestion
852 applicability: Applicability,
855 impl<'tcx> DerefDelegate<'_, 'tcx> {
856 /// build final suggestion:
857 /// - create the ending part of suggestion
858 /// - concatenate starting and ending parts
859 /// - potentially remove needless borrowing
860 pub fn finish(&mut self) -> String {
861 let end_span = Span::new(self.next_pos, self.closure_span.hi(), self.closure_span.ctxt(), None);
862 let end_snip = snippet_with_applicability(self.cx, end_span, "..", &mut self.applicability);
863 let sugg = format!("{}{end_snip}", self.suggestion_start);
864 if self.closure_arg_is_type_annotated_double_ref {
865 sugg.replacen('&', "", 1)
871 /// indicates whether the function from `parent_expr` takes its args by double reference
872 fn func_takes_arg_by_double_ref(&self, parent_expr: &'tcx hir::Expr<'_>, cmt_hir_id: HirId) -> bool {
873 let ty = match parent_expr.kind {
874 ExprKind::MethodCall(_, receiver, call_args, _) => {
875 if let Some(sig) = self
878 .type_dependent_def_id(parent_expr.hir_id)
879 .map(|did| self.cx.tcx.fn_sig(did).skip_binder())
881 std::iter::once(receiver)
882 .chain(call_args.iter())
883 .position(|arg| arg.hir_id == cmt_hir_id)
884 .map(|i| sig.inputs()[i])
889 ExprKind::Call(func, call_args) => {
890 if let Some(sig) = expr_sig(self.cx, func) {
893 .position(|arg| arg.hir_id == cmt_hir_id)
894 .and_then(|i| sig.input(i))
895 .map(ty::Binder::skip_binder)
903 ty.map_or(false, |ty| matches!(ty.kind(), ty::Ref(_, inner, _) if inner.is_ref()))
907 impl<'tcx> Delegate<'tcx> for DerefDelegate<'_, 'tcx> {
908 fn consume(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
910 fn borrow(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId, _: ty::BorrowKind) {
911 if let PlaceBase::Local(id) = cmt.place.base {
912 let map = self.cx.tcx.hir();
913 let span = map.span(cmt.hir_id);
914 let start_span = Span::new(self.next_pos, span.lo(), span.ctxt(), None);
915 let mut start_snip = snippet_with_applicability(self.cx, start_span, "..", &mut self.applicability);
917 // identifier referring to the variable currently triggered (i.e.: `fp`)
918 let ident_str = map.name(id).to_string();
919 // full identifier that includes projection (i.e.: `fp.field`)
920 let ident_str_with_proj = snippet(self.cx, span, "..").to_string();
922 if cmt.place.projections.is_empty() {
923 // handle item without any projection, that needs an explicit borrowing
924 // i.e.: suggest `&x` instead of `x`
925 let _ = write!(self.suggestion_start, "{start_snip}&{ident_str}");
927 // cases where a parent `Call` or `MethodCall` is using the item
928 // i.e.: suggest `.contains(&x)` for `.find(|x| [1, 2, 3].contains(x)).is_none()`
930 // Note about method calls:
931 // - compiler automatically dereference references if the target type is a reference (works also for
933 // - `self` arguments in the case of `x.is_something()` are also automatically (de)referenced, and
934 // no projection should be suggested
935 if let Some(parent_expr) = get_parent_expr_for_hir(self.cx, cmt.hir_id) {
936 match &parent_expr.kind {
937 // given expression is the self argument and will be handled completely by the compiler
938 // i.e.: `|x| x.is_something()`
939 ExprKind::MethodCall(_, self_expr, ..) if self_expr.hir_id == cmt.hir_id => {
940 let _ = write!(self.suggestion_start, "{start_snip}{ident_str_with_proj}");
941 self.next_pos = span.hi();
944 // item is used in a call
945 // i.e.: `Call`: `|x| please(x)` or `MethodCall`: `|x| [1, 2, 3].contains(x)`
946 ExprKind::Call(_, [call_args @ ..]) | ExprKind::MethodCall(_, _, [call_args @ ..], _) => {
947 let expr = self.cx.tcx.hir().expect_expr(cmt.hir_id);
948 let arg_ty_kind = self.cx.typeck_results().expr_ty(expr).kind();
950 if matches!(arg_ty_kind, ty::Ref(_, _, Mutability::Not)) {
951 // suggest ampersand if call function is taking args by double reference
952 let takes_arg_by_double_ref =
953 self.func_takes_arg_by_double_ref(parent_expr, cmt.hir_id);
955 // compiler will automatically dereference field or index projection, so no need
956 // to suggest ampersand, but full identifier that includes projection is required
957 let has_field_or_index_projection =
958 cmt.place.projections.iter().any(|proj| {
959 matches!(proj.kind, ProjectionKind::Field(..) | ProjectionKind::Index)
962 // no need to bind again if the function doesn't take arg by double ref
963 // and if the item is already a double ref
964 let ident_sugg = if !call_args.is_empty()
965 && !takes_arg_by_double_ref
966 && (self.closure_arg_is_type_annotated_double_ref || has_field_or_index_projection)
968 let ident = if has_field_or_index_projection {
973 format!("{start_snip}{ident}")
975 format!("{start_snip}&{ident_str}")
977 self.suggestion_start.push_str(&ident_sugg);
978 self.next_pos = span.hi();
982 self.applicability = Applicability::Unspecified;
988 let mut replacement_str = ident_str;
989 let mut projections_handled = false;
990 cmt.place.projections.iter().enumerate().for_each(|(i, proj)| {
992 // Field projection like `|v| v.foo`
993 // no adjustment needed here, as field projections are handled by the compiler
994 ProjectionKind::Field(..) => match cmt.place.ty_before_projection(i).kind() {
995 ty::Adt(..) | ty::Tuple(_) => {
996 replacement_str = ident_str_with_proj.clone();
997 projections_handled = true;
1001 // Index projection like `|x| foo[x]`
1002 // the index is dropped so we can't get it to build the suggestion,
1003 // so the span is set-up again to get more code, using `span.hi()` (i.e.: `foo[x]`)
1004 // instead of `span.lo()` (i.e.: `foo`)
1005 ProjectionKind::Index => {
1006 let start_span = Span::new(self.next_pos, span.hi(), span.ctxt(), None);
1007 start_snip = snippet_with_applicability(self.cx, start_span, "..", &mut self.applicability);
1008 replacement_str.clear();
1009 projections_handled = true;
1011 // note: unable to trigger `Subslice` kind in tests
1012 ProjectionKind::Subslice => (),
1013 ProjectionKind::Deref => {
1014 // Explicit derefs are typically handled later on, but
1015 // some items do not need explicit deref, such as array accesses,
1016 // so we mark them as already processed
1017 // i.e.: don't suggest `*sub[1..4].len()` for `|sub| sub[1..4].len() == 3`
1018 if let ty::Ref(_, inner, _) = cmt.place.ty_before_projection(i).kind() {
1019 if matches!(inner.kind(), ty::Ref(_, innermost, _) if innermost.is_array()) {
1020 projections_handled = true;
1027 // handle `ProjectionKind::Deref` by removing one explicit deref
1028 // if no special case was detected (i.e.: suggest `*x` instead of `**x`)
1029 if !projections_handled {
1030 let last_deref = cmt
1034 .rposition(|proj| proj.kind == ProjectionKind::Deref);
1036 if let Some(pos) = last_deref {
1037 let mut projections = cmt.place.projections.clone();
1038 projections.truncate(pos);
1040 for item in projections {
1041 if item.kind == ProjectionKind::Deref {
1042 replacement_str = format!("*{replacement_str}");
1048 let _ = write!(self.suggestion_start, "{start_snip}{replacement_str}");
1050 self.next_pos = span.hi();
1054 fn mutate(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
1058 _: &rustc_hir_analysis::expr_use_visitor::PlaceWithHirId<'tcx>,
1069 use rustc_ast::util::parser::AssocOp;
1070 use std::borrow::Cow;
1072 const SUGGESTION: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("function_call()"));
1075 fn make_return_transform_sugg_into_a_return_call() {
1076 assert_eq!("return function_call()", SUGGESTION.make_return().to_string());
1080 fn blockify_transforms_sugg_into_a_block() {
1081 assert_eq!("{ function_call() }", SUGGESTION.blockify().to_string());
1085 fn binop_maybe_par() {
1086 let sugg = Sugg::BinOp(AssocOp::Add, "1".into(), "1".into());
1087 assert_eq!("(1 + 1)", sugg.maybe_par().to_string());
1089 let sugg = Sugg::BinOp(AssocOp::Add, "(1 + 1)".into(), "(1 + 1)".into());
1090 assert_eq!("((1 + 1) + (1 + 1))", sugg.maybe_par().to_string());
1094 use AssocOp::{Add, Equal, Greater, GreaterEqual, LAnd, LOr, Less, LessEqual, NotEqual};
1096 fn test_not(op: AssocOp, correct: &str) {
1097 let sugg = Sugg::BinOp(op, "x".into(), "y".into());
1098 assert_eq!((!sugg).to_string(), correct);
1101 // Invert the comparison operator.
1102 test_not(Equal, "x != y");
1103 test_not(NotEqual, "x == y");
1104 test_not(Less, "x >= y");
1105 test_not(LessEqual, "x > y");
1106 test_not(Greater, "x <= y");
1107 test_not(GreaterEqual, "x < y");
1109 // Other operators are inverted like !(..).
1110 test_not(Add, "!(x + y)");
1111 test_not(LAnd, "!(x && y)");
1112 test_not(LOr, "!(x || y)");