]>
Commit | Line | Data |
---|---|---|
f20569fa XL |
1 | //! Contains utility functions to generate suggestions. |
2 | #![deny(clippy::missing_docs_in_private_items)] | |
3 | ||
2b03887a FG |
4 | use crate::source::{ |
5 | snippet, snippet_opt, snippet_with_applicability, snippet_with_context, snippet_with_macro_callsite, | |
6 | }; | |
064997fb | 7 | use crate::ty::expr_sig; |
a2a8927a | 8 | use crate::{get_parent_expr_for_hir, higher}; |
f20569fa XL |
9 | use rustc_ast::util::parser::AssocOp; |
10 | use rustc_ast::{ast, token}; | |
11 | use rustc_ast_pretty::pprust::token_kind_to_string; | |
12 | use rustc_errors::Applicability; | |
13 | use rustc_hir as hir; | |
064997fb | 14 | use rustc_hir::{Closure, ExprKind, HirId, MutTy, TyKind}; |
2b03887a | 15 | use rustc_hir_typeck::expr_use_visitor::{Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId}; |
a2a8927a | 16 | use rustc_infer::infer::TyCtxtInferExt; |
f20569fa | 17 | use rustc_lint::{EarlyContext, LateContext, LintContext}; |
a2a8927a XL |
18 | use rustc_middle::hir::place::ProjectionKind; |
19 | use rustc_middle::mir::{FakeReadCause, Mutability}; | |
20 | use rustc_middle::ty; | |
21 | use rustc_span::source_map::{BytePos, CharPos, Pos, Span, SyntaxContext}; | |
f20569fa | 22 | use std::borrow::Cow; |
9ffffee4 | 23 | use std::fmt::{self, Display, Write as _}; |
f20569fa XL |
24 | use std::ops::{Add, Neg, Not, Sub}; |
25 | ||
3c0e092e | 26 | /// A helper type to build suggestion correctly handling parentheses. |
2b03887a | 27 | #[derive(Clone, Debug, PartialEq)] |
f20569fa | 28 | pub enum Sugg<'a> { |
3c0e092e | 29 | /// An expression that never needs parentheses such as `1337` or `[0; 42]`. |
f20569fa XL |
30 | NonParen(Cow<'a, str>), |
31 | /// An expression that does not fit in other variants. | |
32 | MaybeParen(Cow<'a, str>), | |
33 | /// A binary operator expression, including `as`-casts and explicit type | |
34 | /// coercion. | |
a2a8927a | 35 | BinOp(AssocOp, Cow<'a, str>, Cow<'a, str>), |
f20569fa XL |
36 | } |
37 | ||
38 | /// Literal constant `0`, for convenience. | |
39 | pub const ZERO: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("0")); | |
40 | /// Literal constant `1`, for convenience. | |
41 | pub const ONE: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("1")); | |
42 | /// a constant represents an empty string, for convenience. | |
43 | pub const EMPTY: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("")); | |
44 | ||
45 | impl Display for Sugg<'_> { | |
46 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { | |
47 | match *self { | |
a2a8927a XL |
48 | Sugg::NonParen(ref s) | Sugg::MaybeParen(ref s) => s.fmt(f), |
49 | Sugg::BinOp(op, ref lhs, ref rhs) => binop_to_string(op, lhs, rhs).fmt(f), | |
f20569fa XL |
50 | } |
51 | } | |
52 | } | |
53 | ||
923072b8 | 54 | #[expect(clippy::wrong_self_convention)] // ok, because of the function `as_ty` method |
f20569fa XL |
55 | impl<'a> Sugg<'a> { |
56 | /// Prepare a suggestion from an expression. | |
57 | pub fn hir_opt(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option<Self> { | |
a2a8927a XL |
58 | let get_snippet = |span| snippet(cx, span, ""); |
59 | snippet_opt(cx, expr.span).map(|_| Self::hir_from_snippet(expr, get_snippet)) | |
f20569fa XL |
60 | } |
61 | ||
62 | /// Convenience function around `hir_opt` for suggestions with a default | |
63 | /// text. | |
64 | pub fn hir(cx: &LateContext<'_>, expr: &hir::Expr<'_>, default: &'a str) -> Self { | |
65 | Self::hir_opt(cx, expr).unwrap_or(Sugg::NonParen(Cow::Borrowed(default))) | |
66 | } | |
67 | ||
68 | /// Same as `hir`, but it adapts the applicability level by following rules: | |
69 | /// | |
70 | /// - Applicability level `Unspecified` will never be changed. | |
71 | /// - If the span is inside a macro, change the applicability level to `MaybeIncorrect`. | |
72 | /// - If the default value is used and the applicability level is `MachineApplicable`, change it | |
73 | /// to | |
74 | /// `HasPlaceholders` | |
75 | pub fn hir_with_applicability( | |
76 | cx: &LateContext<'_>, | |
77 | expr: &hir::Expr<'_>, | |
78 | default: &'a str, | |
79 | applicability: &mut Applicability, | |
80 | ) -> Self { | |
81 | if *applicability != Applicability::Unspecified && expr.span.from_expansion() { | |
82 | *applicability = Applicability::MaybeIncorrect; | |
83 | } | |
84 | Self::hir_opt(cx, expr).unwrap_or_else(|| { | |
85 | if *applicability == Applicability::MachineApplicable { | |
86 | *applicability = Applicability::HasPlaceholders; | |
87 | } | |
88 | Sugg::NonParen(Cow::Borrowed(default)) | |
89 | }) | |
90 | } | |
91 | ||
92 | /// Same as `hir`, but will use the pre expansion span if the `expr` was in a macro. | |
93 | pub fn hir_with_macro_callsite(cx: &LateContext<'_>, expr: &hir::Expr<'_>, default: &'a str) -> Self { | |
a2a8927a XL |
94 | let get_snippet = |span| snippet_with_macro_callsite(cx, span, default); |
95 | Self::hir_from_snippet(expr, get_snippet) | |
f20569fa XL |
96 | } |
97 | ||
17df50a5 XL |
98 | /// Same as `hir`, but first walks the span up to the given context. This will result in the |
99 | /// macro call, rather then the expansion, if the span is from a child context. If the span is | |
100 | /// not from a child context, it will be used directly instead. | |
101 | /// | |
102 | /// e.g. Given the expression `&vec![]`, getting a snippet from the span for `vec![]` as a HIR | |
103 | /// node would result in `box []`. If given the context of the address of expression, this | |
104 | /// function will correctly get a snippet of `vec![]`. | |
105 | pub fn hir_with_context( | |
106 | cx: &LateContext<'_>, | |
107 | expr: &hir::Expr<'_>, | |
108 | ctxt: SyntaxContext, | |
109 | default: &'a str, | |
110 | applicability: &mut Applicability, | |
111 | ) -> Self { | |
a2a8927a XL |
112 | if expr.span.ctxt() == ctxt { |
113 | Self::hir_from_snippet(expr, |span| snippet(cx, span, default)) | |
17df50a5 | 114 | } else { |
2b03887a | 115 | let (snip, _) = snippet_with_context(cx, expr.span, ctxt, default, applicability); |
a2a8927a | 116 | Sugg::NonParen(snip) |
17df50a5 XL |
117 | } |
118 | } | |
119 | ||
f20569fa XL |
120 | /// Generate a suggestion for an expression with the given snippet. This is used by the `hir_*` |
121 | /// function variants of `Sugg`, since these use different snippet functions. | |
a2a8927a | 122 | fn hir_from_snippet(expr: &hir::Expr<'_>, get_snippet: impl Fn(Span) -> Cow<'a, str>) -> Self { |
94222f64 | 123 | if let Some(range) = higher::Range::hir(expr) { |
f20569fa XL |
124 | let op = match range.limits { |
125 | ast::RangeLimits::HalfOpen => AssocOp::DotDot, | |
126 | ast::RangeLimits::Closed => AssocOp::DotDotEq, | |
127 | }; | |
a2a8927a XL |
128 | let start = range.start.map_or("".into(), |expr| get_snippet(expr.span)); |
129 | let end = range.end.map_or("".into(), |expr| get_snippet(expr.span)); | |
130 | ||
131 | return Sugg::BinOp(op, start, end); | |
f20569fa XL |
132 | } |
133 | ||
134 | match expr.kind { | |
135 | hir::ExprKind::AddrOf(..) | |
136 | | hir::ExprKind::Box(..) | |
137 | | hir::ExprKind::If(..) | |
94222f64 | 138 | | hir::ExprKind::Let(..) |
923072b8 | 139 | | hir::ExprKind::Closure { .. } |
f20569fa | 140 | | hir::ExprKind::Unary(..) |
a2a8927a | 141 | | hir::ExprKind::Match(..) => Sugg::MaybeParen(get_snippet(expr.span)), |
f20569fa XL |
142 | hir::ExprKind::Continue(..) |
143 | | hir::ExprKind::Yield(..) | |
144 | | hir::ExprKind::Array(..) | |
145 | | hir::ExprKind::Block(..) | |
146 | | hir::ExprKind::Break(..) | |
147 | | hir::ExprKind::Call(..) | |
148 | | hir::ExprKind::Field(..) | |
149 | | hir::ExprKind::Index(..) | |
150 | | hir::ExprKind::InlineAsm(..) | |
f20569fa XL |
151 | | hir::ExprKind::ConstBlock(..) |
152 | | hir::ExprKind::Lit(..) | |
153 | | hir::ExprKind::Loop(..) | |
154 | | hir::ExprKind::MethodCall(..) | |
155 | | hir::ExprKind::Path(..) | |
156 | | hir::ExprKind::Repeat(..) | |
157 | | hir::ExprKind::Ret(..) | |
158 | | hir::ExprKind::Struct(..) | |
159 | | hir::ExprKind::Tup(..) | |
9ffffee4 | 160 | | hir::ExprKind::Err(_) => Sugg::NonParen(get_snippet(expr.span)), |
2b03887a | 161 | hir::ExprKind::DropTemps(inner) => Self::hir_from_snippet(inner, get_snippet), |
a2a8927a XL |
162 | hir::ExprKind::Assign(lhs, rhs, _) => { |
163 | Sugg::BinOp(AssocOp::Assign, get_snippet(lhs.span), get_snippet(rhs.span)) | |
164 | }, | |
165 | hir::ExprKind::AssignOp(op, lhs, rhs) => { | |
166 | Sugg::BinOp(hirbinop2assignop(op), get_snippet(lhs.span), get_snippet(rhs.span)) | |
167 | }, | |
168 | hir::ExprKind::Binary(op, lhs, rhs) => Sugg::BinOp( | |
169 | AssocOp::from_ast_binop(op.node.into()), | |
170 | get_snippet(lhs.span), | |
171 | get_snippet(rhs.span), | |
172 | ), | |
173 | hir::ExprKind::Cast(lhs, ty) => Sugg::BinOp(AssocOp::As, get_snippet(lhs.span), get_snippet(ty.span)), | |
174 | hir::ExprKind::Type(lhs, ty) => Sugg::BinOp(AssocOp::Colon, get_snippet(lhs.span), get_snippet(ty.span)), | |
f20569fa XL |
175 | } |
176 | } | |
177 | ||
178 | /// Prepare a suggestion from an expression. | |
487cf647 FG |
179 | pub fn ast( |
180 | cx: &EarlyContext<'_>, | |
181 | expr: &ast::Expr, | |
182 | default: &'a str, | |
183 | ctxt: SyntaxContext, | |
184 | app: &mut Applicability, | |
185 | ) -> Self { | |
f20569fa XL |
186 | use rustc_ast::ast::RangeLimits; |
187 | ||
f20569fa | 188 | match expr.kind { |
487cf647 | 189 | _ if expr.span.ctxt() != ctxt => Sugg::NonParen(snippet_with_context(cx, expr.span, ctxt, default, app).0), |
f20569fa XL |
190 | ast::ExprKind::AddrOf(..) |
191 | | ast::ExprKind::Box(..) | |
923072b8 | 192 | | ast::ExprKind::Closure { .. } |
f20569fa XL |
193 | | ast::ExprKind::If(..) |
194 | | ast::ExprKind::Let(..) | |
195 | | ast::ExprKind::Unary(..) | |
487cf647 FG |
196 | | ast::ExprKind::Match(..) => match snippet_with_context(cx, expr.span, ctxt, default, app) { |
197 | (snip, false) => Sugg::MaybeParen(snip), | |
198 | (snip, true) => Sugg::NonParen(snip), | |
199 | }, | |
f20569fa XL |
200 | ast::ExprKind::Async(..) |
201 | | ast::ExprKind::Block(..) | |
202 | | ast::ExprKind::Break(..) | |
203 | | ast::ExprKind::Call(..) | |
204 | | ast::ExprKind::Continue(..) | |
205 | | ast::ExprKind::Yield(..) | |
206 | | ast::ExprKind::Field(..) | |
207 | | ast::ExprKind::ForLoop(..) | |
208 | | ast::ExprKind::Index(..) | |
209 | | ast::ExprKind::InlineAsm(..) | |
f20569fa XL |
210 | | ast::ExprKind::ConstBlock(..) |
211 | | ast::ExprKind::Lit(..) | |
487cf647 | 212 | | ast::ExprKind::IncludedBytes(..) |
f20569fa XL |
213 | | ast::ExprKind::Loop(..) |
214 | | ast::ExprKind::MacCall(..) | |
215 | | ast::ExprKind::MethodCall(..) | |
216 | | ast::ExprKind::Paren(..) | |
217 | | ast::ExprKind::Underscore | |
218 | | ast::ExprKind::Path(..) | |
219 | | ast::ExprKind::Repeat(..) | |
220 | | ast::ExprKind::Ret(..) | |
04454e1e | 221 | | ast::ExprKind::Yeet(..) |
9ffffee4 | 222 | | ast::ExprKind::FormatArgs(..) |
f20569fa XL |
223 | | ast::ExprKind::Struct(..) |
224 | | ast::ExprKind::Try(..) | |
225 | | ast::ExprKind::TryBlock(..) | |
226 | | ast::ExprKind::Tup(..) | |
227 | | ast::ExprKind::Array(..) | |
228 | | ast::ExprKind::While(..) | |
229 | | ast::ExprKind::Await(..) | |
487cf647 | 230 | | ast::ExprKind::Err => Sugg::NonParen(snippet_with_context(cx, expr.span, ctxt, default, app).0), |
a2a8927a XL |
231 | ast::ExprKind::Range(ref lhs, ref rhs, RangeLimits::HalfOpen) => Sugg::BinOp( |
232 | AssocOp::DotDot, | |
487cf647 FG |
233 | lhs.as_ref().map_or("".into(), |lhs| { |
234 | snippet_with_context(cx, lhs.span, ctxt, default, app).0 | |
235 | }), | |
236 | rhs.as_ref().map_or("".into(), |rhs| { | |
237 | snippet_with_context(cx, rhs.span, ctxt, default, app).0 | |
238 | }), | |
a2a8927a XL |
239 | ), |
240 | ast::ExprKind::Range(ref lhs, ref rhs, RangeLimits::Closed) => Sugg::BinOp( | |
241 | AssocOp::DotDotEq, | |
487cf647 FG |
242 | lhs.as_ref().map_or("".into(), |lhs| { |
243 | snippet_with_context(cx, lhs.span, ctxt, default, app).0 | |
244 | }), | |
245 | rhs.as_ref().map_or("".into(), |rhs| { | |
246 | snippet_with_context(cx, rhs.span, ctxt, default, app).0 | |
247 | }), | |
a2a8927a XL |
248 | ), |
249 | ast::ExprKind::Assign(ref lhs, ref rhs, _) => Sugg::BinOp( | |
250 | AssocOp::Assign, | |
487cf647 FG |
251 | snippet_with_context(cx, lhs.span, ctxt, default, app).0, |
252 | snippet_with_context(cx, rhs.span, ctxt, default, app).0, | |
a2a8927a XL |
253 | ), |
254 | ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => Sugg::BinOp( | |
255 | astbinop2assignop(op), | |
487cf647 FG |
256 | snippet_with_context(cx, lhs.span, ctxt, default, app).0, |
257 | snippet_with_context(cx, rhs.span, ctxt, default, app).0, | |
a2a8927a XL |
258 | ), |
259 | ast::ExprKind::Binary(op, ref lhs, ref rhs) => Sugg::BinOp( | |
260 | AssocOp::from_ast_binop(op.node), | |
487cf647 FG |
261 | snippet_with_context(cx, lhs.span, ctxt, default, app).0, |
262 | snippet_with_context(cx, rhs.span, ctxt, default, app).0, | |
a2a8927a XL |
263 | ), |
264 | ast::ExprKind::Cast(ref lhs, ref ty) => Sugg::BinOp( | |
265 | AssocOp::As, | |
487cf647 FG |
266 | snippet_with_context(cx, lhs.span, ctxt, default, app).0, |
267 | snippet_with_context(cx, ty.span, ctxt, default, app).0, | |
a2a8927a XL |
268 | ), |
269 | ast::ExprKind::Type(ref lhs, ref ty) => Sugg::BinOp( | |
270 | AssocOp::Colon, | |
487cf647 FG |
271 | snippet_with_context(cx, lhs.span, ctxt, default, app).0, |
272 | snippet_with_context(cx, ty.span, ctxt, default, app).0, | |
a2a8927a | 273 | ), |
f20569fa XL |
274 | } |
275 | } | |
276 | ||
277 | /// Convenience method to create the `<lhs> && <rhs>` suggestion. | |
278 | pub fn and(self, rhs: &Self) -> Sugg<'static> { | |
279 | make_binop(ast::BinOpKind::And, &self, rhs) | |
280 | } | |
281 | ||
282 | /// Convenience method to create the `<lhs> & <rhs>` suggestion. | |
283 | pub fn bit_and(self, rhs: &Self) -> Sugg<'static> { | |
284 | make_binop(ast::BinOpKind::BitAnd, &self, rhs) | |
285 | } | |
286 | ||
287 | /// Convenience method to create the `<lhs> as <rhs>` suggestion. | |
288 | pub fn as_ty<R: Display>(self, rhs: R) -> Sugg<'static> { | |
289 | make_assoc(AssocOp::As, &self, &Sugg::NonParen(rhs.to_string().into())) | |
290 | } | |
291 | ||
292 | /// Convenience method to create the `&<expr>` suggestion. | |
293 | pub fn addr(self) -> Sugg<'static> { | |
294 | make_unop("&", self) | |
295 | } | |
296 | ||
297 | /// Convenience method to create the `&mut <expr>` suggestion. | |
298 | pub fn mut_addr(self) -> Sugg<'static> { | |
299 | make_unop("&mut ", self) | |
300 | } | |
301 | ||
302 | /// Convenience method to create the `*<expr>` suggestion. | |
303 | pub fn deref(self) -> Sugg<'static> { | |
304 | make_unop("*", self) | |
305 | } | |
306 | ||
307 | /// Convenience method to create the `&*<expr>` suggestion. Currently this | |
308 | /// is needed because `sugg.deref().addr()` produces an unnecessary set of | |
309 | /// parentheses around the deref. | |
310 | pub fn addr_deref(self) -> Sugg<'static> { | |
311 | make_unop("&*", self) | |
312 | } | |
313 | ||
314 | /// Convenience method to create the `&mut *<expr>` suggestion. Currently | |
315 | /// this is needed because `sugg.deref().mut_addr()` produces an unnecessary | |
316 | /// set of parentheses around the deref. | |
317 | pub fn mut_addr_deref(self) -> Sugg<'static> { | |
318 | make_unop("&mut *", self) | |
319 | } | |
320 | ||
321 | /// Convenience method to transform suggestion into a return call | |
322 | pub fn make_return(self) -> Sugg<'static> { | |
2b03887a | 323 | Sugg::NonParen(Cow::Owned(format!("return {self}"))) |
f20569fa XL |
324 | } |
325 | ||
326 | /// Convenience method to transform suggestion into a block | |
327 | /// where the suggestion is a trailing expression | |
328 | pub fn blockify(self) -> Sugg<'static> { | |
2b03887a | 329 | Sugg::NonParen(Cow::Owned(format!("{{ {self} }}"))) |
f20569fa XL |
330 | } |
331 | ||
f2b60f7d FG |
332 | /// Convenience method to prefix the expression with the `async` keyword. |
333 | /// Can be used after `blockify` to create an async block. | |
334 | pub fn asyncify(self) -> Sugg<'static> { | |
2b03887a | 335 | Sugg::NonParen(Cow::Owned(format!("async {self}"))) |
f2b60f7d FG |
336 | } |
337 | ||
f20569fa XL |
338 | /// Convenience method to create the `<lhs>..<rhs>` or `<lhs>...<rhs>` |
339 | /// suggestion. | |
f20569fa XL |
340 | pub fn range(self, end: &Self, limit: ast::RangeLimits) -> Sugg<'static> { |
341 | match limit { | |
342 | ast::RangeLimits::HalfOpen => make_assoc(AssocOp::DotDot, &self, end), | |
343 | ast::RangeLimits::Closed => make_assoc(AssocOp::DotDotEq, &self, end), | |
344 | } | |
345 | } | |
346 | ||
3c0e092e | 347 | /// Adds parentheses to any expression that might need them. Suitable to the |
f20569fa XL |
348 | /// `self` argument of a method call |
349 | /// (e.g., to build `bar.foo()` or `(1 + 2).foo()`). | |
a2a8927a | 350 | #[must_use] |
f20569fa XL |
351 | pub fn maybe_par(self) -> Self { |
352 | match self { | |
353 | Sugg::NonParen(..) => self, | |
354 | // `(x)` and `(x).y()` both don't need additional parens. | |
355 | Sugg::MaybeParen(sugg) => { | |
cdc7bbd5 | 356 | if has_enclosing_paren(&sugg) { |
f20569fa XL |
357 | Sugg::MaybeParen(sugg) |
358 | } else { | |
2b03887a | 359 | Sugg::NonParen(format!("({sugg})").into()) |
f20569fa XL |
360 | } |
361 | }, | |
a2a8927a XL |
362 | Sugg::BinOp(op, lhs, rhs) => { |
363 | let sugg = binop_to_string(op, &lhs, &rhs); | |
2b03887a | 364 | Sugg::NonParen(format!("({sugg})").into()) |
cdc7bbd5 | 365 | }, |
f20569fa XL |
366 | } |
367 | } | |
368 | } | |
369 | ||
a2a8927a XL |
370 | /// Generates a string from the operator and both sides. |
371 | fn binop_to_string(op: AssocOp, lhs: &str, rhs: &str) -> String { | |
372 | match op { | |
373 | AssocOp::Add | |
374 | | AssocOp::Subtract | |
375 | | AssocOp::Multiply | |
376 | | AssocOp::Divide | |
377 | | AssocOp::Modulus | |
378 | | AssocOp::LAnd | |
379 | | AssocOp::LOr | |
380 | | AssocOp::BitXor | |
381 | | AssocOp::BitAnd | |
382 | | AssocOp::BitOr | |
383 | | AssocOp::ShiftLeft | |
384 | | AssocOp::ShiftRight | |
385 | | AssocOp::Equal | |
386 | | AssocOp::Less | |
387 | | AssocOp::LessEqual | |
388 | | AssocOp::NotEqual | |
389 | | AssocOp::Greater | |
f2b60f7d FG |
390 | | AssocOp::GreaterEqual => { |
391 | format!( | |
2b03887a FG |
392 | "{lhs} {} {rhs}", |
393 | op.to_ast_binop().expect("Those are AST ops").to_string() | |
f2b60f7d FG |
394 | ) |
395 | }, | |
2b03887a | 396 | AssocOp::Assign => format!("{lhs} = {rhs}"), |
a2a8927a | 397 | AssocOp::AssignOp(op) => { |
2b03887a | 398 | format!("{lhs} {}= {rhs}", token_kind_to_string(&token::BinOp(op))) |
a2a8927a | 399 | }, |
2b03887a FG |
400 | AssocOp::As => format!("{lhs} as {rhs}"), |
401 | AssocOp::DotDot => format!("{lhs}..{rhs}"), | |
402 | AssocOp::DotDotEq => format!("{lhs}..={rhs}"), | |
403 | AssocOp::Colon => format!("{lhs}: {rhs}"), | |
a2a8927a XL |
404 | } |
405 | } | |
406 | ||
cdc7bbd5 | 407 | /// Return `true` if `sugg` is enclosed in parenthesis. |
5099ac24 | 408 | pub fn has_enclosing_paren(sugg: impl AsRef<str>) -> bool { |
cdc7bbd5 | 409 | let mut chars = sugg.as_ref().chars(); |
c295e0f8 | 410 | if chars.next() == Some('(') { |
cdc7bbd5 | 411 | let mut depth = 1; |
17df50a5 | 412 | for c in &mut chars { |
cdc7bbd5 XL |
413 | if c == '(' { |
414 | depth += 1; | |
415 | } else if c == ')' { | |
416 | depth -= 1; | |
417 | } | |
418 | if depth == 0 { | |
419 | break; | |
420 | } | |
421 | } | |
422 | chars.next().is_none() | |
423 | } else { | |
424 | false | |
425 | } | |
426 | } | |
427 | ||
c295e0f8 | 428 | /// Copied from the rust standard library, and then edited |
f20569fa XL |
429 | macro_rules! forward_binop_impls_to_ref { |
430 | (impl $imp:ident, $method:ident for $t:ty, type Output = $o:ty) => { | |
431 | impl $imp<$t> for &$t { | |
432 | type Output = $o; | |
433 | ||
434 | fn $method(self, other: $t) -> $o { | |
435 | $imp::$method(self, &other) | |
436 | } | |
437 | } | |
438 | ||
439 | impl $imp<&$t> for $t { | |
440 | type Output = $o; | |
441 | ||
442 | fn $method(self, other: &$t) -> $o { | |
443 | $imp::$method(&self, other) | |
444 | } | |
445 | } | |
446 | ||
447 | impl $imp for $t { | |
448 | type Output = $o; | |
449 | ||
450 | fn $method(self, other: $t) -> $o { | |
451 | $imp::$method(&self, &other) | |
452 | } | |
453 | } | |
454 | }; | |
455 | } | |
456 | ||
457 | impl Add for &Sugg<'_> { | |
458 | type Output = Sugg<'static>; | |
459 | fn add(self, rhs: &Sugg<'_>) -> Sugg<'static> { | |
460 | make_binop(ast::BinOpKind::Add, self, rhs) | |
461 | } | |
462 | } | |
463 | ||
464 | impl Sub for &Sugg<'_> { | |
465 | type Output = Sugg<'static>; | |
466 | fn sub(self, rhs: &Sugg<'_>) -> Sugg<'static> { | |
467 | make_binop(ast::BinOpKind::Sub, self, rhs) | |
468 | } | |
469 | } | |
470 | ||
471 | forward_binop_impls_to_ref!(impl Add, add for Sugg<'_>, type Output = Sugg<'static>); | |
472 | forward_binop_impls_to_ref!(impl Sub, sub for Sugg<'_>, type Output = Sugg<'static>); | |
473 | ||
474 | impl Neg for Sugg<'_> { | |
475 | type Output = Sugg<'static>; | |
476 | fn neg(self) -> Sugg<'static> { | |
477 | make_unop("-", self) | |
478 | } | |
479 | } | |
480 | ||
5099ac24 | 481 | impl<'a> Not for Sugg<'a> { |
a2a8927a XL |
482 | type Output = Sugg<'a>; |
483 | fn not(self) -> Sugg<'a> { | |
484 | use AssocOp::{Equal, Greater, GreaterEqual, Less, LessEqual, NotEqual}; | |
485 | ||
486 | if let Sugg::BinOp(op, lhs, rhs) = self { | |
487 | let to_op = match op { | |
488 | Equal => NotEqual, | |
489 | NotEqual => Equal, | |
490 | Less => GreaterEqual, | |
491 | GreaterEqual => Less, | |
492 | Greater => LessEqual, | |
493 | LessEqual => Greater, | |
494 | _ => return make_unop("!", Sugg::BinOp(op, lhs, rhs)), | |
495 | }; | |
496 | Sugg::BinOp(to_op, lhs, rhs) | |
497 | } else { | |
498 | make_unop("!", self) | |
499 | } | |
f20569fa XL |
500 | } |
501 | } | |
502 | ||
503 | /// Helper type to display either `foo` or `(foo)`. | |
504 | struct ParenHelper<T> { | |
505 | /// `true` if parentheses are needed. | |
506 | paren: bool, | |
507 | /// The main thing to display. | |
508 | wrapped: T, | |
509 | } | |
510 | ||
511 | impl<T> ParenHelper<T> { | |
512 | /// Builds a `ParenHelper`. | |
513 | fn new(paren: bool, wrapped: T) -> Self { | |
514 | Self { paren, wrapped } | |
515 | } | |
516 | } | |
517 | ||
518 | impl<T: Display> Display for ParenHelper<T> { | |
519 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { | |
520 | if self.paren { | |
521 | write!(f, "({})", self.wrapped) | |
522 | } else { | |
523 | self.wrapped.fmt(f) | |
524 | } | |
525 | } | |
526 | } | |
527 | ||
528 | /// Builds the string for `<op><expr>` adding parenthesis when necessary. | |
529 | /// | |
530 | /// For convenience, the operator is taken as a string because all unary | |
531 | /// operators have the same | |
532 | /// precedence. | |
533 | pub fn make_unop(op: &str, expr: Sugg<'_>) -> Sugg<'static> { | |
2b03887a | 534 | Sugg::MaybeParen(format!("{op}{}", expr.maybe_par()).into()) |
f20569fa XL |
535 | } |
536 | ||
537 | /// Builds the string for `<lhs> <op> <rhs>` adding parenthesis when necessary. | |
538 | /// | |
539 | /// Precedence of shift operator relative to other arithmetic operation is | |
540 | /// often confusing so | |
541 | /// parenthesis will always be added for a mix of these. | |
542 | pub fn make_assoc(op: AssocOp, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> { | |
543 | /// Returns `true` if the operator is a shift operator `<<` or `>>`. | |
544 | fn is_shift(op: AssocOp) -> bool { | |
545 | matches!(op, AssocOp::ShiftLeft | AssocOp::ShiftRight) | |
546 | } | |
547 | ||
94222f64 | 548 | /// Returns `true` if the operator is an arithmetic operator |
f20569fa XL |
549 | /// (i.e., `+`, `-`, `*`, `/`, `%`). |
550 | fn is_arith(op: AssocOp) -> bool { | |
551 | matches!( | |
552 | op, | |
553 | AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide | AssocOp::Modulus | |
554 | ) | |
555 | } | |
556 | ||
557 | /// Returns `true` if the operator `op` needs parenthesis with the operator | |
558 | /// `other` in the direction `dir`. | |
559 | fn needs_paren(op: AssocOp, other: AssocOp, dir: Associativity) -> bool { | |
560 | other.precedence() < op.precedence() | |
561 | || (other.precedence() == op.precedence() | |
562 | && ((op != other && associativity(op) != dir) | |
563 | || (op == other && associativity(op) != Associativity::Both))) | |
564 | || is_shift(op) && is_arith(other) | |
565 | || is_shift(other) && is_arith(op) | |
566 | } | |
567 | ||
a2a8927a | 568 | let lhs_paren = if let Sugg::BinOp(lop, _, _) = *lhs { |
f20569fa XL |
569 | needs_paren(op, lop, Associativity::Left) |
570 | } else { | |
571 | false | |
572 | }; | |
573 | ||
a2a8927a | 574 | let rhs_paren = if let Sugg::BinOp(rop, _, _) = *rhs { |
f20569fa XL |
575 | needs_paren(op, rop, Associativity::Right) |
576 | } else { | |
577 | false | |
578 | }; | |
579 | ||
a2a8927a XL |
580 | let lhs = ParenHelper::new(lhs_paren, lhs).to_string(); |
581 | let rhs = ParenHelper::new(rhs_paren, rhs).to_string(); | |
582 | Sugg::BinOp(op, lhs.into(), rhs.into()) | |
f20569fa XL |
583 | } |
584 | ||
585 | /// Convenience wrapper around `make_assoc` and `AssocOp::from_ast_binop`. | |
586 | pub fn make_binop(op: ast::BinOpKind, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> { | |
587 | make_assoc(AssocOp::from_ast_binop(op), lhs, rhs) | |
588 | } | |
589 | ||
590 | #[derive(PartialEq, Eq, Clone, Copy)] | |
591 | /// Operator associativity. | |
592 | enum Associativity { | |
593 | /// The operator is both left-associative and right-associative. | |
594 | Both, | |
595 | /// The operator is left-associative. | |
596 | Left, | |
597 | /// The operator is not associative. | |
598 | None, | |
599 | /// The operator is right-associative. | |
600 | Right, | |
601 | } | |
602 | ||
603 | /// Returns the associativity/fixity of an operator. The difference with | |
604 | /// `AssocOp::fixity` is that an operator can be both left and right associative | |
605 | /// (such as `+`: `a + b + c == (a + b) + c == a + (b + c)`. | |
606 | /// | |
607 | /// Chained `as` and explicit `:` type coercion never need inner parenthesis so | |
608 | /// they are considered | |
609 | /// associative. | |
610 | #[must_use] | |
611 | fn associativity(op: AssocOp) -> Associativity { | |
612 | use rustc_ast::util::parser::AssocOp::{ | |
613 | Add, As, Assign, AssignOp, BitAnd, BitOr, BitXor, Colon, Divide, DotDot, DotDotEq, Equal, Greater, | |
614 | GreaterEqual, LAnd, LOr, Less, LessEqual, Modulus, Multiply, NotEqual, ShiftLeft, ShiftRight, Subtract, | |
615 | }; | |
616 | ||
617 | match op { | |
618 | Assign | AssignOp(_) => Associativity::Right, | |
619 | Add | BitAnd | BitOr | BitXor | LAnd | LOr | Multiply | As | Colon => Associativity::Both, | |
620 | Divide | Equal | Greater | GreaterEqual | Less | LessEqual | Modulus | NotEqual | ShiftLeft | ShiftRight | |
621 | | Subtract => Associativity::Left, | |
622 | DotDot | DotDotEq => Associativity::None, | |
623 | } | |
624 | } | |
625 | ||
626 | /// Converts a `hir::BinOp` to the corresponding assigning binary operator. | |
627 | fn hirbinop2assignop(op: hir::BinOp) -> AssocOp { | |
628 | use rustc_ast::token::BinOpToken::{And, Caret, Minus, Or, Percent, Plus, Shl, Shr, Slash, Star}; | |
629 | ||
630 | AssocOp::AssignOp(match op.node { | |
631 | hir::BinOpKind::Add => Plus, | |
632 | hir::BinOpKind::BitAnd => And, | |
633 | hir::BinOpKind::BitOr => Or, | |
634 | hir::BinOpKind::BitXor => Caret, | |
635 | hir::BinOpKind::Div => Slash, | |
636 | hir::BinOpKind::Mul => Star, | |
637 | hir::BinOpKind::Rem => Percent, | |
638 | hir::BinOpKind::Shl => Shl, | |
639 | hir::BinOpKind::Shr => Shr, | |
640 | hir::BinOpKind::Sub => Minus, | |
641 | ||
642 | hir::BinOpKind::And | |
643 | | hir::BinOpKind::Eq | |
644 | | hir::BinOpKind::Ge | |
645 | | hir::BinOpKind::Gt | |
646 | | hir::BinOpKind::Le | |
647 | | hir::BinOpKind::Lt | |
648 | | hir::BinOpKind::Ne | |
649 | | hir::BinOpKind::Or => panic!("This operator does not exist"), | |
650 | }) | |
651 | } | |
652 | ||
653 | /// Converts an `ast::BinOp` to the corresponding assigning binary operator. | |
654 | fn astbinop2assignop(op: ast::BinOp) -> AssocOp { | |
655 | use rustc_ast::ast::BinOpKind::{ | |
656 | Add, And, BitAnd, BitOr, BitXor, Div, Eq, Ge, Gt, Le, Lt, Mul, Ne, Or, Rem, Shl, Shr, Sub, | |
657 | }; | |
658 | use rustc_ast::token::BinOpToken; | |
659 | ||
660 | AssocOp::AssignOp(match op.node { | |
661 | Add => BinOpToken::Plus, | |
662 | BitAnd => BinOpToken::And, | |
663 | BitOr => BinOpToken::Or, | |
664 | BitXor => BinOpToken::Caret, | |
665 | Div => BinOpToken::Slash, | |
666 | Mul => BinOpToken::Star, | |
667 | Rem => BinOpToken::Percent, | |
668 | Shl => BinOpToken::Shl, | |
669 | Shr => BinOpToken::Shr, | |
670 | Sub => BinOpToken::Minus, | |
671 | And | Eq | Ge | Gt | Le | Lt | Ne | Or => panic!("This operator does not exist"), | |
672 | }) | |
673 | } | |
674 | ||
675 | /// Returns the indentation before `span` if there are nothing but `[ \t]` | |
676 | /// before it on its line. | |
677 | fn indentation<T: LintContext>(cx: &T, span: Span) -> Option<String> { | |
678 | let lo = cx.sess().source_map().lookup_char_pos(span.lo()); | |
679 | lo.file | |
680 | .get_line(lo.line - 1 /* line numbers in `Loc` are 1-based */) | |
681 | .and_then(|line| { | |
682 | if let Some((pos, _)) = line.char_indices().find(|&(_, c)| c != ' ' && c != '\t') { | |
683 | // We can mix char and byte positions here because we only consider `[ \t]`. | |
684 | if lo.col == CharPos(pos) { | |
685 | Some(line[..pos].into()) | |
686 | } else { | |
687 | None | |
688 | } | |
689 | } else { | |
690 | None | |
691 | } | |
692 | }) | |
693 | } | |
694 | ||
5e7ed085 FG |
695 | /// Convenience extension trait for `Diagnostic`. |
696 | pub trait DiagnosticExt<T: LintContext> { | |
f20569fa XL |
697 | /// Suggests to add an attribute to an item. |
698 | /// | |
699 | /// Correctly handles indentation of the attribute and item. | |
700 | /// | |
701 | /// # Example | |
702 | /// | |
703 | /// ```rust,ignore | |
704 | /// diag.suggest_item_with_attr(cx, item, "#[derive(Default)]"); | |
705 | /// ``` | |
706 | fn suggest_item_with_attr<D: Display + ?Sized>( | |
707 | &mut self, | |
708 | cx: &T, | |
709 | item: Span, | |
710 | msg: &str, | |
711 | attr: &D, | |
712 | applicability: Applicability, | |
713 | ); | |
714 | ||
715 | /// Suggest to add an item before another. | |
716 | /// | |
717 | /// The item should not be indented (except for inner indentation). | |
718 | /// | |
719 | /// # Example | |
720 | /// | |
721 | /// ```rust,ignore | |
722 | /// diag.suggest_prepend_item(cx, item, | |
723 | /// "fn foo() { | |
724 | /// bar(); | |
725 | /// }"); | |
726 | /// ``` | |
727 | fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability); | |
728 | ||
729 | /// Suggest to completely remove an item. | |
730 | /// | |
731 | /// This will remove an item and all following whitespace until the next non-whitespace | |
732 | /// character. This should work correctly if item is on the same indentation level as the | |
733 | /// following item. | |
734 | /// | |
735 | /// # Example | |
736 | /// | |
737 | /// ```rust,ignore | |
738 | /// diag.suggest_remove_item(cx, item, "remove this") | |
739 | /// ``` | |
740 | fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability); | |
741 | } | |
742 | ||
5e7ed085 | 743 | impl<T: LintContext> DiagnosticExt<T> for rustc_errors::Diagnostic { |
f20569fa XL |
744 | fn suggest_item_with_attr<D: Display + ?Sized>( |
745 | &mut self, | |
746 | cx: &T, | |
747 | item: Span, | |
748 | msg: &str, | |
749 | attr: &D, | |
750 | applicability: Applicability, | |
751 | ) { | |
752 | if let Some(indent) = indentation(cx, item) { | |
753 | let span = item.with_hi(item.lo()); | |
754 | ||
2b03887a | 755 | self.span_suggestion(span, msg, format!("{attr}\n{indent}"), applicability); |
f20569fa XL |
756 | } |
757 | } | |
758 | ||
759 | fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability) { | |
760 | if let Some(indent) = indentation(cx, item) { | |
761 | let span = item.with_hi(item.lo()); | |
762 | ||
763 | let mut first = true; | |
764 | let new_item = new_item | |
765 | .lines() | |
766 | .map(|l| { | |
767 | if first { | |
768 | first = false; | |
2b03887a | 769 | format!("{l}\n") |
f20569fa | 770 | } else { |
2b03887a | 771 | format!("{indent}{l}\n") |
f20569fa XL |
772 | } |
773 | }) | |
774 | .collect::<String>(); | |
775 | ||
2b03887a | 776 | self.span_suggestion(span, msg, format!("{new_item}\n{indent}"), applicability); |
f20569fa XL |
777 | } |
778 | } | |
779 | ||
780 | fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability) { | |
781 | let mut remove_span = item; | |
2b03887a | 782 | let fmpos = cx.sess().source_map().lookup_byte_offset(remove_span.hi()); |
f20569fa XL |
783 | |
784 | if let Some(ref src) = fmpos.sf.src { | |
785 | let non_whitespace_offset = src[fmpos.pos.to_usize()..].find(|c| c != ' ' && c != '\t' && c != '\n'); | |
786 | ||
787 | if let Some(non_whitespace_offset) = non_whitespace_offset { | |
788 | remove_span = remove_span | |
17df50a5 | 789 | .with_hi(remove_span.hi() + BytePos(non_whitespace_offset.try_into().expect("offset too large"))); |
f20569fa XL |
790 | } |
791 | } | |
792 | ||
923072b8 | 793 | self.span_suggestion(remove_span, msg, "", applicability); |
f20569fa XL |
794 | } |
795 | } | |
796 | ||
a2a8927a XL |
797 | /// Suggestion results for handling closure |
798 | /// args dereferencing and borrowing | |
799 | pub struct DerefClosure { | |
800 | /// confidence on the built suggestion | |
801 | pub applicability: Applicability, | |
802 | /// gradually built suggestion | |
803 | pub suggestion: String, | |
804 | } | |
805 | ||
806 | /// Build suggestion gradually by handling closure arg specific usages, | |
807 | /// such as explicit deref and borrowing cases. | |
808 | /// Returns `None` if no such use cases have been triggered in closure body | |
809 | /// | |
810 | /// note: this only works on single line immutable closures with exactly one input parameter. | |
487cf647 | 811 | pub fn deref_closure_args(cx: &LateContext<'_>, closure: &hir::Expr<'_>) -> Option<DerefClosure> { |
9ffffee4 FG |
812 | if let hir::ExprKind::Closure(&Closure { |
813 | fn_decl, def_id, body, .. | |
814 | }) = closure.kind | |
815 | { | |
923072b8 | 816 | let closure_body = cx.tcx.hir().body(body); |
a2a8927a XL |
817 | // is closure arg a type annotated double reference (i.e.: `|x: &&i32| ...`) |
818 | // a type annotation is present if param `kind` is different from `TyKind::Infer` | |
9c376795 | 819 | let closure_arg_is_type_annotated_double_ref = if let TyKind::Ref(_, MutTy { ty, .. }) = fn_decl.inputs[0].kind |
a2a8927a | 820 | { |
9c376795 | 821 | matches!(ty.kind, TyKind::Ref(_, MutTy { .. })) |
a2a8927a XL |
822 | } else { |
823 | false | |
824 | }; | |
825 | ||
826 | let mut visitor = DerefDelegate { | |
827 | cx, | |
828 | closure_span: closure.span, | |
829 | closure_arg_is_type_annotated_double_ref, | |
830 | next_pos: closure.span.lo(), | |
831 | suggestion_start: String::new(), | |
5e7ed085 | 832 | applicability: Applicability::MachineApplicable, |
a2a8927a XL |
833 | }; |
834 | ||
2b03887a | 835 | let infcx = cx.tcx.infer_ctxt().build(); |
9ffffee4 | 836 | ExprUseVisitor::new(&mut visitor, &infcx, def_id, cx.param_env, cx.typeck_results()).consume_body(closure_body); |
a2a8927a XL |
837 | |
838 | if !visitor.suggestion_start.is_empty() { | |
839 | return Some(DerefClosure { | |
840 | applicability: visitor.applicability, | |
841 | suggestion: visitor.finish(), | |
842 | }); | |
843 | } | |
844 | } | |
845 | None | |
846 | } | |
847 | ||
848 | /// Visitor struct used for tracking down | |
849 | /// dereferencing and borrowing of closure's args | |
850 | struct DerefDelegate<'a, 'tcx> { | |
851 | /// The late context of the lint | |
852 | cx: &'a LateContext<'tcx>, | |
853 | /// The span of the input closure to adapt | |
854 | closure_span: Span, | |
855 | /// Indicates if the arg of the closure is a type annotated double reference | |
856 | closure_arg_is_type_annotated_double_ref: bool, | |
857 | /// last position of the span to gradually build the suggestion | |
858 | next_pos: BytePos, | |
859 | /// starting part of the gradually built suggestion | |
860 | suggestion_start: String, | |
861 | /// confidence on the built suggestion | |
862 | applicability: Applicability, | |
863 | } | |
864 | ||
5099ac24 | 865 | impl<'tcx> DerefDelegate<'_, 'tcx> { |
a2a8927a XL |
866 | /// build final suggestion: |
867 | /// - create the ending part of suggestion | |
868 | /// - concatenate starting and ending parts | |
869 | /// - potentially remove needless borrowing | |
870 | pub fn finish(&mut self) -> String { | |
871 | let end_span = Span::new(self.next_pos, self.closure_span.hi(), self.closure_span.ctxt(), None); | |
872 | let end_snip = snippet_with_applicability(self.cx, end_span, "..", &mut self.applicability); | |
2b03887a | 873 | let sugg = format!("{}{end_snip}", self.suggestion_start); |
a2a8927a XL |
874 | if self.closure_arg_is_type_annotated_double_ref { |
875 | sugg.replacen('&', "", 1) | |
876 | } else { | |
877 | sugg | |
878 | } | |
879 | } | |
880 | ||
881 | /// indicates whether the function from `parent_expr` takes its args by double reference | |
882 | fn func_takes_arg_by_double_ref(&self, parent_expr: &'tcx hir::Expr<'_>, cmt_hir_id: HirId) -> bool { | |
064997fb | 883 | let ty = match parent_expr.kind { |
f2b60f7d | 884 | ExprKind::MethodCall(_, receiver, call_args, _) => { |
064997fb FG |
885 | if let Some(sig) = self |
886 | .cx | |
887 | .typeck_results() | |
888 | .type_dependent_def_id(parent_expr.hir_id) | |
9ffffee4 | 889 | .map(|did| self.cx.tcx.fn_sig(did).subst_identity().skip_binder()) |
064997fb | 890 | { |
f2b60f7d FG |
891 | std::iter::once(receiver) |
892 | .chain(call_args.iter()) | |
064997fb FG |
893 | .position(|arg| arg.hir_id == cmt_hir_id) |
894 | .map(|i| sig.inputs()[i]) | |
a2a8927a XL |
895 | } else { |
896 | return false; | |
897 | } | |
898 | }, | |
899 | ExprKind::Call(func, call_args) => { | |
064997fb FG |
900 | if let Some(sig) = expr_sig(self.cx, func) { |
901 | call_args | |
902 | .iter() | |
903 | .position(|arg| arg.hir_id == cmt_hir_id) | |
904 | .and_then(|i| sig.input(i)) | |
905 | .map(ty::Binder::skip_binder) | |
906 | } else { | |
907 | return false; | |
908 | } | |
a2a8927a XL |
909 | }, |
910 | _ => return false, | |
911 | }; | |
912 | ||
064997fb | 913 | ty.map_or(false, |ty| matches!(ty.kind(), ty::Ref(_, inner, _) if inner.is_ref())) |
a2a8927a XL |
914 | } |
915 | } | |
916 | ||
917 | impl<'tcx> Delegate<'tcx> for DerefDelegate<'_, 'tcx> { | |
918 | fn consume(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {} | |
919 | ||
a2a8927a XL |
920 | fn borrow(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId, _: ty::BorrowKind) { |
921 | if let PlaceBase::Local(id) = cmt.place.base { | |
922 | let map = self.cx.tcx.hir(); | |
923 | let span = map.span(cmt.hir_id); | |
924 | let start_span = Span::new(self.next_pos, span.lo(), span.ctxt(), None); | |
925 | let mut start_snip = snippet_with_applicability(self.cx, start_span, "..", &mut self.applicability); | |
926 | ||
927 | // identifier referring to the variable currently triggered (i.e.: `fp`) | |
928 | let ident_str = map.name(id).to_string(); | |
929 | // full identifier that includes projection (i.e.: `fp.field`) | |
930 | let ident_str_with_proj = snippet(self.cx, span, "..").to_string(); | |
931 | ||
932 | if cmt.place.projections.is_empty() { | |
933 | // handle item without any projection, that needs an explicit borrowing | |
934 | // i.e.: suggest `&x` instead of `x` | |
9ffffee4 | 935 | let _: fmt::Result = write!(self.suggestion_start, "{start_snip}&{ident_str}"); |
a2a8927a XL |
936 | } else { |
937 | // cases where a parent `Call` or `MethodCall` is using the item | |
938 | // i.e.: suggest `.contains(&x)` for `.find(|x| [1, 2, 3].contains(x)).is_none()` | |
939 | // | |
940 | // Note about method calls: | |
941 | // - compiler automatically dereference references if the target type is a reference (works also for | |
942 | // function call) | |
943 | // - `self` arguments in the case of `x.is_something()` are also automatically (de)referenced, and | |
944 | // no projection should be suggested | |
945 | if let Some(parent_expr) = get_parent_expr_for_hir(self.cx, cmt.hir_id) { | |
946 | match &parent_expr.kind { | |
947 | // given expression is the self argument and will be handled completely by the compiler | |
948 | // i.e.: `|x| x.is_something()` | |
f2b60f7d | 949 | ExprKind::MethodCall(_, self_expr, ..) if self_expr.hir_id == cmt.hir_id => { |
9ffffee4 | 950 | let _: fmt::Result = write!(self.suggestion_start, "{start_snip}{ident_str_with_proj}"); |
a2a8927a XL |
951 | self.next_pos = span.hi(); |
952 | return; | |
953 | }, | |
954 | // item is used in a call | |
955 | // i.e.: `Call`: `|x| please(x)` or `MethodCall`: `|x| [1, 2, 3].contains(x)` | |
f2b60f7d | 956 | ExprKind::Call(_, [call_args @ ..]) | ExprKind::MethodCall(_, _, [call_args @ ..], _) => { |
a2a8927a XL |
957 | let expr = self.cx.tcx.hir().expect_expr(cmt.hir_id); |
958 | let arg_ty_kind = self.cx.typeck_results().expr_ty(expr).kind(); | |
959 | ||
960 | if matches!(arg_ty_kind, ty::Ref(_, _, Mutability::Not)) { | |
961 | // suggest ampersand if call function is taking args by double reference | |
962 | let takes_arg_by_double_ref = | |
963 | self.func_takes_arg_by_double_ref(parent_expr, cmt.hir_id); | |
964 | ||
965 | // compiler will automatically dereference field or index projection, so no need | |
966 | // to suggest ampersand, but full identifier that includes projection is required | |
967 | let has_field_or_index_projection = | |
968 | cmt.place.projections.iter().any(|proj| { | |
969 | matches!(proj.kind, ProjectionKind::Field(..) | ProjectionKind::Index) | |
970 | }); | |
971 | ||
972 | // no need to bind again if the function doesn't take arg by double ref | |
973 | // and if the item is already a double ref | |
974 | let ident_sugg = if !call_args.is_empty() | |
975 | && !takes_arg_by_double_ref | |
976 | && (self.closure_arg_is_type_annotated_double_ref || has_field_or_index_projection) | |
977 | { | |
978 | let ident = if has_field_or_index_projection { | |
979 | ident_str_with_proj | |
980 | } else { | |
981 | ident_str | |
982 | }; | |
2b03887a | 983 | format!("{start_snip}{ident}") |
a2a8927a | 984 | } else { |
2b03887a | 985 | format!("{start_snip}&{ident_str}") |
a2a8927a XL |
986 | }; |
987 | self.suggestion_start.push_str(&ident_sugg); | |
988 | self.next_pos = span.hi(); | |
989 | return; | |
990 | } | |
991 | ||
992 | self.applicability = Applicability::Unspecified; | |
993 | }, | |
994 | _ => (), | |
995 | } | |
996 | } | |
997 | ||
998 | let mut replacement_str = ident_str; | |
999 | let mut projections_handled = false; | |
1000 | cmt.place.projections.iter().enumerate().for_each(|(i, proj)| { | |
1001 | match proj.kind { | |
1002 | // Field projection like `|v| v.foo` | |
1003 | // no adjustment needed here, as field projections are handled by the compiler | |
1004 | ProjectionKind::Field(..) => match cmt.place.ty_before_projection(i).kind() { | |
1005 | ty::Adt(..) | ty::Tuple(_) => { | |
1006 | replacement_str = ident_str_with_proj.clone(); | |
1007 | projections_handled = true; | |
1008 | }, | |
1009 | _ => (), | |
1010 | }, | |
1011 | // Index projection like `|x| foo[x]` | |
1012 | // the index is dropped so we can't get it to build the suggestion, | |
1013 | // so the span is set-up again to get more code, using `span.hi()` (i.e.: `foo[x]`) | |
1014 | // instead of `span.lo()` (i.e.: `foo`) | |
1015 | ProjectionKind::Index => { | |
1016 | let start_span = Span::new(self.next_pos, span.hi(), span.ctxt(), None); | |
1017 | start_snip = snippet_with_applicability(self.cx, start_span, "..", &mut self.applicability); | |
1018 | replacement_str.clear(); | |
1019 | projections_handled = true; | |
1020 | }, | |
1021 | // note: unable to trigger `Subslice` kind in tests | |
1022 | ProjectionKind::Subslice => (), | |
1023 | ProjectionKind::Deref => { | |
1024 | // Explicit derefs are typically handled later on, but | |
1025 | // some items do not need explicit deref, such as array accesses, | |
1026 | // so we mark them as already processed | |
1027 | // i.e.: don't suggest `*sub[1..4].len()` for `|sub| sub[1..4].len() == 3` | |
1028 | if let ty::Ref(_, inner, _) = cmt.place.ty_before_projection(i).kind() { | |
1029 | if matches!(inner.kind(), ty::Ref(_, innermost, _) if innermost.is_array()) { | |
1030 | projections_handled = true; | |
1031 | } | |
1032 | } | |
1033 | }, | |
1034 | } | |
1035 | }); | |
1036 | ||
1037 | // handle `ProjectionKind::Deref` by removing one explicit deref | |
1038 | // if no special case was detected (i.e.: suggest `*x` instead of `**x`) | |
1039 | if !projections_handled { | |
1040 | let last_deref = cmt | |
1041 | .place | |
1042 | .projections | |
1043 | .iter() | |
1044 | .rposition(|proj| proj.kind == ProjectionKind::Deref); | |
1045 | ||
1046 | if let Some(pos) = last_deref { | |
1047 | let mut projections = cmt.place.projections.clone(); | |
1048 | projections.truncate(pos); | |
1049 | ||
1050 | for item in projections { | |
1051 | if item.kind == ProjectionKind::Deref { | |
2b03887a | 1052 | replacement_str = format!("*{replacement_str}"); |
a2a8927a XL |
1053 | } |
1054 | } | |
1055 | } | |
1056 | } | |
1057 | ||
9ffffee4 | 1058 | let _: fmt::Result = write!(self.suggestion_start, "{start_snip}{replacement_str}"); |
a2a8927a XL |
1059 | } |
1060 | self.next_pos = span.hi(); | |
1061 | } | |
1062 | } | |
1063 | ||
1064 | fn mutate(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {} | |
1065 | ||
2b03887a | 1066 | fn fake_read(&mut self, _: &PlaceWithHirId<'tcx>, _: FakeReadCause, _: HirId) {} |
a2a8927a XL |
1067 | } |
1068 | ||
f20569fa XL |
1069 | #[cfg(test)] |
1070 | mod test { | |
1071 | use super::Sugg; | |
cdc7bbd5 XL |
1072 | |
1073 | use rustc_ast::util::parser::AssocOp; | |
f20569fa XL |
1074 | use std::borrow::Cow; |
1075 | ||
1076 | const SUGGESTION: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("function_call()")); | |
1077 | ||
1078 | #[test] | |
1079 | fn make_return_transform_sugg_into_a_return_call() { | |
1080 | assert_eq!("return function_call()", SUGGESTION.make_return().to_string()); | |
1081 | } | |
1082 | ||
1083 | #[test] | |
1084 | fn blockify_transforms_sugg_into_a_block() { | |
1085 | assert_eq!("{ function_call() }", SUGGESTION.blockify().to_string()); | |
1086 | } | |
cdc7bbd5 XL |
1087 | |
1088 | #[test] | |
1089 | fn binop_maybe_par() { | |
a2a8927a | 1090 | let sugg = Sugg::BinOp(AssocOp::Add, "1".into(), "1".into()); |
cdc7bbd5 XL |
1091 | assert_eq!("(1 + 1)", sugg.maybe_par().to_string()); |
1092 | ||
a2a8927a | 1093 | let sugg = Sugg::BinOp(AssocOp::Add, "(1 + 1)".into(), "(1 + 1)".into()); |
cdc7bbd5 XL |
1094 | assert_eq!("((1 + 1) + (1 + 1))", sugg.maybe_par().to_string()); |
1095 | } | |
a2a8927a XL |
1096 | #[test] |
1097 | fn not_op() { | |
1098 | use AssocOp::{Add, Equal, Greater, GreaterEqual, LAnd, LOr, Less, LessEqual, NotEqual}; | |
1099 | ||
1100 | fn test_not(op: AssocOp, correct: &str) { | |
1101 | let sugg = Sugg::BinOp(op, "x".into(), "y".into()); | |
1102 | assert_eq!((!sugg).to_string(), correct); | |
1103 | } | |
1104 | ||
1105 | // Invert the comparison operator. | |
1106 | test_not(Equal, "x != y"); | |
1107 | test_not(NotEqual, "x == y"); | |
1108 | test_not(Less, "x >= y"); | |
1109 | test_not(LessEqual, "x > y"); | |
1110 | test_not(Greater, "x <= y"); | |
1111 | test_not(GreaterEqual, "x < y"); | |
1112 | ||
1113 | // Other operators are inverted like !(..). | |
1114 | test_not(Add, "!(x + y)"); | |
1115 | test_not(LAnd, "!(x && y)"); | |
1116 | test_not(LOr, "!(x || y)"); | |
1117 | } | |
f20569fa | 1118 | } |