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 /// Prepare a suggestion from an expression.
100 pub fn ast(cx: &EarlyContext<'_>, expr: &ast::Expr, default: &'a str) -> Self {
101 use crate::syntax::ast::RangeLimits;
103 let snippet = snippet(cx, expr.span, default);
106 ast::ExprKind::AddrOf(..) |
107 ast::ExprKind::Box(..) |
108 ast::ExprKind::Closure(..) |
109 ast::ExprKind::If(..) |
110 ast::ExprKind::IfLet(..) |
111 ast::ExprKind::ObsoleteInPlace(..) |
112 ast::ExprKind::Unary(..) |
113 ast::ExprKind::Match(..) => Sugg::MaybeParen(snippet),
114 ast::ExprKind::Async(..) |
115 ast::ExprKind::Block(..) |
116 ast::ExprKind::Break(..) |
117 ast::ExprKind::Call(..) |
118 ast::ExprKind::Continue(..) |
119 ast::ExprKind::Yield(..) |
120 ast::ExprKind::Field(..) |
121 ast::ExprKind::ForLoop(..) |
122 ast::ExprKind::Index(..) |
123 ast::ExprKind::InlineAsm(..) |
124 ast::ExprKind::Lit(..) |
125 ast::ExprKind::Loop(..) |
126 ast::ExprKind::Mac(..) |
127 ast::ExprKind::MethodCall(..) |
128 ast::ExprKind::Paren(..) |
129 ast::ExprKind::Path(..) |
130 ast::ExprKind::Repeat(..) |
131 ast::ExprKind::Ret(..) |
132 ast::ExprKind::Struct(..) |
133 ast::ExprKind::Try(..) |
134 ast::ExprKind::TryBlock(..) |
135 ast::ExprKind::Tup(..) |
136 ast::ExprKind::Array(..) |
137 ast::ExprKind::While(..) |
138 ast::ExprKind::WhileLet(..) => Sugg::NonParen(snippet),
139 ast::ExprKind::Range(.., RangeLimits::HalfOpen) => Sugg::BinOp(AssocOp::DotDot, snippet),
140 ast::ExprKind::Range(.., RangeLimits::Closed) => Sugg::BinOp(AssocOp::DotDotEq, snippet),
141 ast::ExprKind::Assign(..) => Sugg::BinOp(AssocOp::Assign, snippet),
142 ast::ExprKind::AssignOp(op, ..) => Sugg::BinOp(astbinop2assignop(op), snippet),
143 ast::ExprKind::Binary(op, ..) => Sugg::BinOp(AssocOp::from_ast_binop(op.node), snippet),
144 ast::ExprKind::Cast(..) => Sugg::BinOp(AssocOp::As, snippet),
145 ast::ExprKind::Type(..) => Sugg::BinOp(AssocOp::Colon, snippet),
149 /// Convenience method to create the `<lhs> && <rhs>` suggestion.
150 pub fn and(self, rhs: &Self) -> Sugg<'static> {
151 make_binop(ast::BinOpKind::And, &self, rhs)
154 /// Convenience method to create the `<lhs> as <rhs>` suggestion.
155 pub fn as_ty<R: Display>(self, rhs: R) -> Sugg<'static> {
156 make_assoc(AssocOp::As, &self, &Sugg::NonParen(rhs.to_string().into()))
159 /// Convenience method to create the `&<expr>` suggestion.
160 pub fn addr(self) -> Sugg<'static> {
164 /// Convenience method to create the `&mut <expr>` suggestion.
165 pub fn mut_addr(self) -> Sugg<'static> {
166 make_unop("&mut ", self)
169 /// Convenience method to create the `*<expr>` suggestion.
170 pub fn deref(self) -> Sugg<'static> {
174 /// Convenience method to create the `&*<expr>` suggestion. Currently this
175 /// is needed because `sugg.deref().addr()` produces an unnecessary set of
176 /// parentheses around the deref.
177 pub fn addr_deref(self) -> Sugg<'static> {
178 make_unop("&*", self)
181 /// Convenience method to create the `&mut *<expr>` suggestion. Currently
182 /// this is needed because `sugg.deref().mut_addr()` produces an unnecessary
183 /// set of parentheses around the deref.
184 pub fn mut_addr_deref(self) -> Sugg<'static> {
185 make_unop("&mut *", self)
188 /// Convenience method to create the `<lhs>..<rhs>` or `<lhs>...<rhs>`
191 pub fn range(self, end: &Self, limit: ast::RangeLimits) -> Sugg<'static> {
193 ast::RangeLimits::HalfOpen => make_assoc(AssocOp::DotDot, &self, end),
194 ast::RangeLimits::Closed => make_assoc(AssocOp::DotDotEq, &self, end),
198 /// Add parenthesis to any expression that might need them. Suitable to the
199 /// `self` argument of
200 /// a method call (eg. to build `bar.foo()` or `(1 + 2).foo()`).
201 pub fn maybe_par(self) -> Self {
203 Sugg::NonParen(..) => self,
204 // (x) and (x).y() both don't need additional parens
205 Sugg::MaybeParen(sugg) => if sugg.starts_with('(') && sugg.ends_with(')') {
206 Sugg::MaybeParen(sugg)
208 Sugg::NonParen(format!("({})", sugg).into())
210 Sugg::BinOp(_, sugg) => Sugg::NonParen(format!("({})", sugg).into()),
215 impl<'a, 'b> std::ops::Add<Sugg<'b>> for Sugg<'a> {
216 type Output = Sugg<'static>;
217 fn add(self, rhs: Sugg<'b>) -> Sugg<'static> {
218 make_binop(ast::BinOpKind::Add, &self, &rhs)
222 impl<'a, 'b> std::ops::Sub<Sugg<'b>> for Sugg<'a> {
223 type Output = Sugg<'static>;
224 fn sub(self, rhs: Sugg<'b>) -> Sugg<'static> {
225 make_binop(ast::BinOpKind::Sub, &self, &rhs)
229 impl<'a> std::ops::Not for Sugg<'a> {
230 type Output = Sugg<'static>;
231 fn not(self) -> Sugg<'static> {
236 /// Helper type to display either `foo` or `(foo)`.
237 struct ParenHelper<T> {
238 /// Whether parenthesis are needed.
240 /// The main thing to display.
244 impl<T> ParenHelper<T> {
245 /// Build a `ParenHelper`.
246 fn new(paren: bool, wrapped: T) -> Self {
254 impl<T: Display> Display for ParenHelper<T> {
255 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
257 write!(f, "({})", self.wrapped)
264 /// Build the string for `<op><expr>` adding parenthesis when necessary.
266 /// For convenience, the operator is taken as a string because all unary
267 /// operators have the same
269 pub fn make_unop(op: &str, expr: Sugg<'_>) -> Sugg<'static> {
270 Sugg::MaybeParen(format!("{}{}", op, expr.maybe_par()).into())
273 /// Build the string for `<lhs> <op> <rhs>` adding parenthesis when necessary.
275 /// Precedence of shift operator relative to other arithmetic operation is
276 /// often confusing so
277 /// parenthesis will always be added for a mix of these.
278 pub fn make_assoc(op: AssocOp, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
279 /// Whether the operator is a shift operator `<<` or `>>`.
280 fn is_shift(op: &AssocOp) -> bool {
281 matches!(*op, AssocOp::ShiftLeft | AssocOp::ShiftRight)
284 /// Whether the operator is a arithmetic operator (`+`, `-`, `*`, `/`, `%`).
285 fn is_arith(op: &AssocOp) -> bool {
288 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide | AssocOp::Modulus
292 /// Whether the operator `op` needs parenthesis with the operator `other`
295 fn needs_paren(op: &AssocOp, other: &AssocOp, dir: Associativity) -> bool {
296 other.precedence() < op.precedence()
297 || (other.precedence() == op.precedence()
298 && ((op != other && associativity(op) != dir)
299 || (op == other && associativity(op) != Associativity::Both)))
300 || is_shift(op) && is_arith(other) || is_shift(other) && is_arith(op)
303 let lhs_paren = if let Sugg::BinOp(ref lop, _) = *lhs {
304 needs_paren(&op, lop, Associativity::Left)
309 let rhs_paren = if let Sugg::BinOp(ref rop, _) = *rhs {
310 needs_paren(&op, rop, Associativity::Right)
315 let lhs = ParenHelper::new(lhs_paren, lhs);
316 let rhs = ParenHelper::new(rhs_paren, rhs);
317 let sugg = match op {
325 AssocOp::GreaterEqual |
334 AssocOp::ShiftRight |
335 AssocOp::Subtract => format!("{} {} {}", lhs, op.to_ast_binop().expect("Those are AST ops").to_string(), rhs),
336 AssocOp::Assign => format!("{} = {}", lhs, rhs),
337 AssocOp::ObsoleteInPlace => format!("in ({}) {}", lhs, rhs),
338 AssocOp::AssignOp(op) => format!("{} {}= {}", lhs, token_to_string(&token::BinOp(op)), rhs),
339 AssocOp::As => format!("{} as {}", lhs, rhs),
340 AssocOp::DotDot => format!("{}..{}", lhs, rhs),
341 AssocOp::DotDotEq => format!("{}..={}", lhs, rhs),
342 AssocOp::Colon => format!("{}: {}", lhs, rhs),
345 Sugg::BinOp(op, sugg.into())
348 /// Convenience wrapper around `make_assoc` and `AssocOp::from_ast_binop`.
349 pub fn make_binop(op: ast::BinOpKind, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
350 make_assoc(AssocOp::from_ast_binop(op), lhs, rhs)
353 #[derive(PartialEq, Eq, Clone, Copy)]
354 /// Operator associativity.
356 /// The operator is both left-associative and right-associative.
358 /// The operator is left-associative.
360 /// The operator is not associative.
362 /// The operator is right-associative.
366 /// Return the associativity/fixity of an operator. The difference with
367 /// `AssocOp::fixity` is that
368 /// an operator can be both left and right associative (such as `+`:
369 /// `a + b + c == (a + b) + c == a + (b + c)`.
371 /// Chained `as` and explicit `:` type coercion never need inner parenthesis so
372 /// they are considered
374 fn associativity(op: &AssocOp) -> Associativity {
375 use crate::syntax::util::parser::AssocOp::*;
378 ObsoleteInPlace | Assign | AssignOp(_) => Associativity::Right,
379 Add | BitAnd | BitOr | BitXor | LAnd | LOr | Multiply | As | Colon => Associativity::Both,
390 Subtract => Associativity::Left,
391 DotDot | DotDotEq => Associativity::None,
395 /// Convert a `hir::BinOp` to the corresponding assigning binary operator.
396 fn hirbinop2assignop(op: hir::BinOp) -> AssocOp {
397 use crate::syntax::parse::token::BinOpToken::*;
399 AssocOp::AssignOp(match op.node {
400 hir::BinOpKind::Add => Plus,
401 hir::BinOpKind::BitAnd => And,
402 hir::BinOpKind::BitOr => Or,
403 hir::BinOpKind::BitXor => Caret,
404 hir::BinOpKind::Div => Slash,
405 hir::BinOpKind::Mul => Star,
406 hir::BinOpKind::Rem => Percent,
407 hir::BinOpKind::Shl => Shl,
408 hir::BinOpKind::Shr => Shr,
409 hir::BinOpKind::Sub => Minus,
411 | hir::BinOpKind::And
419 => panic!("This operator does not exist"),
423 /// Convert an `ast::BinOp` to the corresponding assigning binary operator.
424 fn astbinop2assignop(op: ast::BinOp) -> AssocOp {
425 use crate::syntax::ast::BinOpKind::*;
426 use crate::syntax::parse::token::BinOpToken;
428 AssocOp::AssignOp(match op.node {
429 Add => BinOpToken::Plus,
430 BitAnd => BinOpToken::And,
431 BitOr => BinOpToken::Or,
432 BitXor => BinOpToken::Caret,
433 Div => BinOpToken::Slash,
434 Mul => BinOpToken::Star,
435 Rem => BinOpToken::Percent,
436 Shl => BinOpToken::Shl,
437 Shr => BinOpToken::Shr,
438 Sub => BinOpToken::Minus,
439 And | Eq | Ge | Gt | Le | Lt | Ne | Or => panic!("This operator does not exist"),
443 /// Return the indentation before `span` if there are nothing but `[ \t]`
444 /// before it on its line.
445 fn indentation<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Option<String> {
446 let lo = cx.sess().source_map().lookup_char_pos(span.lo());
447 if let Some(line) = lo.file
448 .get_line(lo.line - 1 /* line numbers in `Loc` are 1-based */)
450 if let Some((pos, _)) = line.char_indices().find(|&(_, c)| c != ' ' && c != '\t') {
451 // we can mix char and byte positions here because we only consider `[ \t]`
452 if lo.col == CharPos(pos) {
453 Some(line[..pos].into())
465 /// Convenience extension trait for `DiagnosticBuilder`.
466 pub trait DiagnosticBuilderExt<'a, T: LintContext<'a>> {
467 /// Suggests to add an attribute to an item.
469 /// Correctly handles indentation of the attribute and item.
474 /// db.suggest_item_with_attr(cx, item, "#[derive(Default)]");
476 fn suggest_item_with_attr<D: Display + ?Sized>(&mut self, cx: &T, item: Span, msg: &str, attr: &D, applicability: Applicability);
478 /// Suggest to add an item before another.
480 /// The item should not be indented (expect for inner indentation).
485 /// db.suggest_prepend_item(cx, item,
490 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability);
492 /// Suggest to completely remove an item.
494 /// This will remove an item and all following whitespace until the next non-whitespace
495 /// character. This should work correctly if item is on the same indentation level as the
501 /// db.suggest_remove_item(cx, item, "remove this")
503 fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability);
506 impl<'a, 'b, 'c, T: LintContext<'c>> DiagnosticBuilderExt<'c, T> for rustc_errors::DiagnosticBuilder<'b> {
507 fn suggest_item_with_attr<D: Display + ?Sized>(&mut self, cx: &T, item: Span, msg: &str, attr: &D, applicability: Applicability) {
508 if let Some(indent) = indentation(cx, item) {
509 let span = item.with_hi(item.lo());
511 self.span_suggestion_with_applicability(
514 format!("{}\n{}", attr, indent),
520 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability) {
521 if let Some(indent) = indentation(cx, item) {
522 let span = item.with_hi(item.lo());
524 let mut first = true;
525 let new_item = new_item
532 format!("{}{}\n", indent, l)
535 .collect::<String>();
537 self.span_suggestion_with_applicability(
540 format!("{}\n{}", new_item, indent),
546 fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability) {
547 let mut remove_span = item;
548 let hi = cx.sess().source_map().next_point(remove_span).hi();
549 let fmpos = cx.sess().source_map().lookup_byte_offset(hi);
551 if let Some(ref src) = fmpos.fm.src {
552 let non_whitespace_offset = src[fmpos.pos.to_usize()..].find(|c| c != ' ' && c != '\t' && c != '\n');
554 if let Some(non_whitespace_offset) = non_whitespace_offset {
555 remove_span = remove_span.with_hi(remove_span.hi() + BytePos(non_whitespace_offset.try_into().expect("offset too large")))
559 self.span_suggestion_with_applicability(