]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/sugg.rs
Merge pull request #2962 from phansch/further_automate_pre_publish
[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 matches::matches;
7 use rustc::hir;
8 use rustc::lint::{EarlyContext, LateContext, LintContext};
9 use rustc_errors;
10 use std::borrow::Cow;
11 use std::fmt::Display;
12 use std;
13 use syntax::source_map::{CharPos, Span};
14 use syntax::parse::token;
15 use syntax::print::pprust::token_to_string;
16 use syntax::util::parser::AssocOp;
17 use syntax::ast;
18 use crate::utils::{higher, snippet, snippet_opt};
19 use syntax_pos::{BytePos, Pos};
20
21 /// A helper type to build suggestion correctly handling parenthesis.
22 pub enum Sugg<'a> {
23     /// An expression that never needs parenthesis such as `1337` or `[0; 42]`.
24     NonParen(Cow<'a, str>),
25     /// An expression that does not fit in other variants.
26     MaybeParen(Cow<'a, str>),
27     /// A binary operator expression, including `as`-casts and explicit type
28     /// coercion.
29     BinOp(AssocOp, Cow<'a, str>),
30 }
31
32 /// Literal constant `1`, for convenience.
33 pub const ONE: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("1"));
34
35 impl Display for Sugg<'_> {
36     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
37         match *self {
38             Sugg::NonParen(ref s) | Sugg::MaybeParen(ref s) | 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::ExprKind::AddrOf(..) |
51                 hir::ExprKind::Box(..) |
52                 hir::ExprKind::Closure(.., _) |
53                 hir::ExprKind::If(..) |
54                 hir::ExprKind::Unary(..) |
55                 hir::ExprKind::Match(..) => Sugg::MaybeParen(snippet),
56                 hir::ExprKind::Continue(..) |
57                 hir::ExprKind::Yield(..) |
58                 hir::ExprKind::Array(..) |
59                 hir::ExprKind::Block(..) |
60                 hir::ExprKind::Break(..) |
61                 hir::ExprKind::Call(..) |
62                 hir::ExprKind::Field(..) |
63                 hir::ExprKind::Index(..) |
64                 hir::ExprKind::InlineAsm(..) |
65                 hir::ExprKind::Lit(..) |
66                 hir::ExprKind::Loop(..) |
67                 hir::ExprKind::MethodCall(..) |
68                 hir::ExprKind::Path(..) |
69                 hir::ExprKind::Repeat(..) |
70                 hir::ExprKind::Ret(..) |
71                 hir::ExprKind::Struct(..) |
72                 hir::ExprKind::Tup(..) |
73                 hir::ExprKind::While(..) => Sugg::NonParen(snippet),
74                 hir::ExprKind::Assign(..) => Sugg::BinOp(AssocOp::Assign, snippet),
75                 hir::ExprKind::AssignOp(op, ..) => Sugg::BinOp(hirbinop2assignop(op), snippet),
76                 hir::ExprKind::Binary(op, ..) => Sugg::BinOp(AssocOp::from_ast_binop(higher::binop(op.node)), snippet),
77                 hir::ExprKind::Cast(..) => Sugg::BinOp(AssocOp::As, snippet),
78                 hir::ExprKind::Type(..) => 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::ObsoleteInPlace(..) |
102             ast::ExprKind::Unary(..) |
103             ast::ExprKind::Match(..) => Sugg::MaybeParen(snippet),
104             ast::ExprKind::Async(..) |
105             ast::ExprKind::Block(..) |
106             ast::ExprKind::Break(..) |
107             ast::ExprKind::Call(..) |
108             ast::ExprKind::Continue(..) |
109             ast::ExprKind::Yield(..) |
110             ast::ExprKind::Field(..) |
111             ast::ExprKind::ForLoop(..) |
112             ast::ExprKind::Index(..) |
113             ast::ExprKind::InlineAsm(..) |
114             ast::ExprKind::Lit(..) |
115             ast::ExprKind::Loop(..) |
116             ast::ExprKind::Mac(..) |
117             ast::ExprKind::MethodCall(..) |
118             ast::ExprKind::Paren(..) |
119             ast::ExprKind::Path(..) |
120             ast::ExprKind::Repeat(..) |
121             ast::ExprKind::Ret(..) |
122             ast::ExprKind::Struct(..) |
123             ast::ExprKind::Try(..) |
124             ast::ExprKind::TryBlock(..) |
125             ast::ExprKind::Tup(..) |
126             ast::ExprKind::Array(..) |
127             ast::ExprKind::While(..) |
128             ast::ExprKind::WhileLet(..) => Sugg::NonParen(snippet),
129             ast::ExprKind::Range(.., RangeLimits::HalfOpen) => Sugg::BinOp(AssocOp::DotDot, snippet),
130             ast::ExprKind::Range(.., RangeLimits::Closed) => Sugg::BinOp(AssocOp::DotDotEq, snippet),
131             ast::ExprKind::Assign(..) => Sugg::BinOp(AssocOp::Assign, snippet),
132             ast::ExprKind::AssignOp(op, ..) => Sugg::BinOp(astbinop2assignop(op), snippet),
133             ast::ExprKind::Binary(op, ..) => Sugg::BinOp(AssocOp::from_ast_binop(op.node), snippet),
134             ast::ExprKind::Cast(..) => Sugg::BinOp(AssocOp::As, snippet),
135             ast::ExprKind::Type(..) => Sugg::BinOp(AssocOp::Colon, snippet),
136         }
137     }
138
139     /// Convenience method to create the `<lhs> && <rhs>` suggestion.
140     pub fn and(self, rhs: &Self) -> Sugg<'static> {
141         make_binop(ast::BinOpKind::And, &self, rhs)
142     }
143
144     /// Convenience method to create the `<lhs> as <rhs>` suggestion.
145     pub fn as_ty<R: Display>(self, rhs: R) -> Sugg<'static> {
146         make_assoc(AssocOp::As, &self, &Sugg::NonParen(rhs.to_string().into()))
147     }
148
149     /// Convenience method to create the `&<expr>` suggestion.
150     pub fn addr(self) -> Sugg<'static> {
151         make_unop("&", self)
152     }
153
154     /// Convenience method to create the `&mut <expr>` suggestion.
155     pub fn mut_addr(self) -> Sugg<'static> {
156         make_unop("&mut ", self)
157     }
158
159     /// Convenience method to create the `*<expr>` suggestion.
160     pub fn deref(self) -> Sugg<'static> {
161         make_unop("*", self)
162     }
163
164     /// Convenience method to create the `&*<expr>` suggestion. Currently this
165     /// is needed because `sugg.deref().addr()` produces an unnecessary set of
166     /// parentheses around the deref.
167     pub fn addr_deref(self) -> Sugg<'static> {
168         make_unop("&*", self)
169     }
170
171     /// Convenience method to create the `&mut *<expr>` suggestion. Currently
172     /// this is needed because `sugg.deref().mut_addr()` produces an unnecessary
173     /// set of parentheses around the deref.
174     pub fn mut_addr_deref(self) -> Sugg<'static> {
175         make_unop("&mut *", self)
176     }
177
178     /// Convenience method to create the `<lhs>..<rhs>` or `<lhs>...<rhs>`
179     /// suggestion.
180     #[allow(dead_code)]
181     pub fn range(self, end: &Self, limit: ast::RangeLimits) -> Sugg<'static> {
182         match limit {
183             ast::RangeLimits::HalfOpen => make_assoc(AssocOp::DotDot, &self, end),
184             ast::RangeLimits::Closed => make_assoc(AssocOp::DotDotEq, &self, end),
185         }
186     }
187
188     /// Add parenthesis to any expression that might need them. Suitable to the
189     /// `self` argument of
190     /// a method call (eg. to build `bar.foo()` or `(1 + 2).foo()`).
191     pub fn maybe_par(self) -> Self {
192         match self {
193             Sugg::NonParen(..) => self,
194             // (x) and (x).y() both don't need additional parens
195             Sugg::MaybeParen(sugg) => if sugg.starts_with('(') && sugg.ends_with(')') {
196                 Sugg::MaybeParen(sugg)
197             } else {
198                 Sugg::NonParen(format!("({})", sugg).into())
199             },
200             Sugg::BinOp(_, sugg) => Sugg::NonParen(format!("({})", sugg).into()),
201         }
202     }
203 }
204
205 impl<'a, 'b> std::ops::Add<Sugg<'b>> for Sugg<'a> {
206     type Output = Sugg<'static>;
207     fn add(self, rhs: Sugg<'b>) -> Sugg<'static> {
208         make_binop(ast::BinOpKind::Add, &self, &rhs)
209     }
210 }
211
212 impl<'a, 'b> std::ops::Sub<Sugg<'b>> for Sugg<'a> {
213     type Output = Sugg<'static>;
214     fn sub(self, rhs: Sugg<'b>) -> Sugg<'static> {
215         make_binop(ast::BinOpKind::Sub, &self, &rhs)
216     }
217 }
218
219 impl<'a> std::ops::Not for Sugg<'a> {
220     type Output = Sugg<'static>;
221     fn not(self) -> Sugg<'static> {
222         make_unop("!", self)
223     }
224 }
225
226 /// Helper type to display either `foo` or `(foo)`.
227 struct ParenHelper<T> {
228     /// Whether parenthesis are needed.
229     paren: bool,
230     /// The main thing to display.
231     wrapped: T,
232 }
233
234 impl<T> ParenHelper<T> {
235     /// Build a `ParenHelper`.
236     fn new(paren: bool, wrapped: T) -> Self {
237         Self {
238             paren,
239             wrapped,
240         }
241     }
242 }
243
244 impl<T: Display> Display for ParenHelper<T> {
245     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
246         if self.paren {
247             write!(f, "({})", self.wrapped)
248         } else {
249             self.wrapped.fmt(f)
250         }
251     }
252 }
253
254 /// Build the string for `<op><expr>` adding parenthesis when necessary.
255 ///
256 /// For convenience, the operator is taken as a string because all unary
257 /// operators have the same
258 /// precedence.
259 pub fn make_unop(op: &str, expr: Sugg<'_>) -> Sugg<'static> {
260     Sugg::MaybeParen(format!("{}{}", op, expr.maybe_par()).into())
261 }
262
263 /// Build the string for `<lhs> <op> <rhs>` adding parenthesis when necessary.
264 ///
265 /// Precedence of shift operator relative to other arithmetic operation is
266 /// often confusing so
267 /// parenthesis will always be added for a mix of these.
268 pub fn make_assoc(op: AssocOp, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
269     /// Whether the operator is a shift operator `<<` or `>>`.
270     fn is_shift(op: &AssocOp) -> bool {
271         matches!(*op, AssocOp::ShiftLeft | AssocOp::ShiftRight)
272     }
273
274     /// Whether the operator is a arithmetic operator (`+`, `-`, `*`, `/`, `%`).
275     fn is_arith(op: &AssocOp) -> bool {
276         matches!(
277             *op,
278             AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide | AssocOp::Modulus
279         )
280     }
281
282     /// Whether the operator `op` needs parenthesis with the operator `other`
283     /// in the direction
284     /// `dir`.
285     fn needs_paren(op: &AssocOp, other: &AssocOp, dir: Associativity) -> bool {
286         other.precedence() < op.precedence()
287             || (other.precedence() == op.precedence()
288                 && ((op != other && associativity(op) != dir)
289                     || (op == other && associativity(op) != Associativity::Both)))
290             || is_shift(op) && is_arith(other) || is_shift(other) && is_arith(op)
291     }
292
293     let lhs_paren = if let Sugg::BinOp(ref lop, _) = *lhs {
294         needs_paren(&op, lop, Associativity::Left)
295     } else {
296         false
297     };
298
299     let rhs_paren = if let Sugg::BinOp(ref rop, _) = *rhs {
300         needs_paren(&op, rop, Associativity::Right)
301     } else {
302         false
303     };
304
305     let lhs = ParenHelper::new(lhs_paren, lhs);
306     let rhs = ParenHelper::new(rhs_paren, rhs);
307     let sugg = match op {
308         AssocOp::Add |
309         AssocOp::BitAnd |
310         AssocOp::BitOr |
311         AssocOp::BitXor |
312         AssocOp::Divide |
313         AssocOp::Equal |
314         AssocOp::Greater |
315         AssocOp::GreaterEqual |
316         AssocOp::LAnd |
317         AssocOp::LOr |
318         AssocOp::Less |
319         AssocOp::LessEqual |
320         AssocOp::Modulus |
321         AssocOp::Multiply |
322         AssocOp::NotEqual |
323         AssocOp::ShiftLeft |
324         AssocOp::ShiftRight |
325         AssocOp::Subtract => format!("{} {} {}", lhs, op.to_ast_binop().expect("Those are AST ops").to_string(), rhs),
326         AssocOp::Assign => format!("{} = {}", lhs, rhs),
327         AssocOp::ObsoleteInPlace => format!("in ({}) {}", lhs, rhs),
328         AssocOp::AssignOp(op) => format!("{} {}= {}", lhs, token_to_string(&token::BinOp(op)), rhs),
329         AssocOp::As => format!("{} as {}", lhs, rhs),
330         AssocOp::DotDot => format!("{}..{}", lhs, rhs),
331         AssocOp::DotDotEq => format!("{}..={}", lhs, rhs),
332         AssocOp::Colon => format!("{}: {}", lhs, rhs),
333     };
334
335     Sugg::BinOp(op, sugg.into())
336 }
337
338 /// Convenience wrapper around `make_assoc` and `AssocOp::from_ast_binop`.
339 pub fn make_binop(op: ast::BinOpKind, lhs: &Sugg<'_>, rhs: &Sugg<'_>) -> Sugg<'static> {
340     make_assoc(AssocOp::from_ast_binop(op), lhs, rhs)
341 }
342
343 #[derive(PartialEq, Eq, Clone, Copy)]
344 /// Operator associativity.
345 enum Associativity {
346     /// The operator is both left-associative and right-associative.
347     Both,
348     /// The operator is left-associative.
349     Left,
350     /// The operator is not associative.
351     None,
352     /// The operator is right-associative.
353     Right,
354 }
355
356 /// Return the associativity/fixity of an operator. The difference with
357 /// `AssocOp::fixity` is that
358 /// an operator can be both left and right associative (such as `+`:
359 /// `a + b + c == (a + b) + c == a + (b + c)`.
360 ///
361 /// Chained `as` and explicit `:` type coercion never need inner parenthesis so
362 /// they are considered
363 /// associative.
364 fn associativity(op: &AssocOp) -> Associativity {
365     use syntax::util::parser::AssocOp::*;
366
367     match *op {
368         ObsoleteInPlace | Assign | AssignOp(_) => Associativity::Right,
369         Add | BitAnd | BitOr | BitXor | LAnd | LOr | Multiply | As | Colon => Associativity::Both,
370         Divide |
371         Equal |
372         Greater |
373         GreaterEqual |
374         Less |
375         LessEqual |
376         Modulus |
377         NotEqual |
378         ShiftLeft |
379         ShiftRight |
380         Subtract => Associativity::Left,
381         DotDot | DotDotEq => Associativity::None,
382     }
383 }
384
385 /// Convert a `hir::BinOp` to the corresponding assigning binary operator.
386 fn hirbinop2assignop(op: hir::BinOp) -> AssocOp {
387     use syntax::parse::token::BinOpToken::*;
388
389     AssocOp::AssignOp(match op.node {
390         hir::BinOpKind::Add => Plus,
391         hir::BinOpKind::BitAnd => And,
392         hir::BinOpKind::BitOr => Or,
393         hir::BinOpKind::BitXor => Caret,
394         hir::BinOpKind::Div => Slash,
395         hir::BinOpKind::Mul => Star,
396         hir::BinOpKind::Rem => Percent,
397         hir::BinOpKind::Shl => Shl,
398         hir::BinOpKind::Shr => Shr,
399         hir::BinOpKind::Sub => Minus,
400
401         | hir::BinOpKind::And
402         | hir::BinOpKind::Eq
403         | hir::BinOpKind::Ge
404         | hir::BinOpKind::Gt
405         | hir::BinOpKind::Le
406         | hir::BinOpKind::Lt
407         | hir::BinOpKind::Ne
408         | hir::BinOpKind::Or
409         => panic!("This operator does not exist"),
410     })
411 }
412
413 /// Convert an `ast::BinOp` to the corresponding assigning binary operator.
414 fn astbinop2assignop(op: ast::BinOp) -> AssocOp {
415     use syntax::ast::BinOpKind::*;
416     use syntax::parse::token::BinOpToken;
417
418     AssocOp::AssignOp(match op.node {
419         Add => BinOpToken::Plus,
420         BitAnd => BinOpToken::And,
421         BitOr => BinOpToken::Or,
422         BitXor => BinOpToken::Caret,
423         Div => BinOpToken::Slash,
424         Mul => BinOpToken::Star,
425         Rem => BinOpToken::Percent,
426         Shl => BinOpToken::Shl,
427         Shr => BinOpToken::Shr,
428         Sub => BinOpToken::Minus,
429         And | Eq | Ge | Gt | Le | Lt | Ne | Or => panic!("This operator does not exist"),
430     })
431 }
432
433 /// Return the indentation before `span` if there are nothing but `[ \t]`
434 /// before it on its line.
435 fn indentation<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Option<String> {
436     let lo = cx.sess().source_map().lookup_char_pos(span.lo());
437     if let Some(line) = lo.file
438         .get_line(lo.line - 1 /* line numbers in `Loc` are 1-based */)
439     {
440         if let Some((pos, _)) = line.char_indices().find(|&(_, c)| c != ' ' && c != '\t') {
441             // we can mix char and byte positions here because we only consider `[ \t]`
442             if lo.col == CharPos(pos) {
443                 Some(line[..pos].into())
444             } else {
445                 None
446             }
447         } else {
448             None
449         }
450     } else {
451         None
452     }
453 }
454
455 /// Convenience extension trait for `DiagnosticBuilder`.
456 pub trait DiagnosticBuilderExt<'a, T: LintContext<'a>> {
457     /// Suggests to add an attribute to an item.
458     ///
459     /// Correctly handles indentation of the attribute and item.
460     ///
461     /// # Example
462     ///
463     /// ```rust,ignore
464     /// db.suggest_item_with_attr(cx, item, "#[derive(Default)]");
465     /// ```
466     fn suggest_item_with_attr<D: Display + ?Sized>(&mut self, cx: &T, item: Span, msg: &str, attr: &D);
467
468     /// Suggest to add an item before another.
469     ///
470     /// The item should not be indented (expect for inner indentation).
471     ///
472     /// # Example
473     ///
474     /// ```rust,ignore
475     /// db.suggest_prepend_item(cx, item,
476     /// "fn foo() {
477     ///     bar();
478     /// }");
479     /// ```
480     fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str);
481
482     /// Suggest to completely remove an item.
483     ///
484     /// This will remove an item and all following whitespace until the next non-whitespace
485     /// character. This should work correctly if item is on the same indentation level as the
486     /// following item.
487     ///
488     /// # Example
489     ///
490     /// ```rust,ignore
491     /// db.suggest_remove_item(cx, item, "remove this")
492     /// ```
493     fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str);
494 }
495
496 impl<'a, 'b, 'c, T: LintContext<'c>> DiagnosticBuilderExt<'c, T> for rustc_errors::DiagnosticBuilder<'b> {
497     fn suggest_item_with_attr<D: Display + ?Sized>(&mut self, cx: &T, item: Span, msg: &str, attr: &D) {
498         if let Some(indent) = indentation(cx, item) {
499             let span = item.with_hi(item.lo());
500
501             self.span_suggestion(span, msg, format!("{}\n{}", attr, indent));
502         }
503     }
504
505     fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str) {
506         if let Some(indent) = indentation(cx, item) {
507             let span = item.with_hi(item.lo());
508
509             let mut first = true;
510             let new_item = new_item
511                 .lines()
512                 .map(|l| {
513                     if first {
514                         first = false;
515                         format!("{}\n", l)
516                     } else {
517                         format!("{}{}\n", indent, l)
518                     }
519                 })
520                 .collect::<String>();
521
522             self.span_suggestion(span, msg, format!("{}\n{}", new_item, indent));
523         }
524     }
525
526     fn suggest_remove_item(&mut self, cx: &T, item: Span, msg: &str) {
527         let mut remove_span = item;
528         let hi = cx.sess().source_map().next_point(remove_span).hi();
529         let fmpos = cx.sess().source_map().lookup_byte_offset(hi);
530
531         if let Some(ref src) = fmpos.fm.src {
532             let non_whitespace_offset = src[fmpos.pos.to_usize()..].find(|c| c != ' ' && c != '\t' && c != '\n');
533
534             if let Some(non_whitespace_offset) = non_whitespace_offset {
535                 remove_span = remove_span.with_hi(remove_span.hi() + BytePos(non_whitespace_offset as u32))
536             }
537         }
538
539         self.span_suggestion(remove_span, msg, String::new());
540     }
541 }