2 use rustc::lint::{EarlyContext, LateContext};
6 use syntax::util::parser::AssocOp;
7 use utils::{higher, snippet, snippet_opt};
8 use syntax::print::pprust::binop_to_string;
10 /// A helper type to build suggestion correctly handling parenthesis.
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>),
20 /// Literal constant `1`, for convenience.
21 pub const ONE: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("1"));
23 impl<'a> std::fmt::Display for Sugg<'a> {
24 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
26 Sugg::NonParen(ref s) | Sugg::MaybeParen(ref s) | Sugg::BinOp(_, ref s) => {
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);
40 hir::ExprClosure(..) |
43 hir::ExprMatch(..) => Sugg::MaybeParen(snippet),
50 hir::ExprInlineAsm(..) |
53 hir::ExprMethodCall(..) |
59 hir::ExprTupField(..) |
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),
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)))
75 pub fn ast(cx: &EarlyContext, expr: &ast::Expr, default: &'a str) -> Sugg<'a> {
76 use syntax::ast::RangeLimits;
78 let snippet = snippet(cx, expr.span, default);
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),
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)
127 /// Convenience method to create the `&<expr>` suggestion.
128 pub fn addr(self) -> Sugg<'static> {
132 /// Convenience method to create the `&mut <expr>` suggestion.
133 pub fn mut_addr(self) -> Sugg<'static> {
134 make_unop("&mut ", self)
137 /// Convenience method to create the `<lhs>..<rhs>` or `<lhs>...<rhs>` suggestion.
138 pub fn range(self, end: Self, limit: ast::RangeLimits) -> Sugg<'static> {
140 ast::RangeLimits::HalfOpen => make_assoc(AssocOp::DotDot, &self, &end),
141 ast::RangeLimits::Closed => make_assoc(AssocOp::DotDotDot, &self, &end),
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 {
149 Sugg::NonParen(..) => self,
150 Sugg::MaybeParen(sugg) | Sugg::BinOp(_, sugg) => Sugg::NonParen(format!("({})", sugg).into()),
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)
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)
169 impl<'a> std::ops::Not for Sugg<'a> {
170 type Output = Sugg<'static>;
171 fn not(self) -> Sugg<'static> {
176 struct ParenHelper<T> {
181 impl<T> ParenHelper<T> {
182 fn new(paren: bool, wrapped: T) -> Self {
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> {
193 write!(f, "({})", self.wrapped)
200 /// Build the string for `<op><expr>` adding parenthesis when necessary.
202 /// For convenience, the operator is taken as a string because all unary operators have the same
204 pub fn make_unop(op: &str, expr: Sugg) -> Sugg<'static> {
205 Sugg::MaybeParen(format!("{}{}", op, expr.maybe_par()).into())
208 /// Build the string for `<lhs> <op> <rhs>` adding parenthesis when necessary.
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)
217 fn is_arith(op: &AssocOp) -> bool {
218 matches!(*op, AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide | AssocOp::Modulus)
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)
230 let lhs_paren = if let Sugg::BinOp(ref lop, _) = *lhs {
231 needs_paren(&op, lop, Associativity::Left)
236 let rhs_paren = if let Sugg::BinOp(ref rop, _) = *rhs {
237 needs_paren(&op, rop, Associativity::Right)
242 let lhs = ParenHelper::new(lhs_paren, lhs);
243 let rhs = ParenHelper::new(rhs_paren, rhs);
244 let sugg = match op {
252 AssocOp::GreaterEqual |
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),
272 Sugg::BinOp(op, sugg.into())
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)
280 #[derive(PartialEq, Eq)]
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)`.
292 /// Chained `as` and explicit `:` type coercion never need inner parenthesis so they are considered
294 fn associativity(op: &AssocOp) -> Associativity {
295 use syntax::util::parser::AssocOp::*;
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
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::*;
312 AssocOp::AssignOp(match op.node {
323 BiAnd | BiEq | BiGe | BiGt | BiLe | BiLt | BiNe | BiOr => panic!("This operator does not exist"),
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;
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"),