1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
11 //! Contains utility functions to generate suggestions.
12 #![deny(clippy::missing_docs_in_private_items)]
15 use crate::rustc::hir;
16 use crate::rustc::lint::{EarlyContext, LateContext, LintContext};
17 use crate::rustc_errors;
19 use std::convert::TryInto;
20 use std::fmt::Display;
22 use crate::syntax::source_map::{CharPos, Span};
23 use crate::syntax::parse::token;
24 use crate::syntax::print::pprust::token_to_string;
25 use crate::syntax::util::parser::AssocOp;
26 use crate::syntax::ast;
27 use crate::utils::{higher, snippet, snippet_opt};
28 use crate::syntax_pos::{BytePos, Pos};
29 use crate::rustc_errors::Applicability;
31 /// A helper type to build suggestion correctly handling parenthesis.
33 /// An expression that never needs parenthesis such as `1337` or `[0; 42]`.
34 NonParen(Cow<'a, str>),
35 /// An expression that does not fit in other variants.
36 MaybeParen(Cow<'a, str>),
37 /// A binary operator expression, including `as`-casts and explicit type
39 BinOp(AssocOp, Cow<'a, str>),
42 /// Literal constant `1`, for convenience.
43 pub const ONE: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("1"));
45 impl Display for Sugg<'_> {
46 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
48 Sugg::NonParen(ref s) | Sugg::MaybeParen(ref s) | Sugg::BinOp(_, ref s) => s.fmt(f),
53 #[allow(clippy::wrong_self_convention)] // ok, because of the function `as_ty` method
55 /// Prepare a suggestion from an expression.
56 pub fn hir_opt(cx: &LateContext<'_, '_>, expr: &hir::Expr) -> Option<Self> {
57 snippet_opt(cx, expr.span).map(|snippet| {
58 let snippet = Cow::Owned(snippet);
60 hir::ExprKind::AddrOf(..) |
61 hir::ExprKind::Box(..) |
62 hir::ExprKind::Closure(.., _) |
63 hir::ExprKind::If(..) |
64 hir::ExprKind::Unary(..) |
65 hir::ExprKind::Match(..) => Sugg::MaybeParen(snippet),
66 hir::ExprKind::Continue(..) |
67 hir::ExprKind::Yield(..) |
68 hir::ExprKind::Array(..) |
69 hir::ExprKind::Block(..) |
70 hir::ExprKind::Break(..) |
71 hir::ExprKind::Call(..) |
72 hir::ExprKind::Field(..) |
73 hir::ExprKind::Index(..) |
74 hir::ExprKind::InlineAsm(..) |
75 hir::ExprKind::Lit(..) |
76 hir::ExprKind::Loop(..) |
77 hir::ExprKind::MethodCall(..) |
78 hir::ExprKind::Path(..) |
79 hir::ExprKind::Repeat(..) |
80 hir::ExprKind::Ret(..) |
81 hir::ExprKind::Struct(..) |
82 hir::ExprKind::Tup(..) |
83 hir::ExprKind::While(..) => Sugg::NonParen(snippet),
84 hir::ExprKind::Assign(..) => Sugg::BinOp(AssocOp::Assign, snippet),
85 hir::ExprKind::AssignOp(op, ..) => Sugg::BinOp(hirbinop2assignop(op), snippet),
86 hir::ExprKind::Binary(op, ..) => Sugg::BinOp(AssocOp::from_ast_binop(higher::binop(op.node)), snippet),
87 hir::ExprKind::Cast(..) => Sugg::BinOp(AssocOp::As, snippet),
88 hir::ExprKind::Type(..) => Sugg::BinOp(AssocOp::Colon, snippet),
93 /// Convenience function around `hir_opt` for suggestions with a default
95 pub fn hir(cx: &LateContext<'_, '_>, expr: &hir::Expr, default: &'a str) -> Self {
96 Self::hir_opt(cx, expr).unwrap_or_else(|| Sugg::NonParen(Cow::Borrowed(default)))
99 pub fn hir_with_applicability(cx: &LateContext<'_, '_>, expr: &hir::Expr, default: &'a str, applicability: &mut Applicability) -> Self {
100 Self::hir_opt(cx, expr).unwrap_or_else(|| {
101 if *applicability == Applicability::MachineApplicable {
102 *applicability = Applicability::HasPlaceholders;
104 Sugg::NonParen(Cow::Borrowed(default))
108 /// Prepare a suggestion from an expression.
109 pub fn ast(cx: &EarlyContext<'_>, expr: &ast::Expr, default: &'a str) -> Self {
110 use crate::syntax::ast::RangeLimits;
112 let snippet = snippet(cx, expr.span, default);
115 ast::ExprKind::AddrOf(..) |
116 ast::ExprKind::Box(..) |
117 ast::ExprKind::Closure(..) |
118 ast::ExprKind::If(..) |
119 ast::ExprKind::IfLet(..) |
120 ast::ExprKind::ObsoleteInPlace(..) |
121 ast::ExprKind::Unary(..) |
122 ast::ExprKind::Match(..) => Sugg::MaybeParen(snippet),
123 ast::ExprKind::Async(..) |
124 ast::ExprKind::Block(..) |
125 ast::ExprKind::Break(..) |
126 ast::ExprKind::Call(..) |
127 ast::ExprKind::Continue(..) |
128 ast::ExprKind::Yield(..) |
129 ast::ExprKind::Field(..) |
130 ast::ExprKind::ForLoop(..) |
131 ast::ExprKind::Index(..) |
132 ast::ExprKind::InlineAsm(..) |
133 ast::ExprKind::Lit(..) |
134 ast::ExprKind::Loop(..) |
135 ast::ExprKind::Mac(..) |
136 ast::ExprKind::MethodCall(..) |
137 ast::ExprKind::Paren(..) |
138 ast::ExprKind::Path(..) |
139 ast::ExprKind::Repeat(..) |
140 ast::ExprKind::Ret(..) |
141 ast::ExprKind::Struct(..) |
142 ast::ExprKind::Try(..) |
143 ast::ExprKind::TryBlock(..) |
144 ast::ExprKind::Tup(..) |
145 ast::ExprKind::Array(..) |
146 ast::ExprKind::While(..) |
147 ast::ExprKind::WhileLet(..) => Sugg::NonParen(snippet),
148 ast::ExprKind::Range(.., RangeLimits::HalfOpen) => Sugg::BinOp(AssocOp::DotDot, snippet),
149 ast::ExprKind::Range(.., RangeLimits::Closed) => Sugg::BinOp(AssocOp::DotDotEq, snippet),
150 ast::ExprKind::Assign(..) => Sugg::BinOp(AssocOp::Assign, snippet),
151 ast::ExprKind::AssignOp(op, ..) => Sugg::BinOp(astbinop2assignop(op), snippet),
152 ast::ExprKind::Binary(op, ..) => Sugg::BinOp(AssocOp::from_ast_binop(op.node), snippet),
153 ast::ExprKind::Cast(..) => Sugg::BinOp(AssocOp::As, snippet),
154 ast::ExprKind::Type(..) => Sugg::BinOp(AssocOp::Colon, snippet),
158 /// Convenience method to create the `<lhs> && <rhs>` suggestion.
159 pub fn and(self, rhs: &Self) -> Sugg<'static> {
160 make_binop(ast::BinOpKind::And, &self, rhs)
163 /// Convenience method to create the `<lhs> as <rhs>` suggestion.
164 pub fn as_ty<R: Display>(self, rhs: R) -> Sugg<'static> {
165 make_assoc(AssocOp::As, &self, &Sugg::NonParen(rhs.to_string().into()))
168 /// Convenience method to create the `&<expr>` suggestion.
169 pub fn addr(self) -> Sugg<'static> {
173 /// Convenience method to create the `&mut <expr>` suggestion.
174 pub fn mut_addr(self) -> Sugg<'static> {
175 make_unop("&mut ", self)
178 /// Convenience method to create the `*<expr>` suggestion.
179 pub fn deref(self) -> Sugg<'static> {
183 /// Convenience method to create the `&*<expr>` suggestion. Currently this
184 /// is needed because `sugg.deref().addr()` produces an unnecessary set of
185 /// parentheses around the deref.
186 pub fn addr_deref(self) -> Sugg<'static> {
187 make_unop("&*", self)
190 /// Convenience method to create the `&mut *<expr>` suggestion. Currently
191 /// this is needed because `sugg.deref().mut_addr()` produces an unnecessary
192 /// set of parentheses around the deref.
193 pub fn mut_addr_deref(self) -> Sugg<'static> {
194 make_unop("&mut *", self)
197 /// Convenience method to create the `<lhs>..<rhs>` or `<lhs>...<rhs>`
200 pub fn range(self, end: &Self, limit: ast::RangeLimits) -> Sugg<'static> {
202 ast::RangeLimits::HalfOpen => make_assoc(AssocOp::DotDot, &self, end),
203 ast::RangeLimits::Closed => make_assoc(AssocOp::DotDotEq, &self, end),
207 /// Add parenthesis to any expression that might need them. Suitable to the
208 /// `self` argument of
209 /// a method call (eg. to build `bar.foo()` or `(1 + 2).foo()`).
210 pub fn maybe_par(self) -> Self {
212 Sugg::NonParen(..) => self,
213 // (x) and (x).y() both don't need additional parens
214 Sugg::MaybeParen(sugg) => if sugg.starts_with('(') && sugg.ends_with(')') {
215 Sugg::MaybeParen(sugg)
217 Sugg::NonParen(format!("({})", sugg).into())
219 Sugg::BinOp(_, sugg) => Sugg::NonParen(format!("({})", sugg).into()),
224 impl<'a, 'b> std::ops::Add<Sugg<'b>> for Sugg<'a> {
225 type Output = Sugg<'static>;
226 fn add(self, rhs: Sugg<'b>) -> Sugg<'static> {
227 make_binop(ast::BinOpKind::Add, &self, &rhs)
231 impl<'a, 'b> std::ops::Sub<Sugg<'b>> for Sugg<'a> {
232 type Output = Sugg<'static>;
233 fn sub(self, rhs: Sugg<'b>) -> Sugg<'static> {
234 make_binop(ast::BinOpKind::Sub, &self, &rhs)
238 impl<'a> std::ops::Not for Sugg<'a> {
239 type Output = Sugg<'static>;
240 fn not(self) -> Sugg<'static> {
245 /// Helper type to display either `foo` or `(foo)`.
246 struct ParenHelper<T> {
247 /// Whether parenthesis are needed.
249 /// The main thing to display.
253 impl<T> ParenHelper<T> {
254 /// Build a `ParenHelper`.
255 fn new(paren: bool, wrapped: T) -> Self {
263 impl<T: Display> Display for ParenHelper<T> {
264 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
266 write!(f, "({})", self.wrapped)
273 /// Build the string for `<op><expr>` adding parenthesis when necessary.
275 /// For convenience, the operator is taken as a string because all unary
276 /// operators have the same
278 pub fn make_unop(op: &str, expr: Sugg<'_>) -> Sugg<'static> {
279 Sugg::MaybeParen(format!("{}{}", op, expr.maybe_par()).into())
282 /// Build the string for `<lhs> <op> <rhs>` adding parenthesis when necessary.
284 /// Precedence of shift operator relative to other arithmetic operation is
285 /// often confusing so
286 /// parenthesis will always be added for a mix of these.
287 pub fn make_assoc(op: AssocOp, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
288 /// Whether the operator is a shift operator `<<` or `>>`.
289 fn is_shift(op: &AssocOp) -> bool {
290 matches!(*op, AssocOp::ShiftLeft | AssocOp::ShiftRight)
293 /// Whether the operator is a arithmetic operator (`+`, `-`, `*`, `/`, `%`).
294 fn is_arith(op: &AssocOp) -> bool {
297 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide | AssocOp::Modulus
301 /// Whether the operator `op` needs parenthesis with the operator `other`
304 fn needs_paren(op: &AssocOp, other: &AssocOp, dir: Associativity) -> bool {
305 other.precedence() < op.precedence()
306 || (other.precedence() == op.precedence()
307 && ((op != other && associativity(op) != dir)
308 || (op == other && associativity(op) != Associativity::Both)))
309 || is_shift(op) && is_arith(other) || is_shift(other) && is_arith(op)
312 let lhs_paren = if let Sugg::BinOp(ref lop, _) = *lhs {
313 needs_paren(&op, lop, Associativity::Left)
318 let rhs_paren = if let Sugg::BinOp(ref rop, _) = *rhs {
319 needs_paren(&op, rop, Associativity::Right)
324 let lhs = ParenHelper::new(lhs_paren, lhs);
325 let rhs = ParenHelper::new(rhs_paren, rhs);
326 let sugg = match op {
334 AssocOp::GreaterEqual |
343 AssocOp::ShiftRight |
344 AssocOp::Subtract => format!("{} {} {}", lhs, op.to_ast_binop().expect("Those are AST ops").to_string(), rhs),
345 AssocOp::Assign => format!("{} = {}", lhs, rhs),
346 AssocOp::ObsoleteInPlace => format!("in ({}) {}", lhs, rhs),
347 AssocOp::AssignOp(op) => format!("{} {}= {}", lhs, token_to_string(&token::BinOp(op)), rhs),
348 AssocOp::As => format!("{} as {}", lhs, rhs),
349 AssocOp::DotDot => format!("{}..{}", lhs, rhs),
350 AssocOp::DotDotEq => format!("{}..={}", lhs, rhs),
351 AssocOp::Colon => format!("{}: {}", lhs, rhs),
354 Sugg::BinOp(op, sugg.into())
357 /// Convenience wrapper around `make_assoc` and `AssocOp::from_ast_binop`.
358 pub fn make_binop(op: ast::BinOpKind, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
359 make_assoc(AssocOp::from_ast_binop(op), lhs, rhs)
362 #[derive(PartialEq, Eq, Clone, Copy)]
363 /// Operator associativity.
365 /// The operator is both left-associative and right-associative.
367 /// The operator is left-associative.
369 /// The operator is not associative.
371 /// The operator is right-associative.
375 /// Return the associativity/fixity of an operator. The difference with
376 /// `AssocOp::fixity` is that
377 /// an operator can be both left and right associative (such as `+`:
378 /// `a + b + c == (a + b) + c == a + (b + c)`.
380 /// Chained `as` and explicit `:` type coercion never need inner parenthesis so
381 /// they are considered
383 fn associativity(op: &AssocOp) -> Associativity {
384 use crate::syntax::util::parser::AssocOp::*;
387 ObsoleteInPlace | Assign | AssignOp(_) => Associativity::Right,
388 Add | BitAnd | BitOr | BitXor | LAnd | LOr | Multiply | As | Colon => Associativity::Both,
399 Subtract => Associativity::Left,
400 DotDot | DotDotEq => Associativity::None,
404 /// Convert a `hir::BinOp` to the corresponding assigning binary operator.
405 fn hirbinop2assignop(op: hir::BinOp) -> AssocOp {
406 use crate::syntax::parse::token::BinOpToken::*;
408 AssocOp::AssignOp(match op.node {
409 hir::BinOpKind::Add => Plus,
410 hir::BinOpKind::BitAnd => And,
411 hir::BinOpKind::BitOr => Or,
412 hir::BinOpKind::BitXor => Caret,
413 hir::BinOpKind::Div => Slash,
414 hir::BinOpKind::Mul => Star,
415 hir::BinOpKind::Rem => Percent,
416 hir::BinOpKind::Shl => Shl,
417 hir::BinOpKind::Shr => Shr,
418 hir::BinOpKind::Sub => Minus,
420 | hir::BinOpKind::And
428 => panic!("This operator does not exist"),
432 /// Convert an `ast::BinOp` to the corresponding assigning binary operator.
433 fn astbinop2assignop(op: ast::BinOp) -> AssocOp {
434 use crate::syntax::ast::BinOpKind::*;
435 use crate::syntax::parse::token::BinOpToken;
437 AssocOp::AssignOp(match op.node {
438 Add => BinOpToken::Plus,
439 BitAnd => BinOpToken::And,
440 BitOr => BinOpToken::Or,
441 BitXor => BinOpToken::Caret,
442 Div => BinOpToken::Slash,
443 Mul => BinOpToken::Star,
444 Rem => BinOpToken::Percent,
445 Shl => BinOpToken::Shl,
446 Shr => BinOpToken::Shr,
447 Sub => BinOpToken::Minus,
448 And | Eq | Ge | Gt | Le | Lt | Ne | Or => panic!("This operator does not exist"),
452 /// Return the indentation before `span` if there are nothing but `[ \t]`
453 /// before it on its line.
454 fn indentation<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Option<String> {
455 let lo = cx.sess().source_map().lookup_char_pos(span.lo());
456 if let Some(line) = lo.file
457 .get_line(lo.line - 1 /* line numbers in `Loc` are 1-based */)
459 if let Some((pos, _)) = line.char_indices().find(|&(_, c)| c != ' ' && c != '\t') {
460 // we can mix char and byte positions here because we only consider `[ \t]`
461 if lo.col == CharPos(pos) {
462 Some(line[..pos].into())
474 /// Convenience extension trait for `DiagnosticBuilder`.
475 pub trait DiagnosticBuilderExt<'a, T: LintContext<'a>> {
476 /// Suggests to add an attribute to an item.
478 /// Correctly handles indentation of the attribute and item.
483 /// db.suggest_item_with_attr(cx, item, "#[derive(Default)]");
485 fn suggest_item_with_attr<D: Display + ?Sized>(&mut self, cx: &T, item: Span, msg: &str, attr: &D, applicability: Applicability);
487 /// Suggest to add an item before another.
489 /// The item should not be indented (expect for inner indentation).
494 /// db.suggest_prepend_item(cx, item,
499 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability);
501 /// Suggest to completely remove an item.
503 /// This will remove an item and all following whitespace until the next non-whitespace
504 /// character. This should work correctly if item is on the same indentation level as the
510 /// db.suggest_remove_item(cx, item, "remove this")
512 fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability);
515 impl<'a, 'b, 'c, T: LintContext<'c>> DiagnosticBuilderExt<'c, T> for rustc_errors::DiagnosticBuilder<'b> {
516 fn suggest_item_with_attr<D: Display + ?Sized>(&mut self, cx: &T, item: Span, msg: &str, attr: &D, applicability: Applicability) {
517 if let Some(indent) = indentation(cx, item) {
518 let span = item.with_hi(item.lo());
520 self.span_suggestion_with_applicability(
523 format!("{}\n{}", attr, indent),
529 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability) {
530 if let Some(indent) = indentation(cx, item) {
531 let span = item.with_hi(item.lo());
533 let mut first = true;
534 let new_item = new_item
541 format!("{}{}\n", indent, l)
544 .collect::<String>();
546 self.span_suggestion_with_applicability(
549 format!("{}\n{}", new_item, indent),
555 fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability) {
556 let mut remove_span = item;
557 let hi = cx.sess().source_map().next_point(remove_span).hi();
558 let fmpos = cx.sess().source_map().lookup_byte_offset(hi);
560 if let Some(ref src) = fmpos.sf.src {
561 let non_whitespace_offset = src[fmpos.pos.to_usize()..].find(|c| c != ' ' && c != '\t' && c != '\n');
563 if let Some(non_whitespace_offset) = non_whitespace_offset {
564 remove_span = remove_span.with_hi(remove_span.hi() + BytePos(non_whitespace_offset.try_into().expect("offset too large")))
568 self.span_suggestion_with_applicability(