Skip to content

Commit

Permalink
Merge pull request #1642 from dtolnay/rangeprecedence
Browse files Browse the repository at this point in the history
Disallow range with upper bound in lhs of binop
  • Loading branch information
dtolnay committed May 11, 2024
2 parents b15c623 + a794288 commit b1a12f4
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
6 changes: 5 additions & 1 deletion src/expr.rs
Expand Up @@ -1391,7 +1391,11 @@ pub(crate) mod parsing {
) -> Result<Expr> {
loop {
let ahead = input.fork();
if let Ok(op) = ahead.parse::<BinOp>() {
if let Expr::Range(ExprRange { end: Some(_), .. }) = lhs {
// A range with an upper bound cannot be the left-hand side of
// another binary operator.
break;
} else if let Ok(op) = ahead.parse::<BinOp>() {
let precedence = Precedence::of(&op);
if precedence < base {
break;
Expand Down
40 changes: 39 additions & 1 deletion tests/test_expr.rs
Expand Up @@ -331,7 +331,7 @@ fn test_postfix_operator_after_cast() {
}

#[test]
fn test_ranges() {
fn test_range_kinds() {
syn::parse_str::<Expr>("..").unwrap();
syn::parse_str::<Expr>("..hi").unwrap();
syn::parse_str::<Expr>("lo..").unwrap();
Expand All @@ -348,6 +348,44 @@ fn test_ranges() {
syn::parse_str::<Expr>("lo...hi").unwrap_err();
}

#[test]
fn test_range_precedence() {
snapshot!(".. .." as Expr, @r###"
Expr::Range {
limits: RangeLimits::HalfOpen,
end: Some(Expr::Range {
limits: RangeLimits::HalfOpen,
}),
}
"###);

snapshot!(".. .. ()" as Expr, @r###"
Expr::Range {
limits: RangeLimits::HalfOpen,
end: Some(Expr::Range {
limits: RangeLimits::HalfOpen,
end: Some(Expr::Tuple),
}),
}
"###);

snapshot!("() .. .." as Expr, @r###"
Expr::Range {
start: Some(Expr::Tuple),
limits: RangeLimits::HalfOpen,
end: Some(Expr::Range {
limits: RangeLimits::HalfOpen,
}),
}
"###);

// A range with a lower bound cannot be the upper bound of another range,
// and a range with an upper bound cannot be the lower bound of another
// range.
syn::parse_str::<Expr>(".. x ..").unwrap_err();
syn::parse_str::<Expr>("x .. x ..").unwrap_err();
}

#[test]
fn test_ambiguous_label() {
for stmt in [
Expand Down

0 comments on commit b1a12f4

Please sign in to comment.