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