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
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
//! Trace storage and trait for location tracking.
//!
//! This module provides [`AtTrace`] for storing location traces and
//! [`AtTraceable`] for types that embed their own trace.

use alloc::borrow::Cow;
use alloc::boxed::Box;
use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;
use core::panic::Location;

use crate::AtCrateInfo;
use crate::context::{AtContext, AtContextRef};

/// Context entry: (location_index, context).
type ContextEntry = (u16, AtContext);

// ============================================================================
// Depth Limits
// ============================================================================
//
// Arbitrary limits to prevent unbounded growth from consumer bugs (e.g., infinite
// recursion, accidental loops). These are intentionally generous - most real error
// traces have <20 frames and <10 contexts. If you hit these limits, you likely
// have a bug in your error handling code.

/// Maximum number of location frames in a trace.
///
/// This is an arbitrary limit (128) to prevent unbounded memory growth from
/// consumer bugs like infinite recursion. Real-world traces rarely exceed 20 frames.
/// Attempts to push beyond this limit are silently ignored.
pub const AT_MAX_FRAMES: usize = 128;

/// Maximum number of context entries in a trace.
///
/// This is an arbitrary limit (128) to prevent unbounded memory growth from
/// consumer bugs. Real-world traces rarely have more than a handful of contexts.
/// Attempts to add contexts beyond this limit are silently ignored.
pub const AT_MAX_CONTEXTS: usize = 128;

// ============================================================================
// LocationVec - configurable storage for trace locations
// ============================================================================
//
// Locations are stored as Option<&'static Location> where:
// - Some(loc) = a real captured location
// - None = skipped frame marker (displayed as [...])
//
// This eliminates the need for AtContext::Skipped and saves context allocations.
// Option<&T> has the same size as &T due to null pointer optimization.
//
// When tinyvec features are enabled, we use TinyVec which starts with inline
// storage and spills to heap when capacity is exceeded.

/// Location element type. None = skipped frame marker.
type LocationElem = Option<&'static Location<'static>>;

// ============================================================================
// LocationVec - unified via InlineVec abstraction
// ============================================================================
//
// InlineVec provides a consistent API regardless of backend (tinyvec, smallvec,
// or custom inline+heap). The N constant determines inline capacity.

/// Stack-first location storage with 4 inline slots (tinyvec-64-bytes).
#[cfg(all(
    feature = "_tinyvec-64-bytes",
    not(any(feature = "_tinyvec-128-bytes", feature = "_tinyvec-256-bytes"))
))]
type LocationVec = crate::inline_vec::InlineVec<LocationElem, 4>;

/// Stack-first location storage with 12 inline slots (tinyvec-128-bytes).
#[cfg(all(feature = "_tinyvec-128-bytes", not(feature = "_tinyvec-256-bytes")))]
type LocationVec = crate::inline_vec::InlineVec<LocationElem, 12>;

/// Stack-first location storage with 28 inline slots (tinyvec-256-bytes).
#[cfg(all(feature = "_tinyvec-256-bytes", not(feature = "_tinyvec-512-bytes")))]
type LocationVec = crate::inline_vec::InlineVec<LocationElem, 28>;

/// Stack-first location storage with 60 inline slots (tinyvec-512-bytes).
#[cfg(all(feature = "_tinyvec-512-bytes", not(feature = "_smallvec-128-bytes")))]
type LocationVec = crate::inline_vec::InlineVec<LocationElem, 60>;

/// Stack-first location storage with 12 inline slots (smallvec-128-bytes).
#[cfg(all(feature = "_smallvec-128-bytes", not(feature = "_smallvec-256-bytes")))]
type LocationVec = crate::inline_vec::InlineVec<LocationElem, 12>;

/// Stack-first location storage with 28 inline slots (smallvec-256-bytes).
#[cfg(feature = "_smallvec-256-bytes")]
type LocationVec = crate::inline_vec::InlineVec<LocationElem, 28>;

/// Inline-first location storage with 4 inline slots (default).
#[cfg(not(any(
    feature = "_tinyvec-64-bytes",
    feature = "_tinyvec-128-bytes",
    feature = "_tinyvec-256-bytes",
    feature = "_tinyvec-512-bytes",
    feature = "_smallvec-128-bytes",
    feature = "_smallvec-256-bytes"
)))]
type LocationVec = crate::inline_vec::InlineVec<LocationElem, 4>;

/// Create a new LocationVec.
#[inline]
fn location_vec_new() -> LocationVec {
    LocationVec::new()
}

// ============================================================================
// ContextVec - lazily-allocated context storage
// ============================================================================
//
// Context storage is typically empty (most traces have no context).
// Using Option<Box<Vec>> saves 16 bytes vs Vec in the common case (8 vs 24).

/// Lazily-allocated context storage. Most traces have no context.
type ContextVec = Option<Box<Vec<ContextEntry>>>;

// ============================================================================
// Fallible Allocation Helpers
// ============================================================================
//
// Uses stable try_reserve APIs where available. Box::try_new is not yet stable,
// so Box allocations use regular Box::new which can panic on OOM.
// In practice, OOM panics are rare and the error itself still propagates
// (since E is stored inline in At<E>).

/// Try to allocate a Box. Returns Some on success.
/// Note: Box::try_new is not yet stable, so this can panic on OOM.
/// The error E is stored inline, so even if tracing fails, the error propagates.
#[inline]
pub(crate) fn try_box<T>(value: T) -> Option<Box<T>> {
    // TODO: Use Box::try_new when stabilized
    Some(Box::new(value))
}

/// Try to push a location onto a LocationVec, returning false on allocation failure
/// or if [`AT_MAX_FRAMES`] limit is reached.
#[inline]
fn try_push_location(vec: &mut LocationVec, elem: LocationElem) -> bool {
    if vec.len() >= AT_MAX_FRAMES {
        return false;
    }
    vec.try_push(elem)
}

// ============================================================================
// ContextVec Helpers
// ============================================================================

/// Create a new empty ContextVec.
#[inline]
fn context_vec_new() -> ContextVec {
    None
}

/// Try to push a context entry (lazily allocates on first push).
/// Returns false on allocation failure or if [`AT_MAX_CONTEXTS`] limit is reached.
#[inline]
fn try_push_context(vec: &mut ContextVec, entry: ContextEntry) -> bool {
    let inner = vec.get_or_insert_with(|| Box::new(Vec::new()));
    if inner.len() >= AT_MAX_CONTEXTS {
        return false;
    }
    if inner.try_reserve(1).is_err() {
        return false;
    }
    inner.push(entry);
    true
}

/// Iterate over contexts.
#[inline]
fn context_iter(vec: &ContextVec) -> impl DoubleEndedIterator<Item = &ContextEntry> {
    vec.iter().flat_map(|v| v.iter())
}

// ============================================================================
// AtTrace - Trace storage for location and context tracking
// ============================================================================

/// Trace storage for location and context tracking.
///
/// Use this type directly when embedding traces in custom error types.
/// For the common case, use `At<E>` which wraps your error with a boxed trace.
///
/// ## Example: Embedding in custom error
///
/// ```rust
/// use whereat::{AtTrace, AtTraceable};
///
/// struct MyError {
///     kind: &'static str,
///     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, "{}", self.kind)
///     }
/// }
///
/// impl MyError {
///     #[track_caller]
///     fn new(kind: &'static str) -> Self {
///         Self { kind, trace: AtTrace::capture() }
///     }
/// }
///
/// // Now MyError has all the .at_*() methods from AtTraceable
/// let err = MyError::new("not_found").at_str("looking up user");
/// ```
#[derive(Debug)]
pub struct AtTrace {
    /// All locations in order (oldest first).
    locations: LocationVec,
    /// Crate info for generating repository links (stored once, not per-location).
    /// Set by `at!()` macro or `set_crate_info()` method.
    crate_info: Option<&'static AtCrateInfo>,
    /// AtContext associations: (location_index, context).
    /// Index saturates at u16::MAX; out-of-bounds associations are silently ignored.
    contexts: ContextVec,
}

impl AtTrace {
    /// Create an empty trace.
    ///
    /// Use [`capture()`](Self::capture) to create a trace with the caller's location.
    #[inline]
    pub fn new() -> Self {
        Self {
            locations: location_vec_new(),
            crate_info: None,
            contexts: context_vec_new(),
        }
    }

    /// Create a trace with the caller's location captured.
    ///
    /// This is the recommended way to start a trace in error constructors.
    ///
    /// ## Example
    ///
    /// ```rust
    /// use whereat::AtTrace;
    ///
    /// struct MyError {
    ///     trace: AtTrace,
    /// }
    ///
    /// impl MyError {
    ///     #[track_caller]
    ///     fn new() -> Self {
    ///         Self { trace: AtTrace::capture() }
    ///     }
    /// }
    /// ```
    #[track_caller]
    #[inline]
    pub fn capture() -> Self {
        let mut trace = Self::new();
        let _ = trace.try_push(Location::caller());
        trace
    }

    /// Set the crate info for this trace.
    ///
    /// This is used by `at!()` to provide repository metadata for GitHub links.
    /// Only one crate info can be set per trace - subsequent calls overwrite.
    #[inline]
    pub fn set_crate_info(&mut self, info: &'static AtCrateInfo) {
        self.crate_info = Some(info);
    }

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

    /// Add crate boundary marker, using inline storage when possible.
    ///
    /// - If no crate_info is set, stores it inline (no allocation)
    /// - If same crate_info is already set, does nothing
    /// - If different crate_info, adds a context entry (marks boundary crossing)
    #[inline]
    pub(crate) fn try_add_crate_boundary(
        &mut self,
        loc: &'static Location<'static>,
        info: &'static AtCrateInfo,
    ) {
        match self.crate_info {
            None => {
                // First crate info - store inline, no allocation
                self.crate_info = Some(info);
            }
            Some(existing) if core::ptr::eq(existing, info) => {
                // Same crate - nothing to do
            }
            Some(_) => {
                // Different crate - add boundary context
                self.try_add_context(loc, AtContext::Crate(info));
            }
        }
    }

    /// Try to push a location. Returns false if allocation fails.
    #[inline]
    pub(crate) fn try_push(&mut self, loc: &'static Location<'static>) -> bool {
        try_push_location(&mut self.locations, Some(loc))
    }

    /// Try to push a skipped frame marker. Returns false if allocation fails.
    #[inline]
    pub(crate) fn try_push_skipped(&mut self) -> bool {
        try_push_location(&mut self.locations, None)
    }

    /// Add context to the last location, or push a new location if trace is empty.
    ///
    /// This allows `at_str()` etc. to add context without creating duplicate frames.
    /// Use `try_push()` first if you need a new location, then call this for context.
    ///
    /// On allocation failure, the context may be lost but existing data is preserved.
    #[inline]
    pub(crate) fn try_add_context(&mut self, loc: &'static Location<'static>, context: AtContext) {
        // If empty, push a location first
        let idx = if self.locations.is_empty() {
            if !try_push_location(&mut self.locations, Some(loc)) {
                return;
            }
            0u16
        } else {
            (self.locations.len() - 1).min(u16::MAX as usize) as u16
        };
        // Try to push context; silently fail on OOM
        let _ = try_push_context(&mut self.contexts, (idx, context));
    }

    /// Iterate over all location entries, oldest first.
    /// Returns Option where None = skipped frame marker.
    #[inline]
    pub(crate) fn iter(&self) -> impl Iterator<Item = Option<&'static Location<'static>>> + '_ {
        // InlineVec always yields T directly (unified API)
        self.locations.iter()
    }

    /// Iterate over all context entries, newest first (loses location association).
    /// Prefer `frames()` for unified iteration.
    #[inline]
    pub(crate) fn contexts(&self) -> impl Iterator<Item = AtContextRef<'_>> {
        context_iter(&self.contexts)
            .rev()
            .map(|(_, ctx)| AtContextRef { inner: ctx })
    }

    /// Get all contexts at a specific location index.
    #[inline]
    pub(crate) fn contexts_at(&self, idx: usize) -> impl Iterator<Item = &AtContext> {
        context_iter(&self.contexts)
            .filter(move |(i, _)| *i as usize == idx)
            .map(|(_, ctx)| ctx)
    }

    /// 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());
    ///     } else {
    ///         println!("[...]");
    ///     }
    ///     for ctx in frame.contexts() {
    ///         println!("  - {}", ctx);
    ///     }
    /// }
    /// ```
    #[inline]
    pub fn frames(&self) -> impl Iterator<Item = AtFrame<'_>> {
        // InlineVec always yields T directly (unified API)
        self.locations.iter().enumerate().map(|(idx, loc)| AtFrame {
            location: loc,
            trace: self,
            index: idx,
        })
    }

    /// Get the number of frames in the trace.
    #[inline]
    pub fn frame_count(&self) -> usize {
        self.locations.len()
    }

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

    /// Take the entire trace, leaving self empty.
    ///
    /// Preserves crate_info in self (not transferred).
    #[inline]
    pub fn take(&mut self) -> AtTrace {
        AtTrace {
            locations: core::mem::take(&mut self.locations),
            crate_info: self.crate_info, // Copy, don't move
            contexts: core::mem::take(&mut self.contexts),
        }
    }

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

        let last_idx = (self.locations.len() - 1) as u16;
        let location = self.locations.pop()?;

        // Collect contexts for this location (they're stored newest-first in usage,
        // but we need to extract those with matching index)
        let mut contexts = Vec::new();
        if let Some(ref mut ctx_vec) = self.contexts {
            // Count matching contexts first for reservation
            let count = ctx_vec
                .iter()
                .rev()
                .take_while(|(idx, _)| *idx == last_idx)
                .count();
            let _ = contexts.try_reserve(count); // Best effort

            // Remove contexts with matching index from the end
            while let Some(&(idx, _)) = ctx_vec.last() {
                if idx == last_idx {
                    contexts.push(ctx_vec.pop().unwrap().1);
                } else {
                    break;
                }
            }
        }
        contexts.reverse(); // Restore original order

        Some(AtFrameOwned { location, contexts })
    }

    /// Push a segment (location + contexts) to the end of the trace.
    #[inline]
    pub fn push(&mut self, segment: AtFrameOwned) {
        let idx = self.locations.len() as u16;

        // Try to push location
        if !try_push_location(&mut self.locations, segment.location) {
            return;
        }

        // Push contexts
        for ctx in segment.contexts {
            let _ = try_push_context(&mut self.contexts, (idx, ctx));
        }
    }

    /// Pop the oldest location and its contexts from the beginning.
    ///
    /// Returns `None` if the trace is empty.
    ///
    /// Note: This is O(n) as it shifts all remaining elements.
    #[inline]
    pub fn pop_first(&mut self) -> Option<AtFrameOwned> {
        if self.locations.is_empty() {
            return None;
        }

        let location = self.locations.remove(0);

        // Collect and remove contexts for index 0, decrement remaining indices
        let mut contexts = Vec::new();
        if let Some(ref mut ctx_vec) = self.contexts {
            // Count matching contexts first for reservation
            let count = ctx_vec.iter().filter(|(idx, _)| *idx == 0).count();
            let _ = contexts.try_reserve(count); // Best effort

            let mut i = 0;
            while i < ctx_vec.len() {
                if ctx_vec[i].0 == 0 {
                    contexts.push(ctx_vec.remove(i).1);
                } else {
                    // Decrement index for remaining contexts
                    ctx_vec[i].0 -= 1;
                    i += 1;
                }
            }
        }

        Some(AtFrameOwned { location, contexts })
    }

    /// Insert a segment (location + contexts) at the beginning of the trace.
    ///
    /// Note: This is O(n) as it shifts all existing elements.
    /// On allocation failure, the operation is silently skipped.
    #[inline]
    pub fn push_first(&mut self, segment: AtFrameOwned) {
        // Shift all existing context indices up by 1
        if let Some(ref mut ctx_vec) = self.contexts {
            for (idx, _) in ctx_vec.iter_mut() {
                *idx = idx.saturating_add(1);
            }
        }

        // Insert location at beginning (returns false on allocation failure)
        if !self.locations.insert_first(segment.location) {
            return;
        }

        // Insert contexts at beginning with index 0
        if !segment.contexts.is_empty() {
            let ctx_vec = self.contexts.get_or_insert_with(|| Box::new(Vec::new()));
            if ctx_vec.try_reserve(segment.contexts.len()).is_err() {
                return;
            }
            for (i, ctx) in segment.contexts.into_iter().enumerate() {
                ctx_vec.insert(i, (0, ctx));
            }
        }
    }

    /// Append all segments from another trace to the end of this trace.
    ///
    /// The source trace is consumed.
    #[inline]
    pub fn append(&mut self, mut other: AtTrace) {
        while let Some(seg) = other.pop_first() {
            self.push(seg);
        }
    }

    /// Prepend all segments from another trace to the beginning of this trace.
    ///
    /// The source trace is consumed. On allocation failure, partial prepend may occur.
    #[inline]
    pub fn prepend(&mut self, mut other: AtTrace) {
        // Pop from other's end and insert at our beginning (reverse order)
        let count = other.frame_count();
        let mut segments = Vec::new();
        if segments.try_reserve(count).is_err() {
            return; // Silently skip on OOM, like other trace operations
        }
        while let Some(seg) = other.pop() {
            segments.push(seg);
        }
        // Insert in reverse order to maintain original order
        for seg in segments {
            self.push_first(seg);
        }
    }
}

impl Default for AtTrace {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// AtFrameOwned - Owned frame data (one location + contexts)
// ============================================================================

/// A segment of a trace: one location with its associated contexts.
///
/// Used for transferring trace segments between `At<E>` and `AtTraceable` types
/// via [`at_pop()`](AtTraceable::at_pop) and [`at_push()`](AtTraceable::at_push).
///
/// This is an advanced API for trace manipulation. Most users don't need this.
#[doc(hidden)]
#[derive(Debug)]
pub struct AtFrameOwned {
    location: Option<&'static Location<'static>>,
    contexts: Vec<AtContext>,
}

impl AtFrameOwned {
    /// Create a new segment with a location and no contexts.
    #[inline]
    pub fn new(location: Option<&'static Location<'static>>) -> Self {
        Self {
            location,
            contexts: Vec::new(),
        }
    }

    /// Create a new segment capturing the caller's location.
    #[inline]
    #[track_caller]
    pub fn capture() -> Self {
        Self::new(Some(Location::caller()))
    }

    /// Get the location (None means skipped frames marker).
    #[inline]
    pub fn location(&self) -> Option<&'static Location<'static>> {
        self.location
    }

    /// Check if this is a skipped frames marker.
    #[inline]
    pub fn is_skipped(&self) -> bool {
        self.location.is_none()
    }

    /// Iterate over contexts in this segment.
    #[inline]
    pub fn contexts(&self) -> impl Iterator<Item = AtContextRef<'_>> {
        self.contexts.iter().map(|c| AtContextRef { inner: c })
    }

    /// Number of contexts in this segment.
    #[inline]
    pub fn context_count(&self) -> usize {
        self.contexts.len()
    }

    /// Add a static string context.
    #[inline]
    pub fn with_str(mut self, msg: &'static str) -> Self {
        self.contexts.push(AtContext::Text(Cow::Borrowed(msg)));
        self
    }

    /// Add a dynamic string context.
    #[inline]
    pub fn with_string(mut self, msg: String) -> Self {
        self.contexts.push(AtContext::Text(Cow::Owned(msg)));
        self
    }

    /// Add typed context (Display).
    #[inline]
    pub fn with_data<T: fmt::Display + Send + Sync + 'static>(mut self, data: T) -> Self {
        if let Some(boxed) = try_box(data) {
            self.contexts.push(AtContext::Display(boxed));
        }
        self
    }

    /// Add typed context (Debug).
    #[inline]
    pub fn with_debug<T: fmt::Debug + Send + Sync + 'static>(mut self, data: T) -> Self {
        if let Some(boxed) = try_box(data) {
            self.contexts.push(AtContext::Debug(boxed));
        }
        self
    }
}

// ============================================================================
// AtFrame - A single frame in a trace (for iteration)
// ============================================================================

/// A single frame in a trace: location with its associated contexts.
///
/// Returned by [`AtTrace::frames()`] and [`At::frames()`](crate::At::frames).
/// Unlike [`AtFrameOwned`] which owns its data, this is a view into the trace.
///
/// ## Example
///
/// ```rust
/// use whereat::at;
///
/// #[derive(Debug)]
/// struct MyError;
///
/// let err = at(MyError).at_str("loading");
///
/// for frame in err.frames() {
///     if let Some(loc) = frame.location() {
///         println!("{}:{}", loc.file(), loc.line());
///     }
///     for ctx in frame.contexts() {
///         if let Some(text) = ctx.as_text() {
///             println!("  context: {}", text);
///         }
///     }
/// }
/// ```
#[derive(Clone, Copy)]
pub struct AtFrame<'a> {
    location: Option<&'static Location<'static>>,
    trace: &'a AtTrace,
    index: usize,
}

impl<'a> AtFrame<'a> {
    /// Get the source location, or None if this is a skipped-frames marker.
    #[inline]
    pub fn location(&self) -> Option<&'static Location<'static>> {
        self.location
    }

    /// Check if this frame is a skipped-frames marker (`[...]`).
    #[inline]
    pub fn is_skipped(&self) -> bool {
        self.location.is_none()
    }

    /// Iterate over contexts attached to this frame.
    #[inline]
    pub fn contexts(&self) -> impl Iterator<Item = AtContextRef<'a>> {
        let idx = self.index;
        context_iter(&self.trace.contexts)
            .filter(move |(i, _)| *i as usize == idx)
            .map(|(_, ctx)| AtContextRef { inner: ctx })
    }

    /// Check if this frame has any contexts.
    #[inline]
    pub fn has_contexts(&self) -> bool {
        let idx = self.index;
        context_iter(&self.trace.contexts).any(|(i, _)| *i as usize == idx)
    }
}

impl fmt::Debug for AtFrame<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.location {
            Some(loc) => {
                write!(f, "at {}:{}", loc.file(), loc.line())?;
                for ctx in self.contexts() {
                    write!(f, " ({:?})", ctx)?;
                }
                Ok(())
            }
            None => write!(f, "[...]"),
        }
    }
}

// ============================================================================
// AtTraceBoxed - Boxed optional trace for small error footprint
// ============================================================================

/// A boxed optional trace for keeping error types small.
///
/// This type is always 8 bytes (one pointer) regardless of trace size.
/// The trace is allocated lazily on first mutation.
///
/// This is an advanced API. Most users should use `Option<Box<AtTrace>>` directly
/// or embed `AtTrace` inline in their error types.
#[doc(hidden)]
#[derive(Default)]
pub struct AtTraceBoxed(Option<Box<AtTrace>>);

impl AtTraceBoxed {
    /// Create an empty boxed trace (no allocation).
    #[inline]
    pub const fn new() -> Self {
        Self(None)
    }

    /// Create a boxed trace with the caller's location captured.
    #[track_caller]
    #[inline]
    pub fn capture() -> Self {
        Self(Some(Box::new(AtTrace::capture())))
    }

    /// Check if the trace is empty (None or inner is empty).
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.0.as_ref().is_none_or(|t| t.is_empty())
    }

    /// Get immutable reference to the trace, if allocated.
    #[inline]
    pub fn as_ref(&self) -> Option<&AtTrace> {
        self.0.as_deref()
    }

    /// Get mutable reference to the trace, if allocated.
    #[inline]
    pub fn as_mut(&mut self) -> Option<&mut AtTrace> {
        self.0.as_deref_mut()
    }

    /// Get mutable reference, allocating if needed.
    ///
    /// Use this in `AtTraceable::trace_mut()` implementations.
    #[inline]
    pub fn get_or_insert_mut(&mut self) -> &mut AtTrace {
        self.0.get_or_insert_with(|| Box::new(AtTrace::new()))
    }

    /// Take the trace, leaving self empty.
    #[inline]
    pub fn take(&mut self) -> Option<AtTrace> {
        self.0.take().map(|b| *b)
    }

    /// Set the trace from an existing AtTrace.
    #[inline]
    pub fn set(&mut self, trace: AtTrace) {
        if trace.is_empty() {
            self.0 = None;
        } else {
            self.0 = Some(Box::new(trace));
        }
    }

    /// Iterate over frames (location + contexts pairs), oldest first.
    ///
    /// Returns an empty iterator if the trace hasn't been allocated.
    pub fn frames(&self) -> impl Iterator<Item = AtFrame<'_>> {
        self.0.iter().flat_map(|t| t.frames())
    }

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

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

impl fmt::Debug for AtTraceBoxed {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.0 {
            Some(trace) => fmt::Debug::fmt(trace, f),
            None => write!(f, "AtTraceBoxed(empty)"),
        }
    }
}

impl From<AtTrace> for AtTraceBoxed {
    fn from(trace: AtTrace) -> Self {
        if trace.is_empty() {
            Self(None)
        } else {
            Self(Some(Box::new(trace)))
        }
    }
}

impl From<AtTraceBoxed> for Option<AtTrace> {
    fn from(boxed: AtTraceBoxed) -> Self {
        boxed.0.map(|b| *b)
    }
}

// ============================================================================
// AtTraceable Trait - for embedding traces in custom error types
// ============================================================================

/// Trait for types that embed an [`AtTrace`] directly.
///
/// Implement this trait to get all the `.at_*()` methods on your custom error types.
/// Three methods are required:
/// - [`trace_mut()`](Self::trace_mut) - mutable access to trace
/// - [`trace()`](Self::trace) - immutable access to trace
/// - [`fmt_message()`](Self::fmt_message) - format the error message
///
/// ## Example: Inline trace
///
/// ```rust
/// use whereat::{AtTrace, AtTraceable};
/// use std::fmt;
///
/// struct MyError {
///     kind: &'static str,
///     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 fmt::Formatter<'_>) -> fmt::Result {
///         write!(f, "{}", self.kind)
///     }
/// }
///
/// impl MyError {
///     #[track_caller]
///     fn new(kind: &'static str) -> Self {
///         Self { kind, trace: AtTrace::capture() }
///     }
/// }
///
/// // Now you can chain .at_*() methods
/// let err = MyError::new("not_found").at_str("looking up user");
/// ```
///
/// ## Example: Boxed trace (smaller error type)
///
/// ```rust
/// use whereat::{AtTrace, AtTraceable};
/// use std::fmt;
///
/// struct MyError {
///     kind: &'static str,
///     trace: Box<AtTrace>,  // 8 bytes instead of sizeof(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 fmt::Formatter<'_>) -> fmt::Result {
///         write!(f, "{}", self.kind)
///     }
/// }
///
/// impl MyError {
///     #[track_caller]
///     fn new(kind: &'static str) -> Self {
///         Self { kind, trace: Box::new(AtTrace::capture()) }
///     }
/// }
/// ```
///
/// ## Example: Optional boxed trace (lazy allocation)
///
/// ```rust
/// use whereat::{AtTrace, AtTraceable};
/// use std::fmt;
///
/// struct MyError {
///     kind: &'static str,
///     trace: Option<Box<AtTrace>>,  // None until first .at_*() call
/// }
///
/// impl AtTraceable for MyError {
///     fn trace_mut(&mut self) -> &mut AtTrace {
///         self.trace.get_or_insert_with(|| Box::new(AtTrace::new()))
///     }
///     fn trace(&self) -> Option<&AtTrace> { self.trace.as_deref() }
///     fn fmt_message(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
///         write!(f, "{}", self.kind)
///     }
/// }
///
/// impl MyError {
///     fn new(kind: &'static str) -> Self {  // No #[track_caller] needed
///         Self { kind, trace: None }
///     }
/// }
///
/// // Trace allocated lazily on first .at_*() call
/// let err = MyError::new("not_found").at_str("context");
/// ```
///
/// ## Why use this over `At<E>`?
///
/// Use `AtTraceable` when you want:
/// - Full control over your error type's layout
/// - Custom storage strategy (inline, boxed, or optional)
/// - To define your own error constructors
///
/// Use `At<E>` when you want:
/// - Minimal changes to existing code
/// - To wrap errors from external crates
/// - The simplest possible setup
pub trait AtTraceable: Sized {
    /// Get a mutable reference to the embedded trace.
    fn trace_mut(&mut self) -> &mut AtTrace;

    /// Get an immutable reference to the trace, if allocated.
    ///
    /// Returns `None` if no trace has been allocated yet (for lazy storage patterns).
    /// For inline storage, this always returns `Some`.
    fn trace(&self) -> Option<&AtTrace>;

    /// Format just the error message (without trace).
    ///
    /// This is used by the trace formatters to show the error message
    /// separately from the trace. Typically delegates to your error kind's Display.
    ///
    /// ## Example
    ///
    /// ```rust
    /// use whereat::{AtTrace, AtTraceable};
    /// use std::fmt;
    ///
    /// #[derive(Debug)]
    /// enum ErrorKind {
    ///     NotFound,
    ///     InvalidInput(String),
    /// }
    ///
    /// struct MyError {
    ///     kind: ErrorKind,
    ///     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 fmt::Formatter<'_>) -> fmt::Result {
    ///         match &self.kind {
    ///             ErrorKind::NotFound => write!(f, "not found"),
    ///             ErrorKind::InvalidInput(s) => write!(f, "invalid input: {}", s),
    ///         }
    ///     }
    /// }
    /// ```
    fn fmt_message(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result;

    /// Add the caller's location to the trace.
    #[track_caller]
    #[inline]
    fn at(mut self) -> Self {
        let _ = self.trace_mut().try_push(Location::caller());
        self
    }

    /// Add a static string context to the last location (or create one if empty).
    #[track_caller]
    #[inline]
    fn at_str(mut self, msg: &'static str) -> Self {
        let context = AtContext::Text(Cow::Borrowed(msg));
        self.trace_mut()
            .try_add_context(Location::caller(), context);
        self
    }

    /// Add a lazily-computed string context to the last location (or create one if empty).
    #[track_caller]
    #[inline]
    fn at_string(mut self, f: impl FnOnce() -> String) -> Self {
        let context = AtContext::Text(Cow::Owned(f()));
        self.trace_mut()
            .try_add_context(Location::caller(), context);
        self
    }

    /// Add lazily-computed typed context (Display) to the last location (or create one if empty).
    #[track_caller]
    #[inline]
    fn at_data<T: fmt::Display + Send + Sync + 'static>(mut self, f: impl FnOnce() -> T) -> Self {
        let ctx = f();
        let Some(boxed_ctx) = try_box(ctx) else {
            return self;
        };
        let context = AtContext::Display(boxed_ctx);
        self.trace_mut()
            .try_add_context(Location::caller(), context);
        self
    }

    /// Add lazily-computed typed context (Debug) to the last location (or create one if empty).
    #[track_caller]
    #[inline]
    fn at_debug<T: fmt::Debug + Send + Sync + 'static>(mut self, f: impl FnOnce() -> T) -> Self {
        let ctx = f();
        let Some(boxed_ctx) = try_box(ctx) else {
            return self;
        };
        let context = AtContext::Debug(boxed_ctx);
        self.trace_mut()
            .try_add_context(Location::caller(), context);
        self
    }

    /// Attach a related error as diagnostic context on the last frame.
    ///
    /// The attached error is **not** part of the `.source()` chain — it is only
    /// visible via trace display and `.contexts()` iteration.
    #[track_caller]
    #[inline]
    fn at_aside_error<E: core::error::Error + Send + Sync + 'static>(mut self, err: E) -> Self {
        let Some(boxed_err) = try_box(err) else {
            return self;
        };
        let context = AtContext::Error(boxed_err);
        self.trace_mut()
            .try_add_context(Location::caller(), context);
        self
    }

    /// Attach an error as diagnostic context (not in `.source()` chain).
    #[deprecated(
        since = "0.1.4",
        note = "Renamed to `at_aside_error()`. The attached error is NOT part of the `.source()` chain."
    )]
    #[track_caller]
    #[inline]
    fn at_error<E: core::error::Error + Send + Sync + 'static>(mut self, err: E) -> Self {
        let Some(boxed_err) = try_box(err) else {
            return self;
        };
        let context = AtContext::Error(boxed_err);
        self.trace_mut()
            .try_add_context(Location::caller(), context);
        self
    }

    /// Add a crate boundary marker to the last location (or create one if empty).
    ///
    /// Uses inline storage if no crate_info is set yet; only allocates a context
    /// entry when crossing to a different crate.
    #[track_caller]
    #[inline]
    fn at_crate(mut self, info: &'static AtCrateInfo) -> Self {
        self.trace_mut()
            .try_add_crate_boundary(Location::caller(), info);
        self
    }

    /// Add a skip marker to indicate skipped frames.
    /// Displayed as `[...]` in trace output.
    #[doc(hidden)]
    #[inline]
    fn at_skipped_frames(mut self) -> Self {
        // None in locations vec = skipped frame marker
        let _ = self.trace_mut().try_push_skipped();
        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::{AtTrace, AtTraceable};
    ///
    /// 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")
    ///     }
    /// }
    ///
    /// impl MyError {
    ///     #[track_caller]
    ///     fn new() -> Self {
    ///         Self { trace: AtTrace::capture() }
    ///     }
    /// }
    ///
    /// fn do_something() -> Result<(), MyError> {
    ///     Err(MyError::new().at_fn(|| {}))  // Captures file:line + "do_something"
    /// }
    /// ```
    #[track_caller]
    #[inline]
    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_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.
    #[track_caller]
    #[inline]
    fn at_named(mut self, name: &'static str) -> Self {
        let loc = Location::caller();
        let trace = self.trace_mut();
        let _ = trace.try_push(loc);
        let context = AtContext::FunctionName(name);
        trace.try_add_context(loc, context);
        self
    }

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

    /// Pop the most recent location and its contexts from the trace.
    #[inline]
    fn at_pop(&mut self) -> Option<AtFrameOwned> {
        self.trace_mut().pop()
    }

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

    /// Pop the oldest location and its contexts from the trace.
    #[inline]
    fn at_first_pop(&mut self) -> Option<AtFrameOwned> {
        self.trace_mut().pop_first()
    }

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

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

    /// Convert to another `AtTraceable` type, transferring the trace.
    ///
    /// The trace is moved from self to the new error.
    fn map_traceable<E2, F>(mut self, f: F) -> E2
    where
        F: FnOnce(Self) -> E2,
        E2: AtTraceable,
    {
        let trace = self.trace_mut().take();
        let mut new_err = f(self);
        *new_err.trace_mut() = trace;
        new_err
    }

    /// Convert to `At<E2>`, transferring the trace.
    fn into_at<E2, F>(mut self, f: F) -> crate::At<E2>
    where
        F: FnOnce(Self) -> E2,
    {
        let trace = self.trace_mut().take();
        let error = f(self);
        crate::At::from_parts(error, trace)
    }

    // ========================================================================
    // Formatting methods
    // ========================================================================

    /// Format with full trace (message + all frames with contexts).
    ///
    /// Returns a formatter that displays:
    /// - The error message (via `fmt_message`)
    /// - All trace frames with locations
    /// - All context strings attached to each frame
    /// - Nested error chains for error contexts
    ///
    /// ## Example
    ///
    /// ```rust
    /// use whereat::{AtTrace, AtTraceable};
    /// use std::fmt;
    ///
    /// struct MyError {
    ///     msg: &'static str,
    ///     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 fmt::Formatter<'_>) -> fmt::Result {
    ///         write!(f, "{}", self.msg)
    ///     }
    /// }
    ///
    /// impl MyError {
    ///     #[track_caller]
    ///     fn new(msg: &'static str) -> Self {
    ///         Self { msg, trace: AtTrace::capture() }
    ///     }
    /// }
    ///
    /// let err = MyError::new("something failed").at_str("while loading");
    /// println!("{}", err.full_trace());
    /// // Output:
    /// // something failed
    /// //     at src/main.rs:10:15
    /// //         while loading
    /// ```
    fn full_trace(&self) -> impl fmt::Display + '_ {
        FullTraceDisplay { error: self }
    }

    /// Format with trace locations only (message + locations, no context strings).
    ///
    /// Returns a formatter that displays:
    /// - The error message (via `fmt_message`)
    /// - All trace frame locations
    /// - NO context strings (for compact output)
    ///
    /// ## Example
    ///
    /// ```rust
    /// use whereat::{AtTrace, AtTraceable};
    /// use std::fmt;
    ///
    /// struct MyError {
    ///     msg: &'static str,
    ///     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 fmt::Formatter<'_>) -> fmt::Result {
    ///         write!(f, "{}", self.msg)
    ///     }
    /// }
    ///
    /// impl MyError {
    ///     #[track_caller]
    ///     fn new(msg: &'static str) -> Self {
    ///         Self { msg, trace: AtTrace::capture() }
    ///     }
    /// }
    ///
    /// let err = MyError::new("something failed").at_str("while loading");
    /// println!("{}", err.last_error_trace());
    /// // Output:
    /// // something failed
    /// //     at src/main.rs:10:15
    /// // (note: "while loading" context is omitted)
    /// ```
    fn last_error_trace(&self) -> impl fmt::Display + '_ {
        LastErrorTraceDisplay { error: self }
    }

    /// Format just the error message (no trace).
    ///
    /// Returns a formatter that only displays the error message via `fmt_message`.
    /// Use this when you want to show the error without any trace information.
    fn last_error(&self) -> impl fmt::Display + '_ {
        LastErrorDisplay { error: self }
    }
}

// ============================================================================
// Trace formatters for AtTraceable
// ============================================================================

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

impl<E: AtTraceable> fmt::Display for FullTraceDisplay<'_, E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Show the error message
        self.error.fmt_message(f)?;

        // Show trace frames
        if let Some(trace) = self.error.trace() {
            // Track current crate for boundary display
            let mut current_crate: Option<&str> = trace.crate_info().map(|i| i.name());

            for frame in trace.frames() {
                // Check for crate boundary before showing location
                for ctx in frame.contexts() {
                    if let Some(info) = ctx.as_crate_info() {
                        let from = current_crate.unwrap_or("?");
                        let to = info.name();
                        write!(f, "\n    ─── {} (above) → {} (below) ───", from, to)?;
                        current_crate = Some(to);
                    }
                }

                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 (skip crate boundaries, already shown)
                for ctx in frame.contexts() {
                    if ctx.as_crate_info().is_some() {
                        continue;
                    }
                    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 LastErrorTraceDisplay<'a, E: AtTraceable> {
    error: &'a E,
}

impl<E: AtTraceable> fmt::Display for LastErrorTraceDisplay<'_, E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Show the error message
        self.error.fmt_message(f)?;

        // Show trace frames (locations only, no contexts)
        if let Some(trace) = self.error.trace() {
            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 LastErrorDisplay<'a, E: AtTraceable> {
    error: &'a E,
}

impl<E: AtTraceable> fmt::Display for LastErrorDisplay<'_, E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.error.fmt_message(f)
    }
}