# autocontext
[](https://crates.io/crates/autocontext)
[](https://docs.rs/autocontext)
[](#license)
A tiny procedural macro that automatically attaches
[`anyhow::Context`](https://docs.rs/anyhow/latest/anyhow/trait.Context.html)
to function results. No more sprinkling `.context()` over every fallible function.
## Why?
Without `autocontext`:
```rust
fn deploy(env: &str) -> anyhow::Result<()> {
let cfg = load_config(env)
.context("deploy")?;
let client = connect(&cfg.db_url)
.context("deploy")?;
run_migrations(&client)
.context("deploy")?;
Ok(())
}
```
With `autocontext`:
```rust
#[autocontext]
fn deploy(env: &str) -> anyhow::Result<()> {
let cfg = load_config(env)?;
let client = connect(&cfg.db_url)?;
run_migrations(&client)?;
Ok(())
}
```
The error chain still reads:
```
Error: deploy
Caused by:
connection refused: 127.0.0.1:5432
```
## Installation
```toml
[dependencies]
autocontext = "0.1"
anyhow = "1"
```
## Usage
### Default mode -- context on the whole function
```rust
use autocontext::autocontext;
use anyhow::Result;
#[autocontext]
fn parse_config(path: &str) -> Result<Config> {
let raw = std::fs::read_to_string(path)?;
let cfg: Config = toml::from_str(&raw)?;
Ok(cfg)
}
```
The context message defaults to the function name.
### Custom message
```rust
#[autocontext("loading application config")]
fn parse_config(path: &str) -> Result<Config> {
// ...
}
```
### Argument logging
Include function argument values in the context message (via Debug):
```_rust
#[autocontext(args(path, retries))]
fn connect(path: &str, retries: u32) -> Result<Connection> {
// ...
}
```
On error:
```
Error: connect: path="/tmp/sock" retries=3
Caused by:
connection refused
```
You can combine with a custom message:
```rust
#[autocontext("establishing connection", args(path))]
fn connect(path: &str) -> Result<Connection> {
// ...
}
// Error: establishing connection: path="/tmp/sock"
```
### Per-try mode -- context on every ?
```rust
#[autocontext(per_try)]
fn deploy(env: &str) -> Result<()> {
let cfg = load_config(env)?; // context: "deploy [try #0]"
let db = connect(&cfg)?; // context: "deploy [try #1]"
migrate(&db)?; // context: "deploy [try #2]"
Ok(())
}
```
Useful when a function has many fallible steps and you need to know
which one failed without reading a backtrace.
### Per-try + arguments
```_rust
#[autocontext(per_try, args(user_id, attempt))]
fn authenticate(user_id: u64, attempt: u8) -> Result<()> {
let _token = issue_token(user_id)?;
verify(attempt)?;
Ok(())
}
```
On error:
```
Error: authenticate [try #0]: user_id=0 attempt=1
Caused by:
invalid user
```
### Async functions
Works out of the box:
```_rust
#[autocontext]
async fn fetch_user(client: &reqwest::Client, id: u64) -> Result<User> {
let resp = client.get(format!("/users/{id}")).send().await?;
let user = resp.json::<User>().await?;
Ok(user)
}
```
## Attribute syntax reference
| #\[autocontext]` | Context = function name (static, no allocation on success) |
| #[autocontext("msg")] | Context = custom string |
| #[autocontext(per_try)] | Context on every ? operator |
| #[autocontext(args(a, b))] | Include a, b (via Debug) in message |
| #[autocontext(per_try, args(a, b))] | Combined |
| #[autocontext("msg", args(a, b))] | Combined |
Options are comma-separated and fully combinable.
## How it works
| default (sync) | Body wrapped in immediately-invoked closure; .context(msg) or .with_context(|| format!(...)) called on result. |
| default (async) | Body wrapped in async block + .await; same context logic. |
| per_try | Every expr? rewritten to expr.with_context(|| ...)? |
Functions that do not return Result are emitted unchanged.
## Per-try semantics
- Only the ? operator is instrumented. A bare return Err(...) or
return some_fallible_fn() does not receive context.
- When an error propagates through multiple ? sites (e.g. nested
closures), each site appends its own context layer. Use
err.chain() to inspect the full chain, or err.root_cause() for
the original error.
- Numbering is sequential across the entire function body (including
nested closures), following source reading order.
## Notes & Limitations
- Requires return type Result<T> or Result<T, E> where E: Into<anyhow::Error>.
- Arguments passed to args(...) must implement Debug.
- Formatting occurs only on error -- with_context closure is not called
on the success path.
## MSRV
Rust 1.70 (edition 2021). No nightly features required.
## License
MIT license (LICENSE-MIT or https://opensource.org/licenses/MIT)