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