]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/sugg.rs
Merge pull request #2632 from phansch/fix_useless_format_false_positive
[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 use syntax_pos::{BytePos, Pos};
19
20 /// A helper type to build suggestion correctly handling parenthesis.
21 pub enum Sugg<'a> {
22     /// An expression that never needs parenthesis such as `1337` or `[0; 42]`.
23     NonParen(Cow<'a, str>),
24     /// An expression that does not fit in other variants.
25     MaybeParen(Cow<'a, str>),
26     /// A binary operator expression, including `as`-casts and explicit type
27     /// coercion.
28     BinOp(AssocOp, Cow<'a, str>),
29 }
30
31 /// Literal constant `1`, for convenience.
32 pub const ONE: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("1"));
33
34 impl<'a> Display for Sugg<'a> {
35     fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
36         match *self {
37             Sugg::NonParen(ref s) | Sugg::MaybeParen(ref s) | Sugg::BinOp(_, ref s) => s.fmt(f),
38         }
39     }
40 }
41
42 #[allow(wrong_self_convention)] // ok, because of the function `as_ty` method
43 impl<'a> Sugg<'a> {
44     /// Prepare a suggestion from an expression.
45     pub fn hir_opt(cx: &LateContext, expr: &hir::Expr) -> Option<Self> {
46         snippet_opt(cx, expr.span).map(|snippet| {
47             let snippet = Cow::Owned(snippet);
48             match expr.node {
49                 hir::ExprAddrOf(..) |
50                 hir::ExprBox(..) |
51                 hir::ExprClosure(.., _) |
52                 hir::ExprIf(..) |
53                 hir::ExprUnary(..) |
54                 hir::ExprMatch(..) => Sugg::MaybeParen(snippet),
55                 hir::ExprAgain(..) |
56                 hir::ExprYield(..) |
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::Unary(..) |
102             ast::ExprKind::Match(..) => Sugg::MaybeParen(snippet),
103             ast::ExprKind::Block(..) |
104             ast::ExprKind::Break(..) |
105             ast::ExprKind::Call(..) |
106             ast::ExprKind::Catch(..) |
107             ast::ExprKind::Continue(..) |
108             ast::ExprKind::Yield(..) |
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::DotDotEq, 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::DotDotEq, &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) => if sugg.starts_with('(') && sugg.ends_with(')') {
180                 Sugg::MaybeParen(sugg)
181             } else {
182                 Sugg::NonParen(format!("({})", sugg).into())
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         Self {
222             paren,
223             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 |
293         AssocOp::BitAnd |
294         AssocOp::BitOr |
295         AssocOp::BitXor |
296         AssocOp::Divide |
297         AssocOp::Equal |
298         AssocOp::Greater |
299         AssocOp::GreaterEqual |
300         AssocOp::LAnd |
301         AssocOp::LOr |
302         AssocOp::Less |
303         AssocOp::LessEqual |
304         AssocOp::Modulus |
305         AssocOp::Multiply |
306         AssocOp::NotEqual |
307         AssocOp::ShiftLeft |
308         AssocOp::ShiftRight |
309         AssocOp::Subtract => format!("{} {} {}", lhs, op.to_ast_binop().expect("Those are AST ops").to_string(), rhs),
310         AssocOp::Assign => format!("{} = {}", lhs, rhs),
311         AssocOp::AssignOp(op) => format!("{} {}= {}", lhs, token_to_string(&token::BinOp(op)), rhs),
312         AssocOp::As => format!("{} as {}", lhs, rhs),
313         AssocOp::DotDot => format!("{}..{}", lhs, rhs),
314         AssocOp::DotDotEq => format!("{}..={}", lhs, rhs),
315         AssocOp::Colon => format!("{}: {}", lhs, rhs),
316     };
317
318     Sugg::BinOp(op, sugg.into())
319 }
320
321 /// Convinience wrapper arround `make_assoc` and `AssocOp::from_ast_binop`.
322 pub fn make_binop(op: ast::BinOpKind, lhs: &Sugg, rhs: &Sugg) -> Sugg<'static> {
323     make_assoc(AssocOp::from_ast_binop(op), lhs, rhs)
324 }
325
326 #[derive(PartialEq, Eq, Clone, Copy)]
327 /// Operator associativity.
328 enum Associativity {
329     /// The operator is both left-associative and right-associative.
330     Both,
331     /// The operator is left-associative.
332     Left,
333     /// The operator is not associative.
334     None,
335     /// The operator is right-associative.
336     Right,
337 }
338
339 /// Return the associativity/fixity of an operator. The difference with
340 /// `AssocOp::fixity` is that
341 /// an operator can be both left and right associative (such as `+`:
342 /// `a + b + c == (a + b) + c == a + (b + c)`.
343 ///
344 /// Chained `as` and explicit `:` type coercion never need inner parenthesis so
345 /// they are considered
346 /// associative.
347 fn associativity(op: &AssocOp) -> Associativity {
348     use syntax::util::parser::AssocOp::*;
349
350     match *op {
351         Assign | AssignOp(_) => Associativity::Right,
352         Add | BitAnd | BitOr | BitXor | LAnd | LOr | Multiply | As | Colon => Associativity::Both,
353         Divide |
354         Equal |
355         Greater |
356         GreaterEqual |
357         Less |
358         LessEqual |
359         Modulus |
360         NotEqual |
361         ShiftLeft |
362         ShiftRight |
363         Subtract => Associativity::Left,
364         DotDot | DotDotEq => Associativity::None,
365     }
366 }
367
368 /// Convert a `hir::BinOp` to the corresponding assigning binary operator.
369 fn hirbinop2assignop(op: hir::BinOp) -> AssocOp {
370     use rustc::hir::BinOp_::*;
371     use syntax::parse::token::BinOpToken::*;
372
373     AssocOp::AssignOp(match op.node {
374         BiAdd => Plus,
375         BiBitAnd => And,
376         BiBitOr => Or,
377         BiBitXor => Caret,
378         BiDiv => Slash,
379         BiMul => Star,
380         BiRem => Percent,
381         BiShl => Shl,
382         BiShr => Shr,
383         BiSub => Minus,
384         BiAnd | BiEq | BiGe | BiGt | BiLe | BiLt | BiNe | BiOr => panic!("This operator does not exist"),
385     })
386 }
387
388 /// Convert an `ast::BinOp` to the corresponding assigning binary operator.
389 fn astbinop2assignop(op: ast::BinOp) -> AssocOp {
390     use syntax::ast::BinOpKind::*;
391     use syntax::parse::token::BinOpToken;
392
393     AssocOp::AssignOp(match op.node {
394         Add => BinOpToken::Plus,
395         BitAnd => BinOpToken::And,
396         BitOr => BinOpToken::Or,
397         BitXor => BinOpToken::Caret,
398         Div => BinOpToken::Slash,
399         Mul => BinOpToken::Star,
400         Rem => BinOpToken::Percent,
401         Shl => BinOpToken::Shl,
402         Shr => BinOpToken::Shr,
403         Sub => BinOpToken::Minus,
404         And | Eq | Ge | Gt | Le | Lt | Ne | Or => panic!("This operator does not exist"),
405     })
406 }
407
408 /// Return the indentation before `span` if there are nothing but `[ \t]`
409 /// before it on its line.
410 fn indentation<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Option<String> {
411     let lo = cx.sess().codemap().lookup_char_pos(span.lo());
412     if let Some(line) = lo.file
413         .get_line(lo.line - 1 /* line numbers in `Loc` are 1-based */)
414     {
415         if let Some((pos, _)) = line.char_indices().find(|&(_, c)| c != ' ' && c != '\t') {
416             // we can mix char and byte positions here because we only consider `[ \t]`
417             if lo.col == CharPos(pos) {
418                 Some(line[..pos].into())
419             } else {
420                 None
421             }
422         } else {
423             None
424         }
425     } else {
426         None
427     }
428 }
429
430 /// Convenience extension trait for `DiagnosticBuilder`.
431 pub trait DiagnosticBuilderExt<'a, T: LintContext<'a>> {
432     /// Suggests to add an attribute to an item.
433     ///
434     /// Correctly handles indentation of the attribute and item.
435     ///
436     /// # Example
437     ///
438     /// ```rust,ignore
439     /// db.suggest_item_with_attr(cx, item, "#[derive(Default)]");
440     /// ```
441     fn suggest_item_with_attr<D: Display + ?Sized>(&mut self, cx: &T, item: Span, msg: &str, attr: &D);
442
443     /// Suggest to add an item before another.
444     ///
445     /// The item should not be indented (expect for inner indentation).
446     ///
447     /// # Example
448     ///
449     /// ```rust,ignore
450     /// db.suggest_prepend_item(cx, item,
451     /// "fn foo() {
452     ///     bar();
453     /// }");
454     /// ```
455     fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str);
456
457     /// Suggest to completely remove an item.
458     ///
459     /// This will remove an item and all following whitespace until the next non-whitespace
460     /// character. This should work correctly if item is on the same indentation level as the
461     /// following item.
462     ///
463     /// # Example
464     ///
465     /// ```rust,ignore
466     /// db.suggest_remove_item(cx, item, "remove this")
467     /// ```
468     fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str);
469 }
470
471 impl<'a, 'b, 'c, T: LintContext<'c>> DiagnosticBuilderExt<'c, T> for rustc_errors::DiagnosticBuilder<'b> {
472     fn suggest_item_with_attr<D: Display + ?Sized>(&mut self, cx: &T, item: Span, msg: &str, attr: &D) {
473         if let Some(indent) = indentation(cx, item) {
474             let span = item.with_hi(item.lo());
475
476             self.span_suggestion(span, msg, format!("{}\n{}", attr, indent));
477         }
478     }
479
480     fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str) {
481         if let Some(indent) = indentation(cx, item) {
482             let span = item.with_hi(item.lo());
483
484             let mut first = true;
485             let new_item = new_item
486                 .lines()
487                 .map(|l| {
488                     if first {
489                         first = false;
490                         format!("{}\n", l)
491                     } else {
492                         format!("{}{}\n", indent, l)
493                     }
494                 })
495                 .collect::<String>();
496
497             self.span_suggestion(span, msg, format!("{}\n{}", new_item, indent));
498         }
499     }
500
501     fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str) {
502         let mut remove_span = item;
503         let hi = cx.sess().codemap().next_point(remove_span).hi();
504         let fmpos = cx.sess().codemap().lookup_byte_offset(hi);
505
506         if let Some(ref src) = fmpos.fm.src {
507             let non_whitespace_offset = src[fmpos.pos.to_usize()..].find(|c| c != ' ' && c != '\t' && c != '\n');
508
509             if let Some(non_whitespace_offset) = non_whitespace_offset {
510                 remove_span = remove_span.with_hi(remove_span.hi() + BytePos(non_whitespace_offset as u32))
511             }
512         }
513
514         self.span_suggestion(remove_span, msg, String::new());
515     }
516 }