]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/sugg.rs
Rustup (fixes #2002)
[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
19 /// A helper type to build suggestion correctly handling parenthesis.
20 pub enum Sugg<'a> {
21     /// An expression that never needs parenthesis such as `1337` or `[0; 42]`.
22     NonParen(Cow<'a, str>),
23     /// An expression that does not fit in other variants.
24     MaybeParen(Cow<'a, str>),
25     /// A binary operator expression, including `as`-casts and explicit type
26     /// coercion.
27     BinOp(AssocOp, Cow<'a, str>),
28 }
29
30 /// Literal constant `1`, for convenience.
31 pub const ONE: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("1"));
32
33 impl<'a> Display for Sugg<'a> {
34     fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
35         match *self {
36             Sugg::NonParen(ref s) |
37             Sugg::MaybeParen(ref s) |
38             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::ExprAddrOf(..) |
51                 hir::ExprBox(..) |
52                 hir::ExprClosure(.., _) |
53                 hir::ExprIf(..) |
54                 hir::ExprUnary(..) |
55                 hir::ExprMatch(..) => Sugg::MaybeParen(snippet),
56                 hir::ExprAgain(..) |
57                 hir::ExprYield(..) |
58                 hir::ExprArray(..) |
59                 hir::ExprBlock(..) |
60                 hir::ExprBreak(..) |
61                 hir::ExprCall(..) |
62                 hir::ExprField(..) |
63                 hir::ExprIndex(..) |
64                 hir::ExprInlineAsm(..) |
65                 hir::ExprLit(..) |
66                 hir::ExprLoop(..) |
67                 hir::ExprMethodCall(..) |
68                 hir::ExprPath(..) |
69                 hir::ExprRepeat(..) |
70                 hir::ExprRet(..) |
71                 hir::ExprStruct(..) |
72                 hir::ExprTup(..) |
73                 hir::ExprTupField(..) |
74                 hir::ExprWhile(..) => Sugg::NonParen(snippet),
75                 hir::ExprAssign(..) => Sugg::BinOp(AssocOp::Assign, snippet),
76                 hir::ExprAssignOp(op, ..) => Sugg::BinOp(hirbinop2assignop(op), snippet),
77                 hir::ExprBinary(op, ..) => Sugg::BinOp(AssocOp::from_ast_binop(higher::binop(op.node)), snippet),
78                 hir::ExprCast(..) => Sugg::BinOp(AssocOp::As, snippet),
79                 hir::ExprType(..) => Sugg::BinOp(AssocOp::Colon, snippet),
80             }
81         })
82     }
83
84     /// Convenience function around `hir_opt` for suggestions with a default
85     /// text.
86     pub fn hir(cx: &LateContext, expr: &hir::Expr, default: &'a str) -> Self {
87         Self::hir_opt(cx, expr).unwrap_or_else(|| Sugg::NonParen(Cow::Borrowed(default)))
88     }
89
90     /// Prepare a suggestion from an expression.
91     pub fn ast(cx: &EarlyContext, expr: &ast::Expr, default: &'a str) -> Self {
92         use syntax::ast::RangeLimits;
93
94         let snippet = snippet(cx, expr.span, default);
95
96         match expr.node {
97             ast::ExprKind::AddrOf(..) |
98             ast::ExprKind::Box(..) |
99             ast::ExprKind::Closure(..) |
100             ast::ExprKind::If(..) |
101             ast::ExprKind::IfLet(..) |
102             ast::ExprKind::InPlace(..) |
103             ast::ExprKind::Unary(..) |
104             ast::ExprKind::Match(..) => Sugg::MaybeParen(snippet),
105             ast::ExprKind::Block(..) |
106             ast::ExprKind::Break(..) |
107             ast::ExprKind::Call(..) |
108             ast::ExprKind::Catch(..) |
109             ast::ExprKind::Continue(..) |
110             ast::ExprKind::Yield(..) |
111             ast::ExprKind::Field(..) |
112             ast::ExprKind::ForLoop(..) |
113             ast::ExprKind::Index(..) |
114             ast::ExprKind::InlineAsm(..) |
115             ast::ExprKind::Lit(..) |
116             ast::ExprKind::Loop(..) |
117             ast::ExprKind::Mac(..) |
118             ast::ExprKind::MethodCall(..) |
119             ast::ExprKind::Paren(..) |
120             ast::ExprKind::Path(..) |
121             ast::ExprKind::Repeat(..) |
122             ast::ExprKind::Ret(..) |
123             ast::ExprKind::Struct(..) |
124             ast::ExprKind::Try(..) |
125             ast::ExprKind::Tup(..) |
126             ast::ExprKind::TupField(..) |
127             ast::ExprKind::Array(..) |
128             ast::ExprKind::While(..) |
129             ast::ExprKind::WhileLet(..) => Sugg::NonParen(snippet),
130             ast::ExprKind::Range(.., RangeLimits::HalfOpen) => Sugg::BinOp(AssocOp::DotDot, snippet),
131             ast::ExprKind::Range(.., RangeLimits::Closed) => Sugg::BinOp(AssocOp::DotDotDot, snippet),
132             ast::ExprKind::Assign(..) => Sugg::BinOp(AssocOp::Assign, snippet),
133             ast::ExprKind::AssignOp(op, ..) => Sugg::BinOp(astbinop2assignop(op), snippet),
134             ast::ExprKind::Binary(op, ..) => Sugg::BinOp(AssocOp::from_ast_binop(op.node), snippet),
135             ast::ExprKind::Cast(..) => Sugg::BinOp(AssocOp::As, snippet),
136             ast::ExprKind::Type(..) => Sugg::BinOp(AssocOp::Colon, snippet),
137         }
138     }
139
140     /// Convenience method to create the `<lhs> && <rhs>` suggestion.
141     pub fn and(self, rhs: Self) -> Sugg<'static> {
142         make_binop(ast::BinOpKind::And, &self, &rhs)
143     }
144
145     /// Convenience method to create the `<lhs> as <rhs>` suggestion.
146     pub fn as_ty<R: Display>(self, rhs: R) -> Sugg<'static> {
147         make_assoc(AssocOp::As, &self, &Sugg::NonParen(rhs.to_string().into()))
148     }
149
150     /// Convenience method to create the `&<expr>` suggestion.
151     pub fn addr(self) -> Sugg<'static> {
152         make_unop("&", self)
153     }
154
155     /// Convenience method to create the `&mut <expr>` suggestion.
156     pub fn mut_addr(self) -> Sugg<'static> {
157         make_unop("&mut ", self)
158     }
159
160     /// Convenience method to create the `*<expr>` suggestion.
161     pub fn deref(self) -> Sugg<'static> {
162         make_unop("*", self)
163     }
164
165     /// Convenience method to create the `<lhs>..<rhs>` or `<lhs>...<rhs>`
166     /// suggestion.
167     pub fn range(self, end: Self, limit: ast::RangeLimits) -> Sugg<'static> {
168         match limit {
169             ast::RangeLimits::HalfOpen => make_assoc(AssocOp::DotDot, &self, &end),
170             ast::RangeLimits::Closed => make_assoc(AssocOp::DotDotDot, &self, &end),
171         }
172     }
173
174     /// Add parenthesis to any expression that might need them. Suitable to the
175     /// `self` argument of
176     /// a method call (eg. to build `bar.foo()` or `(1 + 2).foo()`).
177     pub fn maybe_par(self) -> Self {
178         match self {
179             Sugg::NonParen(..) => self,
180             // (x) and (x).y() both don't need additional parens
181             Sugg::MaybeParen(sugg) => {
182                 if sugg.starts_with('(') && sugg.ends_with(')') {
183                     Sugg::MaybeParen(sugg)
184                 } else {
185                     Sugg::NonParen(format!("({})", sugg).into())
186                 }
187             },
188             Sugg::BinOp(_, sugg) => Sugg::NonParen(format!("({})", sugg).into()),
189         }
190     }
191 }
192
193 impl<'a, 'b> std::ops::Add<Sugg<'b>> for Sugg<'a> {
194     type Output = Sugg<'static>;
195     fn add(self, rhs: Sugg<'b>) -> Sugg<'static> {
196         make_binop(ast::BinOpKind::Add, &self, &rhs)
197     }
198 }
199
200 impl<'a, 'b> std::ops::Sub<Sugg<'b>> for Sugg<'a> {
201     type Output = Sugg<'static>;
202     fn sub(self, rhs: Sugg<'b>) -> Sugg<'static> {
203         make_binop(ast::BinOpKind::Sub, &self, &rhs)
204     }
205 }
206
207 impl<'a> std::ops::Not for Sugg<'a> {
208     type Output = Sugg<'static>;
209     fn not(self) -> Sugg<'static> {
210         make_unop("!", self)
211     }
212 }
213
214 /// Helper type to display either `foo` or `(foo)`.
215 struct ParenHelper<T> {
216     /// Whether parenthesis are needed.
217     paren: bool,
218     /// The main thing to display.
219     wrapped: T,
220 }
221
222 impl<T> ParenHelper<T> {
223     /// Build a `ParenHelper`.
224     fn new(paren: bool, wrapped: T) -> Self {
225         Self {
226             paren: paren,
227             wrapped: wrapped,
228         }
229     }
230 }
231
232 impl<T: Display> Display for ParenHelper<T> {
233     fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
234         if self.paren {
235             write!(f, "({})", self.wrapped)
236         } else {
237             self.wrapped.fmt(f)
238         }
239     }
240 }
241
242 /// Build the string for `<op><expr>` adding parenthesis when necessary.
243 ///
244 /// For convenience, the operator is taken as a string because all unary
245 /// operators have the same
246 /// precedence.
247 pub fn make_unop(op: &str, expr: Sugg) -> Sugg<'static> {
248     Sugg::MaybeParen(format!("{}{}", op, expr.maybe_par()).into())
249 }
250
251 /// Build the string for `<lhs> <op> <rhs>` adding parenthesis when necessary.
252 ///
253 /// Precedence of shift operator relative to other arithmetic operation is
254 /// often confusing so
255 /// parenthesis will always be added for a mix of these.
256 pub fn make_assoc(op: AssocOp, lhs: &Sugg, rhs: &Sugg) -> Sugg<'static> {
257     /// Whether the operator is a shift operator `<<` or `>>`.
258     fn is_shift(op: &AssocOp) -> bool {
259         matches!(*op, AssocOp::ShiftLeft | AssocOp::ShiftRight)
260     }
261
262     /// Whether the operator is a arithmetic operator (`+`, `-`, `*`, `/`, `%`).
263     fn is_arith(op: &AssocOp) -> bool {
264         matches!(
265             *op,
266             AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide | AssocOp::Modulus
267         )
268     }
269
270     /// Whether the operator `op` needs parenthesis with the operator `other`
271     /// in the direction
272     /// `dir`.
273     fn needs_paren(op: &AssocOp, other: &AssocOp, dir: Associativity) -> bool {
274         other.precedence() < op.precedence() ||
275             (other.precedence() == op.precedence() &&
276                  ((op != other && associativity(op) != dir) ||
277                       (op == other && associativity(op) != Associativity::Both))) ||
278             is_shift(op) && is_arith(other) || is_shift(other) && is_arith(op)
279     }
280
281     let lhs_paren = if let Sugg::BinOp(ref lop, _) = *lhs {
282         needs_paren(&op, lop, Associativity::Left)
283     } else {
284         false
285     };
286
287     let rhs_paren = if let Sugg::BinOp(ref rop, _) = *rhs {
288         needs_paren(&op, rop, Associativity::Right)
289     } else {
290         false
291     };
292
293     let lhs = ParenHelper::new(lhs_paren, lhs);
294     let rhs = ParenHelper::new(rhs_paren, rhs);
295     let sugg = match op {
296         AssocOp::Add | AssocOp::BitAnd | AssocOp::BitOr | AssocOp::BitXor | AssocOp::Divide | AssocOp::Equal |
297         AssocOp::Greater | AssocOp::GreaterEqual | AssocOp::LAnd | AssocOp::LOr | AssocOp::Less |
298         AssocOp::LessEqual | AssocOp::Modulus | AssocOp::Multiply | AssocOp::NotEqual | AssocOp::ShiftLeft |
299         AssocOp::ShiftRight | AssocOp::Subtract => {
300             format!("{} {} {}", lhs, op.to_ast_binop().expect("Those are AST ops").to_string(), rhs)
301         },
302         AssocOp::Inplace => format!("in ({}) {}", lhs, rhs),
303         AssocOp::Assign => format!("{} = {}", lhs, rhs),
304         AssocOp::AssignOp(op) => format!("{} {}= {}", lhs, token_to_string(&token::BinOp(op)), rhs),
305         AssocOp::As => format!("{} as {}", lhs, rhs),
306         AssocOp::DotDot => format!("{}..{}", lhs, rhs),
307         AssocOp::DotDotDot => format!("{}...{}", lhs, rhs),
308         AssocOp::Colon => format!("{}: {}", lhs, rhs),
309     };
310
311     Sugg::BinOp(op, sugg.into())
312 }
313
314 /// Convinience wrapper arround `make_assoc` and `AssocOp::from_ast_binop`.
315 pub fn make_binop(op: ast::BinOpKind, lhs: &Sugg, rhs: &Sugg) -> Sugg<'static> {
316     make_assoc(AssocOp::from_ast_binop(op), lhs, rhs)
317 }
318
319 #[derive(PartialEq, Eq, Clone, Copy)]
320 /// Operator associativity.
321 enum Associativity {
322     /// The operator is both left-associative and right-associative.
323     Both,
324     /// The operator is left-associative.
325     Left,
326     /// The operator is not associative.
327     None,
328     /// The operator is right-associative.
329     Right,
330 }
331
332 /// Return the associativity/fixity of an operator. The difference with
333 /// `AssocOp::fixity` is that
334 /// an operator can be both left and right associative (such as `+`:
335 /// `a + b + c == (a + b) + c == a + (b + c)`.
336 ///
337 /// Chained `as` and explicit `:` type coercion never need inner parenthesis so
338 /// they are considered
339 /// associative.
340 fn associativity(op: &AssocOp) -> Associativity {
341     use syntax::util::parser::AssocOp::*;
342
343     match *op {
344         Inplace | Assign | AssignOp(_) => Associativity::Right,
345         Add | BitAnd | BitOr | BitXor | LAnd | LOr | Multiply | As | Colon => Associativity::Both,
346         Divide | Equal | Greater | GreaterEqual | Less | LessEqual | Modulus | NotEqual | ShiftLeft | ShiftRight |
347         Subtract => Associativity::Left,
348         DotDot | DotDotDot => Associativity::None,
349     }
350 }
351
352 /// Convert a `hir::BinOp` to the corresponding assigning binary operator.
353 fn hirbinop2assignop(op: hir::BinOp) -> AssocOp {
354     use rustc::hir::BinOp_::*;
355     use syntax::parse::token::BinOpToken::*;
356
357     AssocOp::AssignOp(match op.node {
358         BiAdd => Plus,
359         BiBitAnd => And,
360         BiBitOr => Or,
361         BiBitXor => Caret,
362         BiDiv => Slash,
363         BiMul => Star,
364         BiRem => Percent,
365         BiShl => Shl,
366         BiShr => Shr,
367         BiSub => Minus,
368         BiAnd | BiEq | BiGe | BiGt | BiLe | BiLt | BiNe | BiOr => panic!("This operator does not exist"),
369     })
370 }
371
372 /// Convert an `ast::BinOp` to the corresponding assigning binary operator.
373 fn astbinop2assignop(op: ast::BinOp) -> AssocOp {
374     use syntax::ast::BinOpKind::*;
375     use syntax::parse::token::BinOpToken;
376
377     AssocOp::AssignOp(match op.node {
378         Add => BinOpToken::Plus,
379         BitAnd => BinOpToken::And,
380         BitOr => BinOpToken::Or,
381         BitXor => BinOpToken::Caret,
382         Div => BinOpToken::Slash,
383         Mul => BinOpToken::Star,
384         Rem => BinOpToken::Percent,
385         Shl => BinOpToken::Shl,
386         Shr => BinOpToken::Shr,
387         Sub => BinOpToken::Minus,
388         And | Eq | Ge | Gt | Le | Lt | Ne | Or => panic!("This operator does not exist"),
389     })
390 }
391
392 /// Return the indentation before `span` if there are nothing but `[ \t]`
393 /// before it on its line.
394 fn indentation<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Option<String> {
395     let lo = cx.sess().codemap().lookup_char_pos(span.lo);
396     if let Some(line) = lo.file.get_line(
397         lo.line - 1, /* line numbers in `Loc` are 1-based */
398     )
399     {
400         if let Some((pos, _)) = line.char_indices().find(|&(_, c)| c != ' ' && c != '\t') {
401             // we can mix char and byte positions here because we only consider `[ \t]`
402             if lo.col == CharPos(pos) {
403                 Some(line[..pos].into())
404             } else {
405                 None
406             }
407         } else {
408             None
409         }
410     } else {
411         None
412     }
413 }
414
415 /// Convenience extension trait for `DiagnosticBuilder`.
416 pub trait DiagnosticBuilderExt<'a, T: LintContext<'a>> {
417     /// Suggests to add an attribute to an item.
418     ///
419     /// Correctly handles indentation of the attribute and item.
420     ///
421     /// # Example
422     ///
423     /// ```rust,ignore
424     /// db.suggest_item_with_attr(cx, item, "#[derive(Default)]");
425     /// ```
426     fn suggest_item_with_attr<D: Display + ?Sized>(&mut self, cx: &T, item: Span, msg: &str, attr: &D);
427
428     /// Suggest to add an item before another.
429     ///
430     /// The item should not be indented (expect for inner indentation).
431     ///
432     /// # Example
433     ///
434     /// ```rust,ignore
435     /// db.suggest_prepend_item(cx, item,
436     /// "fn foo() {
437     ///     bar();
438     /// }");
439     /// ```
440     fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str);
441 }
442
443 impl<'a, 'b, 'c, T: LintContext<'c>> DiagnosticBuilderExt<'c, T> for rustc_errors::DiagnosticBuilder<'b> {
444     fn suggest_item_with_attr<D: Display + ?Sized>(&mut self, cx: &T, item: Span, msg: &str, attr: &D) {
445         if let Some(indent) = indentation(cx, item) {
446             let span = Span {
447                 hi: item.lo,
448                 ..item
449             };
450
451             self.span_suggestion(span, msg, format!("{}\n{}", attr, indent));
452         }
453     }
454
455     fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str) {
456         if let Some(indent) = indentation(cx, item) {
457             let span = Span {
458                 hi: item.lo,
459                 ..item
460             };
461
462             let mut first = true;
463             let new_item = new_item
464                 .lines()
465                 .map(|l| if first {
466                     first = false;
467                     format!("{}\n", l)
468                 } else {
469                     format!("{}{}\n", indent, l)
470                 })
471                 .collect::<String>();
472
473             self.span_suggestion(span, msg, format!("{}\n{}", new_item, indent));
474         }
475     }
476 }