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