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