1#![deny(clippy::missing_docs_in_private_items)]
3
4use crate::source::{snippet, snippet_opt, snippet_with_applicability, snippet_with_context};
5use crate::ty::expr_sig;
6use crate::{get_parent_expr_for_hir, higher};
7use rustc_ast::ast;
8use rustc_ast::util::parser::AssocOp;
9use rustc_errors::Applicability;
10use rustc_hir as hir;
11use rustc_hir::{Closure, ExprKind, HirId, MutTy, TyKind};
12use rustc_hir_typeck::expr_use_visitor::{Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId};
13use rustc_lint::{EarlyContext, LateContext, LintContext};
14use rustc_middle::hir::place::ProjectionKind;
15use rustc_middle::mir::{FakeReadCause, Mutability};
16use rustc_middle::ty;
17use rustc_span::{BytePos, CharPos, Pos, Span, SyntaxContext};
18use std::borrow::Cow;
19use std::fmt::{self, Display, Write as _};
20use std::ops::{Add, Neg, Not, Sub};
21
22#[derive(Clone, Debug, PartialEq)]
24pub enum Sugg<'a> {
25 NonParen(Cow<'a, str>),
27 MaybeParen(Cow<'a, str>),
29 BinOp(AssocOp, Cow<'a, str>, Cow<'a, str>),
32}
33
34pub const ZERO: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("0"));
36pub const ONE: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("1"));
38pub const EMPTY: Sugg<'static> = Sugg::NonParen(Cow::Borrowed(""));
40
41impl Display for Sugg<'_> {
42 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
43 match *self {
44 Sugg::NonParen(ref s) | Sugg::MaybeParen(ref s) => s.fmt(f),
45 Sugg::BinOp(op, ref lhs, ref rhs) => binop_to_string(op, lhs, rhs).fmt(f),
46 }
47 }
48}
49
50#[expect(clippy::wrong_self_convention)] impl<'a> Sugg<'a> {
52 pub fn hir_opt(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option<Self> {
54 let ctxt = expr.span.ctxt();
55 let get_snippet = |span| snippet_with_context(cx, span, ctxt, "", &mut Applicability::Unspecified).0;
56 snippet_opt(cx, expr.span).map(|_| Self::hir_from_snippet(expr, get_snippet))
57 }
58
59 pub fn hir(cx: &LateContext<'_>, expr: &hir::Expr<'_>, default: &'a str) -> Self {
62 Self::hir_opt(cx, expr).unwrap_or(Sugg::NonParen(Cow::Borrowed(default)))
63 }
64
65 pub fn hir_with_applicability(
72 cx: &LateContext<'_>,
73 expr: &hir::Expr<'_>,
74 default: &'a str,
75 applicability: &mut Applicability,
76 ) -> Self {
77 if *applicability != Applicability::Unspecified && expr.span.from_expansion() {
78 *applicability = Applicability::MaybeIncorrect;
79 }
80 Self::hir_opt(cx, expr).unwrap_or_else(|| {
81 if *applicability == Applicability::MachineApplicable {
82 *applicability = Applicability::HasPlaceholders;
83 }
84 Sugg::NonParen(Cow::Borrowed(default))
85 })
86 }
87
88 pub fn hir_with_context(
96 cx: &LateContext<'_>,
97 expr: &hir::Expr<'_>,
98 ctxt: SyntaxContext,
99 default: &'a str,
100 applicability: &mut Applicability,
101 ) -> Self {
102 if expr.span.ctxt() == ctxt {
103 Self::hir_from_snippet(expr, |span| {
104 snippet_with_context(cx, span, ctxt, default, applicability).0
105 })
106 } else {
107 let (snip, _) = snippet_with_context(cx, expr.span, ctxt, default, applicability);
108 Sugg::NonParen(snip)
109 }
110 }
111
112 fn hir_from_snippet(expr: &hir::Expr<'_>, mut get_snippet: impl FnMut(Span) -> Cow<'a, str>) -> Self {
115 if let Some(range) = higher::Range::hir(expr) {
116 let op = AssocOp::Range(range.limits);
117 let start = range.start.map_or("".into(), |expr| get_snippet(expr.span));
118 let end = range.end.map_or("".into(), |expr| get_snippet(expr.span));
119
120 return Sugg::BinOp(op, start, end);
121 }
122
123 match expr.kind {
124 ExprKind::AddrOf(..)
125 | ExprKind::If(..)
126 | ExprKind::Let(..)
127 | ExprKind::Closure { .. }
128 | ExprKind::Unary(..)
129 | ExprKind::Match(..) => Sugg::MaybeParen(get_snippet(expr.span)),
130 ExprKind::Continue(..)
131 | ExprKind::Yield(..)
132 | ExprKind::Array(..)
133 | ExprKind::Block(..)
134 | ExprKind::Break(..)
135 | ExprKind::Call(..)
136 | ExprKind::Field(..)
137 | ExprKind::Index(..)
138 | ExprKind::InlineAsm(..)
139 | ExprKind::OffsetOf(..)
140 | ExprKind::ConstBlock(..)
141 | ExprKind::Lit(..)
142 | ExprKind::Loop(..)
143 | ExprKind::MethodCall(..)
144 | ExprKind::Path(..)
145 | ExprKind::Repeat(..)
146 | ExprKind::Ret(..)
147 | ExprKind::Become(..)
148 | ExprKind::Struct(..)
149 | ExprKind::Tup(..)
150 | ExprKind::Use(..)
151 | ExprKind::Err(_)
152 | ExprKind::UnsafeBinderCast(..) => Sugg::NonParen(get_snippet(expr.span)),
153 ExprKind::DropTemps(inner) => Self::hir_from_snippet(inner, get_snippet),
154 ExprKind::Assign(lhs, rhs, _) => {
155 Sugg::BinOp(AssocOp::Assign, get_snippet(lhs.span), get_snippet(rhs.span))
156 },
157 ExprKind::AssignOp(op, lhs, rhs) => {
158 Sugg::BinOp(AssocOp::AssignOp(op.node), get_snippet(lhs.span), get_snippet(rhs.span))
159 },
160 ExprKind::Binary(op, lhs, rhs) => Sugg::BinOp(
161 AssocOp::Binary(op.node),
162 get_snippet(lhs.span),
163 get_snippet(rhs.span),
164 ),
165 ExprKind::Cast(lhs, ty) |
166 ExprKind::Type(lhs, ty) => Sugg::BinOp(AssocOp::Cast, get_snippet(lhs.span), get_snippet(ty.span)),
168 }
169 }
170
171 pub fn ast(
173 cx: &EarlyContext<'_>,
174 expr: &ast::Expr,
175 default: &'a str,
176 ctxt: SyntaxContext,
177 app: &mut Applicability,
178 ) -> Self {
179 let mut snippet = |span: Span| snippet_with_context(cx, span, ctxt, default, app).0;
180
181 match expr.kind {
182 _ if expr.span.ctxt() != ctxt => Sugg::NonParen(snippet(expr.span)),
183 ast::ExprKind::AddrOf(..)
184 | ast::ExprKind::Closure { .. }
185 | ast::ExprKind::If(..)
186 | ast::ExprKind::Let(..)
187 | ast::ExprKind::Unary(..)
188 | ast::ExprKind::Match(..) => match snippet_with_context(cx, expr.span, ctxt, default, app) {
189 (snip, false) => Sugg::MaybeParen(snip),
190 (snip, true) => Sugg::NonParen(snip),
191 },
192 ast::ExprKind::Gen(..)
193 | ast::ExprKind::Block(..)
194 | ast::ExprKind::Break(..)
195 | ast::ExprKind::Call(..)
196 | ast::ExprKind::Continue(..)
197 | ast::ExprKind::Yield(..)
198 | ast::ExprKind::Field(..)
199 | ast::ExprKind::ForLoop { .. }
200 | ast::ExprKind::Index(..)
201 | ast::ExprKind::InlineAsm(..)
202 | ast::ExprKind::OffsetOf(..)
203 | ast::ExprKind::ConstBlock(..)
204 | ast::ExprKind::Lit(..)
205 | ast::ExprKind::IncludedBytes(..)
206 | ast::ExprKind::Loop(..)
207 | ast::ExprKind::MacCall(..)
208 | ast::ExprKind::MethodCall(..)
209 | ast::ExprKind::Paren(..)
210 | ast::ExprKind::Underscore
211 | ast::ExprKind::Path(..)
212 | ast::ExprKind::Repeat(..)
213 | ast::ExprKind::Ret(..)
214 | ast::ExprKind::Become(..)
215 | ast::ExprKind::Yeet(..)
216 | ast::ExprKind::FormatArgs(..)
217 | ast::ExprKind::Struct(..)
218 | ast::ExprKind::Try(..)
219 | ast::ExprKind::TryBlock(..)
220 | ast::ExprKind::Tup(..)
221 | ast::ExprKind::Use(..)
222 | ast::ExprKind::Array(..)
223 | ast::ExprKind::While(..)
224 | ast::ExprKind::Await(..)
225 | ast::ExprKind::Err(_)
226 | ast::ExprKind::Dummy
227 | ast::ExprKind::UnsafeBinderCast(..) => Sugg::NonParen(snippet(expr.span)),
228 ast::ExprKind::Range(ref lhs, ref rhs, limits) => Sugg::BinOp(
229 AssocOp::Range(limits),
230 lhs.as_ref().map_or("".into(), |lhs| snippet(lhs.span)),
231 rhs.as_ref().map_or("".into(), |rhs| snippet(rhs.span)),
232 ),
233 ast::ExprKind::Assign(ref lhs, ref rhs, _) => Sugg::BinOp(
234 AssocOp::Assign,
235 snippet(lhs.span),
236 snippet(rhs.span),
237 ),
238 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => Sugg::BinOp(
239 AssocOp::AssignOp(op.node),
240 snippet(lhs.span),
241 snippet(rhs.span),
242 ),
243 ast::ExprKind::Binary(op, ref lhs, ref rhs) => Sugg::BinOp(
244 AssocOp::Binary(op.node),
245 snippet(lhs.span),
246 snippet(rhs.span),
247 ),
248 ast::ExprKind::Cast(ref lhs, ref ty) |
249 ast::ExprKind::Type(ref lhs, ref ty) => Sugg::BinOp(
251 AssocOp::Cast,
252 snippet(lhs.span),
253 snippet(ty.span),
254 ),
255 }
256 }
257
258 pub fn and(self, rhs: &Self) -> Sugg<'static> {
260 make_binop(ast::BinOpKind::And, &self, rhs)
261 }
262
263 pub fn bit_and(self, rhs: &Self) -> Sugg<'static> {
265 make_binop(ast::BinOpKind::BitAnd, &self, rhs)
266 }
267
268 pub fn as_ty<R: Display>(self, rhs: R) -> Sugg<'static> {
270 make_assoc(AssocOp::Cast, &self, &Sugg::NonParen(rhs.to_string().into()))
271 }
272
273 pub fn addr(self) -> Sugg<'static> {
275 make_unop("&", self)
276 }
277
278 pub fn mut_addr(self) -> Sugg<'static> {
280 make_unop("&mut ", self)
281 }
282
283 pub fn deref(self) -> Sugg<'static> {
285 make_unop("*", self)
286 }
287
288 pub fn addr_deref(self) -> Sugg<'static> {
292 make_unop("&*", self)
293 }
294
295 pub fn mut_addr_deref(self) -> Sugg<'static> {
299 make_unop("&mut *", self)
300 }
301
302 pub fn make_return(self) -> Sugg<'static> {
304 Sugg::NonParen(Cow::Owned(format!("return {self}")))
305 }
306
307 pub fn blockify(self) -> Sugg<'static> {
310 Sugg::NonParen(Cow::Owned(format!("{{ {self} }}")))
311 }
312
313 pub fn asyncify(self) -> Sugg<'static> {
316 Sugg::NonParen(Cow::Owned(format!("async {self}")))
317 }
318
319 pub fn range(self, end: &Self, limits: ast::RangeLimits) -> Sugg<'static> {
322 make_assoc(AssocOp::Range(limits), &self, end)
323 }
324
325 #[must_use]
329 pub fn maybe_par(self) -> Self {
330 match self {
331 Sugg::NonParen(..) => self,
332 Sugg::MaybeParen(sugg) => {
334 if has_enclosing_paren(&sugg) {
335 Sugg::MaybeParen(sugg)
336 } else {
337 Sugg::NonParen(format!("({sugg})").into())
338 }
339 },
340 Sugg::BinOp(op, lhs, rhs) => {
341 let sugg = binop_to_string(op, &lhs, &rhs);
342 Sugg::NonParen(format!("({sugg})").into())
343 },
344 }
345 }
346
347 pub fn into_string(self) -> String {
348 match self {
349 Sugg::NonParen(p) | Sugg::MaybeParen(p) => p.into_owned(),
350 Sugg::BinOp(b, l, r) => binop_to_string(b, &l, &r),
351 }
352 }
353}
354
355fn binop_to_string(op: AssocOp, lhs: &str, rhs: &str) -> String {
357 match op {
358 AssocOp::Binary(op) => format!("{lhs} {} {rhs}", op.as_str()),
359 AssocOp::Assign => format!("{lhs} = {rhs}"),
360 AssocOp::AssignOp(op) => format!("{lhs} {} {rhs}", op.as_str()),
361 AssocOp::Cast => format!("{lhs} as {rhs}"),
362 AssocOp::Range(limits) => format!("{lhs}{}{rhs}", limits.as_str()),
363 }
364}
365
366pub fn has_enclosing_paren(sugg: impl AsRef<str>) -> bool {
368 let mut chars = sugg.as_ref().chars();
369 if chars.next() == Some('(') {
370 let mut depth = 1;
371 for c in &mut chars {
372 if c == '(' {
373 depth += 1;
374 } else if c == ')' {
375 depth -= 1;
376 }
377 if depth == 0 {
378 break;
379 }
380 }
381 chars.next().is_none()
382 } else {
383 false
384 }
385}
386
387macro_rules! forward_binop_impls_to_ref {
389 (impl $imp:ident, $method:ident for $t:ty, type Output = $o:ty) => {
390 impl $imp<$t> for &$t {
391 type Output = $o;
392
393 fn $method(self, other: $t) -> $o {
394 $imp::$method(self, &other)
395 }
396 }
397
398 impl $imp<&$t> for $t {
399 type Output = $o;
400
401 fn $method(self, other: &$t) -> $o {
402 $imp::$method(&self, other)
403 }
404 }
405
406 impl $imp for $t {
407 type Output = $o;
408
409 fn $method(self, other: $t) -> $o {
410 $imp::$method(&self, &other)
411 }
412 }
413 };
414}
415
416impl Add for &Sugg<'_> {
417 type Output = Sugg<'static>;
418 fn add(self, rhs: &Sugg<'_>) -> Sugg<'static> {
419 make_binop(ast::BinOpKind::Add, self, rhs)
420 }
421}
422
423impl Sub for &Sugg<'_> {
424 type Output = Sugg<'static>;
425 fn sub(self, rhs: &Sugg<'_>) -> Sugg<'static> {
426 make_binop(ast::BinOpKind::Sub, self, rhs)
427 }
428}
429
430forward_binop_impls_to_ref!(impl Add, add for Sugg<'_>, type Output = Sugg<'static>);
431forward_binop_impls_to_ref!(impl Sub, sub for Sugg<'_>, type Output = Sugg<'static>);
432
433impl Neg for Sugg<'_> {
434 type Output = Sugg<'static>;
435 fn neg(self) -> Sugg<'static> {
436 match &self {
437 Self::BinOp(AssocOp::Cast, ..) => Sugg::MaybeParen(format!("-({self})").into()),
438 _ => make_unop("-", self),
439 }
440 }
441}
442
443impl<'a> Not for Sugg<'a> {
444 type Output = Sugg<'a>;
445 fn not(self) -> Sugg<'a> {
446 use AssocOp::Binary;
447 use ast::BinOpKind::{Eq, Ge, Gt, Le, Lt, Ne};
448
449 if let Sugg::BinOp(op, lhs, rhs) = self {
450 let to_op = match op {
451 Binary(Eq) => Binary(Ne),
452 Binary(Ne) => Binary(Eq),
453 Binary(Lt) => Binary(Ge),
454 Binary(Ge) => Binary(Lt),
455 Binary(Gt) => Binary(Le),
456 Binary(Le) => Binary(Gt),
457 _ => return make_unop("!", Sugg::BinOp(op, lhs, rhs)),
458 };
459 Sugg::BinOp(to_op, lhs, rhs)
460 } else {
461 make_unop("!", self)
462 }
463 }
464}
465
466struct ParenHelper<T> {
468 paren: bool,
470 wrapped: T,
472}
473
474impl<T> ParenHelper<T> {
475 fn new(paren: bool, wrapped: T) -> Self {
477 Self { paren, wrapped }
478 }
479}
480
481impl<T: Display> Display for ParenHelper<T> {
482 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
483 if self.paren {
484 write!(f, "({})", self.wrapped)
485 } else {
486 self.wrapped.fmt(f)
487 }
488 }
489}
490
491pub fn make_unop(op: &str, expr: Sugg<'_>) -> Sugg<'static> {
497 Sugg::MaybeParen(format!("{op}{}", expr.maybe_par()).into())
498}
499
500pub fn make_assoc(op: AssocOp, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
506 fn is_shift(op: AssocOp) -> bool {
508 matches!(op, AssocOp::Binary(ast::BinOpKind::Shl | ast::BinOpKind::Shr))
509 }
510
511 fn is_arith(op: AssocOp) -> bool {
514 matches!(
515 op,
516 AssocOp::Binary(
517 ast::BinOpKind::Add
518 | ast::BinOpKind::Sub
519 | ast::BinOpKind::Mul
520 | ast::BinOpKind::Div
521 | ast::BinOpKind::Rem
522 )
523 )
524 }
525
526 fn needs_paren(op: AssocOp, other: AssocOp, dir: Associativity) -> bool {
529 other.precedence() < op.precedence()
530 || (other.precedence() == op.precedence()
531 && ((op != other && associativity(op) != dir)
532 || (op == other && associativity(op) != Associativity::Both)))
533 || is_shift(op) && is_arith(other)
534 || is_shift(other) && is_arith(op)
535 }
536
537 let lhs_paren = if let Sugg::BinOp(lop, _, _) = *lhs {
538 needs_paren(op, lop, Associativity::Left)
539 } else {
540 false
541 };
542
543 let rhs_paren = if let Sugg::BinOp(rop, _, _) = *rhs {
544 needs_paren(op, rop, Associativity::Right)
545 } else {
546 false
547 };
548
549 let lhs = ParenHelper::new(lhs_paren, lhs).to_string();
550 let rhs = ParenHelper::new(rhs_paren, rhs).to_string();
551 Sugg::BinOp(op, lhs.into(), rhs.into())
552}
553
554pub fn make_binop(op: ast::BinOpKind, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
556 make_assoc(AssocOp::Binary(op), lhs, rhs)
557}
558
559#[derive(PartialEq, Eq, Clone, Copy)]
560enum Associativity {
562 Both,
564 Left,
566 None,
568 Right,
570}
571
572#[must_use]
580fn associativity(op: AssocOp) -> Associativity {
581 use ast::BinOpKind::{Add, And, BitAnd, BitOr, BitXor, Div, Eq, Ge, Gt, Le, Lt, Mul, Ne, Or, Rem, Shl, Shr, Sub};
582 use rustc_ast::util::parser::AssocOp::{Assign, AssignOp, Binary, Cast, Range};
583
584 match op {
585 Assign | AssignOp(_) => Associativity::Right,
586 Binary(Add | BitAnd | BitOr | BitXor | And | Or | Mul) | Cast => Associativity::Both,
587 Binary(Div | Eq | Gt | Ge | Lt | Le | Rem | Ne | Shl | Shr | Sub) => Associativity::Left,
588 Range(_) => Associativity::None,
589 }
590}
591
592fn indentation<T: LintContext>(cx: &T, span: Span) -> Option<String> {
595 let lo = cx.sess().source_map().lookup_char_pos(span.lo());
596 lo.file
597 .get_line(lo.line - 1 )
598 .and_then(|line| {
599 if let Some((pos, _)) = line.char_indices().find(|&(_, c)| c != ' ' && c != '\t') {
600 if lo.col == CharPos(pos) {
602 Some(line[..pos].into())
603 } else {
604 None
605 }
606 } else {
607 None
608 }
609 })
610}
611
612pub trait DiagExt<T: LintContext> {
614 fn suggest_item_with_attr<D: Display + ?Sized>(
624 &mut self,
625 cx: &T,
626 item: Span,
627 msg: &str,
628 attr: &D,
629 applicability: Applicability,
630 );
631
632 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability);
645
646 fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability);
658}
659
660impl<T: LintContext> DiagExt<T> for rustc_errors::Diag<'_, ()> {
661 fn suggest_item_with_attr<D: Display + ?Sized>(
662 &mut self,
663 cx: &T,
664 item: Span,
665 msg: &str,
666 attr: &D,
667 applicability: Applicability,
668 ) {
669 if let Some(indent) = indentation(cx, item) {
670 let span = item.with_hi(item.lo());
671
672 self.span_suggestion(span, msg.to_string(), format!("{attr}\n{indent}"), applicability);
673 }
674 }
675
676 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability) {
677 if let Some(indent) = indentation(cx, item) {
678 let span = item.with_hi(item.lo());
679
680 let mut first = true;
681 let new_item = new_item
682 .lines()
683 .map(|l| {
684 if first {
685 first = false;
686 format!("{l}\n")
687 } else {
688 format!("{indent}{l}\n")
689 }
690 })
691 .collect::<String>();
692
693 self.span_suggestion(span, msg.to_string(), format!("{new_item}\n{indent}"), applicability);
694 }
695 }
696
697 fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability) {
698 let mut remove_span = item;
699 let fmpos = cx.sess().source_map().lookup_byte_offset(remove_span.hi());
700
701 if let Some(ref src) = fmpos.sf.src {
702 let non_whitespace_offset = src[fmpos.pos.to_usize()..].find(|c| c != ' ' && c != '\t' && c != '\n');
703
704 if let Some(non_whitespace_offset) = non_whitespace_offset {
705 remove_span = remove_span
706 .with_hi(remove_span.hi() + BytePos(non_whitespace_offset.try_into().expect("offset too large")));
707 }
708 }
709
710 self.span_suggestion(remove_span, msg.to_string(), "", applicability);
711 }
712}
713
714pub struct DerefClosure {
717 pub applicability: Applicability,
719 pub suggestion: String,
721}
722
723pub fn deref_closure_args(cx: &LateContext<'_>, closure: &hir::Expr<'_>) -> Option<DerefClosure> {
729 if let ExprKind::Closure(&Closure {
730 fn_decl, def_id, body, ..
731 }) = closure.kind
732 {
733 let closure_body = cx.tcx.hir_body(body);
734 let closure_arg_is_type_annotated_double_ref = if let TyKind::Ref(_, MutTy { ty, .. }) = fn_decl.inputs[0].kind
737 {
738 matches!(ty.kind, TyKind::Ref(_, MutTy { .. }))
739 } else {
740 false
741 };
742
743 let mut visitor = DerefDelegate {
744 cx,
745 closure_span: closure.span,
746 closure_arg_is_type_annotated_double_ref,
747 next_pos: closure.span.lo(),
748 suggestion_start: String::new(),
749 applicability: Applicability::MachineApplicable,
750 };
751
752 ExprUseVisitor::for_clippy(cx, def_id, &mut visitor)
753 .consume_body(closure_body)
754 .into_ok();
755
756 if !visitor.suggestion_start.is_empty() {
757 return Some(DerefClosure {
758 applicability: visitor.applicability,
759 suggestion: visitor.finish(),
760 });
761 }
762 }
763 None
764}
765
766struct DerefDelegate<'a, 'tcx> {
769 cx: &'a LateContext<'tcx>,
771 closure_span: Span,
773 closure_arg_is_type_annotated_double_ref: bool,
775 next_pos: BytePos,
777 suggestion_start: String,
779 applicability: Applicability,
781}
782
783impl<'tcx> DerefDelegate<'_, 'tcx> {
784 pub fn finish(&mut self) -> String {
789 let end_span = Span::new(self.next_pos, self.closure_span.hi(), self.closure_span.ctxt(), None);
790 let end_snip = snippet_with_applicability(self.cx, end_span, "..", &mut self.applicability);
791 let sugg = format!("{}{end_snip}", self.suggestion_start);
792 if self.closure_arg_is_type_annotated_double_ref {
793 sugg.replacen('&', "", 1)
794 } else {
795 sugg
796 }
797 }
798
799 fn func_takes_arg_by_double_ref(&self, parent_expr: &'tcx hir::Expr<'_>, cmt_hir_id: HirId) -> bool {
801 let ty = match parent_expr.kind {
802 ExprKind::MethodCall(_, receiver, call_args, _) => {
803 if let Some(sig) = self
804 .cx
805 .typeck_results()
806 .type_dependent_def_id(parent_expr.hir_id)
807 .map(|did| self.cx.tcx.fn_sig(did).instantiate_identity().skip_binder())
808 {
809 std::iter::once(receiver)
810 .chain(call_args.iter())
811 .position(|arg| arg.hir_id == cmt_hir_id)
812 .map(|i| sig.inputs()[i])
813 } else {
814 return false;
815 }
816 },
817 ExprKind::Call(func, call_args) => {
818 if let Some(sig) = expr_sig(self.cx, func) {
819 call_args
820 .iter()
821 .position(|arg| arg.hir_id == cmt_hir_id)
822 .and_then(|i| sig.input(i))
823 .map(ty::Binder::skip_binder)
824 } else {
825 return false;
826 }
827 },
828 _ => return false,
829 };
830
831 ty.is_some_and(|ty| matches!(ty.kind(), ty::Ref(_, inner, _) if inner.is_ref()))
832 }
833}
834
835impl<'tcx> Delegate<'tcx> for DerefDelegate<'_, 'tcx> {
836 fn consume(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
837
838 fn use_cloned(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
839
840 fn borrow(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId, _: ty::BorrowKind) {
841 if let PlaceBase::Local(id) = cmt.place.base {
842 let span = self.cx.tcx.hir_span(cmt.hir_id);
843 let start_span = Span::new(self.next_pos, span.lo(), span.ctxt(), None);
844 let mut start_snip = snippet_with_applicability(self.cx, start_span, "..", &mut self.applicability);
845
846 let ident_str = self.cx.tcx.hir_name(id).to_string();
848 let ident_str_with_proj = snippet(self.cx, span, "..").to_string();
850
851 if cmt.place.projections.is_empty() {
852 let _: fmt::Result = write!(self.suggestion_start, "{start_snip}&{ident_str}");
855 } else {
856 if let Some(parent_expr) = get_parent_expr_for_hir(self.cx, cmt.hir_id) {
865 match &parent_expr.kind {
866 ExprKind::MethodCall(_, self_expr, ..) if self_expr.hir_id == cmt.hir_id => {
869 let _: fmt::Result = write!(self.suggestion_start, "{start_snip}{ident_str_with_proj}");
870 self.next_pos = span.hi();
871 return;
872 },
873 ExprKind::Call(_, call_args) | ExprKind::MethodCall(_, _, call_args, _) => {
876 let expr = self.cx.tcx.hir_expect_expr(cmt.hir_id);
877 let arg_ty_kind = self.cx.typeck_results().expr_ty(expr).kind();
878
879 if matches!(arg_ty_kind, ty::Ref(_, _, Mutability::Not)) {
880 let takes_arg_by_double_ref =
882 self.func_takes_arg_by_double_ref(parent_expr, cmt.hir_id);
883
884 let has_field_or_index_projection =
887 cmt.place.projections.iter().any(|proj| {
888 matches!(proj.kind, ProjectionKind::Field(..) | ProjectionKind::Index)
889 });
890
891 let ident_sugg = if !call_args.is_empty()
894 && !takes_arg_by_double_ref
895 && (self.closure_arg_is_type_annotated_double_ref || has_field_or_index_projection)
896 {
897 let ident = if has_field_or_index_projection {
898 ident_str_with_proj
899 } else {
900 ident_str
901 };
902 format!("{start_snip}{ident}")
903 } else {
904 format!("{start_snip}&{ident_str}")
905 };
906 self.suggestion_start.push_str(&ident_sugg);
907 self.next_pos = span.hi();
908 return;
909 }
910
911 self.applicability = Applicability::Unspecified;
912 },
913 _ => (),
914 }
915 }
916
917 let mut replacement_str = ident_str;
918 let mut projections_handled = false;
919 cmt.place.projections.iter().enumerate().for_each(|(i, proj)| {
920 match proj.kind {
921 ProjectionKind::Field(..) => match cmt.place.ty_before_projection(i).kind() {
924 ty::Adt(..) | ty::Tuple(_) => {
925 replacement_str.clone_from(&ident_str_with_proj);
926 projections_handled = true;
927 },
928 _ => (),
929 },
930 ProjectionKind::Index => {
935 let start_span = Span::new(self.next_pos, span.hi(), span.ctxt(), None);
936 start_snip = snippet_with_applicability(self.cx, start_span, "..", &mut self.applicability);
937 replacement_str.clear();
938 projections_handled = true;
939 },
940 ProjectionKind::Subslice |
942 ProjectionKind::OpaqueCast => (),
944 ProjectionKind::Deref => {
945 if let ty::Ref(_, inner, _) = cmt.place.ty_before_projection(i).kind() {
950 if matches!(inner.kind(), ty::Ref(_, innermost, _) if innermost.is_array()) {
951 projections_handled = true;
952 }
953 }
954 },
955 }
956 });
957
958 if !projections_handled {
961 let last_deref = cmt
962 .place
963 .projections
964 .iter()
965 .rposition(|proj| proj.kind == ProjectionKind::Deref);
966
967 if let Some(pos) = last_deref {
968 let mut projections = cmt.place.projections.clone();
969 projections.truncate(pos);
970
971 for item in projections {
972 if item.kind == ProjectionKind::Deref {
973 replacement_str = format!("*{replacement_str}");
974 }
975 }
976 }
977 }
978
979 let _: fmt::Result = write!(self.suggestion_start, "{start_snip}{replacement_str}");
980 }
981 self.next_pos = span.hi();
982 }
983 }
984
985 fn mutate(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
986
987 fn fake_read(&mut self, _: &PlaceWithHirId<'tcx>, _: FakeReadCause, _: HirId) {}
988}
989
990#[cfg(test)]
991mod test {
992 use super::Sugg;
993
994 use rustc_ast as ast;
995 use rustc_ast::util::parser::AssocOp;
996 use std::borrow::Cow;
997
998 const SUGGESTION: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("function_call()"));
999
1000 #[test]
1001 fn make_return_transform_sugg_into_a_return_call() {
1002 assert_eq!("return function_call()", SUGGESTION.make_return().to_string());
1003 }
1004
1005 #[test]
1006 fn blockify_transforms_sugg_into_a_block() {
1007 assert_eq!("{ function_call() }", SUGGESTION.blockify().to_string());
1008 }
1009
1010 #[test]
1011 fn binop_maybe_par() {
1012 let sugg = Sugg::BinOp(AssocOp::Binary(ast::BinOpKind::Add), "1".into(), "1".into());
1013 assert_eq!("(1 + 1)", sugg.maybe_par().to_string());
1014
1015 let sugg = Sugg::BinOp(AssocOp::Binary(ast::BinOpKind::Add), "(1 + 1)".into(), "(1 + 1)".into());
1016 assert_eq!("((1 + 1) + (1 + 1))", sugg.maybe_par().to_string());
1017 }
1018 #[test]
1019 fn not_op() {
1020 use ast::BinOpKind::{Add, And, Eq, Ge, Gt, Le, Lt, Ne, Or};
1021
1022 fn test_not(op: AssocOp, correct: &str) {
1023 let sugg = Sugg::BinOp(op, "x".into(), "y".into());
1024 assert_eq!((!sugg).to_string(), correct);
1025 }
1026
1027 test_not(AssocOp::Binary(Eq), "x != y");
1029 test_not(AssocOp::Binary(Ne), "x == y");
1030 test_not(AssocOp::Binary(Lt), "x >= y");
1031 test_not(AssocOp::Binary(Le), "x > y");
1032 test_not(AssocOp::Binary(Gt), "x <= y");
1033 test_not(AssocOp::Binary(Ge), "x < y");
1034
1035 test_not(AssocOp::Binary(Add), "!(x + y)");
1037 test_not(AssocOp::Binary(And), "!(x && y)");
1038 test_not(AssocOp::Binary(Or), "!(x || y)");
1039 }
1040}