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