]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/sugg.rs
Use `utils::sugg` in swap lints
[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 `<lhs>..<rhs>` or `<lhs>...<rhs>` suggestion.
138     pub fn range(self, end: Self, limit: ast::RangeLimits) -> Sugg<'static> {
139         match limit {
140             ast::RangeLimits::HalfOpen => make_assoc(AssocOp::DotDot, &self, &end),
141             ast::RangeLimits::Closed => make_assoc(AssocOp::DotDotDot, &self, &end),
142         }
143     }
144
145     /// Add parenthesis to any expression that might need them. Suitable to the `self` argument of
146     /// a method call (eg. to build `bar.foo()` or `(1 + 2).foo()`).
147     pub fn maybe_par(self) -> Self {
148         match self {
149             Sugg::NonParen(..) => self,
150             Sugg::MaybeParen(sugg) | Sugg::BinOp(_, sugg) => Sugg::NonParen(format!("({})", sugg).into()),
151         }
152     }
153 }
154
155 impl<'a, 'b> std::ops::Add<Sugg<'b>> for Sugg<'a> {
156     type Output = Sugg<'static>;
157     fn add(self, rhs: Sugg<'b>) -> Sugg<'static> {
158         make_binop(ast::BinOpKind::Add, &self, &rhs)
159     }
160 }
161
162 impl<'a, 'b> std::ops::Sub<Sugg<'b>> for Sugg<'a> {
163     type Output = Sugg<'static>;
164     fn sub(self, rhs: Sugg<'b>) -> Sugg<'static> {
165         make_binop(ast::BinOpKind::Sub, &self, &rhs)
166     }
167 }
168
169 impl<'a> std::ops::Not for Sugg<'a> {
170     type Output = Sugg<'static>;
171     fn not(self) -> Sugg<'static> {
172         make_unop("!", self)
173     }
174 }
175
176 struct ParenHelper<T> {
177     paren: bool,
178     wrapped: T,
179 }
180
181 impl<T> ParenHelper<T> {
182     fn new(paren: bool, wrapped: T) -> Self {
183         ParenHelper {
184             paren: paren,
185             wrapped: wrapped,
186         }
187     }
188 }
189
190 impl<T: std::fmt::Display> std::fmt::Display for ParenHelper<T> {
191     fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
192         if self.paren {
193             write!(f, "({})", self.wrapped)
194         } else {
195             self.wrapped.fmt(f)
196         }
197     }
198 }
199
200 /// Build the string for `<op><expr>` adding parenthesis when necessary.
201 ///
202 /// For convenience, the operator is taken as a string because all unary operators have the same
203 /// precedence.
204 pub fn make_unop(op: &str, expr: Sugg) -> Sugg<'static> {
205     Sugg::MaybeParen(format!("{}{}", op, expr.maybe_par()).into())
206 }
207
208 /// Build the string for `<lhs> <op> <rhs>` adding parenthesis when necessary.
209 ///
210 /// Precedence of shift operator relative to other arithmetic operation is often confusing so
211 /// parenthesis will always be added for a mix of these.
212 pub fn make_assoc(op: AssocOp, lhs: &Sugg, rhs: &Sugg) -> Sugg<'static> {
213     fn is_shift(op: &AssocOp) -> bool {
214         matches!(*op, AssocOp::ShiftLeft | AssocOp::ShiftRight)
215     }
216
217     fn is_arith(op: &AssocOp) -> bool {
218         matches!(*op, AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide | AssocOp::Modulus)
219     }
220
221     fn needs_paren(op: &AssocOp, other: &AssocOp, dir: Associativity) -> bool {
222         other.precedence() < op.precedence() ||
223             (other.precedence() == op.precedence() &&
224                 ((op != other && associativity(op) != dir) ||
225                  (op == other && associativity(op) != Associativity::Both))) ||
226              is_shift(op) && is_arith(other) ||
227              is_shift(other) && is_arith(op)
228     }
229
230     let lhs_paren = if let Sugg::BinOp(ref lop, _) = *lhs {
231         needs_paren(&op, lop, Associativity::Left)
232     } else {
233         false
234     };
235
236     let rhs_paren = if let Sugg::BinOp(ref rop, _) = *rhs {
237         needs_paren(&op, rop, Associativity::Right)
238     } else {
239         false
240     };
241
242     let lhs = ParenHelper::new(lhs_paren, lhs);
243     let rhs = ParenHelper::new(rhs_paren, rhs);
244     let sugg = match op {
245         AssocOp::Add |
246         AssocOp::BitAnd |
247         AssocOp::BitOr |
248         AssocOp::BitXor |
249         AssocOp::Divide |
250         AssocOp::Equal |
251         AssocOp::Greater |
252         AssocOp::GreaterEqual |
253         AssocOp::LAnd |
254         AssocOp::LOr |
255         AssocOp::Less |
256         AssocOp::LessEqual |
257         AssocOp::Modulus |
258         AssocOp::Multiply |
259         AssocOp::NotEqual |
260         AssocOp::ShiftLeft |
261         AssocOp::ShiftRight |
262         AssocOp::Subtract => format!("{} {} {}", lhs, op.to_ast_binop().expect("Those are AST ops").to_string(), rhs),
263         AssocOp::Inplace => format!("in ({}) {}", lhs, rhs),
264         AssocOp::Assign => format!("{} = {}", lhs, rhs),
265         AssocOp::AssignOp(op) => format!("{} {}= {}", lhs, binop_to_string(op), rhs),
266         AssocOp::As => format!("{} as {}", lhs, rhs),
267         AssocOp::DotDot => format!("{}..{}", lhs, rhs),
268         AssocOp::DotDotDot => format!("{}...{}", lhs, rhs),
269         AssocOp::Colon => format!("{}: {}", lhs, rhs),
270     };
271
272     Sugg::BinOp(op, sugg.into())
273 }
274
275 /// Convinience wrapper arround `make_assoc` and `AssocOp::from_ast_binop`.
276 pub fn make_binop(op: ast::BinOpKind, lhs: &Sugg, rhs: &Sugg) -> Sugg<'static> {
277     make_assoc(AssocOp::from_ast_binop(op), lhs, rhs)
278 }
279
280 #[derive(PartialEq, Eq)]
281 enum Associativity {
282     Both,
283     Left,
284     None,
285     Right,
286 }
287
288 /// Return the associativity/fixity of an operator. The difference with `AssocOp::fixity` is that
289 /// an operator can be both left and right associative (such as `+`:
290 /// `a + b + c == (a + b) + c == a + (b + c)`.
291 ///
292 /// Chained `as` and explicit `:` type coercion never need inner parenthesis so they are considered
293 /// associative.
294 fn associativity(op: &AssocOp) -> Associativity {
295     use syntax::util::parser::AssocOp::*;
296
297     match *op {
298         Inplace | Assign | AssignOp(_) => Associativity::Right,
299         Add | BitAnd | BitOr | BitXor | LAnd | LOr | Multiply |
300         As | Colon => Associativity::Both,
301     Divide | Equal | Greater | GreaterEqual | Less | LessEqual | Modulus | NotEqual | ShiftLeft |
302         ShiftRight | Subtract => Associativity::Left,
303         DotDot | DotDotDot => Associativity::None
304     }
305 }
306
307 /// Convert a `hir::BinOp` to the corresponding assigning binary operator.
308 fn hirbinop2assignop(op: hir::BinOp) -> AssocOp {
309     use rustc::hir::BinOp_::*;
310     use syntax::parse::token::BinOpToken::*;
311
312     AssocOp::AssignOp(match op.node {
313         BiAdd => Plus,
314         BiBitAnd => And,
315         BiBitOr => Or,
316         BiBitXor => Caret,
317         BiDiv => Slash,
318         BiMul => Star,
319         BiRem => Percent,
320         BiShl => Shl,
321         BiShr => Shr,
322         BiSub => Minus,
323         BiAnd | BiEq | BiGe | BiGt | BiLe | BiLt | BiNe | BiOr => panic!("This operator does not exist"),
324     })
325 }
326
327 /// Convert an `ast::BinOp` to the corresponding assigning binary operator.
328 fn astbinop2assignop(op: ast::BinOp) -> AssocOp {
329     use syntax::ast::BinOpKind::*;
330     use syntax::parse::token::BinOpToken;
331
332     AssocOp::AssignOp(match op.node {
333         Add => BinOpToken::Plus,
334         BitAnd => BinOpToken::And,
335         BitOr => BinOpToken::Or,
336         BitXor => BinOpToken::Caret,
337         Div => BinOpToken::Slash,
338         Mul => BinOpToken::Star,
339         Rem => BinOpToken::Percent,
340         Shl => BinOpToken::Shl,
341         Shr => BinOpToken::Shr,
342         Sub => BinOpToken::Minus,
343         And | Eq | Ge | Gt | Le | Lt | Ne | Or => panic!("This operator does not exist"),
344     })
345 }