]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/sugg.rs
Merge pull request #2819 from zayenz/no-op-ref-in-macro
[rust.git] / clippy_lints / src / utils / sugg.rs
1 //! Contains utility functions to generate suggestions.
2 #![deny(missing_docs_in_private_items)]
3 // currently ignores lifetimes and generics
4 #![allow(use_self)]
5
6 use rustc::hir;
7 use rustc::lint::{EarlyContext, LateContext, LintContext};
8 use rustc_errors;
9 use std::borrow::Cow;
10 use std::fmt::Display;
11 use std;
12 use syntax::codemap::{CharPos, Span};
13 use syntax::parse::token;
14 use syntax::print::pprust::token_to_string;
15 use syntax::util::parser::AssocOp;
16 use syntax::ast;
17 use crate::utils::{higher, snippet, snippet_opt};
18 use syntax_pos::{BytePos, Pos};
19
20 /// A helper type to build suggestion correctly handling parenthesis.
21 pub enum Sugg<'a> {
22     /// An expression that never needs parenthesis such as `1337` or `[0; 42]`.
23     NonParen(Cow<'a, str>),
24     /// An expression that does not fit in other variants.
25     MaybeParen(Cow<'a, str>),
26     /// A binary operator expression, including `as`-casts and explicit type
27     /// coercion.
28     BinOp(AssocOp, Cow<'a, str>),
29 }
30
31 /// Literal constant `1`, for convenience.
32 pub const ONE: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("1"));
33
34 impl<'a> Display for Sugg<'a> {
35     fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
36         match *self {
37             Sugg::NonParen(ref s) | Sugg::MaybeParen(ref s) | Sugg::BinOp(_, ref s) => s.fmt(f),
38         }
39     }
40 }
41
42 #[allow(wrong_self_convention)] // ok, because of the function `as_ty` method
43 impl<'a> Sugg<'a> {
44     /// Prepare a suggestion from an expression.
45     pub fn hir_opt(cx: &LateContext, expr: &hir::Expr) -> Option<Self> {
46         snippet_opt(cx, expr.span).map(|snippet| {
47             let snippet = Cow::Owned(snippet);
48             match expr.node {
49                 hir::ExprAddrOf(..) |
50                 hir::ExprBox(..) |
51                 hir::ExprClosure(.., _) |
52                 hir::ExprIf(..) |
53                 hir::ExprUnary(..) |
54                 hir::ExprMatch(..) => Sugg::MaybeParen(snippet),
55                 hir::ExprAgain(..) |
56                 hir::ExprYield(..) |
57                 hir::ExprArray(..) |
58                 hir::ExprBlock(..) |
59                 hir::ExprBreak(..) |
60                 hir::ExprCall(..) |
61                 hir::ExprField(..) |
62                 hir::ExprIndex(..) |
63                 hir::ExprInlineAsm(..) |
64                 hir::ExprLit(..) |
65                 hir::ExprLoop(..) |
66                 hir::ExprMethodCall(..) |
67                 hir::ExprPath(..) |
68                 hir::ExprRepeat(..) |
69                 hir::ExprRet(..) |
70                 hir::ExprStruct(..) |
71                 hir::ExprTup(..) |
72                 hir::ExprWhile(..) => Sugg::NonParen(snippet),
73                 hir::ExprAssign(..) => Sugg::BinOp(AssocOp::Assign, snippet),
74                 hir::ExprAssignOp(op, ..) => Sugg::BinOp(hirbinop2assignop(op), snippet),
75                 hir::ExprBinary(op, ..) => Sugg::BinOp(AssocOp::from_ast_binop(higher::binop(op.node)), snippet),
76                 hir::ExprCast(..) => Sugg::BinOp(AssocOp::As, snippet),
77                 hir::ExprType(..) => Sugg::BinOp(AssocOp::Colon, snippet),
78             }
79         })
80     }
81
82     /// Convenience function around `hir_opt` for suggestions with a default
83     /// text.
84     pub fn hir(cx: &LateContext, expr: &hir::Expr, default: &'a str) -> Self {
85         Self::hir_opt(cx, expr).unwrap_or_else(|| Sugg::NonParen(Cow::Borrowed(default)))
86     }
87
88     /// Prepare a suggestion from an expression.
89     pub fn ast(cx: &EarlyContext, expr: &ast::Expr, default: &'a str) -> Self {
90         use syntax::ast::RangeLimits;
91
92         let snippet = snippet(cx, expr.span, default);
93
94         match expr.node {
95             ast::ExprKind::AddrOf(..) |
96             ast::ExprKind::Box(..) |
97             ast::ExprKind::Closure(..) |
98             ast::ExprKind::If(..) |
99             ast::ExprKind::IfLet(..) |
100             ast::ExprKind::ObsoleteInPlace(..) |
101             ast::ExprKind::Unary(..) |
102             ast::ExprKind::Match(..) => Sugg::MaybeParen(snippet),
103             ast::ExprKind::Block(..) |
104             ast::ExprKind::Break(..) |
105             ast::ExprKind::Call(..) |
106             ast::ExprKind::Catch(..) |
107             ast::ExprKind::Continue(..) |
108             ast::ExprKind::Yield(..) |
109             ast::ExprKind::Field(..) |
110             ast::ExprKind::ForLoop(..) |
111             ast::ExprKind::Index(..) |
112             ast::ExprKind::InlineAsm(..) |
113             ast::ExprKind::Lit(..) |
114             ast::ExprKind::Loop(..) |
115             ast::ExprKind::Mac(..) |
116             ast::ExprKind::MethodCall(..) |
117             ast::ExprKind::Paren(..) |
118             ast::ExprKind::Path(..) |
119             ast::ExprKind::Repeat(..) |
120             ast::ExprKind::Ret(..) |
121             ast::ExprKind::Struct(..) |
122             ast::ExprKind::Try(..) |
123             ast::ExprKind::Tup(..) |
124             ast::ExprKind::Array(..) |
125             ast::ExprKind::While(..) |
126             ast::ExprKind::WhileLet(..) => Sugg::NonParen(snippet),
127             ast::ExprKind::Range(.., RangeLimits::HalfOpen) => Sugg::BinOp(AssocOp::DotDot, snippet),
128             ast::ExprKind::Range(.., RangeLimits::Closed) => Sugg::BinOp(AssocOp::DotDotEq, snippet),
129             ast::ExprKind::Assign(..) => Sugg::BinOp(AssocOp::Assign, snippet),
130             ast::ExprKind::AssignOp(op, ..) => Sugg::BinOp(astbinop2assignop(op), snippet),
131             ast::ExprKind::Binary(op, ..) => Sugg::BinOp(AssocOp::from_ast_binop(op.node), snippet),
132             ast::ExprKind::Cast(..) => Sugg::BinOp(AssocOp::As, snippet),
133             ast::ExprKind::Type(..) => Sugg::BinOp(AssocOp::Colon, snippet),
134         }
135     }
136
137     /// Convenience method to create the `<lhs> && <rhs>` suggestion.
138     pub fn and(self, rhs: &Self) -> Sugg<'static> {
139         make_binop(ast::BinOpKind::And, &self, rhs)
140     }
141
142     /// Convenience method to create the `<lhs> as <rhs>` suggestion.
143     pub fn as_ty<R: Display>(self, rhs: R) -> Sugg<'static> {
144         make_assoc(AssocOp::As, &self, &Sugg::NonParen(rhs.to_string().into()))
145     }
146
147     /// Convenience method to create the `&<expr>` suggestion.
148     pub fn addr(self) -> Sugg<'static> {
149         make_unop("&", self)
150     }
151
152     /// Convenience method to create the `&mut <expr>` suggestion.
153     pub fn mut_addr(self) -> Sugg<'static> {
154         make_unop("&mut ", self)
155     }
156
157     /// Convenience method to create the `*<expr>` suggestion.
158     pub fn deref(self) -> Sugg<'static> {
159         make_unop("*", self)
160     }
161
162     /// Convenience method to create the `&*<expr>` suggestion. Currently this
163     /// is needed because `sugg.deref().addr()` produces an unnecessary set of
164     /// parentheses around the deref.
165     pub fn addr_deref(self) -> Sugg<'static> {
166         make_unop("&*", self)
167     }
168
169     /// Convenience method to create the `&mut *<expr>` suggestion. Currently
170     /// this is needed because `sugg.deref().mut_addr()` produces an unnecessary
171     /// set of parentheses around the deref.
172     pub fn mut_addr_deref(self) -> Sugg<'static> {
173         make_unop("&mut *", self)
174     }
175
176     /// Convenience method to create the `<lhs>..<rhs>` or `<lhs>...<rhs>`
177     /// suggestion.
178     pub fn range(self, end: &Self, limit: ast::RangeLimits) -> Sugg<'static> {
179         match limit {
180             ast::RangeLimits::HalfOpen => make_assoc(AssocOp::DotDot, &self, end),
181             ast::RangeLimits::Closed => make_assoc(AssocOp::DotDotEq, &self, end),
182         }
183     }
184
185     /// Add parenthesis to any expression that might need them. Suitable to the
186     /// `self` argument of
187     /// a method call (eg. to build `bar.foo()` or `(1 + 2).foo()`).
188     pub fn maybe_par(self) -> Self {
189         match self {
190             Sugg::NonParen(..) => self,
191             // (x) and (x).y() both don't need additional parens
192             Sugg::MaybeParen(sugg) => if sugg.starts_with('(') && sugg.ends_with(')') {
193                 Sugg::MaybeParen(sugg)
194             } else {
195                 Sugg::NonParen(format!("({})", sugg).into())
196             },
197             Sugg::BinOp(_, sugg) => Sugg::NonParen(format!("({})", sugg).into()),
198         }
199     }
200 }
201
202 impl<'a, 'b> std::ops::Add<Sugg<'b>> for Sugg<'a> {
203     type Output = Sugg<'static>;
204     fn add(self, rhs: Sugg<'b>) -> Sugg<'static> {
205         make_binop(ast::BinOpKind::Add, &self, &rhs)
206     }
207 }
208
209 impl<'a, 'b> std::ops::Sub<Sugg<'b>> for Sugg<'a> {
210     type Output = Sugg<'static>;
211     fn sub(self, rhs: Sugg<'b>) -> Sugg<'static> {
212         make_binop(ast::BinOpKind::Sub, &self, &rhs)
213     }
214 }
215
216 impl<'a> std::ops::Not for Sugg<'a> {
217     type Output = Sugg<'static>;
218     fn not(self) -> Sugg<'static> {
219         make_unop("!", self)
220     }
221 }
222
223 /// Helper type to display either `foo` or `(foo)`.
224 struct ParenHelper<T> {
225     /// Whether parenthesis are needed.
226     paren: bool,
227     /// The main thing to display.
228     wrapped: T,
229 }
230
231 impl<T> ParenHelper<T> {
232     /// Build a `ParenHelper`.
233     fn new(paren: bool, wrapped: T) -> Self {
234         Self {
235             paren,
236             wrapped,
237         }
238     }
239 }
240
241 impl<T: Display> Display for ParenHelper<T> {
242     fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
243         if self.paren {
244             write!(f, "({})", self.wrapped)
245         } else {
246             self.wrapped.fmt(f)
247         }
248     }
249 }
250
251 /// Build the string for `<op><expr>` adding parenthesis when necessary.
252 ///
253 /// For convenience, the operator is taken as a string because all unary
254 /// operators have the same
255 /// precedence.
256 pub fn make_unop(op: &str, expr: Sugg) -> Sugg<'static> {
257     Sugg::MaybeParen(format!("{}{}", op, expr.maybe_par()).into())
258 }
259
260 /// Build the string for `<lhs> <op> <rhs>` adding parenthesis when necessary.
261 ///
262 /// Precedence of shift operator relative to other arithmetic operation is
263 /// often confusing so
264 /// parenthesis will always be added for a mix of these.
265 pub fn make_assoc(op: AssocOp, lhs: &Sugg, rhs: &Sugg) -> Sugg<'static> {
266     /// Whether the operator is a shift operator `<<` or `>>`.
267     fn is_shift(op: &AssocOp) -> bool {
268         matches!(*op, AssocOp::ShiftLeft | AssocOp::ShiftRight)
269     }
270
271     /// Whether the operator is a arithmetic operator (`+`, `-`, `*`, `/`, `%`).
272     fn is_arith(op: &AssocOp) -> bool {
273         matches!(
274             *op,
275             AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide | AssocOp::Modulus
276         )
277     }
278
279     /// Whether the operator `op` needs parenthesis with the operator `other`
280     /// in the direction
281     /// `dir`.
282     fn needs_paren(op: &AssocOp, other: &AssocOp, dir: Associativity) -> bool {
283         other.precedence() < op.precedence()
284             || (other.precedence() == op.precedence()
285                 && ((op != other && associativity(op) != dir)
286                     || (op == other && associativity(op) != Associativity::Both)))
287             || is_shift(op) && is_arith(other) || is_shift(other) && is_arith(op)
288     }
289
290     let lhs_paren = if let Sugg::BinOp(ref lop, _) = *lhs {
291         needs_paren(&op, lop, Associativity::Left)
292     } else {
293         false
294     };
295
296     let rhs_paren = if let Sugg::BinOp(ref rop, _) = *rhs {
297         needs_paren(&op, rop, Associativity::Right)
298     } else {
299         false
300     };
301
302     let lhs = ParenHelper::new(lhs_paren, lhs);
303     let rhs = ParenHelper::new(rhs_paren, rhs);
304     let sugg = match op {
305         AssocOp::Add |
306         AssocOp::BitAnd |
307         AssocOp::BitOr |
308         AssocOp::BitXor |
309         AssocOp::Divide |
310         AssocOp::Equal |
311         AssocOp::Greater |
312         AssocOp::GreaterEqual |
313         AssocOp::LAnd |
314         AssocOp::LOr |
315         AssocOp::Less |
316         AssocOp::LessEqual |
317         AssocOp::Modulus |
318         AssocOp::Multiply |
319         AssocOp::NotEqual |
320         AssocOp::ShiftLeft |
321         AssocOp::ShiftRight |
322         AssocOp::Subtract => format!("{} {} {}", lhs, op.to_ast_binop().expect("Those are AST ops").to_string(), rhs),
323         AssocOp::Assign => format!("{} = {}", lhs, rhs),
324         AssocOp::ObsoleteInPlace => format!("in ({}) {}", lhs, rhs),
325         AssocOp::AssignOp(op) => format!("{} {}= {}", lhs, token_to_string(&token::BinOp(op)), rhs),
326         AssocOp::As => format!("{} as {}", lhs, rhs),
327         AssocOp::DotDot => format!("{}..{}", lhs, rhs),
328         AssocOp::DotDotEq => format!("{}..={}", lhs, rhs),
329         AssocOp::Colon => format!("{}: {}", lhs, rhs),
330     };
331
332     Sugg::BinOp(op, sugg.into())
333 }
334
335 /// Convinience wrapper arround `make_assoc` and `AssocOp::from_ast_binop`.
336 pub fn make_binop(op: ast::BinOpKind, lhs: &Sugg, rhs: &Sugg) -> Sugg<'static> {
337     make_assoc(AssocOp::from_ast_binop(op), lhs, rhs)
338 }
339
340 #[derive(PartialEq, Eq, Clone, Copy)]
341 /// Operator associativity.
342 enum Associativity {
343     /// The operator is both left-associative and right-associative.
344     Both,
345     /// The operator is left-associative.
346     Left,
347     /// The operator is not associative.
348     None,
349     /// The operator is right-associative.
350     Right,
351 }
352
353 /// Return the associativity/fixity of an operator. The difference with
354 /// `AssocOp::fixity` is that
355 /// an operator can be both left and right associative (such as `+`:
356 /// `a + b + c == (a + b) + c == a + (b + c)`.
357 ///
358 /// Chained `as` and explicit `:` type coercion never need inner parenthesis so
359 /// they are considered
360 /// associative.
361 fn associativity(op: &AssocOp) -> Associativity {
362     use syntax::util::parser::AssocOp::*;
363
364     match *op {
365         ObsoleteInPlace | Assign | AssignOp(_) => Associativity::Right,
366         Add | BitAnd | BitOr | BitXor | LAnd | LOr | Multiply | As | Colon => Associativity::Both,
367         Divide |
368         Equal |
369         Greater |
370         GreaterEqual |
371         Less |
372         LessEqual |
373         Modulus |
374         NotEqual |
375         ShiftLeft |
376         ShiftRight |
377         Subtract => Associativity::Left,
378         DotDot | DotDotEq => Associativity::None,
379     }
380 }
381
382 /// Convert a `hir::BinOp` to the corresponding assigning binary operator.
383 fn hirbinop2assignop(op: hir::BinOp) -> AssocOp {
384     use rustc::hir::BinOp_::*;
385     use syntax::parse::token::BinOpToken::*;
386
387     AssocOp::AssignOp(match op.node {
388         BiAdd => Plus,
389         BiBitAnd => And,
390         BiBitOr => Or,
391         BiBitXor => Caret,
392         BiDiv => Slash,
393         BiMul => Star,
394         BiRem => Percent,
395         BiShl => Shl,
396         BiShr => Shr,
397         BiSub => Minus,
398         BiAnd | BiEq | BiGe | BiGt | BiLe | BiLt | BiNe | BiOr => panic!("This operator does not exist"),
399     })
400 }
401
402 /// Convert an `ast::BinOp` to the corresponding assigning binary operator.
403 fn astbinop2assignop(op: ast::BinOp) -> AssocOp {
404     use syntax::ast::BinOpKind::*;
405     use syntax::parse::token::BinOpToken;
406
407     AssocOp::AssignOp(match op.node {
408         Add => BinOpToken::Plus,
409         BitAnd => BinOpToken::And,
410         BitOr => BinOpToken::Or,
411         BitXor => BinOpToken::Caret,
412         Div => BinOpToken::Slash,
413         Mul => BinOpToken::Star,
414         Rem => BinOpToken::Percent,
415         Shl => BinOpToken::Shl,
416         Shr => BinOpToken::Shr,
417         Sub => BinOpToken::Minus,
418         And | Eq | Ge | Gt | Le | Lt | Ne | Or => panic!("This operator does not exist"),
419     })
420 }
421
422 /// Return the indentation before `span` if there are nothing but `[ \t]`
423 /// before it on its line.
424 fn indentation<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Option<String> {
425     let lo = cx.sess().codemap().lookup_char_pos(span.lo());
426     if let Some(line) = lo.file
427         .get_line(lo.line - 1 /* line numbers in `Loc` are 1-based */)
428     {
429         if let Some((pos, _)) = line.char_indices().find(|&(_, c)| c != ' ' && c != '\t') {
430             // we can mix char and byte positions here because we only consider `[ \t]`
431             if lo.col == CharPos(pos) {
432                 Some(line[..pos].into())
433             } else {
434                 None
435             }
436         } else {
437             None
438         }
439     } else {
440         None
441     }
442 }
443
444 /// Convenience extension trait for `DiagnosticBuilder`.
445 pub trait DiagnosticBuilderExt<'a, T: LintContext<'a>> {
446     /// Suggests to add an attribute to an item.
447     ///
448     /// Correctly handles indentation of the attribute and item.
449     ///
450     /// # Example
451     ///
452     /// ```rust,ignore
453     /// db.suggest_item_with_attr(cx, item, "#[derive(Default)]");
454     /// ```
455     fn suggest_item_with_attr<D: Display + ?Sized>(&mut self, cx: &T, item: Span, msg: &str, attr: &D);
456
457     /// Suggest to add an item before another.
458     ///
459     /// The item should not be indented (expect for inner indentation).
460     ///
461     /// # Example
462     ///
463     /// ```rust,ignore
464     /// db.suggest_prepend_item(cx, item,
465     /// "fn foo() {
466     ///     bar();
467     /// }");
468     /// ```
469     fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str);
470
471     /// Suggest to completely remove an item.
472     ///
473     /// This will remove an item and all following whitespace until the next non-whitespace
474     /// character. This should work correctly if item is on the same indentation level as the
475     /// following item.
476     ///
477     /// # Example
478     ///
479     /// ```rust,ignore
480     /// db.suggest_remove_item(cx, item, "remove this")
481     /// ```
482     fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str);
483 }
484
485 impl<'a, 'b, 'c, T: LintContext<'c>> DiagnosticBuilderExt<'c, T> for rustc_errors::DiagnosticBuilder<'b> {
486     fn suggest_item_with_attr<D: Display + ?Sized>(&mut self, cx: &T, item: Span, msg: &str, attr: &D) {
487         if let Some(indent) = indentation(cx, item) {
488             let span = item.with_hi(item.lo());
489
490             self.span_suggestion(span, msg, format!("{}\n{}", attr, indent));
491         }
492     }
493
494     fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str) {
495         if let Some(indent) = indentation(cx, item) {
496             let span = item.with_hi(item.lo());
497
498             let mut first = true;
499             let new_item = new_item
500                 .lines()
501                 .map(|l| {
502                     if first {
503                         first = false;
504                         format!("{}\n", l)
505                     } else {
506                         format!("{}{}\n", indent, l)
507                     }
508                 })
509                 .collect::<String>();
510
511             self.span_suggestion(span, msg, format!("{}\n{}", new_item, indent));
512         }
513     }
514
515     fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str) {
516         let mut remove_span = item;
517         let hi = cx.sess().codemap().next_point(remove_span).hi();
518         let fmpos = cx.sess().codemap().lookup_byte_offset(hi);
519
520         if let Some(ref src) = fmpos.fm.src {
521             let non_whitespace_offset = src[fmpos.pos.to_usize()..].find(|c| c != ' ' && c != '\t' && c != '\n');
522
523             if let Some(non_whitespace_offset) = non_whitespace_offset {
524                 remove_span = remove_span.with_hi(remove_span.hi() + BytePos(non_whitespace_offset as u32))
525             }
526         }
527
528         self.span_suggestion(remove_span, msg, String::new());
529     }
530 }