dtolnay / dtolnay/anyhow

`ensure!` doesn't accept inline const blocks

Open
#458 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
Rust
Stars
6.7k
Forks
224
PR merge metrics
No merged PRs in 30d

Description

`ensure!` doesn't accept inline const blocks, even though plain Rust and `assert!` both do:

```rust
ensure!(const { 1 + 1 } == 3);
ensure!(3 == const { 1 + 1 });
ensure!(const { false });
```

All three give:

```
error: no rules expected keyword `const`
--> src/lib.rs:4:33
|
4 | fn a() -> Result<()> { ensure!(const { 1 + 1 } == 3); Ok(()) }
| ^^^^^ no rules expected this token in macro call
```

In #298 you added the const block rule to `__parse_ensure` with a note that it's mostly useless because of rust-lang/rust#86730, and that it would be good to have the case there to revisit in the future.

The parse rules do handle all three. What actually fails is one step later, `__fancy_ensure` matching `$lhs:expr` and `$rhs:expr`, and for the bare condition `__fallback_ensure` matching `$cond:expr`.

The thing I didn't expect is that the matcher only rejects a const block when it's the first token of the fragment. `ensure!(true && const { false })` compiles today for that reason. So putting the block behind a token tree group is enough to get it past the matcher, and no edition bump is needed.

The tradeoff is that the const block then shows up parenthesized in the message:

```
Condition failed: `(const { 1 + 1 }) == 3` (2 vs 3)
```

Happy to leave this alone if that isn't worth it to you, since const blocks in `ensure!` are pretty rare.

Contributor guide

No contributing guide indexed for this repository

Research direction

Start in src/lib.rs, tracing the const-block handling from __parse_ensure into the __fancy_ensure and __fallback_ensure matcher rules. Reproduce the three failing ensure! examples and the working nested condition, then verify that inline const blocks are accepted without an edition bump and that the resulting diagnostic behavior matches the intended tradeoff.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Active
Clarity
Clearly specified
Newbie friendliness
74/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.