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