]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/sugg.rs
Merge branch 'master' into sugg
[rust.git] / clippy_lints / src / utils / sugg.rs
1 use rustc::hir;
2 use rustc::lint::{EarlyContext, LateContext};
3 use std::borrow::Cow;
4 use std;
5 use syntax::ast;
6 use syntax::util::parser::AssocOp;
7 use utils::{higher, snippet, snippet_opt};
8 use syntax::print::pprust::binop_to_string;
9
10 /// A helper type to build suggestion correctly handling parenthesis.
11 pub enum Sugg<'a> {
12     /// An expression that never needs parenthesis such as `1337` or `[0; 42]`.
13     NonParen(Cow<'a, str>),
14     /// An expression that does not fit in other variants.
15     MaybeParen(Cow<'a, str>),
16     /// A binary operator expression, including `as`-casts and explicit type coercion.
17     BinOp(AssocOp, Cow<'a, str>),
18 }
19
20 /// Literal constant `1`, for convenience.
21 pub const ONE: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("1"));
22
23 impl<'a> std::fmt::Display for Sugg<'a> {
24     fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
25         match *self {
26             Sugg::NonParen(ref s) | Sugg::MaybeParen(ref s) | Sugg::BinOp(_, ref s) => {
27                 s.fmt(f)
28             }
29         }
30     }
31 }
32
33 impl<'a> Sugg<'a> {
34     pub fn hir_opt(cx: &LateContext, expr: &hir::Expr) -> Option<Sugg<'a>> {
35         snippet_opt(cx, expr.span).map(|snippet| {
36             let snippet = Cow::Owned(snippet);
37             match expr.node {
38                 hir::ExprAddrOf(..) |
39                 hir::ExprBox(..) |
40                 hir::ExprClosure(..) |
41                 hir::ExprIf(..) |
42                 hir::ExprUnary(..) |
43                 hir::ExprMatch(..) => Sugg::MaybeParen(snippet),
44                 hir::ExprAgain(..) |
45                 hir::ExprBlock(..) |
46                 hir::ExprBreak(..) |
47                 hir::ExprCall(..) |
48                 hir::ExprField(..) |
49                 hir::ExprIndex(..) |
50                 hir::ExprInlineAsm(..) |
51                 hir::ExprLit(..) |
52                 hir::ExprLoop(..) |
53                 hir::ExprMethodCall(..) |
54                 hir::ExprPath(..) |
55                 hir::ExprRepeat(..) |
56                 hir::ExprRet(..) |
57                 hir::ExprStruct(..) |
58                 hir::ExprTup(..) |
59                 hir::ExprTupField(..) |
60                 hir::ExprVec(..) |
61                 hir::ExprWhile(..) => Sugg::NonParen(snippet),
62                 hir::ExprAssign(..) => Sugg::BinOp(AssocOp::Assign, snippet),
63                 hir::ExprAssignOp(op, ..) => Sugg::BinOp(hirbinop2assignop(op), snippet),
64                 hir::ExprBinary(op, ..) => Sugg::BinOp(AssocOp::from_ast_binop(higher::binop(op.node)), snippet),
65                 hir::ExprCast(..) => Sugg::BinOp(AssocOp::As, snippet),
66                 hir::ExprType(..) => Sugg::BinOp(AssocOp::Colon, snippet),
67             }
68         })
69     }
70
71     pub fn hir(cx: &LateContext, expr: &hir::Expr, default: &'a str) -> Sugg<'a> {
72         Self::hir_opt(cx, expr).unwrap_or_else(|| Sugg::NonParen(Cow::Borrowed(default)))
73     }
74
75     pub fn ast(cx: &EarlyContext, expr: &ast::Expr, default: &'a str) -> Sugg<'a> {
76         use syntax::ast::RangeLimits;
77
78         let snippet = snippet(cx, expr.span, default);
79
80         match expr.node {
81             ast::ExprKind::AddrOf(..) |
82             ast::ExprKind::Box(..) |
83             ast::ExprKind::Closure(..) |
84             ast::ExprKind::If(..) |
85             ast::ExprKind::IfLet(..) |
86             ast::ExprKind::InPlace(..) |
87             ast::ExprKind::Unary(..) |
88             ast::ExprKind::Match(..) => Sugg::MaybeParen(snippet),
89             ast::ExprKind::Block(..) |
90             ast::ExprKind::Break(..) |
91             ast::ExprKind::Call(..) |
92             ast::ExprKind::Continue(..) |
93             ast::ExprKind::Field(..) |
94             ast::ExprKind::ForLoop(..) |
95             ast::ExprKind::Index(..) |
96             ast::ExprKind::InlineAsm(..) |
97             ast::ExprKind::Lit(..) |
98             ast::ExprKind::Loop(..) |
99             ast::ExprKind::Mac(..) |
100             ast::ExprKind::MethodCall(..) |
101             ast::ExprKind::Paren(..) |
102             ast::ExprKind::Path(..) |
103             ast::ExprKind::Repeat(..) |
104             ast::ExprKind::Ret(..) |
105             ast::ExprKind::Struct(..) |
106             ast::ExprKind::Try(..) |
107             ast::ExprKind::Tup(..) |
108             ast::ExprKind::TupField(..) |
109             ast::ExprKind::Vec(..) |
110             ast::ExprKind::While(..) |
111             ast::ExprKind::WhileLet(..) => Sugg::NonParen(snippet),
112             ast::ExprKind::Range(.., RangeLimits::HalfOpen) => Sugg::BinOp(AssocOp::DotDot, snippet),
113             ast::ExprKind::Range(.., RangeLimits::Closed) => Sugg::BinOp(AssocOp::DotDotDot, snippet),
114             ast::ExprKind::Assign(..) => Sugg::BinOp(AssocOp::Assign, snippet),
115             ast::ExprKind::AssignOp(op, ..) => Sugg::BinOp(astbinop2assignop(op), snippet),
116             ast::ExprKind::Binary(op, ..) => Sugg::BinOp(AssocOp::from_ast_binop(op.node), snippet),
117             ast::ExprKind::Cast(..) => Sugg::BinOp(AssocOp::As, snippet),
118             ast::ExprKind::Type(..) => Sugg::BinOp(AssocOp::Colon, snippet),
119         }
120     }
121
122     /// Convenience method to create the `<lhs> && <rhs>` suggestion.
123     pub fn and(self, rhs: Self) -> Sugg<'static> {
124         make_binop(ast::BinOpKind::And, &self, &rhs)
125     }
126
127     /// Convenience method to create the `&<expr>` suggestion.
128     pub fn addr(self) -> Sugg<'static> {
129         make_unop("&", self)
130     }
131
132     /// Convenience method to create the `&mut <expr>` suggestion.
133     pub fn mut_addr(self) -> Sugg<'static> {
134         make_unop("&mut ", self)
135     }
136
137     /// Convenience method to create the `*<expr>` suggestion.
138     pub fn deref(self) -> Sugg<'static> {
139         make_unop("*", self)
140     }
141
142     /// Convenience method to create the `<lhs>..<rhs>` or `<lhs>...<rhs>` suggestion.
143     pub fn range(self, end: Self, limit: ast::RangeLimits) -> Sugg<'static> {
144         match limit {
145             ast::RangeLimits::HalfOpen => make_assoc(AssocOp::DotDot, &self, &end),
146             ast::RangeLimits::Closed => make_assoc(AssocOp::DotDotDot, &self, &end),
147         }
148     }
149
150     /// Add parenthesis to any expression that might need them. Suitable to the `self` argument of
151     /// a method call (eg. to build `bar.foo()` or `(1 + 2).foo()`).
152     pub fn maybe_par(self) -> Self {
153         match self {
154             Sugg::NonParen(..) => self,
155             Sugg::MaybeParen(sugg) | Sugg::BinOp(_, sugg) => Sugg::NonParen(format!("({})", sugg).into()),
156         }
157     }
158 }
159
160 impl<'a, 'b> std::ops::Add<Sugg<'b>> for Sugg<'a> {
161     type Output = Sugg<'static>;
162     fn add(self, rhs: Sugg<'b>) -> Sugg<'static> {
163         make_binop(ast::BinOpKind::Add, &self, &rhs)
164     }
165 }
166
167 impl<'a, 'b> std::ops::Sub<Sugg<'b>> for Sugg<'a> {
168     type Output = Sugg<'static>;
169     fn sub(self, rhs: Sugg<'b>) -> Sugg<'static> {
170         make_binop(ast::BinOpKind::Sub, &self, &rhs)
171     }
172 }
173
174 impl<'a> std::ops::Not for Sugg<'a> {
175     type Output = Sugg<'static>;
176     fn not(self) -> Sugg<'static> {
177         make_unop("!", self)
178     }
179 }
180
181 struct ParenHelper<T> {
182     paren: bool,
183     wrapped: T,
184 }
185
186 impl<T> ParenHelper<T> {
187     fn new(paren: bool, wrapped: T) -> Self {
188         ParenHelper {
189             paren: paren,
190             wrapped: wrapped,
191         }
192     }
193 }
194
195 impl<T: std::fmt::Display> std::fmt::Display for ParenHelper<T> {
196     fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
197         if self.paren {
198             write!(f, "({})", self.wrapped)
199         } else {
200             self.wrapped.fmt(f)
201         }
202     }
203 }
204
205 /// Build the string for `<op><expr>` adding parenthesis when necessary.
206 ///
207 /// For convenience, the operator is taken as a string because all unary operators have the same
208 /// precedence.
209 pub fn make_unop(op: &str, expr: Sugg) -> Sugg<'static> {
210     Sugg::MaybeParen(format!("{}{}", op, expr.maybe_par()).into())
211 }
212
213 /// Build the string for `<lhs> <op> <rhs>` adding parenthesis when necessary.
214 ///
215 /// Precedence of shift operator relative to other arithmetic operation is often confusing so
216 /// parenthesis will always be added for a mix of these.
217 pub fn make_assoc(op: AssocOp, lhs: &Sugg, rhs: &Sugg) -> Sugg<'static> {
218     fn is_shift(op: &AssocOp) -> bool {
219         matches!(*op, AssocOp::ShiftLeft | AssocOp::ShiftRight)
220     }
221
222     fn is_arith(op: &AssocOp) -> bool {
223         matches!(*op, AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide | AssocOp::Modulus)
224     }
225
226     fn needs_paren(op: &AssocOp, other: &AssocOp, dir: Associativity) -> bool {
227         other.precedence() < op.precedence() ||
228             (other.precedence() == op.precedence() &&
229                 ((op != other && associativity(op) != dir) ||
230                  (op == other && associativity(op) != Associativity::Both))) ||
231              is_shift(op) && is_arith(other) ||
232              is_shift(other) && is_arith(op)
233     }
234
235     let lhs_paren = if let Sugg::BinOp(ref lop, _) = *lhs {
236         needs_paren(&op, lop, Associativity::Left)
237     } else {
238         false
239     };
240
241     let rhs_paren = if let Sugg::BinOp(ref rop, _) = *rhs {
242         needs_paren(&op, rop, Associativity::Right)
243     } else {
244         false
245     };
246
247     let lhs = ParenHelper::new(lhs_paren, lhs);
248     let rhs = ParenHelper::new(rhs_paren, rhs);
249     let sugg = match op {
250         AssocOp::Add |
251         AssocOp::BitAnd |
252         AssocOp::BitOr |
253         AssocOp::BitXor |
254         AssocOp::Divide |
255         AssocOp::Equal |
256         AssocOp::Greater |
257         AssocOp::GreaterEqual |
258         AssocOp::LAnd |
259         AssocOp::LOr |
260         AssocOp::Less |
261         AssocOp::LessEqual |
262         AssocOp::Modulus |
263         AssocOp::Multiply |
264         AssocOp::NotEqual |
265         AssocOp::ShiftLeft |
266         AssocOp::ShiftRight |
267         AssocOp::Subtract => format!("{} {} {}", lhs, op.to_ast_binop().expect("Those are AST ops").to_string(), rhs),
268         AssocOp::Inplace => format!("in ({}) {}", lhs, rhs),
269         AssocOp::Assign => format!("{} = {}", lhs, rhs),
270         AssocOp::AssignOp(op) => format!("{} {}= {}", lhs, binop_to_string(op), rhs),
271         AssocOp::As => format!("{} as {}", lhs, rhs),
272         AssocOp::DotDot => format!("{}..{}", lhs, rhs),
273         AssocOp::DotDotDot => format!("{}...{}", lhs, rhs),
274         AssocOp::Colon => format!("{}: {}", lhs, rhs),
275     };
276
277     Sugg::BinOp(op, sugg.into())
278 }
279
280 /// Convinience wrapper arround `make_assoc` and `AssocOp::from_ast_binop`.
281 pub fn make_binop(op: ast::BinOpKind, lhs: &Sugg, rhs: &Sugg) -> Sugg<'static> {
282     make_assoc(AssocOp::from_ast_binop(op), lhs, rhs)
283 }
284
285 #[derive(PartialEq, Eq)]
286 enum Associativity {
287     Both,
288     Left,
289     None,
290     Right,
291 }
292
293 /// Return the associativity/fixity of an operator. The difference with `AssocOp::fixity` is that
294 /// an operator can be both left and right associative (such as `+`:
295 /// `a + b + c == (a + b) + c == a + (b + c)`.
296 ///
297 /// Chained `as` and explicit `:` type coercion never need inner parenthesis so they are considered
298 /// associative.
299 fn associativity(op: &AssocOp) -> Associativity {
300     use syntax::util::parser::AssocOp::*;
301
302     match *op {
303         Inplace | Assign | AssignOp(_) => Associativity::Right,
304         Add | BitAnd | BitOr | BitXor | LAnd | LOr | Multiply |
305         As | Colon => Associativity::Both,
306     Divide | Equal | Greater | GreaterEqual | Less | LessEqual | Modulus | NotEqual | ShiftLeft |
307         ShiftRight | Subtract => Associativity::Left,
308         DotDot | DotDotDot => Associativity::None
309     }
310 }
311
312 /// Convert a `hir::BinOp` to the corresponding assigning binary operator.
313 fn hirbinop2assignop(op: hir::BinOp) -> AssocOp {
314     use rustc::hir::BinOp_::*;
315     use syntax::parse::token::BinOpToken::*;
316
317     AssocOp::AssignOp(match op.node {
318         BiAdd => Plus,
319         BiBitAnd => And,
320         BiBitOr => Or,
321         BiBitXor => Caret,
322         BiDiv => Slash,
323         BiMul => Star,
324         BiRem => Percent,
325         BiShl => Shl,
326         BiShr => Shr,
327         BiSub => Minus,
328         BiAnd | BiEq | BiGe | BiGt | BiLe | BiLt | BiNe | BiOr => panic!("This operator does not exist"),
329     })
330 }
331
332 /// Convert an `ast::BinOp` to the corresponding assigning binary operator.
333 fn astbinop2assignop(op: ast::BinOp) -> AssocOp {
334     use syntax::ast::BinOpKind::*;
335     use syntax::parse::token::BinOpToken;
336
337     AssocOp::AssignOp(match op.node {
338         Add => BinOpToken::Plus,
339         BitAnd => BinOpToken::And,
340         BitOr => BinOpToken::Or,
341         BitXor => BinOpToken::Caret,
342         Div => BinOpToken::Slash,
343         Mul => BinOpToken::Star,
344         Rem => BinOpToken::Percent,
345         Shl => BinOpToken::Shl,
346         Shr => BinOpToken::Shr,
347         Sub => BinOpToken::Minus,
348         And | Eq | Ge | Gt | Le | Lt | Ne | Or => panic!("This operator does not exist"),
349     })
350 }