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