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.
10 //! Contains utility functions to generate suggestions.
11 #![deny(clippy::missing_docs_in_private_items)]
13 use crate::rustc::hir;
14 use crate::rustc::lint::{EarlyContext, LateContext, LintContext};
15 use crate::rustc_errors;
16 use crate::rustc_errors::Applicability;
17 use crate::syntax::ast;
18 use crate::syntax::parse::token;
19 use crate::syntax::print::pprust::token_to_string;
20 use crate::syntax::source_map::{CharPos, Span};
21 use crate::syntax::util::parser::AssocOp;
22 use crate::syntax_pos::{BytePos, Pos};
23 use crate::utils::{higher, in_macro, snippet, snippet_opt};
27 use std::convert::TryInto;
28 use std::fmt::Display;
30 /// A helper type to build suggestion correctly handling parenthesis.
32 /// An expression that never needs parenthesis such as `1337` or `[0; 42]`.
33 NonParen(Cow<'a, str>),
34 /// An expression that does not fit in other variants.
35 MaybeParen(Cow<'a, str>),
36 /// A binary operator expression, including `as`-casts and explicit type
38 BinOp(AssocOp, Cow<'a, str>),
41 /// Literal constant `1`, for convenience.
42 pub const ONE: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("1"));
44 impl Display for Sugg<'_> {
45 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
47 Sugg::NonParen(ref s) | Sugg::MaybeParen(ref s) | Sugg::BinOp(_, ref s) => s.fmt(f),
52 #[allow(clippy::wrong_self_convention)] // ok, because of the function `as_ty` method
54 /// Prepare a suggestion from an expression.
55 pub fn hir_opt(cx: &LateContext<'_, '_>, expr: &hir::Expr) -> Option<Self> {
56 snippet_opt(cx, expr.span).map(|snippet| {
57 let snippet = Cow::Owned(snippet);
59 hir::ExprKind::AddrOf(..)
60 | hir::ExprKind::Box(..)
61 | hir::ExprKind::Closure(.., _)
62 | hir::ExprKind::If(..)
63 | hir::ExprKind::Unary(..)
64 | hir::ExprKind::Match(..) => Sugg::MaybeParen(snippet),
65 hir::ExprKind::Continue(..)
66 | hir::ExprKind::Yield(..)
67 | hir::ExprKind::Array(..)
68 | hir::ExprKind::Block(..)
69 | hir::ExprKind::Break(..)
70 | hir::ExprKind::Call(..)
71 | hir::ExprKind::Field(..)
72 | hir::ExprKind::Index(..)
73 | hir::ExprKind::InlineAsm(..)
74 | hir::ExprKind::Lit(..)
75 | hir::ExprKind::Loop(..)
76 | hir::ExprKind::MethodCall(..)
77 | hir::ExprKind::Path(..)
78 | hir::ExprKind::Repeat(..)
79 | hir::ExprKind::Ret(..)
80 | hir::ExprKind::Struct(..)
81 | hir::ExprKind::Tup(..)
82 | hir::ExprKind::While(..) => Sugg::NonParen(snippet),
83 hir::ExprKind::Assign(..) => Sugg::BinOp(AssocOp::Assign, snippet),
84 hir::ExprKind::AssignOp(op, ..) => Sugg::BinOp(hirbinop2assignop(op), snippet),
85 hir::ExprKind::Binary(op, ..) => Sugg::BinOp(AssocOp::from_ast_binop(higher::binop(op.node)), snippet),
86 hir::ExprKind::Cast(..) => Sugg::BinOp(AssocOp::As, snippet),
87 hir::ExprKind::Type(..) => Sugg::BinOp(AssocOp::Colon, snippet),
92 /// Convenience function around `hir_opt` for suggestions with a default
94 pub fn hir(cx: &LateContext<'_, '_>, expr: &hir::Expr, default: &'a str) -> Self {
95 Self::hir_opt(cx, expr).unwrap_or_else(|| Sugg::NonParen(Cow::Borrowed(default)))
98 /// Same as `hir`, but it adapts the applicability level by following rules:
100 /// - Applicability level `Unspecified` will never be changed.
101 /// - If the span is inside a macro, change the applicability level to `MaybeIncorrect`.
102 /// - If the default value is used and the applicability level is `MachineApplicable`, change it
104 /// `HasPlaceholders`
105 pub fn hir_with_applicability(
106 cx: &LateContext<'_, '_>,
109 applicability: &mut Applicability,
111 if *applicability != Applicability::Unspecified && in_macro(expr.span) {
112 *applicability = Applicability::MaybeIncorrect;
114 Self::hir_opt(cx, expr).unwrap_or_else(|| {
115 if *applicability == Applicability::MachineApplicable {
116 *applicability = Applicability::HasPlaceholders;
118 Sugg::NonParen(Cow::Borrowed(default))
122 /// Prepare a suggestion from an expression.
123 pub fn ast(cx: &EarlyContext<'_>, expr: &ast::Expr, default: &'a str) -> Self {
124 use crate::syntax::ast::RangeLimits;
126 let snippet = snippet(cx, expr.span, default);
129 ast::ExprKind::AddrOf(..)
130 | ast::ExprKind::Box(..)
131 | ast::ExprKind::Closure(..)
132 | ast::ExprKind::If(..)
133 | ast::ExprKind::IfLet(..)
134 | ast::ExprKind::ObsoleteInPlace(..)
135 | ast::ExprKind::Unary(..)
136 | ast::ExprKind::Match(..) => Sugg::MaybeParen(snippet),
137 ast::ExprKind::Async(..)
138 | ast::ExprKind::Block(..)
139 | ast::ExprKind::Break(..)
140 | ast::ExprKind::Call(..)
141 | ast::ExprKind::Continue(..)
142 | ast::ExprKind::Yield(..)
143 | ast::ExprKind::Field(..)
144 | ast::ExprKind::ForLoop(..)
145 | ast::ExprKind::Index(..)
146 | ast::ExprKind::InlineAsm(..)
147 | ast::ExprKind::Lit(..)
148 | ast::ExprKind::Loop(..)
149 | ast::ExprKind::Mac(..)
150 | ast::ExprKind::MethodCall(..)
151 | ast::ExprKind::Paren(..)
152 | ast::ExprKind::Path(..)
153 | ast::ExprKind::Repeat(..)
154 | ast::ExprKind::Ret(..)
155 | ast::ExprKind::Struct(..)
156 | ast::ExprKind::Try(..)
157 | ast::ExprKind::TryBlock(..)
158 | ast::ExprKind::Tup(..)
159 | ast::ExprKind::Array(..)
160 | ast::ExprKind::While(..)
161 | ast::ExprKind::WhileLet(..) => Sugg::NonParen(snippet),
162 ast::ExprKind::Range(.., RangeLimits::HalfOpen) => Sugg::BinOp(AssocOp::DotDot, snippet),
163 ast::ExprKind::Range(.., RangeLimits::Closed) => Sugg::BinOp(AssocOp::DotDotEq, snippet),
164 ast::ExprKind::Assign(..) => Sugg::BinOp(AssocOp::Assign, snippet),
165 ast::ExprKind::AssignOp(op, ..) => Sugg::BinOp(astbinop2assignop(op), snippet),
166 ast::ExprKind::Binary(op, ..) => Sugg::BinOp(AssocOp::from_ast_binop(op.node), snippet),
167 ast::ExprKind::Cast(..) => Sugg::BinOp(AssocOp::As, snippet),
168 ast::ExprKind::Type(..) => Sugg::BinOp(AssocOp::Colon, snippet),
172 /// Convenience method to create the `<lhs> && <rhs>` suggestion.
173 pub fn and(self, rhs: &Self) -> Sugg<'static> {
174 make_binop(ast::BinOpKind::And, &self, rhs)
177 /// Convenience method to create the `<lhs> & <rhs>` suggestion.
178 pub fn bit_and(self, rhs: &Self) -> Sugg<'static> {
179 make_binop(ast::BinOpKind::BitAnd, &self, rhs)
182 /// Convenience method to create the `<lhs> as <rhs>` suggestion.
183 pub fn as_ty<R: Display>(self, rhs: R) -> Sugg<'static> {
184 make_assoc(AssocOp::As, &self, &Sugg::NonParen(rhs.to_string().into()))
187 /// Convenience method to create the `&<expr>` suggestion.
188 pub fn addr(self) -> Sugg<'static> {
192 /// Convenience method to create the `&mut <expr>` suggestion.
193 pub fn mut_addr(self) -> Sugg<'static> {
194 make_unop("&mut ", self)
197 /// Convenience method to create the `*<expr>` suggestion.
198 pub fn deref(self) -> Sugg<'static> {
202 /// Convenience method to create the `&*<expr>` suggestion. Currently this
203 /// is needed because `sugg.deref().addr()` produces an unnecessary set of
204 /// parentheses around the deref.
205 pub fn addr_deref(self) -> Sugg<'static> {
206 make_unop("&*", self)
209 /// Convenience method to create the `&mut *<expr>` suggestion. Currently
210 /// this is needed because `sugg.deref().mut_addr()` produces an unnecessary
211 /// set of parentheses around the deref.
212 pub fn mut_addr_deref(self) -> Sugg<'static> {
213 make_unop("&mut *", self)
216 /// Convenience method to create the `<lhs>..<rhs>` or `<lhs>...<rhs>`
219 pub fn range(self, end: &Self, limit: ast::RangeLimits) -> Sugg<'static> {
221 ast::RangeLimits::HalfOpen => make_assoc(AssocOp::DotDot, &self, end),
222 ast::RangeLimits::Closed => make_assoc(AssocOp::DotDotEq, &self, end),
226 /// Add parenthesis to any expression that might need them. Suitable to the
227 /// `self` argument of
228 /// a method call (eg. to build `bar.foo()` or `(1 + 2).foo()`).
229 pub fn maybe_par(self) -> Self {
231 Sugg::NonParen(..) => self,
232 // (x) and (x).y() both don't need additional parens
233 Sugg::MaybeParen(sugg) => {
234 if sugg.starts_with('(') && sugg.ends_with(')') {
235 Sugg::MaybeParen(sugg)
237 Sugg::NonParen(format!("({})", sugg).into())
240 Sugg::BinOp(_, sugg) => Sugg::NonParen(format!("({})", sugg).into()),
245 impl<'a, 'b> std::ops::Add<Sugg<'b>> for Sugg<'a> {
246 type Output = Sugg<'static>;
247 fn add(self, rhs: Sugg<'b>) -> Sugg<'static> {
248 make_binop(ast::BinOpKind::Add, &self, &rhs)
252 impl<'a, 'b> std::ops::Sub<Sugg<'b>> for Sugg<'a> {
253 type Output = Sugg<'static>;
254 fn sub(self, rhs: Sugg<'b>) -> Sugg<'static> {
255 make_binop(ast::BinOpKind::Sub, &self, &rhs)
259 impl<'a> std::ops::Not for Sugg<'a> {
260 type Output = Sugg<'static>;
261 fn not(self) -> Sugg<'static> {
266 /// Helper type to display either `foo` or `(foo)`.
267 struct ParenHelper<T> {
268 /// Whether parenthesis are needed.
270 /// The main thing to display.
274 impl<T> ParenHelper<T> {
275 /// Build a `ParenHelper`.
276 fn new(paren: bool, wrapped: T) -> Self {
277 Self { paren, wrapped }
281 impl<T: Display> Display for ParenHelper<T> {
282 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
284 write!(f, "({})", self.wrapped)
291 /// Build the string for `<op><expr>` adding parenthesis when necessary.
293 /// For convenience, the operator is taken as a string because all unary
294 /// operators have the same
296 pub fn make_unop(op: &str, expr: Sugg<'_>) -> Sugg<'static> {
297 Sugg::MaybeParen(format!("{}{}", op, expr.maybe_par()).into())
300 /// Build the string for `<lhs> <op> <rhs>` adding parenthesis when necessary.
302 /// Precedence of shift operator relative to other arithmetic operation is
303 /// often confusing so
304 /// parenthesis will always be added for a mix of these.
305 pub fn make_assoc(op: AssocOp, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
306 /// Whether the operator is a shift operator `<<` or `>>`.
307 fn is_shift(op: &AssocOp) -> bool {
308 matches!(*op, AssocOp::ShiftLeft | AssocOp::ShiftRight)
311 /// Whether the operator is a arithmetic operator (`+`, `-`, `*`, `/`, `%`).
312 fn is_arith(op: &AssocOp) -> bool {
315 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide | AssocOp::Modulus
319 /// Whether the operator `op` needs parenthesis with the operator `other`
322 fn needs_paren(op: &AssocOp, other: &AssocOp, dir: Associativity) -> bool {
323 other.precedence() < op.precedence()
324 || (other.precedence() == op.precedence()
325 && ((op != other && associativity(op) != dir)
326 || (op == other && associativity(op) != Associativity::Both)))
327 || is_shift(op) && is_arith(other)
328 || is_shift(other) && is_arith(op)
331 let lhs_paren = if let Sugg::BinOp(ref lop, _) = *lhs {
332 needs_paren(&op, lop, Associativity::Left)
337 let rhs_paren = if let Sugg::BinOp(ref rop, _) = *rhs {
338 needs_paren(&op, rop, Associativity::Right)
343 let lhs = ParenHelper::new(lhs_paren, lhs);
344 let rhs = ParenHelper::new(rhs_paren, rhs);
345 let sugg = match op {
353 | AssocOp::GreaterEqual
362 | AssocOp::ShiftRight
363 | AssocOp::Subtract => format!(
366 op.to_ast_binop().expect("Those are AST ops").to_string(),
369 AssocOp::Assign => format!("{} = {}", lhs, rhs),
370 AssocOp::ObsoleteInPlace => format!("in ({}) {}", lhs, rhs),
371 AssocOp::AssignOp(op) => format!("{} {}= {}", lhs, token_to_string(&token::BinOp(op)), rhs),
372 AssocOp::As => format!("{} as {}", lhs, rhs),
373 AssocOp::DotDot => format!("{}..{}", lhs, rhs),
374 AssocOp::DotDotEq => format!("{}..={}", lhs, rhs),
375 AssocOp::Colon => format!("{}: {}", lhs, rhs),
378 Sugg::BinOp(op, sugg.into())
381 /// Convenience wrapper around `make_assoc` and `AssocOp::from_ast_binop`.
382 pub fn make_binop(op: ast::BinOpKind, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
383 make_assoc(AssocOp::from_ast_binop(op), lhs, rhs)
386 #[derive(PartialEq, Eq, Clone, Copy)]
387 /// Operator associativity.
389 /// The operator is both left-associative and right-associative.
391 /// The operator is left-associative.
393 /// The operator is not associative.
395 /// The operator is right-associative.
399 /// Return the associativity/fixity of an operator. The difference with
400 /// `AssocOp::fixity` is that
401 /// an operator can be both left and right associative (such as `+`:
402 /// `a + b + c == (a + b) + c == a + (b + c)`.
404 /// Chained `as` and explicit `:` type coercion never need inner parenthesis so
405 /// they are considered
407 fn associativity(op: &AssocOp) -> Associativity {
408 use crate::syntax::util::parser::AssocOp::*;
411 ObsoleteInPlace | Assign | AssignOp(_) => Associativity::Right,
412 Add | BitAnd | BitOr | BitXor | LAnd | LOr | Multiply | As | Colon => Associativity::Both,
413 Divide | Equal | Greater | GreaterEqual | Less | LessEqual | Modulus | NotEqual | ShiftLeft | ShiftRight
414 | Subtract => Associativity::Left,
415 DotDot | DotDotEq => Associativity::None,
419 /// Convert a `hir::BinOp` to the corresponding assigning binary operator.
420 fn hirbinop2assignop(op: hir::BinOp) -> AssocOp {
421 use crate::syntax::parse::token::BinOpToken::*;
423 AssocOp::AssignOp(match op.node {
424 hir::BinOpKind::Add => Plus,
425 hir::BinOpKind::BitAnd => And,
426 hir::BinOpKind::BitOr => Or,
427 hir::BinOpKind::BitXor => Caret,
428 hir::BinOpKind::Div => Slash,
429 hir::BinOpKind::Mul => Star,
430 hir::BinOpKind::Rem => Percent,
431 hir::BinOpKind::Shl => Shl,
432 hir::BinOpKind::Shr => Shr,
433 hir::BinOpKind::Sub => Minus,
442 | hir::BinOpKind::Or => panic!("This operator does not exist"),
446 /// Convert an `ast::BinOp` to the corresponding assigning binary operator.
447 fn astbinop2assignop(op: ast::BinOp) -> AssocOp {
448 use crate::syntax::ast::BinOpKind::*;
449 use crate::syntax::parse::token::BinOpToken;
451 AssocOp::AssignOp(match op.node {
452 Add => BinOpToken::Plus,
453 BitAnd => BinOpToken::And,
454 BitOr => BinOpToken::Or,
455 BitXor => BinOpToken::Caret,
456 Div => BinOpToken::Slash,
457 Mul => BinOpToken::Star,
458 Rem => BinOpToken::Percent,
459 Shl => BinOpToken::Shl,
460 Shr => BinOpToken::Shr,
461 Sub => BinOpToken::Minus,
462 And | Eq | Ge | Gt | Le | Lt | Ne | Or => panic!("This operator does not exist"),
466 /// Return the indentation before `span` if there are nothing but `[ \t]`
467 /// before it on its line.
468 fn indentation<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Option<String> {
469 let lo = cx.sess().source_map().lookup_char_pos(span.lo());
470 if let Some(line) = lo.file.get_line(lo.line - 1 /* line numbers in `Loc` are 1-based */) {
471 if let Some((pos, _)) = line.char_indices().find(|&(_, c)| c != ' ' && c != '\t') {
472 // we can mix char and byte positions here because we only consider `[ \t]`
473 if lo.col == CharPos(pos) {
474 Some(line[..pos].into())
486 /// Convenience extension trait for `DiagnosticBuilder`.
487 pub trait DiagnosticBuilderExt<'a, T: LintContext<'a>> {
488 /// Suggests to add an attribute to an item.
490 /// Correctly handles indentation of the attribute and item.
495 /// db.suggest_item_with_attr(cx, item, "#[derive(Default)]");
497 fn suggest_item_with_attr<D: Display + ?Sized>(
503 applicability: Applicability,
506 /// Suggest to add an item before another.
508 /// The item should not be indented (expect for inner indentation).
513 /// db.suggest_prepend_item(cx, item,
518 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability);
520 /// Suggest to completely remove an item.
522 /// This will remove an item and all following whitespace until the next non-whitespace
523 /// character. This should work correctly if item is on the same indentation level as the
529 /// db.suggest_remove_item(cx, item, "remove this")
531 fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability);
534 impl<'a, 'b, 'c, T: LintContext<'c>> DiagnosticBuilderExt<'c, T> for rustc_errors::DiagnosticBuilder<'b> {
535 fn suggest_item_with_attr<D: Display + ?Sized>(
541 applicability: Applicability,
543 if let Some(indent) = indentation(cx, item) {
544 let span = item.with_hi(item.lo());
546 self.span_suggestion_with_applicability(span, msg, format!("{}\n{}", attr, indent), applicability);
550 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability) {
551 if let Some(indent) = indentation(cx, item) {
552 let span = item.with_hi(item.lo());
554 let mut first = true;
555 let new_item = new_item
562 format!("{}{}\n", indent, l)
565 .collect::<String>();
567 self.span_suggestion_with_applicability(span, msg, format!("{}\n{}", new_item, indent), applicability);
571 fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability) {
572 let mut remove_span = item;
573 let hi = cx.sess().source_map().next_point(remove_span).hi();
574 let fmpos = cx.sess().source_map().lookup_byte_offset(hi);
576 if let Some(ref src) = fmpos.sf.src {
577 let non_whitespace_offset = src[fmpos.pos.to_usize()..].find(|c| c != ' ' && c != '\t' && c != '\n');
579 if let Some(non_whitespace_offset) = non_whitespace_offset {
580 remove_span = remove_span
581 .with_hi(remove_span.hi() + BytePos(non_whitespace_offset.try_into().expect("offset too large")))
585 self.span_suggestion_with_applicability(remove_span, msg, String::new(), applicability);