]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/sugg.rs
rustup to rustc 1.15.0-dev (3b248a184 2016-12-05)
[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) | Sugg::MaybeParen(ref s) | Sugg::BinOp(_, ref s) => {
33                 s.fmt(f)
34             }
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) => if sugg.starts_with('(') && sugg.ends_with(')') {
172                 Sugg::MaybeParen(sugg)
173             } else {
174                 Sugg::NonParen(format!("({})", sugg).into())
175             },
176             Sugg::BinOp(_, sugg) => Sugg::NonParen(format!("({})", sugg).into()),
177         }
178     }
179 }
180
181 impl<'a, 'b> std::ops::Add<Sugg<'b>> for Sugg<'a> {
182     type Output = Sugg<'static>;
183     fn add(self, rhs: Sugg<'b>) -> Sugg<'static> {
184         make_binop(ast::BinOpKind::Add, &self, &rhs)
185     }
186 }
187
188 impl<'a, 'b> std::ops::Sub<Sugg<'b>> for Sugg<'a> {
189     type Output = Sugg<'static>;
190     fn sub(self, rhs: Sugg<'b>) -> Sugg<'static> {
191         make_binop(ast::BinOpKind::Sub, &self, &rhs)
192     }
193 }
194
195 impl<'a> std::ops::Not for Sugg<'a> {
196     type Output = Sugg<'static>;
197     fn not(self) -> Sugg<'static> {
198         make_unop("!", self)
199     }
200 }
201
202 /// Helper type to display either `foo` or `(foo)`.
203 struct ParenHelper<T> {
204     /// Whether parenthesis are needed.
205     paren: bool,
206     /// The main thing to display.
207     wrapped: T,
208 }
209
210 impl<T> ParenHelper<T> {
211     /// Build a `ParenHelper`.
212     fn new(paren: bool, wrapped: T) -> Self {
213         ParenHelper {
214             paren: paren,
215             wrapped: wrapped,
216         }
217     }
218 }
219
220 impl<T: Display> Display for ParenHelper<T> {
221     fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
222         if self.paren {
223             write!(f, "({})", self.wrapped)
224         } else {
225             self.wrapped.fmt(f)
226         }
227     }
228 }
229
230 /// Build the string for `<op><expr>` adding parenthesis when necessary.
231 ///
232 /// For convenience, the operator is taken as a string because all unary operators have the same
233 /// precedence.
234 pub fn make_unop(op: &str, expr: Sugg) -> Sugg<'static> {
235     Sugg::MaybeParen(format!("{}{}", op, expr.maybe_par()).into())
236 }
237
238 /// Build the string for `<lhs> <op> <rhs>` adding parenthesis when necessary.
239 ///
240 /// Precedence of shift operator relative to other arithmetic operation is often confusing so
241 /// parenthesis will always be added for a mix of these.
242 pub fn make_assoc(op: AssocOp, lhs: &Sugg, rhs: &Sugg) -> Sugg<'static> {
243     /// Whether the operator is a shift operator `<<` or `>>`.
244     fn is_shift(op: &AssocOp) -> bool {
245         matches!(*op, AssocOp::ShiftLeft | AssocOp::ShiftRight)
246     }
247
248     /// Whether the operator is a arithmetic operator (`+`, `-`, `*`, `/`, `%`).
249     fn is_arith(op: &AssocOp) -> bool {
250         matches!(*op, AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide | AssocOp::Modulus)
251     }
252
253     /// Whether the operator `op` needs parenthesis with the operator `other` in the direction
254     /// `dir`.
255     fn needs_paren(op: &AssocOp, other: &AssocOp, dir: Associativity) -> bool {
256         other.precedence() < op.precedence() ||
257             (other.precedence() == op.precedence() &&
258                 ((op != other && associativity(op) != dir) ||
259                  (op == other && associativity(op) != Associativity::Both))) ||
260              is_shift(op) && is_arith(other) ||
261              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 |
280         AssocOp::BitAnd |
281         AssocOp::BitOr |
282         AssocOp::BitXor |
283         AssocOp::Divide |
284         AssocOp::Equal |
285         AssocOp::Greater |
286         AssocOp::GreaterEqual |
287         AssocOp::LAnd |
288         AssocOp::LOr |
289         AssocOp::Less |
290         AssocOp::LessEqual |
291         AssocOp::Modulus |
292         AssocOp::Multiply |
293         AssocOp::NotEqual |
294         AssocOp::ShiftLeft |
295         AssocOp::ShiftRight |
296         AssocOp::Subtract => format!("{} {} {}", lhs, op.to_ast_binop().expect("Those are AST ops").to_string(), rhs),
297         AssocOp::Inplace => format!("in ({}) {}", lhs, rhs),
298         AssocOp::Assign => format!("{} = {}", lhs, rhs),
299         AssocOp::AssignOp(op) => format!("{} {}= {}", lhs, binop_to_string(op), rhs),
300         AssocOp::As => format!("{} as {}", lhs, rhs),
301         AssocOp::DotDot => format!("{}..{}", lhs, rhs),
302         AssocOp::DotDotDot => format!("{}...{}", lhs, rhs),
303         AssocOp::Colon => format!("{}: {}", lhs, rhs),
304     };
305
306     Sugg::BinOp(op, sugg.into())
307 }
308
309 /// Convinience wrapper arround `make_assoc` and `AssocOp::from_ast_binop`.
310 pub fn make_binop(op: ast::BinOpKind, lhs: &Sugg, rhs: &Sugg) -> Sugg<'static> {
311     make_assoc(AssocOp::from_ast_binop(op), lhs, rhs)
312 }
313
314 #[derive(PartialEq, Eq)]
315 /// Operator associativity.
316 enum Associativity {
317     /// The operator is both left-associative and right-associative.
318     Both,
319     /// The operator is left-associative.
320     Left,
321     /// The operator is not associative.
322     None,
323     /// The operator is right-associative.
324     Right,
325 }
326
327 /// Return the associativity/fixity of an operator. The difference with `AssocOp::fixity` is that
328 /// an operator can be both left and right associative (such as `+`:
329 /// `a + b + c == (a + b) + c == a + (b + c)`.
330 ///
331 /// Chained `as` and explicit `:` type coercion never need inner parenthesis so they are considered
332 /// associative.
333 fn associativity(op: &AssocOp) -> Associativity {
334     use syntax::util::parser::AssocOp::*;
335
336     match *op {
337         Inplace | Assign | AssignOp(_) => Associativity::Right,
338         Add | BitAnd | BitOr | BitXor | LAnd | LOr | Multiply |
339         As | Colon => Associativity::Both,
340     Divide | Equal | Greater | GreaterEqual | Less | LessEqual | Modulus | NotEqual | ShiftLeft |
341         ShiftRight | Subtract => Associativity::Left,
342         DotDot | DotDotDot => Associativity::None
343     }
344 }
345
346 /// Convert a `hir::BinOp` to the corresponding assigning binary operator.
347 fn hirbinop2assignop(op: hir::BinOp) -> AssocOp {
348     use rustc::hir::BinOp_::*;
349     use syntax::parse::token::BinOpToken::*;
350
351     AssocOp::AssignOp(match op.node {
352         BiAdd => Plus,
353         BiBitAnd => And,
354         BiBitOr => Or,
355         BiBitXor => Caret,
356         BiDiv => Slash,
357         BiMul => Star,
358         BiRem => Percent,
359         BiShl => Shl,
360         BiShr => Shr,
361         BiSub => Minus,
362         BiAnd | BiEq | BiGe | BiGt | BiLe | BiLt | BiNe | BiOr => panic!("This operator does not exist"),
363     })
364 }
365
366 /// Convert an `ast::BinOp` to the corresponding assigning binary operator.
367 fn astbinop2assignop(op: ast::BinOp) -> AssocOp {
368     use syntax::ast::BinOpKind::*;
369     use syntax::parse::token::BinOpToken;
370
371     AssocOp::AssignOp(match op.node {
372         Add => BinOpToken::Plus,
373         BitAnd => BinOpToken::And,
374         BitOr => BinOpToken::Or,
375         BitXor => BinOpToken::Caret,
376         Div => BinOpToken::Slash,
377         Mul => BinOpToken::Star,
378         Rem => BinOpToken::Percent,
379         Shl => BinOpToken::Shl,
380         Shr => BinOpToken::Shr,
381         Sub => BinOpToken::Minus,
382         And | Eq | Ge | Gt | Le | Lt | Ne | Or => panic!("This operator does not exist"),
383     })
384 }
385
386 /// Return the indentation before `span` if there are nothing but `[ \t]` before it on its line.
387 fn indentation<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Option<String> {
388     let lo = cx.sess().codemap().lookup_char_pos(span.lo);
389     if let Some(line) = lo.file.get_line(lo.line - 1 /* line numbers in `Loc` are 1-based */) {
390         if let Some((pos, _)) = line.char_indices().find(|&(_, c)| c != ' ' && c != '\t') {
391             // we can mix char and byte positions here because we only consider `[ \t]`
392             if lo.col == CharPos(pos) {
393                 Some(line[..pos].into())
394             } else {
395                 None
396             }
397         } else {
398             None
399         }
400     } else {
401         None
402     }
403 }
404
405 /// Convenience extension trait for `DiagnosticBuilder`.
406 pub trait DiagnosticBuilderExt<'a, T: LintContext<'a>> {
407     /// Suggests to add an attribute to an item.
408     ///
409     /// Correctly handles indentation of the attribute and item.
410     ///
411     /// # Example
412     ///
413     /// ```rust
414     /// db.suggest_item_with_attr(cx, item, "#[derive(Default)]");
415     /// ```
416     fn suggest_item_with_attr<D: Display+?Sized>(&mut self, cx: &T, item: Span, msg: &str, attr: &D);
417
418     /// Suggest to add an item before another.
419     ///
420     /// The item should not be indented (expect for inner indentation).
421     ///
422     /// # Example
423     ///
424     /// ```rust
425     /// db.suggest_prepend_item(cx, item,
426     /// "fn foo() {
427     ///     bar();
428     /// }");
429     /// ```
430     fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str);
431 }
432
433 impl<'a, 'b, 'c, T: LintContext<'c>> DiagnosticBuilderExt<'c, T> for rustc_errors::DiagnosticBuilder<'b> {
434     fn suggest_item_with_attr<D: Display+?Sized>(&mut self, cx: &T, item: Span, msg: &str, attr: &D) {
435         if let Some(indent) = indentation(cx, item) {
436             let span = Span {
437                 hi: item.lo,
438                 ..item
439             };
440
441             self.span_suggestion(span, msg, format!("{}\n{}", attr, indent));
442         }
443     }
444
445     fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str) {
446         if let Some(indent) = indentation(cx, item) {
447             let span = Span {
448                 hi: item.lo,
449                 ..item
450             };
451
452             let mut first = true;
453             let new_item = new_item.lines().map(|l| {
454                 if first {
455                     first = false;
456                     format!("{}\n", l)
457                 } else {
458                     format!("{}{}\n", indent, l)
459                 }
460             }).collect::<String>();
461
462             self.span_suggestion(span, msg, format!("{}\n{}", new_item, indent));
463         }
464     }
465 }