Skip to content

Commit c79cea1

Browse files
authored
Merge pull request #1643 from dtolnay/chainedcompare
Require parens for chained comparison binops
2 parents da509d5 + dc4ffde commit c79cea1

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

src/expr.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1400,6 +1400,13 @@ pub(crate) mod parsing {
14001400
if precedence < base {
14011401
break;
14021402
}
1403+
if precedence == Precedence::Compare {
1404+
if let Expr::Binary(lhs) = &lhs {
1405+
if Precedence::of(&lhs.op) == Precedence::Compare {
1406+
break;
1407+
}
1408+
}
1409+
}
14031410
input.advance_to(&ahead);
14041411
let right = parse_binop_rhs(input, allow_struct, precedence)?;
14051412
lhs = Expr::Binary(ExprBinary {
@@ -1455,6 +1462,13 @@ pub(crate) mod parsing {
14551462
if precedence < base {
14561463
break;
14571464
}
1465+
if precedence == Precedence::Compare {
1466+
if let Expr::Binary(lhs) = &lhs {
1467+
if Precedence::of(&lhs.op) == Precedence::Compare {
1468+
break;
1469+
}
1470+
}
1471+
}
14581472
input.advance_to(&ahead);
14591473
let right = parse_binop_rhs(input, precedence)?;
14601474
lhs = Expr::Binary(ExprBinary {

tests/test_expr.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -577,6 +577,38 @@ fn test_tuple_comma() {
577577
"###);
578578
}
579579

580+
#[test]
581+
fn test_binop_associativity() {
582+
// Left to right.
583+
snapshot!("() + () + ()" as Expr, @r###"
584+
Expr::Binary {
585+
left: Expr::Binary {
586+
left: Expr::Tuple,
587+
op: BinOp::Add,
588+
right: Expr::Tuple,
589+
},
590+
op: BinOp::Add,
591+
right: Expr::Tuple,
592+
}
593+
"###);
594+
595+
// Right to left.
596+
snapshot!("() += () += ()" as Expr, @r###"
597+
Expr::Binary {
598+
left: Expr::Tuple,
599+
op: BinOp::AddAssign,
600+
right: Expr::Binary {
601+
left: Expr::Tuple,
602+
op: BinOp::AddAssign,
603+
right: Expr::Tuple,
604+
},
605+
}
606+
"###);
607+
608+
// Parenthesization is required.
609+
syn::parse_str::<Expr>("() == () == ()").unwrap_err();
610+
}
611+
580612
#[test]
581613
fn test_assign_range_precedence() {
582614
// Range has higher precedence as the right-hand of an assignment, but

0 commit comments

Comments
 (0)