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::utils::{higher, in_macro, snippet, snippet_opt};
16 use rustc::lint::{EarlyContext, LateContext, LintContext};
18 use rustc_errors::Applicability;
21 use std::convert::TryInto;
22 use std::fmt::Display;
24 use syntax::parse::token;
25 use syntax::print::pprust::token_to_string;
26 use syntax::source_map::{CharPos, Span};
27 use syntax::util::parser::AssocOp;
28 use syntax_pos::{BytePos, Pos};
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(..)
83 | hir::ExprKind::Err => 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 /// Same as `hir`, but it adapts the applicability level by following rules:
101 /// - Applicability level `Unspecified` will never be changed.
102 /// - If the span is inside a macro, change the applicability level to `MaybeIncorrect`.
103 /// - If the default value is used and the applicability level is `MachineApplicable`, change it
105 /// `HasPlaceholders`
106 pub fn hir_with_applicability(
107 cx: &LateContext<'_, '_>,
110 applicability: &mut Applicability,
112 if *applicability != Applicability::Unspecified && in_macro(expr.span) {
113 *applicability = Applicability::MaybeIncorrect;
115 Self::hir_opt(cx, expr).unwrap_or_else(|| {
116 if *applicability == Applicability::MachineApplicable {
117 *applicability = Applicability::HasPlaceholders;
119 Sugg::NonParen(Cow::Borrowed(default))
123 /// Prepare a suggestion from an expression.
124 pub fn ast(cx: &EarlyContext<'_>, expr: &ast::Expr, default: &'a str) -> Self {
125 use syntax::ast::RangeLimits;
127 let snippet = snippet(cx, expr.span, default);
130 ast::ExprKind::AddrOf(..)
131 | ast::ExprKind::Box(..)
132 | ast::ExprKind::Closure(..)
133 | ast::ExprKind::If(..)
134 | ast::ExprKind::IfLet(..)
135 | ast::ExprKind::ObsoleteInPlace(..)
136 | ast::ExprKind::Unary(..)
137 | ast::ExprKind::Match(..) => Sugg::MaybeParen(snippet),
138 ast::ExprKind::Async(..)
139 | ast::ExprKind::Block(..)
140 | ast::ExprKind::Break(..)
141 | ast::ExprKind::Call(..)
142 | ast::ExprKind::Continue(..)
143 | ast::ExprKind::Yield(..)
144 | ast::ExprKind::Field(..)
145 | ast::ExprKind::ForLoop(..)
146 | ast::ExprKind::Index(..)
147 | ast::ExprKind::InlineAsm(..)
148 | ast::ExprKind::Lit(..)
149 | ast::ExprKind::Loop(..)
150 | ast::ExprKind::Mac(..)
151 | ast::ExprKind::MethodCall(..)
152 | ast::ExprKind::Paren(..)
153 | ast::ExprKind::Path(..)
154 | ast::ExprKind::Repeat(..)
155 | ast::ExprKind::Ret(..)
156 | ast::ExprKind::Struct(..)
157 | ast::ExprKind::Try(..)
158 | ast::ExprKind::TryBlock(..)
159 | ast::ExprKind::Tup(..)
160 | ast::ExprKind::Array(..)
161 | ast::ExprKind::While(..)
162 | ast::ExprKind::WhileLet(..)
163 | ast::ExprKind::Err => Sugg::NonParen(snippet),
164 ast::ExprKind::Range(.., RangeLimits::HalfOpen) => Sugg::BinOp(AssocOp::DotDot, snippet),
165 ast::ExprKind::Range(.., RangeLimits::Closed) => Sugg::BinOp(AssocOp::DotDotEq, snippet),
166 ast::ExprKind::Assign(..) => Sugg::BinOp(AssocOp::Assign, snippet),
167 ast::ExprKind::AssignOp(op, ..) => Sugg::BinOp(astbinop2assignop(op), snippet),
168 ast::ExprKind::Binary(op, ..) => Sugg::BinOp(AssocOp::from_ast_binop(op.node), snippet),
169 ast::ExprKind::Cast(..) => Sugg::BinOp(AssocOp::As, snippet),
170 ast::ExprKind::Type(..) => Sugg::BinOp(AssocOp::Colon, snippet),
174 /// Convenience method to create the `<lhs> && <rhs>` suggestion.
175 pub fn and(self, rhs: &Self) -> Sugg<'static> {
176 make_binop(ast::BinOpKind::And, &self, rhs)
179 /// Convenience method to create the `<lhs> & <rhs>` suggestion.
180 pub fn bit_and(self, rhs: &Self) -> Sugg<'static> {
181 make_binop(ast::BinOpKind::BitAnd, &self, rhs)
184 /// Convenience method to create the `<lhs> as <rhs>` suggestion.
185 pub fn as_ty<R: Display>(self, rhs: R) -> Sugg<'static> {
186 make_assoc(AssocOp::As, &self, &Sugg::NonParen(rhs.to_string().into()))
189 /// Convenience method to create the `&<expr>` suggestion.
190 pub fn addr(self) -> Sugg<'static> {
194 /// Convenience method to create the `&mut <expr>` suggestion.
195 pub fn mut_addr(self) -> Sugg<'static> {
196 make_unop("&mut ", self)
199 /// Convenience method to create the `*<expr>` suggestion.
200 pub fn deref(self) -> Sugg<'static> {
204 /// Convenience method to create the `&*<expr>` suggestion. Currently this
205 /// is needed because `sugg.deref().addr()` produces an unnecessary set of
206 /// parentheses around the deref.
207 pub fn addr_deref(self) -> Sugg<'static> {
208 make_unop("&*", self)
211 /// Convenience method to create the `&mut *<expr>` suggestion. Currently
212 /// this is needed because `sugg.deref().mut_addr()` produces an unnecessary
213 /// set of parentheses around the deref.
214 pub fn mut_addr_deref(self) -> Sugg<'static> {
215 make_unop("&mut *", self)
218 /// Convenience method to create the `<lhs>..<rhs>` or `<lhs>...<rhs>`
221 pub fn range(self, end: &Self, limit: ast::RangeLimits) -> Sugg<'static> {
223 ast::RangeLimits::HalfOpen => make_assoc(AssocOp::DotDot, &self, end),
224 ast::RangeLimits::Closed => make_assoc(AssocOp::DotDotEq, &self, end),
228 /// Add parenthesis to any expression that might need them. Suitable to the
229 /// `self` argument of
230 /// a method call (eg. to build `bar.foo()` or `(1 + 2).foo()`).
231 pub fn maybe_par(self) -> Self {
233 Sugg::NonParen(..) => self,
234 // (x) and (x).y() both don't need additional parens
235 Sugg::MaybeParen(sugg) => {
236 if sugg.starts_with('(') && sugg.ends_with(')') {
237 Sugg::MaybeParen(sugg)
239 Sugg::NonParen(format!("({})", sugg).into())
242 Sugg::BinOp(_, sugg) => Sugg::NonParen(format!("({})", sugg).into()),
247 impl<'a, 'b> std::ops::Add<Sugg<'b>> for Sugg<'a> {
248 type Output = Sugg<'static>;
249 fn add(self, rhs: Sugg<'b>) -> Sugg<'static> {
250 make_binop(ast::BinOpKind::Add, &self, &rhs)
254 impl<'a, 'b> std::ops::Sub<Sugg<'b>> for Sugg<'a> {
255 type Output = Sugg<'static>;
256 fn sub(self, rhs: Sugg<'b>) -> Sugg<'static> {
257 make_binop(ast::BinOpKind::Sub, &self, &rhs)
261 impl<'a> std::ops::Not for Sugg<'a> {
262 type Output = Sugg<'static>;
263 fn not(self) -> Sugg<'static> {
268 /// Helper type to display either `foo` or `(foo)`.
269 struct ParenHelper<T> {
270 /// Whether parenthesis are needed.
272 /// The main thing to display.
276 impl<T> ParenHelper<T> {
277 /// Build a `ParenHelper`.
278 fn new(paren: bool, wrapped: T) -> Self {
279 Self { paren, wrapped }
283 impl<T: Display> Display for ParenHelper<T> {
284 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
286 write!(f, "({})", self.wrapped)
293 /// Build the string for `<op><expr>` adding parenthesis when necessary.
295 /// For convenience, the operator is taken as a string because all unary
296 /// operators have the same
298 pub fn make_unop(op: &str, expr: Sugg<'_>) -> Sugg<'static> {
299 Sugg::MaybeParen(format!("{}{}", op, expr.maybe_par()).into())
302 /// Build the string for `<lhs> <op> <rhs>` adding parenthesis when necessary.
304 /// Precedence of shift operator relative to other arithmetic operation is
305 /// often confusing so
306 /// parenthesis will always be added for a mix of these.
307 pub fn make_assoc(op: AssocOp, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
308 /// Whether the operator is a shift operator `<<` or `>>`.
309 fn is_shift(op: &AssocOp) -> bool {
310 matches!(*op, AssocOp::ShiftLeft | AssocOp::ShiftRight)
313 /// Whether the operator is a arithmetic operator (`+`, `-`, `*`, `/`, `%`).
314 fn is_arith(op: &AssocOp) -> bool {
317 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide | AssocOp::Modulus
321 /// Whether the operator `op` needs parenthesis with the operator `other`
324 fn needs_paren(op: &AssocOp, other: &AssocOp, dir: Associativity) -> bool {
325 other.precedence() < op.precedence()
326 || (other.precedence() == op.precedence()
327 && ((op != other && associativity(op) != dir)
328 || (op == other && associativity(op) != Associativity::Both)))
329 || is_shift(op) && is_arith(other)
330 || is_shift(other) && is_arith(op)
333 let lhs_paren = if let Sugg::BinOp(ref lop, _) = *lhs {
334 needs_paren(&op, lop, Associativity::Left)
339 let rhs_paren = if let Sugg::BinOp(ref rop, _) = *rhs {
340 needs_paren(&op, rop, Associativity::Right)
345 let lhs = ParenHelper::new(lhs_paren, lhs);
346 let rhs = ParenHelper::new(rhs_paren, rhs);
347 let sugg = match op {
355 | AssocOp::GreaterEqual
364 | AssocOp::ShiftRight
365 | AssocOp::Subtract => format!(
368 op.to_ast_binop().expect("Those are AST ops").to_string(),
371 AssocOp::Assign => format!("{} = {}", lhs, rhs),
372 AssocOp::ObsoleteInPlace => format!("in ({}) {}", lhs, rhs),
373 AssocOp::AssignOp(op) => format!("{} {}= {}", lhs, token_to_string(&token::BinOp(op)), rhs),
374 AssocOp::As => format!("{} as {}", lhs, rhs),
375 AssocOp::DotDot => format!("{}..{}", lhs, rhs),
376 AssocOp::DotDotEq => format!("{}..={}", lhs, rhs),
377 AssocOp::Colon => format!("{}: {}", lhs, rhs),
380 Sugg::BinOp(op, sugg.into())
383 /// Convenience wrapper around `make_assoc` and `AssocOp::from_ast_binop`.
384 pub fn make_binop(op: ast::BinOpKind, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
385 make_assoc(AssocOp::from_ast_binop(op), lhs, rhs)
388 #[derive(PartialEq, Eq, Clone, Copy)]
389 /// Operator associativity.
391 /// The operator is both left-associative and right-associative.
393 /// The operator is left-associative.
395 /// The operator is not associative.
397 /// The operator is right-associative.
401 /// Return the associativity/fixity of an operator. The difference with
402 /// `AssocOp::fixity` is that
403 /// an operator can be both left and right associative (such as `+`:
404 /// `a + b + c == (a + b) + c == a + (b + c)`.
406 /// Chained `as` and explicit `:` type coercion never need inner parenthesis so
407 /// they are considered
409 fn associativity(op: &AssocOp) -> Associativity {
410 use syntax::util::parser::AssocOp::*;
413 ObsoleteInPlace | Assign | AssignOp(_) => Associativity::Right,
414 Add | BitAnd | BitOr | BitXor | LAnd | LOr | Multiply | As | Colon => Associativity::Both,
415 Divide | Equal | Greater | GreaterEqual | Less | LessEqual | Modulus | NotEqual | ShiftLeft | ShiftRight
416 | Subtract => Associativity::Left,
417 DotDot | DotDotEq => Associativity::None,
421 /// Convert a `hir::BinOp` to the corresponding assigning binary operator.
422 fn hirbinop2assignop(op: hir::BinOp) -> AssocOp {
423 use syntax::parse::token::BinOpToken::*;
425 AssocOp::AssignOp(match op.node {
426 hir::BinOpKind::Add => Plus,
427 hir::BinOpKind::BitAnd => And,
428 hir::BinOpKind::BitOr => Or,
429 hir::BinOpKind::BitXor => Caret,
430 hir::BinOpKind::Div => Slash,
431 hir::BinOpKind::Mul => Star,
432 hir::BinOpKind::Rem => Percent,
433 hir::BinOpKind::Shl => Shl,
434 hir::BinOpKind::Shr => Shr,
435 hir::BinOpKind::Sub => Minus,
444 | hir::BinOpKind::Or => panic!("This operator does not exist"),
448 /// Convert an `ast::BinOp` to the corresponding assigning binary operator.
449 fn astbinop2assignop(op: ast::BinOp) -> AssocOp {
450 use syntax::ast::BinOpKind::*;
451 use syntax::parse::token::BinOpToken;
453 AssocOp::AssignOp(match op.node {
454 Add => BinOpToken::Plus,
455 BitAnd => BinOpToken::And,
456 BitOr => BinOpToken::Or,
457 BitXor => BinOpToken::Caret,
458 Div => BinOpToken::Slash,
459 Mul => BinOpToken::Star,
460 Rem => BinOpToken::Percent,
461 Shl => BinOpToken::Shl,
462 Shr => BinOpToken::Shr,
463 Sub => BinOpToken::Minus,
464 And | Eq | Ge | Gt | Le | Lt | Ne | Or => panic!("This operator does not exist"),
468 /// Return the indentation before `span` if there are nothing but `[ \t]`
469 /// before it on its line.
470 fn indentation<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Option<String> {
471 let lo = cx.sess().source_map().lookup_char_pos(span.lo());
472 if let Some(line) = lo.file.get_line(lo.line - 1 /* line numbers in `Loc` are 1-based */) {
473 if let Some((pos, _)) = line.char_indices().find(|&(_, c)| c != ' ' && c != '\t') {
474 // we can mix char and byte positions here because we only consider `[ \t]`
475 if lo.col == CharPos(pos) {
476 Some(line[..pos].into())
488 /// Convenience extension trait for `DiagnosticBuilder`.
489 pub trait DiagnosticBuilderExt<'a, T: LintContext<'a>> {
490 /// Suggests to add an attribute to an item.
492 /// Correctly handles indentation of the attribute and item.
497 /// db.suggest_item_with_attr(cx, item, "#[derive(Default)]");
499 fn suggest_item_with_attr<D: Display + ?Sized>(
505 applicability: Applicability,
508 /// Suggest to add an item before another.
510 /// The item should not be indented (expect for inner indentation).
515 /// db.suggest_prepend_item(cx, item,
520 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability);
522 /// Suggest to completely remove an item.
524 /// This will remove an item and all following whitespace until the next non-whitespace
525 /// character. This should work correctly if item is on the same indentation level as the
531 /// db.suggest_remove_item(cx, item, "remove this")
533 fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability);
536 impl<'a, 'b, 'c, T: LintContext<'c>> DiagnosticBuilderExt<'c, T> for rustc_errors::DiagnosticBuilder<'b> {
537 fn suggest_item_with_attr<D: Display + ?Sized>(
543 applicability: Applicability,
545 if let Some(indent) = indentation(cx, item) {
546 let span = item.with_hi(item.lo());
548 self.span_suggestion_with_applicability(span, msg, format!("{}\n{}", attr, indent), applicability);
552 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str, applicability: Applicability) {
553 if let Some(indent) = indentation(cx, item) {
554 let span = item.with_hi(item.lo());
556 let mut first = true;
557 let new_item = new_item
564 format!("{}{}\n", indent, l)
567 .collect::<String>();
569 self.span_suggestion_with_applicability(span, msg, format!("{}\n{}", new_item, indent), applicability);
573 fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str, applicability: Applicability) {
574 let mut remove_span = item;
575 let hi = cx.sess().source_map().next_point(remove_span).hi();
576 let fmpos = cx.sess().source_map().lookup_byte_offset(hi);
578 if let Some(ref src) = fmpos.sf.src {
579 let non_whitespace_offset = src[fmpos.pos.to_usize()..].find(|c| c != ' ' && c != '\t' && c != '\n');
581 if let Some(non_whitespace_offset) = non_whitespace_offset {
582 remove_span = remove_span
583 .with_hi(remove_span.hi() + BytePos(non_whitespace_offset.try_into().expect("offset too large")))
587 self.span_suggestion_with_applicability(remove_span, msg, String::new(), applicability);