]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/sugg.rs
Merge branch 'master' into move_links
[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
24     /// coercion.
25     BinOp(AssocOp, Cow<'a, str>),
26 }
27
28 /// Literal constant `1`, for convenience.
29 pub const ONE: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("1"));
30
31 impl<'a> Display for Sugg<'a> {
32     fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
33         match *self {
34             Sugg::NonParen(ref s) |
35             Sugg::MaybeParen(ref s) |
36             Sugg::BinOp(_, ref s) => s.fmt(f),
37         }
38     }
39 }
40
41 #[allow(wrong_self_convention)] // ok, because of the function `as_ty` method
42 impl<'a> Sugg<'a> {
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);
47             match expr.node {
48                 hir::ExprAddrOf(..) |
49                 hir::ExprBox(..) |
50                 hir::ExprClosure(..) |
51                 hir::ExprIf(..) |
52                 hir::ExprUnary(..) |
53                 hir::ExprMatch(..) => Sugg::MaybeParen(snippet),
54                 hir::ExprAgain(..) |
55                 hir::ExprArray(..) |
56                 hir::ExprBlock(..) |
57                 hir::ExprBreak(..) |
58                 hir::ExprCall(..) |
59                 hir::ExprField(..) |
60                 hir::ExprIndex(..) |
61                 hir::ExprInlineAsm(..) |
62                 hir::ExprLit(..) |
63                 hir::ExprLoop(..) |
64                 hir::ExprMethodCall(..) |
65                 hir::ExprPath(..) |
66                 hir::ExprRepeat(..) |
67                 hir::ExprRet(..) |
68                 hir::ExprStruct(..) |
69                 hir::ExprTup(..) |
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),
77             }
78         })
79     }
80
81     /// Convenience function around `hir_opt` for suggestions with a default
82     /// text.
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)))
85     }
86
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;
90
91         let snippet = snippet(cx, expr.span, default);
92
93         match expr.node {
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),
133         }
134     }
135
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)
139     }
140
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()))
144     }
145
146     /// Convenience method to create the `&<expr>` suggestion.
147     pub fn addr(self) -> Sugg<'static> {
148         make_unop("&", self)
149     }
150
151     /// Convenience method to create the `&mut <expr>` suggestion.
152     pub fn mut_addr(self) -> Sugg<'static> {
153         make_unop("&mut ", self)
154     }
155
156     /// Convenience method to create the `*<expr>` suggestion.
157     pub fn deref(self) -> Sugg<'static> {
158         make_unop("*", self)
159     }
160
161     /// Convenience method to create the `<lhs>..<rhs>` or `<lhs>...<rhs>`
162     /// suggestion.
163     pub fn range(self, end: Self, limit: ast::RangeLimits) -> Sugg<'static> {
164         match limit {
165             ast::RangeLimits::HalfOpen => make_assoc(AssocOp::DotDot, &self, &end),
166             ast::RangeLimits::Closed => make_assoc(AssocOp::DotDotDot, &self, &end),
167         }
168     }
169
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 {
174         match 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)
180                 } else {
181                     Sugg::NonParen(format!("({})", sugg).into())
182                 }
183             },
184             Sugg::BinOp(_, sugg) => Sugg::NonParen(format!("({})", sugg).into()),
185         }
186     }
187 }
188
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)
193     }
194 }
195
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)
200     }
201 }
202
203 impl<'a> std::ops::Not for Sugg<'a> {
204     type Output = Sugg<'static>;
205     fn not(self) -> Sugg<'static> {
206         make_unop("!", self)
207     }
208 }
209
210 /// Helper type to display either `foo` or `(foo)`.
211 struct ParenHelper<T> {
212     /// Whether parenthesis are needed.
213     paren: bool,
214     /// The main thing to display.
215     wrapped: T,
216 }
217
218 impl<T> ParenHelper<T> {
219     /// Build a `ParenHelper`.
220     fn new(paren: bool, wrapped: T) -> Self {
221         ParenHelper {
222             paren: paren,
223             wrapped: wrapped,
224         }
225     }
226 }
227
228 impl<T: Display> Display for ParenHelper<T> {
229     fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
230         if self.paren {
231             write!(f, "({})", self.wrapped)
232         } else {
233             self.wrapped.fmt(f)
234         }
235     }
236 }
237
238 /// Build the string for `<op><expr>` adding parenthesis when necessary.
239 ///
240 /// For convenience, the operator is taken as a string because all unary
241 /// operators have the same
242 /// precedence.
243 pub fn make_unop(op: &str, expr: Sugg) -> Sugg<'static> {
244     Sugg::MaybeParen(format!("{}{}", op, expr.maybe_par()).into())
245 }
246
247 /// Build the string for `<lhs> <op> <rhs>` adding parenthesis when necessary.
248 ///
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)
256     }
257
258     /// Whether the operator is a arithmetic operator (`+`, `-`, `*`, `/`, `%`).
259     fn is_arith(op: &AssocOp) -> bool {
260         matches!(
261             *op,
262             AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide | AssocOp::Modulus
263         )
264     }
265
266     /// Whether the operator `op` needs parenthesis with the operator `other`
267     /// in the direction
268     /// `dir`.
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)
275     }
276
277     let lhs_paren = if let Sugg::BinOp(ref lop, _) = *lhs {
278         needs_paren(&op, lop, Associativity::Left)
279     } else {
280         false
281     };
282
283     let rhs_paren = if let Sugg::BinOp(ref rop, _) = *rhs {
284         needs_paren(&op, rop, Associativity::Right)
285     } else {
286         false
287     };
288
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)
297         },
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),
305     };
306
307     Sugg::BinOp(op, sugg.into())
308 }
309
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)
313 }
314
315 #[derive(PartialEq, Eq, Clone, Copy)]
316 /// Operator associativity.
317 enum Associativity {
318     /// The operator is both left-associative and right-associative.
319     Both,
320     /// The operator is left-associative.
321     Left,
322     /// The operator is not associative.
323     None,
324     /// The operator is right-associative.
325     Right,
326 }
327
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)`.
332 ///
333 /// Chained `as` and explicit `:` type coercion never need inner parenthesis so
334 /// they are considered
335 /// associative.
336 fn associativity(op: &AssocOp) -> Associativity {
337     use syntax::util::parser::AssocOp::*;
338
339     match *op {
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,
345     }
346 }
347
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::*;
352
353     AssocOp::AssignOp(match op.node {
354         BiAdd => Plus,
355         BiBitAnd => And,
356         BiBitOr => Or,
357         BiBitXor => Caret,
358         BiDiv => Slash,
359         BiMul => Star,
360         BiRem => Percent,
361         BiShl => Shl,
362         BiShr => Shr,
363         BiSub => Minus,
364         BiAnd | BiEq | BiGe | BiGt | BiLe | BiLt | BiNe | BiOr => panic!("This operator does not exist"),
365     })
366 }
367
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;
372
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"),
385     })
386 }
387
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 */
394     )
395     {
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())
400             } else {
401                 None
402             }
403         } else {
404             None
405         }
406     } else {
407         None
408     }
409 }
410
411 /// Convenience extension trait for `DiagnosticBuilder`.
412 pub trait DiagnosticBuilderExt<'a, T: LintContext<'a>> {
413     /// Suggests to add an attribute to an item.
414     ///
415     /// Correctly handles indentation of the attribute and item.
416     ///
417     /// # Example
418     ///
419     /// ```rust,ignore
420     /// db.suggest_item_with_attr(cx, item, "#[derive(Default)]");
421     /// ```
422     fn suggest_item_with_attr<D: Display + ?Sized>(&mut self, cx: &T, item: Span, msg: &str, attr: &D);
423
424     /// Suggest to add an item before another.
425     ///
426     /// The item should not be indented (expect for inner indentation).
427     ///
428     /// # Example
429     ///
430     /// ```rust,ignore
431     /// db.suggest_prepend_item(cx, item,
432     /// "fn foo() {
433     ///     bar();
434     /// }");
435     /// ```
436     fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str);
437 }
438
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) {
442             let span = Span {
443                 hi: item.lo,
444                 ..item
445             };
446
447             self.span_suggestion(span, msg, format!("{}\n{}", attr, indent));
448         }
449     }
450
451     fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str) {
452         if let Some(indent) = indentation(cx, item) {
453             let span = Span {
454                 hi: item.lo,
455                 ..item
456             };
457
458             let mut first = true;
459             let new_item = new_item
460                 .lines()
461                 .map(|l| if first {
462                     first = false;
463                     format!("{}\n", l)
464                 } else {
465                     format!("{}{}\n", indent, l)
466                 })
467                 .collect::<String>();
468
469             self.span_suggestion(span, msg, format!("{}\n{}", new_item, indent));
470         }
471     }
472 }