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