whereat 0.1.5

Lightweight error location tracking with small sizeof and no_std support
Documentation
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
//! The `At<E>` wrapper type for error location tracking.
//!
//! This module provides the core [`At<E>`] type that wraps any error with a trace
//! of source locations. It's the primary API surface for whereat.

use alloc::borrow::Cow;
use alloc::boxed::Box;
use alloc::string::{String, ToString};
use core::fmt;
use core::hash::{Hash, Hasher};
use core::panic::Location;

use crate::AtCrateInfo;
use crate::context::{AtContext, AtContextRef};
use crate::trace::{AtFrame, AtFrameOwned, AtTrace, AtTraceBoxed};

// ============================================================================
// At<E> - Core wrapper type
// ============================================================================

/// An error with location tracking - wraps any error type.
///
/// ## Size
///
/// `At<E>` is `sizeof(E) + 8` bytes on 64-bit platforms:
/// - The error `E` is stored inline
/// - The trace is boxed (8-byte pointer, null when empty)
///
/// ## Equality and Hashing
///
/// `At<E>` implements `PartialEq`, `Eq`, and `Hash` based **only on the inner
/// error `E`**, ignoring the trace. The trace is metadata about *where* an
/// error was created, not *what* the error is.
///
/// This means two `At<E>` values are equal if their inner errors are equal,
/// even if they were created at different source locations:
///
/// ```rust
/// use whereat::at;
///
/// #[derive(Debug, PartialEq)]
/// struct MyError(u32);
///
/// let err1 = at(MyError(42));  // Created here
/// let err2 = at(MyError(42));  // Created on different line
/// assert_eq!(err1, err2);      // Equal because inner errors match
/// ```
///
/// ## Example
///
/// ```rust
/// use whereat::{at, At};
///
/// #[derive(Debug)]
/// enum MyError { Oops }
///
/// // Create a traced error using at() function
/// let err: At<MyError> = at(MyError::Oops);
/// assert_eq!(err.frame_count(), 1);
/// ```
///
/// ## Note: Avoid `At<At<E>>`
///
/// Nesting `At<At<E>>` is supported but unnecessary and wasteful.
/// Each `At` has its own trace, so nesting allocates two `Box<AtTrace>`
/// instead of one. Use `.at()` on Results to extend the existing trace:
///
/// ```rust
/// use whereat::{at, At};
///
/// #[derive(Debug)]
/// struct MyError;
///
/// // GOOD: Extend existing trace
/// fn good() -> Result<(), At<MyError>> {
///     let err: At<MyError> = at(MyError);
///     Err(err.at())  // Same trace, new location
/// }
///
/// // UNNECESSARY: Creates two separate traces
/// fn unnecessary() -> At<At<MyError>> {
///     at(at(MyError))  // Two allocations
/// }
/// ```
pub struct At<E> {
    error: E,
    trace: AtTraceBoxed,
}

// ============================================================================
// At<E> Implementation
// ============================================================================

impl<E> At<E> {
    /// Wrap an error without capturing any location.
    ///
    /// Use this when you want to defer tracing until later (e.g., exiting a hot loop).
    /// Call `.at()` to add the first location when ready.
    ///
    /// For normal use, prefer [`at()`](crate::at()) or [`at!()`](crate::at!) which
    /// capture the caller's location immediately.
    #[inline]
    pub const fn wrap(error: E) -> Self {
        Self {
            error,
            trace: AtTraceBoxed::new(),
        }
    }

    /// Create an `At<E>` from an error and an existing trace.
    ///
    /// Used for transferring traces between error types.
    #[inline]
    pub fn from_parts(error: E, trace: AtTrace) -> Self {
        let mut boxed = AtTraceBoxed::new();
        boxed.set(trace);
        Self {
            error,
            trace: boxed,
        }
    }

    /// Ensure trace exists, creating it if necessary.
    fn ensure_trace(&mut self) -> &mut AtTrace {
        self.trace.get_or_insert_mut()
    }

    /// Add the caller's location to the trace.
    ///
    /// This is the primary API for building up a stack trace as errors propagate.
    /// If allocation fails, the location is silently skipped.
    ///
    /// ## Example
    ///
    /// ```rust
    /// use whereat::At;
    ///
    /// #[derive(Debug)]
    /// enum MyError { Oops }
    ///
    /// fn inner() -> Result<(), At<MyError>> {
    ///     Err(At::wrap(MyError::Oops).at())
    /// }
    ///
    /// fn outer() -> Result<(), At<MyError>> {
    ///     inner().map_err(|e| e.at())
    /// }
    /// ```
    #[track_caller]
    #[inline]
    pub fn at(mut self) -> Self {
        let loc = Location::caller();
        let trace = self.trace.get_or_insert_mut();
        let _ = trace.try_push(loc);
        self
    }

    /// Add a location frame with the caller's function name as context.
    ///
    /// Captures both file:line:col AND the function name at zero runtime cost.
    /// Pass an empty closure `|| {}` - its type includes the parent function name.
    ///
    /// ## Example
    ///
    /// ```rust
    /// use whereat::{at, At};
    ///
    /// #[derive(Debug)]
    /// enum MyError { NotFound }
    ///
    /// fn load_config() -> Result<(), At<MyError>> {
    ///     Err(at(MyError::NotFound).at_fn(|| {}))
    /// }
    ///
    /// // Output will include:
    /// //     at src/lib.rs:10:5
    /// //         in my_crate::load_config
    /// ```
    #[track_caller]
    #[inline]
    pub fn at_fn<F: Fn()>(mut self, _marker: F) -> Self {
        let full_name = core::any::type_name::<F>();
        // Type looks like: "crate::module::function::{{closure}}"
        // Strip "::{{closure}}" suffix if present
        let name = full_name.strip_suffix("::{{closure}}").unwrap_or(full_name);
        let loc = Location::caller();
        let trace = self.trace.get_or_insert_mut();
        // First push a new location frame
        let _ = trace.try_push(loc);
        // Then add function name context to that frame
        let context = AtContext::FunctionName(name);
        trace.try_add_context(loc, context);
        self
    }

    /// Add a location frame with an explicit name as context.
    ///
    /// Like [`at_fn`](Self::at_fn) but with an explicit label instead of
    /// auto-detecting the function name. Useful for naming checkpoints,
    /// phases, or operations within a function.
    ///
    /// ## Example
    ///
    /// ```rust
    /// use whereat::{at, At};
    ///
    /// #[derive(Debug)]
    /// enum MyError { Failed }
    ///
    /// fn process() -> Result<(), At<MyError>> {
    ///     // ... validation phase ...
    ///     Err(at(MyError::Failed).at_named("validation"))
    /// }
    ///
    /// // Output will include:
    /// //     at src/lib.rs:10:5
    /// //         in validation
    /// ```
    #[track_caller]
    #[inline]
    pub fn at_named(mut self, name: &'static str) -> Self {
        let loc = Location::caller();
        let trace = self.trace.get_or_insert_mut();
        // Push a new location frame
        let _ = trace.try_push(loc);
        // Add the name as function-name-style context
        let context = AtContext::FunctionName(name);
        trace.try_add_context(loc, context);
        self
    }

    /// Add a static string context to the last location frame.
    ///
    /// **Does not add a new location frame** - attaches context to the most recent
    /// frame in the trace. If the trace is empty, creates a frame at the caller's
    /// location first.
    ///
    /// Zero-cost for static strings - just stores a pointer.
    /// For dynamically-computed strings, use [`at_string()`](Self::at_string).
    ///
    /// ## Frame behavior
    ///
    /// ```rust
    /// use whereat::at;
    ///
    /// #[derive(Debug)]
    /// struct E;
    ///
    /// // One frame with two contexts
    /// let e = at(E).at_str("a").at_str("b");
    /// assert_eq!(e.frame_count(), 1);
    ///
    /// // Two frames: first from at(), second gets the context
    /// let e = at(E).at().at_str("on second frame");
    /// assert_eq!(e.frame_count(), 2);
    /// ```
    ///
    /// ## Example
    ///
    /// ```rust
    /// use whereat::{at, At, ResultAtExt};
    ///
    /// #[derive(Debug)]
    /// enum MyError { IoError }
    ///
    /// fn read_config() -> Result<(), At<MyError>> {
    ///     Err(at(MyError::IoError))
    /// }
    ///
    /// fn init() -> Result<(), At<MyError>> {
    ///     read_config().at_str("while loading configuration")?;
    ///     Ok(())
    /// }
    /// ```
    #[track_caller]
    #[inline]
    pub fn at_str(mut self, msg: &'static str) -> Self {
        let loc = Location::caller();
        let context = AtContext::Text(Cow::Borrowed(msg));
        let trace = self.trace.get_or_insert_mut();
        trace.try_add_context(loc, context);
        self
    }

    /// Add a lazily-computed string context to the last location frame.
    ///
    /// **Does not add a new location frame** - attaches context to the most recent
    /// frame in the trace. If the trace is empty, creates a frame at the caller's
    /// location first.
    ///
    /// The closure is only called on error path, avoiding allocation on success.
    /// For static strings, use [`at_str()`](Self::at_str) instead for zero overhead.
    ///
    /// ## Example
    ///
    /// ```rust
    /// use whereat::{at, At, ResultAtExt};
    ///
    /// #[derive(Debug)]
    /// enum MyError { NotFound }
    ///
    /// fn load(path: &str) -> Result<(), At<MyError>> {
    ///     Err(at(MyError::NotFound))
    /// }
    ///
    /// fn init(path: &str) -> Result<(), At<MyError>> {
    ///     // Closure only runs on Err - no allocation on Ok path
    ///     load(path).at_string(|| format!("loading {}", path))?;
    ///     Ok(())
    /// }
    /// ```
    #[track_caller]
    #[inline]
    pub fn at_string(mut self, f: impl FnOnce() -> String) -> Self {
        let loc = Location::caller();
        let context = AtContext::Text(Cow::Owned(f()));
        let trace = self.trace.get_or_insert_mut();
        trace.try_add_context(loc, context);
        self
    }

    /// Add lazily-computed typed context (Display) to the last location frame.
    ///
    /// **Does not add a new location frame** - attaches context to the most recent
    /// frame in the trace. If the trace is empty, creates a frame at the caller's
    /// location first.
    ///
    /// The closure is only called on error path, avoiding allocation on success.
    /// Use for typed data that you want to format with `Display` and later retrieve
    /// via [`downcast_ref::<T>()`](crate::AtContextRef::downcast_ref).
    ///
    /// For plain string messages, prefer [`at_str()`](Self::at_str) or [`at_string()`](Self::at_string).
    /// For Debug-formatted data, use [`at_debug()`](Self::at_debug).
    ///
    /// ## Example
    ///
    /// ```rust
    /// use whereat::{at, At};
    ///
    /// #[derive(Debug)]
    /// enum MyError { NotFound }
    ///
    /// // Custom Display type for rich context
    /// struct PathContext(String);
    /// impl std::fmt::Display for PathContext {
    ///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    ///         write!(f, "path: {}", self.0)
    ///     }
    /// }
    ///
    /// fn load(path: &str) -> Result<(), At<MyError>> {
    ///     Err(at(MyError::NotFound))
    /// }
    ///
    /// fn init(path: &str) -> Result<(), At<MyError>> {
    ///     load(path).map_err(|e| e.at_data(|| PathContext(path.into())))?;
    ///     Ok(())
    /// }
    /// ```
    #[track_caller]
    #[inline]
    pub fn at_data<T: fmt::Display + Send + Sync + 'static>(
        mut self,
        f: impl FnOnce() -> T,
    ) -> Self {
        let loc = Location::caller();
        let ctx = f();
        let context = AtContext::Display(Box::new(ctx));
        let trace = self.trace.get_or_insert_mut();
        trace.try_add_context(loc, context);
        self
    }

    /// Add lazily-computed typed context (Debug) to the last location frame.
    ///
    /// **Does not add a new location frame** - attaches context to the most recent
    /// frame in the trace. If the trace is empty, creates a frame at the caller's
    /// location first.
    ///
    /// The closure is only called on error path, avoiding allocation on success.
    /// Use [`contexts()`](Self::contexts) to retrieve entries and
    /// [`downcast_ref()`](crate::AtContextRef::downcast_ref) to access typed data.
    ///
    /// ## Example
    ///
    /// ```rust
    /// use whereat::at;
    ///
    /// #[derive(Debug)]
    /// struct RequestInfo { user_id: u64, path: String }
    ///
    /// #[derive(Debug)]
    /// enum MyError { Forbidden }
    ///
    /// let err = at(MyError::Forbidden)
    ///     .at_debug(|| RequestInfo { user_id: 42, path: "/admin".into() });
    ///
    /// // Later, retrieve the context
    /// for ctx in err.contexts() {
    ///     if let Some(req) = ctx.downcast_ref::<RequestInfo>() {
    ///         assert_eq!(req.user_id, 42);
    ///     }
    /// }
    /// ```
    #[track_caller]
    #[inline]
    pub fn at_debug<T: fmt::Debug + Send + Sync + 'static>(
        mut self,
        f: impl FnOnce() -> T,
    ) -> Self {
        let loc = Location::caller();
        let ctx = f();
        let context = AtContext::Debug(Box::new(ctx));
        let trace = self.trace.get_or_insert_mut();
        trace.try_add_context(loc, context);
        self
    }

    /// Attach an error as diagnostic context to the last location frame.
    ///
    /// **Does not add a new location frame** - attaches context to the most recent
    /// frame in the trace. If the trace is empty, creates a frame at the caller's
    /// location first.
    ///
    /// Attach a related error as **diagnostic context** on the last frame.
    ///
    /// **Does not add a new location frame** — attaches to the most recent frame.
    /// If the trace is empty, creates a frame at the caller's location first.
    ///
    /// The attached error is visible via [`contexts()`](Self::contexts) iteration
    /// and [`full_trace()`](Self::full_trace) display, but is **not** part of the
    /// [`Error::source()`] chain. `At<E>::source()` always delegates to `E::source()`.
    ///
    /// This is intentional: `.source()` models a linear causal chain ("A was caused
    /// by B"), while `.at_aside_error()` models an observation ("while handling A,
    /// we also saw X"). These are different relationships, and forcing the latter
    /// into a linear chain would be lossy — a trace can have multiple
    /// `.at_aside_error()` calls at different frames.
    ///
    /// If you need an error to appear in the `.source()` chain, store it inside
    /// your error type `E` directly.
    ///
    /// ## Example
    ///
    /// ```rust
    /// use whereat::at;
    /// use std::io;
    ///
    /// #[derive(Debug)]
    /// struct MyError;
    ///
    /// fn wrap_io_error(io_err: io::Error) -> whereat::At<MyError> {
    ///     at(MyError).at_aside_error(io_err)
    /// }
    /// ```
    #[track_caller]
    #[inline]
    pub fn at_aside_error<Err: core::error::Error + Send + Sync + 'static>(
        mut self,
        err: Err,
    ) -> Self {
        let loc = Location::caller();
        let context = AtContext::Error(Box::new(err));
        let trace = self.trace.get_or_insert_mut();
        trace.try_add_context(loc, context);
        self
    }

    /// Attach an error as diagnostic context (not in `.source()` chain).
    ///
    /// # Deprecated
    ///
    /// Renamed to [`at_aside_error()`](Self::at_aside_error) to clarify that the
    /// attached error is diagnostic context, not part of the standard error chain.
    /// Code that iterates `.source()` will never see errors attached this way.
    #[deprecated(
        since = "0.1.4",
        note = "Renamed to `at_aside_error()`. The attached error is diagnostic context \
                only — it is NOT part of the `.source()` chain."
    )]
    #[track_caller]
    #[inline]
    pub fn at_error<Err: core::error::Error + Send + Sync + 'static>(mut self, err: Err) -> Self {
        let loc = Location::caller();
        let context = AtContext::Error(Box::new(err));
        let trace = self.trace.get_or_insert_mut();
        trace.try_add_context(loc, context);
        self
    }

    /// Add a crate boundary marker to the last location frame.
    ///
    /// **Does not add a new location frame** - attaches context to the most recent
    /// frame in the trace. If the trace is empty, creates a frame at the caller's
    /// location first.
    ///
    /// This marks that subsequent locations belong to a different crate,
    /// enabling correct GitHub links in cross-crate traces.
    ///
    /// Requires [`define_at_crate_info!()`](crate::define_at_crate_info!) or
    /// a custom `at_crate_info()` getter.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// // Requires define_at_crate_info!() setup
    /// use whereat::{at, At};
    ///
    /// whereat::define_at_crate_info!();
    ///
    /// #[derive(Debug)]
    /// enum MyError { Wrapped(String) }
    ///
    /// fn wrap_external_error(msg: &str) -> At<MyError> {
    ///     at(MyError::Wrapped(msg.into()))
    ///         .at_crate(crate::at_crate_info())
    /// }
    /// ```
    #[track_caller]
    #[inline]
    pub fn at_crate(mut self, info: &'static AtCrateInfo) -> Self {
        let loc = Location::caller();
        let trace = self.trace.get_or_insert_mut();
        trace.try_add_crate_boundary(loc, info);
        self
    }

    /// Add a skip marker (`[...]`) to the trace.
    ///
    /// Use this to indicate that some frames were skipped, either because
    /// tracing started late in the call stack or because intermediate frames
    /// are not meaningful.
    #[doc(hidden)]
    #[inline]
    pub fn at_skipped_frames(mut self) -> Self {
        let trace = self.trace.get_or_insert_mut();
        let _ = trace.try_push_skipped();
        self
    }

    /// Set the crate info for this trace.
    ///
    /// This is used by `at!()` to provide repository metadata for GitHub links.
    /// Calling this creates the trace if it doesn't exist yet.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// // Requires define_at_crate_info!() setup
    /// whereat::define_at_crate_info!();
    ///
    /// #[derive(Debug)]
    /// enum MyError { Oops }
    ///
    /// let err = At::wrap(MyError::Oops)
    ///     .set_crate_info(crate::at_crate_info())
    ///     .at();
    /// ```
    #[inline]
    pub fn set_crate_info(mut self, info: &'static AtCrateInfo) -> Self {
        let trace = self.trace.get_or_insert_mut();
        trace.set_crate_info(info);
        self
    }

    /// Get the crate info for this trace, if set.
    #[inline]
    pub fn crate_info(&self) -> Option<&'static AtCrateInfo> {
        self.trace.as_ref().and_then(|t| t.crate_info())
    }

    /// Get a reference to the inner error.
    #[inline]
    pub fn error(&self) -> &E {
        &self.error
    }

    /// Get a mutable reference to the inner error.
    #[inline]
    pub fn error_mut(&mut self) -> &mut E {
        &mut self.error
    }

    /// Consume self and return the inner error, **discarding the trace**.
    ///
    /// # Deprecated
    ///
    /// Use [`decompose()`](Self::decompose) to get both the error and trace,
    /// or [`map_error()`](Self::map_error) to convert the error type while
    /// preserving the trace.
    ///
    /// ```rust
    /// use whereat::at;
    ///
    /// #[derive(Debug, PartialEq)]
    /// struct MyError;
    ///
    /// let traced = at(MyError);
    ///
    /// // Instead of: let err = traced.into_inner();  // trace lost!
    /// let (err, trace) = traced.decompose();         // trace preserved
    /// assert_eq!(err, MyError);
    /// assert!(trace.is_some());
    /// ```
    #[deprecated(
        since = "0.1.4",
        note = "Discards the trace. Use `decompose()` to get both error and trace, \
                or `map_error()` to convert types while preserving the trace."
    )]
    #[inline]
    pub fn into_inner(self) -> E {
        self.error
    }

    /// Consume self and return both the error and the trace.
    ///
    /// This is the recommended way to take apart an `At<E>` without losing
    /// location information. If you need to convert the error type while
    /// keeping the trace, use [`map_error()`](Self::map_error) instead.
    ///
    /// ```rust
    /// use whereat::at;
    ///
    /// #[derive(Debug, PartialEq)]
    /// struct MyError;
    ///
    /// let traced = at(MyError);
    /// let (err, trace) = traced.decompose();
    /// assert_eq!(err, MyError);
    /// assert!(trace.is_some());  // trace is preserved
    /// ```
    #[inline]
    pub fn decompose(mut self) -> (E, Option<AtTrace>) {
        let trace = self.trace.take();
        (self.error, trace)
    }

    /// Check if the trace is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.trace.is_empty()
    }

    /// Iterate over all traced locations, oldest first.
    ///
    /// Skipped frame markers (`[...]`) are not included in this iteration.
    /// Use [`frames()`](Self::frames) for full iteration including contexts.
    #[inline]
    #[allow(dead_code)] // Used in tests
    pub(crate) fn locations(&self) -> impl Iterator<Item = &'static Location<'static>> + '_ {
        self.trace
            .as_ref()
            .into_iter()
            .flat_map(|t| t.iter())
            .flatten() // Filter out None (skipped frame markers)
    }

    /// Get the first (oldest) location in the trace, if any.
    #[inline]
    #[allow(dead_code)] // Used in tests
    pub(crate) fn first_location(&self) -> Option<&'static Location<'static>> {
        self.locations().next()
    }

    /// Get the last (most recent) location in the trace, if any.
    #[inline]
    #[allow(dead_code)] // Used in tests
    pub(crate) fn last_location(&self) -> Option<&'static Location<'static>> {
        self.locations().last()
    }

    /// Get a reference to the underlying trace, if any.
    #[inline]
    #[allow(dead_code)] // Used in format module
    pub(crate) fn trace_ref(&self) -> Option<&AtTrace> {
        self.trace.as_ref()
    }

    /// Iterate over all context entries, newest first.
    ///
    /// Each call to `at_str()`, `at_string()`, `at_data()`, or `at_debug()` creates
    /// a context entry. Use [`AtContextRef`] methods to inspect context data.
    ///
    /// **Note:** Prefer [`frames()`](Self::frames) for unified iteration over
    /// locations with their contexts.
    ///
    /// ## Example
    ///
    /// ```rust
    /// use whereat::at;
    ///
    /// #[derive(Debug)]
    /// struct MyError;
    ///
    /// let err = at(MyError)
    ///     .at_str("loading config")
    ///     .at_str("initializing");
    ///
    /// let texts: Vec<_> = err.contexts()
    ///     .filter_map(|ctx| ctx.as_text())
    ///     .collect();
    /// assert_eq!(texts, vec!["initializing", "loading config"]); // newest first
    /// ```
    #[inline]
    pub fn contexts(&self) -> impl Iterator<Item = AtContextRef<'_>> {
        self.trace.as_ref().into_iter().flat_map(|t| t.contexts())
    }

    /// Iterate over frames (location + contexts pairs), oldest first.
    ///
    /// This is the recommended way to traverse a trace. Each frame contains
    /// a location (or None for skipped-frames marker) and its associated contexts.
    ///
    /// ## Example
    ///
    /// ```rust
    /// use whereat::at;
    ///
    /// #[derive(Debug)]
    /// struct MyError;
    ///
    /// let err = at(MyError)
    ///     .at_str("loading config")
    ///     .at();
    ///
    /// for frame in err.frames() {
    ///     if let Some(loc) = frame.location() {
    ///         println!("at {}:{}", loc.file(), loc.line());
    ///     }
    ///     for ctx in frame.contexts() {
    ///         println!("  - {}", ctx);
    ///     }
    /// }
    /// ```
    #[inline]
    pub fn frames(&self) -> impl Iterator<Item = AtFrame<'_>> {
        self.trace.frames()
    }

    /// Get the number of frames in the trace.
    #[inline]
    pub fn frame_count(&self) -> usize {
        self.trace.as_ref().map_or(0, |t| t.frame_count())
    }

    // ========================================================================
    // Trace manipulation methods
    // ========================================================================

    /// Pop the most recent location and its contexts from the trace.
    ///
    /// Returns `None` if the trace is empty.
    #[inline]
    pub fn at_pop(&mut self) -> Option<AtFrameOwned> {
        self.trace.as_mut()?.pop()
    }

    /// Push a segment (location + contexts) to the end of the trace.
    #[inline]
    pub fn at_push(&mut self, segment: AtFrameOwned) {
        self.ensure_trace().push(segment);
    }

    /// Pop the oldest location and its contexts from the trace.
    ///
    /// Returns `None` if the trace is empty.
    #[inline]
    pub fn at_first_pop(&mut self) -> Option<AtFrameOwned> {
        self.trace.as_mut()?.pop_first()
    }

    /// Insert a segment (location + contexts) at the beginning of the trace.
    #[inline]
    pub fn at_first_insert(&mut self, segment: AtFrameOwned) {
        self.ensure_trace().push_first(segment);
    }

    /// Take the entire trace, leaving self with an empty trace.
    #[inline]
    pub fn take_trace(&mut self) -> Option<AtTrace> {
        self.trace.take()
    }

    /// Set the trace, replacing any existing trace.
    #[inline]
    pub fn set_trace(&mut self, trace: AtTrace) {
        self.trace.set(trace);
    }

    // ========================================================================
    // Error conversion methods
    // ========================================================================

    /// Convert the error type while preserving the trace.
    ///
    /// ## Example
    ///
    /// ```rust
    /// use whereat::{at, At};
    ///
    /// #[derive(Debug)]
    /// struct Error1;
    /// #[derive(Debug)]
    /// struct Error2;
    ///
    /// impl From<Error1> for Error2 {
    ///     fn from(_: Error1) -> Self { Error2 }
    /// }
    ///
    /// let err1: At<Error1> = at(Error1).at_str("context");
    /// let err2: At<Error2> = err1.map_error(Error2::from);
    /// assert_eq!(err2.frame_count(), 1);
    /// ```
    #[inline]
    pub fn map_error<E2, F>(self, f: F) -> At<E2>
    where
        F: FnOnce(E) -> E2,
    {
        At {
            error: f(self.error),
            trace: self.trace,
        }
    }

    /// Convert to an `AtTraceable` type, transferring the trace.
    ///
    /// The closure receives the inner error and should return an error type
    /// that implements `AtTraceable`. The trace is then transferred to the
    /// new error's embedded trace.
    ///
    /// ## Example
    ///
    /// ```rust
    /// use whereat::{at, At, AtTrace, AtTraceable};
    ///
    /// #[derive(Debug)]
    /// struct Inner;
    ///
    /// struct MyError {
    ///     trace: AtTrace,
    /// }
    ///
    /// impl AtTraceable for MyError {
    ///     fn trace_mut(&mut self) -> &mut AtTrace { &mut self.trace }
    ///     fn trace(&self) -> Option<&AtTrace> { Some(&self.trace) }
    ///     fn fmt_message(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    ///         write!(f, "my error")
    ///     }
    /// }
    ///
    /// let at_err: At<Inner> = at(Inner).at_str("context");
    /// let my_err: MyError = at_err.into_traceable(|_| MyError { trace: AtTrace::new() });
    /// ```
    #[inline]
    pub fn into_traceable<E2, F>(mut self, f: F) -> E2
    where
        F: FnOnce(E) -> E2,
        E2: crate::trace::AtTraceable,
    {
        let mut new_err = f(self.error);
        if let Some(trace) = self.trace.take() {
            *new_err.trace_mut() = trace;
        }
        new_err
    }
}

// ============================================================================
// Debug impl for At<E>
// ============================================================================

impl<E: fmt::Debug> fmt::Debug for At<E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Error header
        writeln!(f, "Error: {:?}", self.error)?;

        let Some(trace) = self.trace.as_ref() else {
            return Ok(());
        };

        writeln!(f)?;

        // Simple iteration: walk locations, show all contexts at each index
        // None = skipped frame marker
        for (i, loc_opt) in trace.iter().enumerate() {
            match loc_opt {
                Some(loc) => {
                    writeln!(f, "    at {}:{}", loc.file(), loc.line())?;
                    for context in trace.contexts_at(i) {
                        match context {
                            AtContext::Text(msg) => writeln!(f, "       ╰─ {}", msg)?,
                            AtContext::FunctionName(name) => writeln!(f, "       ╰─ in {}", name)?,
                            AtContext::Debug(t) => writeln!(f, "       ╰─ {:?}", &**t)?,
                            AtContext::Display(t) => writeln!(f, "       ╰─ {}", &**t)?,
                            AtContext::Error(e) => writeln!(f, "       ╰─ caused by: {}", e)?,
                            AtContext::Crate(_) => {} // Crate boundaries don't display in basic Debug
                        }
                    }
                }
                None => {
                    writeln!(f, "    [...]")?;
                }
            }
        }

        Ok(())
    }
}

// ============================================================================
// Enhanced display with AtCrateInfo from trace
// ============================================================================

impl<E: fmt::Debug> At<E> {
    /// Format the error with GitHub links using AtCrateInfo from the trace.
    ///
    /// When you use `at!()` or `.at_crate()`, the crate metadata is stored in
    /// the trace. This method uses that metadata to generate clickable GitHub
    /// links for each location.
    ///
    /// For cross-crate traces, each `at_crate()` call updates the repository
    /// used for subsequent locations until another crate boundary is encountered.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// // Requires define_at_crate_info!() setup
    /// use whereat::{at, At};
    ///
    /// whereat::define_at_crate_info!();
    ///
    /// #[derive(Debug)]
    /// struct MyError;
    ///
    /// let err = at!(MyError);
    /// println!("{}", err.display_with_meta());
    /// ```
    #[inline]
    pub fn display_with_meta(&self) -> impl fmt::Display + '_ {
        DisplayWithMeta { traced: self }
    }
}

/// Wrapper for displaying At<E> with AtCrateInfo enhancements.
struct DisplayWithMeta<'a, E> {
    traced: &'a At<E>,
}

impl<E: fmt::Debug> fmt::Display for DisplayWithMeta<'_, E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Error header
        writeln!(f, "Error: {:?}", self.traced.error)?;

        let Some(trace) = self.traced.trace.as_ref() else {
            return Ok(());
        };

        // Use crate_info field first (set by at!() macro)
        // at_crate() context entries can override this per-location
        let initial_crate = trace.crate_info();

        // Show crate info if available
        if let Some(info) = initial_crate {
            writeln!(f, "  crate: {}", info.name())?;
        }

        writeln!(f)?;

        // Cache GitHub base URL - rebuild when crate boundary changes
        let mut link_template: Option<String> = initial_crate.and_then(build_link_base);

        // Walk locations, updating GitHub base when we encounter crate boundaries
        // None = skipped frame marker
        for (i, loc_opt) in trace.iter().enumerate() {
            // Check for crate boundary at this location - rebuild URL only when crate changes
            for context in trace.contexts_at(i) {
                if let AtContext::Crate(info) = context {
                    link_template = build_link_base(info);
                }
            }

            match loc_opt {
                Some(loc) => {
                    write_location_meta(f, loc, link_template.as_deref())?;

                    // Show non-crate contexts
                    for context in trace.contexts_at(i) {
                        match context {
                            AtContext::Text(msg) => writeln!(f, "       ╰─ {}", msg)?,
                            AtContext::FunctionName(name) => writeln!(f, "       ╰─ in {}", name)?,
                            AtContext::Debug(t) => writeln!(f, "       ╰─ {:?}", &**t)?,
                            AtContext::Display(t) => writeln!(f, "       ╰─ {}", &**t)?,
                            AtContext::Error(e) => writeln!(f, "       ╰─ caused by: {}", e)?,
                            AtContext::Crate(_) => {} // Already handled above
                        }
                    }
                }
                None => {
                    writeln!(f, "    [...]")?;
                }
            }
        }

        Ok(())
    }
}

/// Build URL base from crate info using the configured link format.
/// Returns the formatted URL base or None if repo/commit unavailable.
///
/// The format string can contain placeholders: `{repo}`, `{commit}`, `{path}`.
/// The `{file}` and `{line}` placeholders are handled by `write_location_meta`.
fn build_link_base(info: &AtCrateInfo) -> Option<String> {
    match (info.repo(), info.commit()) {
        (Some(repo), Some(commit)) => {
            let repo = repo.trim_end_matches('/');
            let path = info.crate_path().unwrap_or("");
            let format = info.link_format();

            // Build the base URL by replacing {repo}, {commit}, {path}
            // Leave {file} and {line} for write_location_meta
            let mut result =
                String::with_capacity(format.len() + repo.len() + commit.len() + path.len());
            let mut chars = format.chars().peekable();

            while let Some(c) = chars.next() {
                if c == '{' {
                    // Look for placeholder
                    let mut placeholder = String::new();
                    while let Some(&next) = chars.peek() {
                        if next == '}' {
                            chars.next(); // consume '}'
                            break;
                        }
                        placeholder.push(chars.next().unwrap());
                    }
                    match placeholder.as_str() {
                        "repo" => result.push_str(repo),
                        "commit" => result.push_str(commit),
                        "path" => result.push_str(path),
                        // Keep {file} and {line} as-is for later substitution
                        other => {
                            result.push('{');
                            result.push_str(other);
                            result.push('}');
                        }
                    }
                } else {
                    result.push(c);
                }
            }
            Some(result)
        }
        _ => None,
    }
}

/// Helper to write a location with optional repository link.
///
/// The `link_template` should have {repo}, {commit}, {path} already substituted,
/// but {file} and {line} still present as placeholders.
fn write_location_meta(
    f: &mut fmt::Formatter<'_>,
    loc: &'static Location<'static>,
    link_template: Option<&str>,
) -> fmt::Result {
    writeln!(f, "    at {}:{}", loc.file(), loc.line())?;
    if let Some(template) = link_template {
        // Convert backslashes to forward slashes for Windows paths
        let file = loc.file().replace('\\', "/");
        let line = loc.line();

        // Replace {file} and {line} placeholders
        let link = template
            .replace("{file}", &file)
            .replace("{line}", &line.to_string());
        writeln!(f, "       {}", link)?;
    }
    Ok(())
}

// ============================================================================
// Formatting methods for At<E>
// ============================================================================

impl<E: fmt::Display> At<E> {
    /// Format with full trace (message + locations + all contexts).
    ///
    /// Returns a formatter that displays:
    /// - The error message (via `Display`)
    /// - All trace frame locations
    /// - All context strings at each location
    ///
    /// ## Example
    ///
    /// ```rust
    /// use whereat::{at, At};
    ///
    /// #[derive(Debug)]
    /// struct MyError(&'static str);
    ///
    /// impl std::fmt::Display for MyError {
    ///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    ///         write!(f, "{}", self.0)
    ///     }
    /// }
    ///
    /// let err: At<MyError> = at(MyError("failed")).at_str("loading config");
    /// println!("{}", err.full_trace());
    /// // Output:
    /// // failed
    /// //     at src/main.rs:10:1
    /// //         loading config
    /// ```
    #[inline]
    pub fn full_trace(&self) -> impl fmt::Display + '_ {
        AtFullTraceDisplay { at: self }
    }

    /// Format with trace locations only (message + locations, no context strings).
    ///
    /// Returns a formatter that displays:
    /// - The error message (via `Display`)
    /// - All trace frame locations
    /// - NO context strings (for compact output)
    ///
    /// ## Example
    ///
    /// ```rust
    /// use whereat::{at, At};
    ///
    /// #[derive(Debug)]
    /// struct MyError(&'static str);
    ///
    /// impl std::fmt::Display for MyError {
    ///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    ///         write!(f, "{}", self.0)
    ///     }
    /// }
    ///
    /// let err: At<MyError> = at(MyError("failed")).at_str("loading config");
    /// println!("{}", err.last_error_trace());
    /// // Output:
    /// // failed
    /// //     at src/main.rs:10:1
    /// ```
    #[inline]
    pub fn last_error_trace(&self) -> impl fmt::Display + '_ {
        AtLastErrorTraceDisplay { at: self }
    }

    /// Format just the error message (no trace).
    ///
    /// Returns a formatter that only displays the error message via `Display`.
    /// Use this when you want to show the error without any trace information.
    ///
    /// This is equivalent to using the `Display` impl directly.
    #[inline]
    pub fn last_error(&self) -> impl fmt::Display + '_ {
        AtLastErrorDisplay { at: self }
    }
}

/// Formatter that shows error message + full trace with all contexts.
struct AtFullTraceDisplay<'a, E> {
    at: &'a At<E>,
}

impl<E: fmt::Display> fmt::Display for AtFullTraceDisplay<'_, E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Show the error message
        write!(f, "{}", self.at.error)?;

        // Show trace frames
        if let Some(trace) = self.at.trace.as_ref() {
            for frame in trace.frames() {
                if let Some(loc) = frame.location() {
                    write!(f, "\n    at {}:{}:{}", loc.file(), loc.line(), loc.column())?;
                } else {
                    write!(f, "\n    [...]")?;
                }

                // Show contexts for this frame
                for ctx in frame.contexts() {
                    if let Some(text) = ctx.as_text() {
                        write!(f, "\n        {}", text)?;
                    } else if let Some(fn_name) = ctx.as_function_name() {
                        write!(f, "\n        in {}", fn_name)?;
                    } else if let Some(err) = ctx.as_error() {
                        write!(f, "\n        caused by: {}", err)?;
                        // Write nested error chain
                        let mut source = err.source();
                        let mut depth = 2;
                        while let Some(src) = source {
                            let indent = "    ".repeat(depth);
                            write!(f, "\n{}caused by: {}", indent, src)?;
                            source = src.source();
                            depth += 1;
                        }
                    } else {
                        write!(f, "\n        {}", ctx)?;
                    }
                }
            }
        }
        Ok(())
    }
}

/// Formatter that shows error message + trace locations only (no contexts).
struct AtLastErrorTraceDisplay<'a, E> {
    at: &'a At<E>,
}

impl<E: fmt::Display> fmt::Display for AtLastErrorTraceDisplay<'_, E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Show the error message
        write!(f, "{}", self.at.error)?;

        // Show trace frames (locations only, no contexts)
        if let Some(trace) = self.at.trace.as_ref() {
            for frame in trace.frames() {
                if let Some(loc) = frame.location() {
                    write!(f, "\n    at {}:{}:{}", loc.file(), loc.line(), loc.column())?;
                } else {
                    write!(f, "\n    [...]")?;
                }
            }
        }
        Ok(())
    }
}

/// Formatter that shows just the error message (no trace).
struct AtLastErrorDisplay<'a, E> {
    at: &'a At<E>,
}

impl<E: fmt::Display> fmt::Display for AtLastErrorDisplay<'_, E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.at.error)
    }
}

// ============================================================================
// Display impl for At<E>
// ============================================================================

impl<E: fmt::Display> fmt::Display for At<E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.error)
    }
}

// ============================================================================
// Error impl for At<E>
// ============================================================================

/// `At<E>` delegates [`source()`](core::error::Error::source) to `E::source()`.
///
/// Errors attached via [`.at_aside_error()`](At::at_aside_error) are **not** part of this
/// chain — they are diagnostic context stored in the trace, accessible via
/// [`.contexts()`](At::contexts) and [`.full_trace()`](At::full_trace).
///
/// See [`.at_aside_error()`](At::at_aside_error) for the rationale.
impl<E: core::error::Error> core::error::Error for At<E> {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        self.error.source()
    }
}

// ============================================================================
// From impl for At<E>
// ============================================================================

impl<E> From<E> for At<E> {
    #[inline]
    fn from(error: E) -> Self {
        At::wrap(error)
    }
}

// ============================================================================
// PartialEq impl for At<E> - compares only the error, not the trace
// ============================================================================

impl<E: PartialEq> PartialEq for At<E> {
    /// Compare two `At<E>` errors by their inner error only.
    ///
    /// The trace is metadata about *where* the error was created, not *what*
    /// the error is. Two errors with the same `E` value are equal regardless
    /// of their traces.
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.error == other.error
    }
}

impl<E: Eq> Eq for At<E> {}

impl<E: Hash> Hash for At<E> {
    /// Hash only the inner error, not the trace.
    ///
    /// Consistent with `PartialEq`: the trace is metadata, not identity.
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.error.hash(state);
    }
}

// ============================================================================
// AsRef impl for At<E>
// ============================================================================

impl<E> AsRef<E> for At<E> {
    #[inline]
    fn as_ref(&self) -> &E {
        &self.error
    }
}