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