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