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