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) => {
33 #[allow(wrong_self_convention)] // ok, because of the function `as_ty` method
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);
41 hir::ExprClosure(..) |
44 hir::ExprMatch(..) => Sugg::MaybeParen(snippet),
51 hir::ExprInlineAsm(..) |
54 hir::ExprMethodCall(..) |
60 hir::ExprTupField(..) |
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),
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)))
76 pub fn ast(cx: &EarlyContext, expr: &ast::Expr, default: &'a str) -> Sugg<'a> {
77 use syntax::ast::RangeLimits;
79 let snippet = snippet(cx, expr.span, default);
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),
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)
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()))
133 /// Convenience method to create the `&<expr>` suggestion.
134 pub fn addr(self) -> Sugg<'static> {
138 /// Convenience method to create the `&mut <expr>` suggestion.
139 pub fn mut_addr(self) -> Sugg<'static> {
140 make_unop("&mut ", self)
143 /// Convenience method to create the `*<expr>` suggestion.
144 pub fn deref(self) -> Sugg<'static> {
148 /// Convenience method to create the `<lhs>..<rhs>` or `<lhs>...<rhs>` suggestion.
149 pub fn range(self, end: Self, limit: ast::RangeLimits) -> Sugg<'static> {
151 ast::RangeLimits::HalfOpen => make_assoc(AssocOp::DotDot, &self, &end),
152 ast::RangeLimits::Closed => make_assoc(AssocOp::DotDotDot, &self, &end),
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 {
160 Sugg::NonParen(..) => self,
161 Sugg::MaybeParen(sugg) | Sugg::BinOp(_, sugg) => Sugg::NonParen(format!("({})", sugg).into()),
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)
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)
180 impl<'a> std::ops::Not for Sugg<'a> {
181 type Output = Sugg<'static>;
182 fn not(self) -> Sugg<'static> {
187 struct ParenHelper<T> {
192 impl<T> ParenHelper<T> {
193 fn new(paren: bool, wrapped: T) -> Self {
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> {
204 write!(f, "({})", self.wrapped)
211 /// Build the string for `<op><expr>` adding parenthesis when necessary.
213 /// For convenience, the operator is taken as a string because all unary operators have the same
215 pub fn make_unop(op: &str, expr: Sugg) -> Sugg<'static> {
216 Sugg::MaybeParen(format!("{}{}", op, expr.maybe_par()).into())
219 /// Build the string for `<lhs> <op> <rhs>` adding parenthesis when necessary.
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)
228 fn is_arith(op: &AssocOp) -> bool {
229 matches!(*op, AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide | AssocOp::Modulus)
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)
241 let lhs_paren = if let Sugg::BinOp(ref lop, _) = *lhs {
242 needs_paren(&op, lop, Associativity::Left)
247 let rhs_paren = if let Sugg::BinOp(ref rop, _) = *rhs {
248 needs_paren(&op, rop, Associativity::Right)
253 let lhs = ParenHelper::new(lhs_paren, lhs);
254 let rhs = ParenHelper::new(rhs_paren, rhs);
255 let sugg = match op {
263 AssocOp::GreaterEqual |
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),
283 Sugg::BinOp(op, sugg.into())
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)
291 #[derive(PartialEq, Eq)]
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)`.
303 /// Chained `as` and explicit `:` type coercion never need inner parenthesis so they are considered
305 fn associativity(op: &AssocOp) -> Associativity {
306 use syntax::util::parser::AssocOp::*;
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
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::*;
323 AssocOp::AssignOp(match op.node {
334 BiAnd | BiEq | BiGe | BiGt | BiLe | BiLt | BiNe | BiOr => panic!("This operator does not exist"),
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;
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"),