1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
//! # whereat - Lightweight error location tracking
//!
//! **150x faster than `backtrace`** — production error tracing without debuginfo, panic, or overhead.
//!
//! ```text
//! Error: UserNotFound
//! at src/db.rs:142:9
//! ╰─ user_id = 42
//! at src/api.rs:89:5
//! ╰─ in handle_request
//! at myapp @ https://github.com/you/myapp/blob/a1b2c3d/src/main.rs#L23
//! ```
//!
//! ## Try It Now
//!
//! [`at()`] creates a traced error. [`.at()?`](ResultAtExt::at) propagates it.
//! [`map_err_at`](ResultAtExt::map_err_at) converts between error types without losing the trace.
//!
//! ```rust
//! use whereat::{at, At, ResultAtExt};
//!
//! #[derive(Debug)]
//! struct DbError;
//! #[derive(Debug)]
//! enum AppError { Db(DbError) }
//!
//! fn db_query(id: u64) -> Result<String, At<DbError>> {
//! if id == 0 { return Err(at(DbError)); }
//! Ok("alice".into())
//! }
//!
//! fn handler(id: u64) -> Result<String, At<AppError>> {
//! let user = db_query(id)
//! .at() // new frame at this call site
//! .at_str("looking up user") // context on that frame
//! .map_err_at(AppError::Db)?; // DbError → AppError, trace preserved
//! Ok(user)
//! }
//!
//! let err = handler(0).unwrap_err();
//! assert_eq!(err.frame_count(), 2);
//! ```
//!
//! ## Production Setup
//!
//! For **clickable GitHub links** in traces, add one line to your crate root and use [`at!()`](at!):
//!
//! ```rust,ignore
//! // In lib.rs or main.rs
//! whereat::define_at_crate_info!();
//!
//! fn find_user(id: u64) -> Result<String, At<MyError>> {
//! Err(at!(MyError::NotFound)) // Now includes repo links in traces
//! }
//! ```
//!
//! The `at!()` macro desugars to:
//! ```rust,ignore
//! At::wrap(err)
//! .set_crate_info(crate::at_crate_info()) // Enables GitHub/GitLab links
//! .at() // Captures file:line:col
//! ```
//!
//! ## Which Approach?
//!
//! | Situation | Use |
//! |-----------|-----|
//! | Existing struct/enum you don't want to modify | Wrap with [`At<YourError>`](At) |
//! | Want traces embedded inside your error type | Implement [`AtTraceable`] trait |
//!
//! **Wrapper approach** (most common): Return `Result<T, At<YourError>>` from functions.
//!
//! **Embedded approach**: Implement [`AtTraceable`] and store an [`AtTrace`] (or `Box<AtTrace>`)
//! field inside your error type. Return `Result<T, YourError>` directly.
//!
//! ## Starting a Trace
//!
//! | Function | Crate info | Use when |
//! |----------|------------|----------|
//! | [`at(err)`](at()) | ❌ None | Prototyping — no setup needed |
//! | [`at!(err)`](at!) | ✅ GitHub links | **Production** — requires [`define_at_crate_info!()`](define_at_crate_info) |
//! | [`err.start_at()`](ErrorAtExt::start_at) | ❌ None | Chaining on `Error` trait types |
//!
//! Start with `at()` to try things out. Upgrade to `at!()` before shipping — you'll want
//! those clickable links when debugging production issues.
//!
//! ## Extending a Trace
//!
//! **Create a new location frame** (call site is recorded):
//!
//! | Method | Effect |
//! |--------|--------|
//! | [`.at()`](ResultAtExt::at) | New frame with just file:line:col |
//! | [`.at_fn(\|\| {})`](ResultAtExt::at_fn) | New frame + captures function name |
//! | [`.at_named("step")`](ResultAtExt::at_named) | New frame + custom label |
//!
//! **Add context to the last frame** (no new location):
//!
//! | Method | Effect |
//! |--------|--------|
//! | [`.at_str("msg")`](ResultAtExt::at_str) | Static string (zero-cost) |
//! | [`.at_string(\|\| format!(...))`](ResultAtExt::at_string) | Dynamic string (lazy) |
//! | [`.at_data(\|\| value)`](ResultAtExt::at_data) | Typed via Display (lazy) |
//! | [`.at_debug(\|\| value)`](ResultAtExt::at_debug) | Typed via Debug (lazy) |
//! | [`.at_aside_error(err)`](ResultAtExt::at_aside_error) | Attach a related error (diagnostic only, **not** in `.source()` chain) |
//! | [`.map_err_at(\|e\| ...)`](ResultAtExt::map_err_at) | Convert error type, **preserve trace** |
//!
//! **Inspect / decompose:**
//!
//! | Method | Returns |
//! |--------|---------|
//! | [`.error()`](At::error) | `&E` |
//! | [`.decompose()`](At::decompose) | `(E, Option<AtTrace>)` — preserves the trace |
//! | [`.map_error(\|e\| ...)`](At::map_error) | `At<E2>` — convert type, keep trace |
//! | [`.frame_count()`](At::frame_count) | `usize` |
//! | [`.full_trace()`](At::full_trace) | Display formatter with all frames + contexts |
//!
//! **Key distinction**: `.at()` creates a NEW frame. `.at_str()` and friends add to the LAST frame.
//!
//! ```rust
//! use whereat::{at, At, ResultAtExt};
//!
//! #[derive(Debug)]
//! struct MyError;
//!
//! fn example() -> Result<(), At<MyError>> {
//! // One frame with two contexts attached
//! let e = at(MyError).at_str("a").at_str("b");
//! assert_eq!(e.frame_count(), 1);
//!
//! // Two frames: at() creates first, .at() creates second
//! let e = at(MyError).at().at_str("on second frame");
//! assert_eq!(e.frame_count(), 2);
//! Ok(())
//! }
//! # example().ok();
//! ```
//!
//! ## Foreign Crates and Errors
//!
//! When consuming errors from other crates, use [`at_crate!()`](at_crate) to mark the boundary.
//! This ensures traces show your crate's GitHub links, not confusing paths from dependencies.
//!
//! ```rust,ignore
//! whereat::define_at_crate_info!(); // Once in lib.rs
//!
//! use whereat::{at_crate, At, ResultAtExt};
//!
//! fn call_dependency() -> Result<(), At<DependencyError>> {
//! at_crate!(dependency::do_thing())?; // Marks crate boundary
//! Ok(())
//! }
//! ```
//!
//! The `at_crate!()` macro desugars to:
//! ```rust,ignore
//! result.at_crate(crate::at_crate_info()) // Adds boundary marker with your crate's info
//! ```
//!
//! For plain errors without traces (e.g., `std::io::Error`), use `map_err(at)` to start tracing:
//!
//! ```rust
//! use whereat::{At, at, ResultAtExt};
//!
//! fn external_api() -> Result<(), &'static str> {
//! Err("external error")
//! }
//!
//! fn wrapper() -> Result<(), At<&'static str>> {
//! external_api().map_err(at).at_str("calling external API")?;
//! Ok(())
//! }
//! ```
//!
//! ## Design Goals
//!
//! - **Tiny overhead**: `At<E>` is `sizeof(E) + 8` bytes; zero heap allocation on the Ok path
//! - **Zero-cost context**: `.at_str("literal")` stores a pointer, no copy or allocation
//! - **Lazy evaluation**: `.at_string(|| ...)` closures only run on error
//! - **no_std compatible**: Works with just `core` + `alloc`
//!
//! ## OOM Behavior
//!
//! Trace allocations are fallible where possible — on OOM, trace entries are silently skipped
//! but your error `E` always propagates (it's stored inline). See the README for details.
extern crate alloc;
pub use At;
pub use AtContextRef;
pub use ;
pub use ;
pub use ;
// ============================================================================
// Crate-level error tracking info (for whereat's own at!() / at_crate!() usage)
// ============================================================================
//
// This is what `define_at_crate_info!()` generates. We define it manually here
// because the macro isn't defined yet at this point in the file.
// whereat's own crate info for internal at!() usage in doctests
pub static __AT_CRATE_INFO: AtCrateInfo = builder
.name
.repo
.commit
.module
.build;
/// Internal macro for commit detection chain.
/// Define crate-level error tracking info. Call once in your crate root (lib.rs or main.rs).
///
/// This creates a static and getter function that `at!()` and `at_crate!()` use.
/// For compile-time configuration, use this macro. For runtime configuration,
/// define your own `at_crate_info()` function using `OnceLock`.
///
/// ## Basic Usage
///
/// ```rust,ignore
/// // In lib.rs or main.rs
/// whereat::define_at_crate_info!();
/// ```
///
/// ## With Options
///
/// ```rust,ignore
/// whereat::define_at_crate_info!(
/// path = "crates/mylib/",
/// meta = &[("team", "platform"), ("service", "auth")],
/// );
/// ```
///
/// ## Runtime Configuration
///
/// For runtime metadata (e.g., instance IDs), define your own getter:
///
/// ```rust,ignore
/// use std::sync::OnceLock;
/// use whereat::AtCrateInfo;
///
/// static CRATE_INFO: OnceLock<AtCrateInfo> = OnceLock::new();
///
/// pub(crate) fn at_crate_info() -> &'static AtCrateInfo {
/// CRATE_INFO.get_or_init(|| {
/// AtCrateInfo::builder()
/// .name_owned(env!("CARGO_PKG_NAME").into())
/// .meta_owned(vec![("instance_id".into(), get_instance_id())])
/// .build()
/// })
/// }
/// ```
///
/// ## Available Options
///
/// - `path = "..."` - Crate path within repository (for workspace crates)
/// - `meta = &[...]` - Custom key-value metadata (compile-time)
///
/// ## How It Works
///
/// The macro captures at compile time:
/// - `CARGO_PKG_NAME` - crate name
/// - `CARGO_PKG_REPOSITORY` - repository URL from Cargo.toml
/// - `GIT_COMMIT` / `GITHUB_SHA` / `CI_COMMIT_SHA` - commit hash (or `v{VERSION}` fallback)
/// Start tracing an error with crate metadata for repository links.
///
/// Requires `define_at_crate_info!()` or a custom `at_crate_info()` function.
///
/// ## Setup (once in lib.rs)
///
/// ```rust,ignore
/// whereat::define_at_crate_info!();
/// ```
///
/// ## Usage
///
/// ```rust,ignore
/// use whereat::{at, At};
///
/// fn find_user(id: u64) -> Result<String, At<MyError>> {
/// if id == 0 {
/// return Err(at!(MyError::NotFound));
/// }
/// Ok(format!("User {}", id))
/// }
/// ```
///
/// ## Without Crate Info
///
/// If you don't need GitHub links, use the `at()` function instead:
///
/// ```rust
/// use whereat::{at, At};
///
/// #[derive(Debug)]
/// struct MyError;
///
/// let err: At<MyError> = at(MyError); // No crate info, no getter needed
/// ```
// Intentional: calls caller's crate getter
/// Add crate boundary marker to a Result with an `At<E>` error.
///
/// Requires `define_at_crate_info!()` or a custom `at_crate_info()` function.
/// Use at crate boundaries when consuming errors from dependencies.
///
/// ## Setup (once in lib.rs)
///
/// ```rust,ignore
/// whereat::define_at_crate_info!();
/// ```
///
/// ## Usage
///
/// ```rust,ignore
/// use whereat::{at_crate, At, ResultAtExt};
///
/// fn my_function() -> Result<(), At<DepError>> {
/// at_crate!(dependency::call())?; // Mark crate boundary
/// Ok(())
/// }
/// ```
// Intentional: calls caller's crate getter
/// Wrap any value in `At<E>` and capture the caller's location.
///
/// This function works with any type, not just `Error` types.
/// For types implementing `Error`, you can also use `.start_at()`.
/// For crate-aware tracing with GitHub links, use `at!()` instead.
///
/// ## Example
///
/// ```rust
/// use whereat::{at, At};
///
/// #[derive(Debug)]
/// struct SimpleError { code: u32 }
///
/// fn fallible() -> Result<(), At<SimpleError>> {
/// Err(at(SimpleError { code: 42 }))
/// }
/// ```
// Extension traits are in ext.rs