1 //! Contains utility functions to generate suggestions.
2 #![deny(missing_docs_in_private_items)]
5 use rustc::lint::{EarlyContext, LateContext, LintContext};
10 use syntax::codemap::{CharPos, Span};
11 use syntax::parse::token;
12 use syntax::print::pprust::token_to_string;
13 use syntax::util::parser::AssocOp;
15 use utils::{higher, snippet, snippet_opt};
17 /// A helper type to build suggestion correctly handling parenthesis.
19 /// An expression that never needs parenthesis such as `1337` or `[0; 42]`.
20 NonParen(Cow<'a, str>),
21 /// An expression that does not fit in other variants.
22 MaybeParen(Cow<'a, str>),
23 /// A binary operator expression, including `as`-casts and explicit type
25 BinOp(AssocOp, Cow<'a, str>),
28 /// Literal constant `1`, for convenience.
29 pub const ONE: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("1"));
31 impl<'a> Display for Sugg<'a> {
32 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
34 Sugg::NonParen(ref s) |
35 Sugg::MaybeParen(ref s) |
36 Sugg::BinOp(_, ref s) => s.fmt(f),
41 #[allow(wrong_self_convention)] // ok, because of the function `as_ty` method
43 /// Prepare a suggestion from an expression.
44 pub fn hir_opt(cx: &LateContext, expr: &hir::Expr) -> Option<Sugg<'a>> {
45 snippet_opt(cx, expr.span).map(|snippet| {
46 let snippet = Cow::Owned(snippet);
50 hir::ExprClosure(..) |
53 hir::ExprMatch(..) => Sugg::MaybeParen(snippet),
61 hir::ExprInlineAsm(..) |
64 hir::ExprMethodCall(..) |
70 hir::ExprTupField(..) |
71 hir::ExprWhile(..) => Sugg::NonParen(snippet),
72 hir::ExprAssign(..) => Sugg::BinOp(AssocOp::Assign, snippet),
73 hir::ExprAssignOp(op, ..) => Sugg::BinOp(hirbinop2assignop(op), snippet),
74 hir::ExprBinary(op, ..) => Sugg::BinOp(AssocOp::from_ast_binop(higher::binop(op.node)), snippet),
75 hir::ExprCast(..) => Sugg::BinOp(AssocOp::As, snippet),
76 hir::ExprType(..) => Sugg::BinOp(AssocOp::Colon, snippet),
81 /// Convenience function around `hir_opt` for suggestions with a default
83 pub fn hir(cx: &LateContext, expr: &hir::Expr, default: &'a str) -> Sugg<'a> {
84 Self::hir_opt(cx, expr).unwrap_or_else(|| Sugg::NonParen(Cow::Borrowed(default)))
87 /// Prepare a suggestion from an expression.
88 pub fn ast(cx: &EarlyContext, expr: &ast::Expr, default: &'a str) -> Sugg<'a> {
89 use syntax::ast::RangeLimits;
91 let snippet = snippet(cx, expr.span, default);
94 ast::ExprKind::AddrOf(..) |
95 ast::ExprKind::Box(..) |
96 ast::ExprKind::Closure(..) |
97 ast::ExprKind::If(..) |
98 ast::ExprKind::IfLet(..) |
99 ast::ExprKind::InPlace(..) |
100 ast::ExprKind::Unary(..) |
101 ast::ExprKind::Match(..) => Sugg::MaybeParen(snippet),
102 ast::ExprKind::Block(..) |
103 ast::ExprKind::Break(..) |
104 ast::ExprKind::Call(..) |
105 ast::ExprKind::Catch(..) |
106 ast::ExprKind::Continue(..) |
107 ast::ExprKind::Field(..) |
108 ast::ExprKind::ForLoop(..) |
109 ast::ExprKind::Index(..) |
110 ast::ExprKind::InlineAsm(..) |
111 ast::ExprKind::Lit(..) |
112 ast::ExprKind::Loop(..) |
113 ast::ExprKind::Mac(..) |
114 ast::ExprKind::MethodCall(..) |
115 ast::ExprKind::Paren(..) |
116 ast::ExprKind::Path(..) |
117 ast::ExprKind::Repeat(..) |
118 ast::ExprKind::Ret(..) |
119 ast::ExprKind::Struct(..) |
120 ast::ExprKind::Try(..) |
121 ast::ExprKind::Tup(..) |
122 ast::ExprKind::TupField(..) |
123 ast::ExprKind::Array(..) |
124 ast::ExprKind::While(..) |
125 ast::ExprKind::WhileLet(..) => Sugg::NonParen(snippet),
126 ast::ExprKind::Range(.., RangeLimits::HalfOpen) => Sugg::BinOp(AssocOp::DotDot, snippet),
127 ast::ExprKind::Range(.., RangeLimits::Closed) => Sugg::BinOp(AssocOp::DotDotDot, snippet),
128 ast::ExprKind::Assign(..) => Sugg::BinOp(AssocOp::Assign, snippet),
129 ast::ExprKind::AssignOp(op, ..) => Sugg::BinOp(astbinop2assignop(op), snippet),
130 ast::ExprKind::Binary(op, ..) => Sugg::BinOp(AssocOp::from_ast_binop(op.node), snippet),
131 ast::ExprKind::Cast(..) => Sugg::BinOp(AssocOp::As, snippet),
132 ast::ExprKind::Type(..) => Sugg::BinOp(AssocOp::Colon, snippet),
136 /// Convenience method to create the `<lhs> && <rhs>` suggestion.
137 pub fn and(self, rhs: Self) -> Sugg<'static> {
138 make_binop(ast::BinOpKind::And, &self, &rhs)
141 /// Convenience method to create the `<lhs> as <rhs>` suggestion.
142 pub fn as_ty<R: Display>(self, rhs: R) -> Sugg<'static> {
143 make_assoc(AssocOp::As, &self, &Sugg::NonParen(rhs.to_string().into()))
146 /// Convenience method to create the `&<expr>` suggestion.
147 pub fn addr(self) -> Sugg<'static> {
151 /// Convenience method to create the `&mut <expr>` suggestion.
152 pub fn mut_addr(self) -> Sugg<'static> {
153 make_unop("&mut ", self)
156 /// Convenience method to create the `*<expr>` suggestion.
157 pub fn deref(self) -> Sugg<'static> {
161 /// Convenience method to create the `<lhs>..<rhs>` or `<lhs>...<rhs>`
163 pub fn range(self, end: Self, limit: ast::RangeLimits) -> Sugg<'static> {
165 ast::RangeLimits::HalfOpen => make_assoc(AssocOp::DotDot, &self, &end),
166 ast::RangeLimits::Closed => make_assoc(AssocOp::DotDotDot, &self, &end),
170 /// Add parenthesis to any expression that might need them. Suitable to the
171 /// `self` argument of
172 /// a method call (eg. to build `bar.foo()` or `(1 + 2).foo()`).
173 pub fn maybe_par(self) -> Self {
175 Sugg::NonParen(..) => self,
176 // (x) and (x).y() both don't need additional parens
177 Sugg::MaybeParen(sugg) => {
178 if sugg.starts_with('(') && sugg.ends_with(')') {
179 Sugg::MaybeParen(sugg)
181 Sugg::NonParen(format!("({})", sugg).into())
184 Sugg::BinOp(_, sugg) => Sugg::NonParen(format!("({})", sugg).into()),
189 impl<'a, 'b> std::ops::Add<Sugg<'b>> for Sugg<'a> {
190 type Output = Sugg<'static>;
191 fn add(self, rhs: Sugg<'b>) -> Sugg<'static> {
192 make_binop(ast::BinOpKind::Add, &self, &rhs)
196 impl<'a, 'b> std::ops::Sub<Sugg<'b>> for Sugg<'a> {
197 type Output = Sugg<'static>;
198 fn sub(self, rhs: Sugg<'b>) -> Sugg<'static> {
199 make_binop(ast::BinOpKind::Sub, &self, &rhs)
203 impl<'a> std::ops::Not for Sugg<'a> {
204 type Output = Sugg<'static>;
205 fn not(self) -> Sugg<'static> {
210 /// Helper type to display either `foo` or `(foo)`.
211 struct ParenHelper<T> {
212 /// Whether parenthesis are needed.
214 /// The main thing to display.
218 impl<T> ParenHelper<T> {
219 /// Build a `ParenHelper`.
220 fn new(paren: bool, wrapped: T) -> Self {
228 impl<T: Display> Display for ParenHelper<T> {
229 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
231 write!(f, "({})", self.wrapped)
238 /// Build the string for `<op><expr>` adding parenthesis when necessary.
240 /// For convenience, the operator is taken as a string because all unary
241 /// operators have the same
243 pub fn make_unop(op: &str, expr: Sugg) -> Sugg<'static> {
244 Sugg::MaybeParen(format!("{}{}", op, expr.maybe_par()).into())
247 /// Build the string for `<lhs> <op> <rhs>` adding parenthesis when necessary.
249 /// Precedence of shift operator relative to other arithmetic operation is
250 /// often confusing so
251 /// parenthesis will always be added for a mix of these.
252 pub fn make_assoc(op: AssocOp, lhs: &Sugg, rhs: &Sugg) -> Sugg<'static> {
253 /// Whether the operator is a shift operator `<<` or `>>`.
254 fn is_shift(op: &AssocOp) -> bool {
255 matches!(*op, AssocOp::ShiftLeft | AssocOp::ShiftRight)
258 /// Whether the operator is a arithmetic operator (`+`, `-`, `*`, `/`, `%`).
259 fn is_arith(op: &AssocOp) -> bool {
262 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide | AssocOp::Modulus
266 /// Whether the operator `op` needs parenthesis with the operator `other`
269 fn needs_paren(op: &AssocOp, other: &AssocOp, dir: Associativity) -> bool {
270 other.precedence() < op.precedence() ||
271 (other.precedence() == op.precedence() &&
272 ((op != other && associativity(op) != dir) ||
273 (op == other && associativity(op) != Associativity::Both))) ||
274 is_shift(op) && is_arith(other) || is_shift(other) && is_arith(op)
277 let lhs_paren = if let Sugg::BinOp(ref lop, _) = *lhs {
278 needs_paren(&op, lop, Associativity::Left)
283 let rhs_paren = if let Sugg::BinOp(ref rop, _) = *rhs {
284 needs_paren(&op, rop, Associativity::Right)
289 let lhs = ParenHelper::new(lhs_paren, lhs);
290 let rhs = ParenHelper::new(rhs_paren, rhs);
291 let sugg = match op {
292 AssocOp::Add | AssocOp::BitAnd | AssocOp::BitOr | AssocOp::BitXor | AssocOp::Divide | AssocOp::Equal |
293 AssocOp::Greater | AssocOp::GreaterEqual | AssocOp::LAnd | AssocOp::LOr | AssocOp::Less |
294 AssocOp::LessEqual | AssocOp::Modulus | AssocOp::Multiply | AssocOp::NotEqual | AssocOp::ShiftLeft |
295 AssocOp::ShiftRight | AssocOp::Subtract => {
296 format!("{} {} {}", lhs, op.to_ast_binop().expect("Those are AST ops").to_string(), rhs)
298 AssocOp::Inplace => format!("in ({}) {}", lhs, rhs),
299 AssocOp::Assign => format!("{} = {}", lhs, rhs),
300 AssocOp::AssignOp(op) => format!("{} {}= {}", lhs, token_to_string(&token::BinOp(op)), rhs),
301 AssocOp::As => format!("{} as {}", lhs, rhs),
302 AssocOp::DotDot => format!("{}..{}", lhs, rhs),
303 AssocOp::DotDotDot => format!("{}...{}", lhs, rhs),
304 AssocOp::Colon => format!("{}: {}", lhs, rhs),
307 Sugg::BinOp(op, sugg.into())
310 /// Convinience wrapper arround `make_assoc` and `AssocOp::from_ast_binop`.
311 pub fn make_binop(op: ast::BinOpKind, lhs: &Sugg, rhs: &Sugg) -> Sugg<'static> {
312 make_assoc(AssocOp::from_ast_binop(op), lhs, rhs)
315 #[derive(PartialEq, Eq, Clone, Copy)]
316 /// Operator associativity.
318 /// The operator is both left-associative and right-associative.
320 /// The operator is left-associative.
322 /// The operator is not associative.
324 /// The operator is right-associative.
328 /// Return the associativity/fixity of an operator. The difference with
329 /// `AssocOp::fixity` is that
330 /// an operator can be both left and right associative (such as `+`:
331 /// `a + b + c == (a + b) + c == a + (b + c)`.
333 /// Chained `as` and explicit `:` type coercion never need inner parenthesis so
334 /// they are considered
336 fn associativity(op: &AssocOp) -> Associativity {
337 use syntax::util::parser::AssocOp::*;
340 Inplace | Assign | AssignOp(_) => Associativity::Right,
341 Add | BitAnd | BitOr | BitXor | LAnd | LOr | Multiply | As | Colon => Associativity::Both,
342 Divide | Equal | Greater | GreaterEqual | Less | LessEqual | Modulus | NotEqual | ShiftLeft | ShiftRight |
343 Subtract => Associativity::Left,
344 DotDot | DotDotDot => Associativity::None,
348 /// Convert a `hir::BinOp` to the corresponding assigning binary operator.
349 fn hirbinop2assignop(op: hir::BinOp) -> AssocOp {
350 use rustc::hir::BinOp_::*;
351 use syntax::parse::token::BinOpToken::*;
353 AssocOp::AssignOp(match op.node {
364 BiAnd | BiEq | BiGe | BiGt | BiLe | BiLt | BiNe | BiOr => panic!("This operator does not exist"),
368 /// Convert an `ast::BinOp` to the corresponding assigning binary operator.
369 fn astbinop2assignop(op: ast::BinOp) -> AssocOp {
370 use syntax::ast::BinOpKind::*;
371 use syntax::parse::token::BinOpToken;
373 AssocOp::AssignOp(match op.node {
374 Add => BinOpToken::Plus,
375 BitAnd => BinOpToken::And,
376 BitOr => BinOpToken::Or,
377 BitXor => BinOpToken::Caret,
378 Div => BinOpToken::Slash,
379 Mul => BinOpToken::Star,
380 Rem => BinOpToken::Percent,
381 Shl => BinOpToken::Shl,
382 Shr => BinOpToken::Shr,
383 Sub => BinOpToken::Minus,
384 And | Eq | Ge | Gt | Le | Lt | Ne | Or => panic!("This operator does not exist"),
388 /// Return the indentation before `span` if there are nothing but `[ \t]`
389 /// before it on its line.
390 fn indentation<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Option<String> {
391 let lo = cx.sess().codemap().lookup_char_pos(span.lo);
392 if let Some(line) = lo.file.get_line(
393 lo.line - 1, /* line numbers in `Loc` are 1-based */
396 if let Some((pos, _)) = line.char_indices().find(|&(_, c)| c != ' ' && c != '\t') {
397 // we can mix char and byte positions here because we only consider `[ \t]`
398 if lo.col == CharPos(pos) {
399 Some(line[..pos].into())
411 /// Convenience extension trait for `DiagnosticBuilder`.
412 pub trait DiagnosticBuilderExt<'a, T: LintContext<'a>> {
413 /// Suggests to add an attribute to an item.
415 /// Correctly handles indentation of the attribute and item.
420 /// db.suggest_item_with_attr(cx, item, "#[derive(Default)]");
422 fn suggest_item_with_attr<D: Display + ?Sized>(&mut self, cx: &T, item: Span, msg: &str, attr: &D);
424 /// Suggest to add an item before another.
426 /// The item should not be indented (expect for inner indentation).
431 /// db.suggest_prepend_item(cx, item,
436 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str);
439 impl<'a, 'b, 'c, T: LintContext<'c>> DiagnosticBuilderExt<'c, T> for rustc_errors::DiagnosticBuilder<'b> {
440 fn suggest_item_with_attr<D: Display + ?Sized>(&mut self, cx: &T, item: Span, msg: &str, attr: &D) {
441 if let Some(indent) = indentation(cx, item) {
447 self.span_suggestion(span, msg, format!("{}\n{}", attr, indent));
451 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str) {
452 if let Some(indent) = indentation(cx, item) {
458 let mut first = true;
459 let new_item = new_item
465 format!("{}{}\n", indent, l)
467 .collect::<String>();
469 self.span_suggestion(span, msg, format!("{}\n{}", new_item, indent));