facet-pretty 0.44.4

Pretty-printing for Facet types with syntax highlighting and customizable formatting
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
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
//! Pretty printer for Shape types as Rust-like code
//!
//! This module provides functionality to format a `Shape` as Rust source code,
//! showing the type definition with its attributes.

use alloc::borrow::Cow;
use alloc::collections::BTreeMap;
use alloc::collections::BTreeSet;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use core::fmt::Write;

use facet_core::{
    Attr, ConstTypeId, Def, EnumRepr, EnumType, Field, PointerType, Shape, StructKind, StructType,
    Type, UserType, Variant,
};
use owo_colors::OwoColorize;

/// Tokyo Night color scheme for syntax highlighting
pub mod colors {
    use owo_colors::Style;

    /// Keywords: struct, enum, pub, etc. (purple)
    pub const fn keyword() -> Style {
        Style::new().fg_rgb::<187, 154, 247>()
    }

    /// Type names and identifiers (light blue)
    pub const fn type_name() -> Style {
        Style::new().fg_rgb::<192, 202, 245>()
    }

    /// Field names (cyan)
    pub const fn field_name() -> Style {
        Style::new().fg_rgb::<125, 207, 255>()
    }

    /// Primitive types: u8, i32, bool, String, etc. (teal)
    pub const fn primitive() -> Style {
        Style::new().fg_rgb::<115, 218, 202>()
    }

    /// Punctuation: {, }, (, ), :, etc. (gray-blue)
    pub const fn punctuation() -> Style {
        Style::new().fg_rgb::<154, 165, 206>()
    }

    /// Attribute markers: #[...] (light cyan)
    pub const fn attribute() -> Style {
        Style::new().fg_rgb::<137, 221, 255>()
    }

    /// Attribute content: derive, facet, repr (blue)
    pub const fn attribute_content() -> Style {
        Style::new().fg_rgb::<122, 162, 247>()
    }

    /// String literals (green)
    pub const fn string() -> Style {
        Style::new().fg_rgb::<158, 206, 106>()
    }

    /// Container types: Vec, Option, HashMap (orange)
    pub const fn container() -> Style {
        Style::new().fg_rgb::<255, 158, 100>()
    }

    /// Doc comments (muted gray)
    pub const fn comment() -> Style {
        Style::new().fg_rgb::<86, 95, 137>()
    }
}

/// Configuration options for shape formatting
#[derive(Clone, Debug, Default)]
pub struct ShapeFormatConfig {
    /// Whether to include doc comments in the output
    pub show_doc_comments: bool,
    /// Whether to include third-party (namespaced) attributes
    pub show_third_party_attrs: bool,
    /// Whether to expand and print nested types (default: true)
    pub expand_nested_types: bool,
}

impl ShapeFormatConfig {
    /// Create a new config with default settings (no doc comments, no third-party attrs, expand nested)
    pub fn new() -> Self {
        Self {
            expand_nested_types: true,
            ..Self::default()
        }
    }

    /// Enable doc comment display
    pub const fn with_doc_comments(mut self) -> Self {
        self.show_doc_comments = true;
        self
    }

    /// Enable third-party attribute display
    pub const fn with_third_party_attrs(mut self) -> Self {
        self.show_third_party_attrs = true;
        self
    }

    /// Enable all metadata (doc comments and third-party attrs)
    pub const fn with_all_metadata(mut self) -> Self {
        self.show_doc_comments = true;
        self.show_third_party_attrs = true;
        self
    }

    /// Disable nested type expansion (only format the root type)
    pub const fn without_nested_types(mut self) -> Self {
        self.expand_nested_types = false;
        self
    }
}

/// A segment in a path through a type structure
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum PathSegment {
    /// A field name in a struct
    Field(Cow<'static, str>),
    /// A variant name in an enum
    Variant(Cow<'static, str>),
    /// An index in a list/array/tuple
    Index(usize),
    /// A key in a map (stored as formatted string representation)
    Key(Cow<'static, str>),
}

/// A path to a location within a type structure
pub type Path = Vec<PathSegment>;

/// A byte span in formatted output (start, end)
pub type Span = (usize, usize);

/// Spans for a field or variant, tracking both key (name) and value (type) positions
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FieldSpan {
    /// Span of the field/variant name (e.g., "max_retries" in "max_retries: u8")
    pub key: Span,
    /// Span of the type annotation (e.g., "u8" in "max_retries: u8")
    pub value: Span,
}

/// Result of formatting a shape with span tracking
#[derive(Debug)]
pub struct FormattedShape {
    /// The formatted text (plain text, no ANSI colors)
    pub text: String,
    /// Map from paths to their field spans (key + value) in `text`
    pub spans: BTreeMap<Path, FieldSpan>,
    /// Span of the type name (e.g., "Server" in "struct Server {")
    pub type_name_span: Option<Span>,
    /// Span covering the whole type definition
    pub type_span: Option<Span>,
    /// Span of the end token for the type definition (e.g., "}" or ";")
    pub type_end_span: Option<Span>,
}

/// Strip ANSI escape codes from a string
pub fn strip_ansi(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    let mut chars = s.chars().peekable();

    while let Some(c) = chars.next() {
        if c == '\x1b' {
            // Skip escape sequence
            if chars.peek() == Some(&'[') {
                chars.next(); // consume '['
                // Skip until we hit a letter (the terminator)
                while let Some(&next) = chars.peek() {
                    chars.next();
                    if next.is_ascii_alphabetic() {
                        break;
                    }
                }
            }
        } else {
            result.push(c);
        }
    }
    result
}

/// Format a Shape as Rust-like source code (plain text, no colors)
///
/// By default, this includes doc comments and third-party attributes.
pub fn format_shape(shape: &Shape) -> String {
    strip_ansi(&format_shape_colored(shape))
}

/// Format a Shape as Rust-like source code with config options (plain text, no colors)
pub fn format_shape_with_config(shape: &Shape, config: &ShapeFormatConfig) -> String {
    strip_ansi(&format_shape_colored_with_config(shape, config))
}

/// Format a Shape with span tracking for each field/variant
/// Note: spans are computed on the plain text (no ANSI codes)
///
/// By default, this includes doc comments and third-party attributes.
pub fn format_shape_with_spans(shape: &Shape) -> FormattedShape {
    format_shape_with_spans_and_config(shape, &ShapeFormatConfig::default().with_all_metadata())
}

/// Format a Shape with span tracking and config options
/// Note: spans are computed on the plain text (no ANSI codes)
pub fn format_shape_with_spans_and_config(
    shape: &Shape,
    config: &ShapeFormatConfig,
) -> FormattedShape {
    let mut ctx = SpanTrackingContext::new(config);
    format_shape_into_with_spans(shape, &mut ctx).expect("Formatting failed");
    FormattedShape {
        text: ctx.output,
        spans: ctx.spans,
        type_name_span: ctx.type_name_span,
        type_span: ctx.type_span,
        type_end_span: ctx.type_end_span,
    }
}

/// Format a Shape as Rust-like source code with ANSI colors (Tokyo Night theme)
///
/// By default, this includes doc comments and third-party attributes.
pub fn format_shape_colored(shape: &Shape) -> String {
    format_shape_colored_with_config(shape, &ShapeFormatConfig::default().with_all_metadata())
}

/// Format a Shape as Rust-like source code with ANSI colors and config options
pub fn format_shape_colored_with_config(shape: &Shape, config: &ShapeFormatConfig) -> String {
    let mut output = String::new();
    format_shape_colored_into_with_config(shape, &mut output, config).expect("Formatting failed");
    output
}

/// Format a Shape with ANSI colors into an existing String
pub fn format_shape_colored_into(shape: &Shape, output: &mut String) -> core::fmt::Result {
    format_shape_colored_into_with_config(shape, output, &ShapeFormatConfig::default())
}

/// Format a Shape with ANSI colors into an existing String with config options
pub fn format_shape_colored_into_with_config(
    shape: &Shape,
    output: &mut String,
    config: &ShapeFormatConfig,
) -> core::fmt::Result {
    let mut printed: BTreeSet<ConstTypeId> = BTreeSet::new();
    let mut queue: Vec<&Shape> = Vec::new();
    queue.push(shape);

    while let Some(current) = queue.pop() {
        if !printed.insert(current.id) {
            continue;
        }

        if printed.len() > 1 {
            writeln!(output)?;
            writeln!(output)?;
        }

        match current.def {
            Def::Map(_) | Def::List(_) | Def::Option(_) | Def::Array(_) => {
                printed.remove(&current.id);
                continue;
            }
            _ => {}
        }

        match &current.ty {
            Type::User(user_type) => match user_type {
                UserType::Struct(struct_type) => {
                    format_struct_colored(current, struct_type, output, config)?;
                    collect_nested_types(struct_type, &mut queue);
                }
                UserType::Enum(enum_type) => {
                    format_enum_colored(current, enum_type, output, config)?;
                    for variant in enum_type.variants {
                        collect_nested_types(&variant.data, &mut queue);
                    }
                }
                UserType::Union(_) | UserType::Opaque => {
                    printed.remove(&current.id);
                }
            },
            _ => {
                printed.remove(&current.id);
            }
        }
    }
    Ok(())
}

fn format_struct_colored(
    shape: &Shape,
    struct_type: &StructType,
    output: &mut String,
    config: &ShapeFormatConfig,
) -> core::fmt::Result {
    // Write doc comments for the struct if enabled
    if config.show_doc_comments {
        write_doc_comments_colored(shape.doc, output, "")?;
    }

    // #[derive(Facet)]
    write!(output, "{}", "#[".style(colors::attribute()))?;
    write!(output, "{}", "derive".style(colors::attribute_content()))?;
    write!(output, "{}", "(".style(colors::attribute()))?;
    write!(output, "{}", "Facet".style(colors::attribute_content()))?;
    writeln!(output, "{}", ")]".style(colors::attribute()))?;

    // Write facet attributes if any
    write_facet_attrs_colored(shape, output)?;

    // Write third-party attributes if enabled
    if config.show_third_party_attrs {
        write_third_party_attrs_colored(shape.attributes, output, "")?;
    }

    match struct_type.kind {
        StructKind::Struct => {
            write!(output, "{} ", "struct".style(colors::keyword()))?;
            write!(
                output,
                "{}",
                shape.type_identifier.style(colors::type_name())
            )?;
            writeln!(output, " {}", "{".style(colors::punctuation()))?;

            for (i, field) in struct_type.fields.iter().enumerate() {
                // Blank line between fields (not before the first one)
                if i > 0 {
                    writeln!(output)?;
                }
                // Write doc comments for the field if enabled
                if config.show_doc_comments {
                    write_doc_comments_colored(field.doc, output, "    ")?;
                }
                // Write third-party attributes for the field if enabled
                if config.show_third_party_attrs {
                    write_field_third_party_attrs_colored(field, output, "    ")?;
                }
                write!(output, "    {}", field.name.style(colors::field_name()))?;
                write!(output, "{} ", ":".style(colors::punctuation()))?;
                write_type_name_colored(field.shape(), output)?;
                writeln!(output, "{}", ",".style(colors::punctuation()))?;
            }
            write!(output, "{}", "}".style(colors::punctuation()))?;
        }
        StructKind::Tuple | StructKind::TupleStruct => {
            write!(output, "{} ", "struct".style(colors::keyword()))?;
            write!(
                output,
                "{}",
                shape.type_identifier.style(colors::type_name())
            )?;
            write!(output, "{}", "(".style(colors::punctuation()))?;
            for (i, field) in struct_type.fields.iter().enumerate() {
                if i > 0 {
                    write!(output, "{} ", ",".style(colors::punctuation()))?;
                }
                write_type_name_colored(field.shape(), output)?;
            }
            write!(
                output,
                "{}{}",
                ")".style(colors::punctuation()),
                ";".style(colors::punctuation())
            )?;
        }
        StructKind::Unit => {
            write!(output, "{} ", "struct".style(colors::keyword()))?;
            write!(
                output,
                "{}",
                shape.type_identifier.style(colors::type_name())
            )?;
            write!(output, "{}", ";".style(colors::punctuation()))?;
        }
    }
    Ok(())
}

fn format_enum_colored(
    shape: &Shape,
    enum_type: &EnumType,
    output: &mut String,
    config: &ShapeFormatConfig,
) -> core::fmt::Result {
    // Write doc comments for the enum if enabled
    if config.show_doc_comments {
        write_doc_comments_colored(shape.doc, output, "")?;
    }

    // #[derive(Facet)]
    write!(output, "{}", "#[".style(colors::attribute()))?;
    write!(output, "{}", "derive".style(colors::attribute_content()))?;
    write!(output, "{}", "(".style(colors::attribute()))?;
    write!(output, "{}", "Facet".style(colors::attribute_content()))?;
    writeln!(output, "{}", ")]".style(colors::attribute()))?;

    // Write repr for the discriminant type
    let repr_str = match enum_type.enum_repr {
        EnumRepr::Rust => None,
        EnumRepr::RustNPO => None,
        EnumRepr::U8 => Some("u8"),
        EnumRepr::U16 => Some("u16"),
        EnumRepr::U32 => Some("u32"),
        EnumRepr::U64 => Some("u64"),
        EnumRepr::USize => Some("usize"),
        EnumRepr::I8 => Some("i8"),
        EnumRepr::I16 => Some("i16"),
        EnumRepr::I32 => Some("i32"),
        EnumRepr::I64 => Some("i64"),
        EnumRepr::ISize => Some("isize"),
    };

    if let Some(repr) = repr_str {
        write!(output, "{}", "#[".style(colors::attribute()))?;
        write!(output, "{}", "repr".style(colors::attribute_content()))?;
        write!(output, "{}", "(".style(colors::attribute()))?;
        write!(output, "{}", repr.style(colors::primitive()))?;
        writeln!(output, "{}", ")]".style(colors::attribute()))?;
    }

    // Write facet attributes if any
    write_facet_attrs_colored(shape, output)?;

    // Write third-party attributes if enabled
    if config.show_third_party_attrs {
        write_third_party_attrs_colored(shape.attributes, output, "")?;
    }

    // enum Name {
    write!(output, "{} ", "enum".style(colors::keyword()))?;
    write!(
        output,
        "{}",
        shape.type_identifier.style(colors::type_name())
    )?;
    writeln!(output, " {}", "{".style(colors::punctuation()))?;

    for (vi, variant) in enum_type.variants.iter().enumerate() {
        // Blank line between variants (not before the first one)
        if vi > 0 {
            writeln!(output)?;
        }
        // Write doc comments for the variant if enabled
        if config.show_doc_comments {
            write_doc_comments_colored(variant.doc, output, "    ")?;
        }
        // Write third-party attributes for the variant if enabled
        if config.show_third_party_attrs {
            write_variant_third_party_attrs_colored(variant, output, "    ")?;
        }

        match variant.data.kind {
            StructKind::Unit => {
                write!(output, "    {}", variant.name.style(colors::type_name()))?;
                writeln!(output, "{}", ",".style(colors::punctuation()))?;
            }
            StructKind::Tuple | StructKind::TupleStruct => {
                write!(output, "    {}", variant.name.style(colors::type_name()))?;
                write!(output, "{}", "(".style(colors::punctuation()))?;
                for (i, field) in variant.data.fields.iter().enumerate() {
                    if i > 0 {
                        write!(output, "{} ", ",".style(colors::punctuation()))?;
                    }
                    write_type_name_colored(field.shape(), output)?;
                }
                write!(output, "{}", ")".style(colors::punctuation()))?;
                writeln!(output, "{}", ",".style(colors::punctuation()))?;
            }
            StructKind::Struct => {
                write!(output, "    {}", variant.name.style(colors::type_name()))?;
                writeln!(output, " {}", "{".style(colors::punctuation()))?;
                for (fi, field) in variant.data.fields.iter().enumerate() {
                    // Blank line between variant fields (not before the first one)
                    if fi > 0 {
                        writeln!(output)?;
                    }
                    // Write doc comments for variant fields if enabled
                    if config.show_doc_comments {
                        write_doc_comments_colored(field.doc, output, "        ")?;
                    }
                    // Write third-party attributes for variant fields if enabled
                    if config.show_third_party_attrs {
                        write_field_third_party_attrs_colored(field, output, "        ")?;
                    }
                    write!(output, "        {}", field.name.style(colors::field_name()))?;
                    write!(output, "{} ", ":".style(colors::punctuation()))?;
                    write_type_name_colored(field.shape(), output)?;
                    writeln!(output, "{}", ",".style(colors::punctuation()))?;
                }
                write!(output, "    {}", "}".style(colors::punctuation()))?;
                writeln!(output, "{}", ",".style(colors::punctuation()))?;
            }
        }
    }

    write!(output, "{}", "}".style(colors::punctuation()))?;
    Ok(())
}

fn write_facet_attrs_colored(shape: &Shape, output: &mut String) -> core::fmt::Result {
    let mut attrs: Vec<String> = Vec::new();

    if let Some(tag) = shape.get_tag_attr() {
        if let Some(content) = shape.get_content_attr() {
            attrs.push(alloc::format!(
                "{}{}{}{}{}{}{}{}{}",
                "tag".style(colors::attribute_content()),
                " = ".style(colors::punctuation()),
                "\"".style(colors::string()),
                tag.style(colors::string()),
                "\"".style(colors::string()),
                ", ".style(colors::punctuation()),
                "content".style(colors::attribute_content()),
                " = ".style(colors::punctuation()),
                format!("\"{content}\"").style(colors::string()),
            ));
        } else {
            attrs.push(alloc::format!(
                "{}{}{}",
                "tag".style(colors::attribute_content()),
                " = ".style(colors::punctuation()),
                format!("\"{tag}\"").style(colors::string()),
            ));
        }
    }

    if shape.is_untagged() {
        attrs.push(alloc::format!(
            "{}",
            "untagged".style(colors::attribute_content())
        ));
    }

    if shape.has_deny_unknown_fields_attr() {
        attrs.push(alloc::format!(
            "{}",
            "deny_unknown_fields".style(colors::attribute_content())
        ));
    }

    if !attrs.is_empty() {
        write!(output, "{}", "#[".style(colors::attribute()))?;
        write!(output, "{}", "facet".style(colors::attribute_content()))?;
        write!(output, "{}", "(".style(colors::attribute()))?;
        write!(
            output,
            "{}",
            attrs.join(&format!("{}", ", ".style(colors::punctuation())))
        )?;
        writeln!(output, "{}", ")]".style(colors::attribute()))?;
    }

    Ok(())
}

/// Write doc comments with the given indentation prefix
fn write_doc_comments_colored(
    doc: &[&str],
    output: &mut String,
    indent: &str,
) -> core::fmt::Result {
    for line in doc {
        write!(output, "{indent}")?;
        writeln!(output, "{}", format!("///{line}").style(colors::comment()))?;
    }
    Ok(())
}

/// Write third-party (namespaced) attributes from a Shape's attributes
/// Groups attributes by namespace, e.g. `#[facet(args::named, args::short)]`
fn write_third_party_attrs_colored(
    attributes: &[Attr],
    output: &mut String,
    indent: &str,
) -> core::fmt::Result {
    // Group attributes by namespace
    let mut by_namespace: BTreeMap<&'static str, Vec<&'static str>> = BTreeMap::new();
    for attr in attributes {
        if let Some(ns) = attr.ns {
            by_namespace.entry(ns).or_default().push(attr.key);
        }
    }

    // Write one line per namespace with all keys
    for (ns, keys) in by_namespace {
        write!(output, "{indent}")?;
        write!(output, "{}", "#[".style(colors::attribute()))?;
        write!(output, "{}", "facet".style(colors::attribute_content()))?;
        write!(output, "{}", "(".style(colors::attribute()))?;

        for (i, key) in keys.iter().enumerate() {
            if i > 0 {
                write!(output, "{}", ", ".style(colors::punctuation()))?;
            }
            write!(output, "{}", ns.style(colors::attribute_content()))?;
            write!(output, "{}", "::".style(colors::punctuation()))?;
            write!(output, "{}", key.style(colors::attribute_content()))?;
        }

        write!(output, "{}", ")".style(colors::attribute()))?;
        writeln!(output, "{}", "]".style(colors::attribute()))?;
    }
    Ok(())
}

/// Write third-party attributes for a field
fn write_field_third_party_attrs_colored(
    field: &Field,
    output: &mut String,
    indent: &str,
) -> core::fmt::Result {
    write_third_party_attrs_colored(field.attributes, output, indent)
}

/// Write third-party attributes for a variant
fn write_variant_third_party_attrs_colored(
    variant: &Variant,
    output: &mut String,
    indent: &str,
) -> core::fmt::Result {
    write_third_party_attrs_colored(variant.attributes, output, indent)
}

fn write_type_name_colored(shape: &Shape, output: &mut String) -> core::fmt::Result {
    match shape.def {
        Def::Scalar => {
            // Check if it's a primitive type
            let id = shape.type_identifier;
            if is_primitive_type(id) {
                write!(output, "{}", id.style(colors::primitive()))?;
            } else {
                write!(output, "{}", id.style(colors::type_name()))?;
            }
        }
        Def::Pointer(_) => {
            if let Type::Pointer(PointerType::Reference(r)) = shape.ty
                && let Def::Array(array_def) = r.target.def
            {
                write!(output, "{}", "&[".style(colors::punctuation()))?;
                write_type_name_colored(array_def.t, output)?;
                write!(
                    output,
                    "{}{}{}",
                    "; ".style(colors::punctuation()),
                    array_def.n.style(colors::primitive()),
                    "]".style(colors::punctuation())
                )?;
                return Ok(());
            }
            write!(
                output,
                "{}",
                shape.type_identifier.style(colors::type_name())
            )?;
        }
        Def::List(list_def) => {
            write!(output, "{}", "Vec".style(colors::container()))?;
            write!(output, "{}", "<".style(colors::punctuation()))?;
            write_type_name_colored(list_def.t, output)?;
            write!(output, "{}", ">".style(colors::punctuation()))?;
        }
        Def::Array(array_def) => {
            write!(output, "{}", "[".style(colors::punctuation()))?;
            write_type_name_colored(array_def.t, output)?;
            write!(
                output,
                "{}{}{}",
                "; ".style(colors::punctuation()),
                array_def.n.style(colors::primitive()),
                "]".style(colors::punctuation())
            )?;
        }
        Def::Map(map_def) => {
            let map_name = if shape.type_identifier.contains("BTreeMap") {
                "BTreeMap"
            } else {
                "HashMap"
            };
            write!(output, "{}", map_name.style(colors::container()))?;
            write!(output, "{}", "<".style(colors::punctuation()))?;
            write_type_name_colored(map_def.k, output)?;
            write!(output, "{} ", ",".style(colors::punctuation()))?;
            write_type_name_colored(map_def.v, output)?;
            write!(output, "{}", ">".style(colors::punctuation()))?;
        }
        Def::Option(option_def) => {
            write!(output, "{}", "Option".style(colors::container()))?;
            write!(output, "{}", "<".style(colors::punctuation()))?;
            write_type_name_colored(option_def.t, output)?;
            write!(output, "{}", ">".style(colors::punctuation()))?;
        }
        _ => {
            let id = shape.type_identifier;
            if is_primitive_type(id) {
                write!(output, "{}", id.style(colors::primitive()))?;
            } else {
                write!(output, "{}", id.style(colors::type_name()))?;
            }
        }
    }
    Ok(())
}

/// Check if a type identifier is a primitive type
fn is_primitive_type(id: &str) -> bool {
    matches!(
        id,
        "u8" | "u16"
            | "u32"
            | "u64"
            | "u128"
            | "usize"
            | "i8"
            | "i16"
            | "i32"
            | "i64"
            | "i128"
            | "isize"
            | "f32"
            | "f64"
            | "bool"
            | "char"
            | "str"
            | "&str"
            | "String"
    )
}

/// Context for tracking spans during formatting
struct SpanTrackingContext<'a> {
    output: String,
    spans: BTreeMap<Path, FieldSpan>,
    /// Span of the type name (struct/enum identifier)
    type_name_span: Option<Span>,
    /// Span covering the whole type definition
    type_span: Option<Span>,
    /// Span of the end token for the type definition (e.g., "}" or ";")
    type_end_span: Option<Span>,
    /// Current path prefix (for nested types)
    current_type: Option<&'static str>,
    /// Configuration for what to include
    config: &'a ShapeFormatConfig,
}

impl<'a> SpanTrackingContext<'a> {
    const fn new(config: &'a ShapeFormatConfig) -> Self {
        Self {
            output: String::new(),
            spans: BTreeMap::new(),
            type_name_span: None,
            type_span: None,
            type_end_span: None,
            current_type: None,
            config,
        }
    }

    const fn len(&self) -> usize {
        self.output.len()
    }

    fn record_field_span(&mut self, path: Path, key_span: Span, value_span: Span) {
        self.spans.insert(
            path,
            FieldSpan {
                key: key_span,
                value: value_span,
            },
        );
    }
}

/// Format a Shape with span tracking
fn format_shape_into_with_spans(shape: &Shape, ctx: &mut SpanTrackingContext) -> core::fmt::Result {
    // Track which types we've already printed to avoid duplicates
    let mut printed: BTreeSet<ConstTypeId> = BTreeSet::new();
    // Queue of types to print
    let mut queue: Vec<&Shape> = Vec::new();

    // Start with the root shape
    queue.push(shape);

    while let Some(current) = queue.pop() {
        // Skip if we've already printed this type
        if !printed.insert(current.id) {
            continue;
        }

        // Add separator between type definitions
        if printed.len() > 1 {
            writeln!(ctx.output)?;
            writeln!(ctx.output)?;
        }

        // First check def for container types (Map, List, Option, Array)
        // These have rich generic info even when ty is Opaque
        match current.def {
            Def::Map(_) | Def::List(_) | Def::Option(_) | Def::Array(_) => {
                // Don't print container types as definitions, they're inline
                printed.remove(&current.id);
                continue;
            }
            _ => {}
        }

        // Then check ty for user-defined types
        match &current.ty {
            Type::User(user_type) => match user_type {
                UserType::Struct(struct_type) => {
                    ctx.current_type = Some(current.type_identifier);
                    format_struct_with_spans(current, struct_type, ctx)?;
                    ctx.current_type = None;
                    // Queue nested types from fields (if expansion enabled)
                    if ctx.config.expand_nested_types {
                        collect_nested_types(struct_type, &mut queue);
                    }
                }
                UserType::Enum(enum_type) => {
                    ctx.current_type = Some(current.type_identifier);
                    format_enum_with_spans(current, enum_type, ctx)?;
                    ctx.current_type = None;
                    // Queue nested types from variants (if expansion enabled)
                    if ctx.config.expand_nested_types {
                        for variant in enum_type.variants {
                            collect_nested_types(&variant.data, &mut queue);
                        }
                    }
                }
                UserType::Union(_) | UserType::Opaque => {
                    // For union/opaque types, just show the type identifier
                    // Don't actually print anything since we can't expand them
                    printed.remove(&current.id);
                }
            },
            _ => {
                // For non-user types (primitives, pointers, etc.), don't print
                printed.remove(&current.id);
            }
        }
    }
    Ok(())
}

fn format_struct_with_spans(
    shape: &Shape,
    struct_type: &StructType,
    ctx: &mut SpanTrackingContext,
) -> core::fmt::Result {
    // Track start of the whole type definition
    let type_start = ctx.len();

    // Write doc comments if enabled
    if ctx.config.show_doc_comments {
        write_doc_comments(shape.doc, &mut ctx.output, "")?;
    }

    // Write #[derive(Facet)]
    writeln!(ctx.output, "#[derive(Facet)]")?;

    // Write facet attributes if any
    write_facet_attrs(shape, &mut ctx.output)?;

    // Write third-party attributes if enabled
    if ctx.config.show_third_party_attrs {
        write_third_party_attrs(shape.attributes, &mut ctx.output, "")?;
    }

    // Write struct definition
    match struct_type.kind {
        StructKind::Struct => {
            write!(ctx.output, "struct ")?;
            let type_name_start = ctx.len();
            write!(ctx.output, "{}", shape.type_identifier)?;
            let type_name_end = ctx.len();
            ctx.type_name_span = Some((type_name_start, type_name_end));
            writeln!(ctx.output, " {{")?;
            for field in struct_type.fields {
                // Write doc comments for the field if enabled
                if ctx.config.show_doc_comments {
                    write_doc_comments(field.doc, &mut ctx.output, "    ")?;
                }
                // Write third-party attributes for the field if enabled
                if ctx.config.show_third_party_attrs {
                    write_field_third_party_attrs(field, &mut ctx.output, "    ")?;
                }
                write!(ctx.output, "    ")?;
                // Track the span of the field name (key)
                let key_start = ctx.len();
                write!(ctx.output, "{}", field.name)?;
                let key_end = ctx.len();
                write!(ctx.output, ": ")?;
                // Track the span of the type annotation (value)
                let value_start = ctx.len();
                write_type_name(field.shape(), &mut ctx.output)?;
                let value_end = ctx.len();
                ctx.record_field_span(
                    vec![PathSegment::Field(Cow::Borrowed(field.name))],
                    (key_start, key_end),
                    (value_start, value_end),
                );
                writeln!(ctx.output, ",")?;
            }
            let type_end_start = ctx.len();
            write!(ctx.output, "}}")?;
            let type_end_end = ctx.len();
            ctx.type_end_span = Some((type_end_start, type_end_end));
        }
        StructKind::Tuple | StructKind::TupleStruct => {
            write!(ctx.output, "struct ")?;
            let type_name_start = ctx.len();
            write!(ctx.output, "{}", shape.type_identifier)?;
            let type_name_end = ctx.len();
            ctx.type_name_span = Some((type_name_start, type_name_end));
            write!(ctx.output, "(")?;
            for (i, field) in struct_type.fields.iter().enumerate() {
                if i > 0 {
                    write!(ctx.output, ", ")?;
                }
                // For tuple structs, key and value span are the same (just the type)
                let type_start = ctx.len();
                write_type_name(field.shape(), &mut ctx.output)?;
                let type_end = ctx.len();
                // Use field name if available, otherwise use index as string
                let field_name = if !field.name.is_empty() {
                    field.name
                } else {
                    // Tuple fields don't have names, skip span tracking
                    continue;
                };
                ctx.record_field_span(
                    vec![PathSegment::Field(Cow::Borrowed(field_name))],
                    (type_start, type_end), // key is the type itself for tuples
                    (type_start, type_end),
                );
            }
            let type_end_start = ctx.len();
            write!(ctx.output, ");")?;
            let type_end_end = ctx.len();
            ctx.type_end_span = Some((type_end_start, type_end_end));
        }
        StructKind::Unit => {
            write!(ctx.output, "struct ")?;
            let type_name_start = ctx.len();
            write!(ctx.output, "{}", shape.type_identifier)?;
            let type_name_end = ctx.len();
            ctx.type_name_span = Some((type_name_start, type_name_end));
            let type_end_start = ctx.len();
            write!(ctx.output, ";")?;
            let type_end_end = ctx.len();
            ctx.type_end_span = Some((type_end_start, type_end_end));
        }
    }

    // Record span for the root (empty path) covering the whole type
    let type_end = ctx.len();
    ctx.type_span = Some((type_start, type_end));
    ctx.record_field_span(vec![], (type_start, type_end), (type_start, type_end));

    Ok(())
}

fn format_enum_with_spans(
    shape: &Shape,
    enum_type: &EnumType,
    ctx: &mut SpanTrackingContext,
) -> core::fmt::Result {
    // Track start of the whole type definition
    let type_start = ctx.len();

    // Write doc comments if enabled
    if ctx.config.show_doc_comments {
        write_doc_comments(shape.doc, &mut ctx.output, "")?;
    }

    // Write #[derive(Facet)]
    writeln!(ctx.output, "#[derive(Facet)]")?;

    // Write repr for the discriminant type
    let repr_str = match enum_type.enum_repr {
        EnumRepr::Rust => None,
        EnumRepr::RustNPO => None,
        EnumRepr::U8 => Some("u8"),
        EnumRepr::U16 => Some("u16"),
        EnumRepr::U32 => Some("u32"),
        EnumRepr::U64 => Some("u64"),
        EnumRepr::USize => Some("usize"),
        EnumRepr::I8 => Some("i8"),
        EnumRepr::I16 => Some("i16"),
        EnumRepr::I32 => Some("i32"),
        EnumRepr::I64 => Some("i64"),
        EnumRepr::ISize => Some("isize"),
    };

    if let Some(repr) = repr_str {
        writeln!(ctx.output, "#[repr({repr})]")?;
    }

    // Write facet attributes if any
    write_facet_attrs(shape, &mut ctx.output)?;

    // Write third-party attributes if enabled
    if ctx.config.show_third_party_attrs {
        write_third_party_attrs(shape.attributes, &mut ctx.output, "")?;
    }

    // Write enum definition
    write!(ctx.output, "enum ")?;
    let type_name_start = ctx.len();
    write!(ctx.output, "{}", shape.type_identifier)?;
    let type_name_end = ctx.len();
    ctx.type_name_span = Some((type_name_start, type_name_end));
    writeln!(ctx.output, " {{")?;

    for variant in enum_type.variants {
        // Write doc comments for the variant if enabled
        if ctx.config.show_doc_comments {
            write_doc_comments(variant.doc, &mut ctx.output, "    ")?;
        }
        // Write third-party attributes for the variant if enabled
        if ctx.config.show_third_party_attrs {
            write_variant_third_party_attrs(variant, &mut ctx.output, "    ")?;
        }

        match variant.data.kind {
            StructKind::Unit => {
                write!(ctx.output, "    ")?;
                // For unit variants, key and value are the same (just the variant name)
                let name_start = ctx.len();
                write!(ctx.output, "{}", variant.name)?;
                let name_end = ctx.len();
                ctx.record_field_span(
                    vec![PathSegment::Variant(Cow::Borrowed(variant.name))],
                    (name_start, name_end),
                    (name_start, name_end),
                );
                writeln!(ctx.output, ",")?;
            }
            StructKind::Tuple | StructKind::TupleStruct => {
                write!(ctx.output, "    ")?;
                let variant_name_start = ctx.len();
                write!(ctx.output, "{}", variant.name)?;
                let variant_name_end = ctx.len();
                write!(ctx.output, "(")?;
                let tuple_start = ctx.len();
                for (i, field) in variant.data.fields.iter().enumerate() {
                    if i > 0 {
                        write!(ctx.output, ", ")?;
                    }
                    let type_start = ctx.len();
                    write_type_name(field.shape(), &mut ctx.output)?;
                    let type_end = ctx.len();
                    // Track span for variant field
                    if !field.name.is_empty() {
                        ctx.record_field_span(
                            vec![
                                PathSegment::Variant(Cow::Borrowed(variant.name)),
                                PathSegment::Field(Cow::Borrowed(field.name)),
                            ],
                            (type_start, type_end),
                            (type_start, type_end),
                        );
                    }
                }
                write!(ctx.output, ")")?;
                let tuple_end = ctx.len();
                // Record variant span: key is the name, value is the tuple contents
                ctx.record_field_span(
                    vec![PathSegment::Variant(Cow::Borrowed(variant.name))],
                    (variant_name_start, variant_name_end),
                    (tuple_start, tuple_end),
                );
                writeln!(ctx.output, ",")?;
            }
            StructKind::Struct => {
                write!(ctx.output, "    ")?;
                let variant_name_start = ctx.len();
                write!(ctx.output, "{}", variant.name)?;
                let variant_name_end = ctx.len();
                writeln!(ctx.output, " {{")?;
                let struct_start = ctx.len();
                for field in variant.data.fields {
                    // Write doc comments for variant fields if enabled
                    if ctx.config.show_doc_comments {
                        write_doc_comments(field.doc, &mut ctx.output, "        ")?;
                    }
                    // Write third-party attributes for variant fields if enabled
                    if ctx.config.show_third_party_attrs {
                        write_field_third_party_attrs(field, &mut ctx.output, "        ")?;
                    }
                    write!(ctx.output, "        ")?;
                    let key_start = ctx.len();
                    write!(ctx.output, "{}", field.name)?;
                    let key_end = ctx.len();
                    write!(ctx.output, ": ")?;
                    let value_start = ctx.len();
                    write_type_name(field.shape(), &mut ctx.output)?;
                    let value_end = ctx.len();
                    ctx.record_field_span(
                        vec![
                            PathSegment::Variant(Cow::Borrowed(variant.name)),
                            PathSegment::Field(Cow::Borrowed(field.name)),
                        ],
                        (key_start, key_end),
                        (value_start, value_end),
                    );
                    writeln!(ctx.output, ",")?;
                }
                write!(ctx.output, "    }}")?;
                let struct_end = ctx.len();
                // Record variant span: key is the name, value is the struct body
                ctx.record_field_span(
                    vec![PathSegment::Variant(Cow::Borrowed(variant.name))],
                    (variant_name_start, variant_name_end),
                    (struct_start, struct_end),
                );
                writeln!(ctx.output, ",")?;
            }
        }
    }

    let type_end_start = ctx.len();
    write!(ctx.output, "}}")?;
    let type_end_end = ctx.len();
    ctx.type_end_span = Some((type_end_start, type_end_end));

    // Record span for the root (empty path) covering the whole type
    let type_end = ctx.len();
    ctx.type_span = Some((type_start, type_end));
    ctx.record_field_span(vec![], (type_start, type_end), (type_start, type_end));

    Ok(())
}

/// Collect nested user-defined types from struct fields
fn collect_nested_types<'a>(struct_type: &'a StructType, queue: &mut Vec<&'a Shape>) {
    for field in struct_type.fields {
        collect_from_shape(field.shape(), queue);
    }
}

/// Recursively collect user-defined types from a shape (handles containers)
fn collect_from_shape<'a>(shape: &'a Shape, queue: &mut Vec<&'a Shape>) {
    match shape.def {
        Def::List(list_def) => collect_from_shape(list_def.t, queue),
        Def::Array(array_def) => collect_from_shape(array_def.t, queue),
        Def::Map(map_def) => {
            collect_from_shape(map_def.k, queue);
            collect_from_shape(map_def.v, queue);
        }
        Def::Option(option_def) => collect_from_shape(option_def.t, queue),
        _ => {
            // Check if it's a user-defined type worth expanding
            if let Type::User(UserType::Struct(_) | UserType::Enum(_)) = &shape.ty {
                queue.push(shape);
            }
        }
    }
}

// Plain text helpers for span tracking (ANSI codes would break byte offsets)
fn write_facet_attrs(shape: &Shape, output: &mut String) -> core::fmt::Result {
    let mut attrs: Vec<String> = Vec::new();

    if let Some(tag) = shape.get_tag_attr() {
        if let Some(content) = shape.get_content_attr() {
            attrs.push(alloc::format!("tag = \"{tag}\", content = \"{content}\""));
        } else {
            attrs.push(alloc::format!("tag = \"{tag}\""));
        }
    }

    if shape.is_untagged() {
        attrs.push("untagged".into());
    }

    if shape.has_deny_unknown_fields_attr() {
        attrs.push("deny_unknown_fields".into());
    }

    if !attrs.is_empty() {
        writeln!(output, "#[facet({})]", attrs.join(", "))?;
    }

    Ok(())
}

/// Write doc comments (plain text) with the given indentation prefix
fn write_doc_comments(doc: &[&str], output: &mut String, indent: &str) -> core::fmt::Result {
    for line in doc {
        write!(output, "{indent}")?;
        writeln!(output, "///{line}")?;
    }
    Ok(())
}

/// Write third-party (namespaced) attributes (plain text)
fn write_third_party_attrs(
    attributes: &[Attr],
    output: &mut String,
    indent: &str,
) -> core::fmt::Result {
    // Group attributes by namespace
    let mut by_namespace: BTreeMap<&'static str, Vec<&'static str>> = BTreeMap::new();
    for attr in attributes {
        if let Some(ns) = attr.ns {
            by_namespace.entry(ns).or_default().push(attr.key);
        }
    }

    // Write one line per namespace with all keys
    for (ns, keys) in by_namespace {
        write!(output, "{indent}")?;
        write!(output, "#[facet(")?;
        for (i, key) in keys.iter().enumerate() {
            if i > 0 {
                write!(output, ", ")?;
            }
            write!(output, "{ns}::{key}")?;
        }
        writeln!(output, ")]")?;
    }
    Ok(())
}

/// Write third-party attributes for a field (plain text)
fn write_field_third_party_attrs(
    field: &Field,
    output: &mut String,
    indent: &str,
) -> core::fmt::Result {
    write_third_party_attrs(field.attributes, output, indent)
}

/// Write third-party attributes for a variant (plain text)
fn write_variant_third_party_attrs(
    variant: &Variant,
    output: &mut String,
    indent: &str,
) -> core::fmt::Result {
    write_third_party_attrs(variant.attributes, output, indent)
}

fn write_type_name(shape: &Shape, output: &mut String) -> core::fmt::Result {
    match shape.def {
        Def::Scalar => {
            write!(output, "{}", shape.type_identifier)?;
        }
        Def::Pointer(_) => {
            if let Type::Pointer(PointerType::Reference(r)) = shape.ty
                && let Def::Array(array_def) = r.target.def
            {
                write!(output, "&[")?;
                write_type_name(array_def.t, output)?;
                write!(output, "; {}]", array_def.n)?;
                return Ok(());
            }
            write!(output, "{}", shape.type_identifier)?;
        }
        Def::List(list_def) => {
            write!(output, "Vec<")?;
            write_type_name(list_def.t, output)?;
            write!(output, ">")?;
        }
        Def::Array(array_def) => {
            write!(output, "[")?;
            write_type_name(array_def.t, output)?;
            write!(output, "; {}]", array_def.n)?;
        }
        Def::Map(map_def) => {
            let map_name = if shape.type_identifier.contains("BTreeMap") {
                "BTreeMap"
            } else {
                "HashMap"
            };
            write!(output, "{map_name}<")?;
            write_type_name(map_def.k, output)?;
            write!(output, ", ")?;
            write_type_name(map_def.v, output)?;
            write!(output, ">")?;
        }
        Def::Option(option_def) => {
            write!(output, "Option<")?;
            write_type_name(option_def.t, output)?;
            write!(output, ">")?;
        }
        _ => {
            write!(output, "{}", shape.type_identifier)?;
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use facet::Facet;

    #[test]
    fn test_simple_struct() {
        #[derive(Facet)]
        struct Simple {
            name: String,
            count: u32,
        }

        let output = format_shape(Simple::SHAPE);
        assert!(output.contains("struct Simple"));
        assert!(output.contains("name: String"));
        assert!(output.contains("count: u32"));
    }

    #[test]
    fn test_enum_with_tag() {
        #[derive(Facet)]
        #[repr(C)]
        #[facet(tag = "type")]
        #[allow(dead_code)]
        enum Tagged {
            A { x: i32 },
            B { y: String },
        }

        let output = format_shape(Tagged::SHAPE);
        assert!(output.contains("enum Tagged"));
        assert!(output.contains("#[facet(tag = \"type\")]"));
    }

    #[test]
    fn test_nested_types() {
        #[derive(Facet)]
        #[allow(dead_code)]
        struct Inner {
            value: i32,
        }

        #[derive(Facet)]
        #[allow(dead_code)]
        struct Outer {
            inner: Inner,
            name: String,
        }

        let output = format_shape(Outer::SHAPE);
        // Should contain both Outer and Inner definitions
        assert!(output.contains("struct Outer"), "Missing Outer: {output}");
        assert!(
            output.contains("inner: Inner"),
            "Missing inner field: {output}"
        );
        assert!(
            output.contains("struct Inner"),
            "Missing Inner definition: {output}"
        );
        assert!(
            output.contains("value: i32"),
            "Missing value field: {output}"
        );
    }

    #[test]
    fn test_nested_in_vec() {
        #[derive(Facet)]
        #[allow(dead_code)]
        struct Item {
            id: u32,
        }

        #[derive(Facet)]
        #[allow(dead_code)]
        struct Container {
            items: Vec<Item>,
        }

        let output = format_shape(Container::SHAPE);
        // Should contain both Container and Item definitions
        assert!(
            output.contains("struct Container"),
            "Missing Container: {output}"
        );
        assert!(
            output.contains("items: Vec<Item>"),
            "Missing items field: {output}"
        );
        assert!(
            output.contains("struct Item"),
            "Missing Item definition: {output}"
        );
    }

    #[test]
    fn test_format_shape_with_spans() {
        #[derive(Facet)]
        #[allow(dead_code)]
        struct Config {
            name: String,
            max_retries: u8,
            enabled: bool,
        }

        let result = format_shape_with_spans(Config::SHAPE);

        // Check that spans were recorded for each field
        let name_path = vec![PathSegment::Field(Cow::Borrowed("name"))];
        let retries_path = vec![PathSegment::Field(Cow::Borrowed("max_retries"))];
        let enabled_path = vec![PathSegment::Field(Cow::Borrowed("enabled"))];

        assert!(
            result.spans.contains_key(&name_path),
            "Missing span for 'name' field. Spans: {:?}",
            result.spans
        );
        assert!(
            result.spans.contains_key(&retries_path),
            "Missing span for 'max_retries' field. Spans: {:?}",
            result.spans
        );
        assert!(
            result.spans.contains_key(&enabled_path),
            "Missing span for 'enabled' field. Spans: {:?}",
            result.spans
        );

        // Verify the span for max_retries points to "u8"
        let field_span = &result.spans[&retries_path];
        let spanned_text = &result.text[field_span.value.0..field_span.value.1];
        assert_eq!(spanned_text, "u8", "Expected 'u8', got '{spanned_text}'");
    }

    #[test]
    fn test_format_enum_with_spans() {
        #[derive(Facet)]
        #[repr(u8)]
        #[allow(dead_code)]
        enum Status {
            Active,
            Pending,
            Error { code: i32, message: String },
        }

        let result = format_shape_with_spans(Status::SHAPE);

        // Check variant spans
        let active_path = vec![PathSegment::Variant(Cow::Borrowed("Active"))];
        let error_path = vec![PathSegment::Variant(Cow::Borrowed("Error"))];
        let error_code_path = vec![
            PathSegment::Variant(Cow::Borrowed("Error")),
            PathSegment::Field(Cow::Borrowed("code")),
        ];

        assert!(
            result.spans.contains_key(&active_path),
            "Missing span for 'Active' variant. Spans: {:?}",
            result.spans
        );
        assert!(
            result.spans.contains_key(&error_path),
            "Missing span for 'Error' variant. Spans: {:?}",
            result.spans
        );
        assert!(
            result.spans.contains_key(&error_code_path),
            "Missing span for 'Error.code' field. Spans: {:?}",
            result.spans
        );

        // Verify the span for code points to "i32"
        let field_span = &result.spans[&error_code_path];
        let spanned_text = &result.text[field_span.value.0..field_span.value.1];
        assert_eq!(spanned_text, "i32", "Expected 'i32', got '{spanned_text}'");
    }

    #[test]
    fn test_format_with_doc_comments() {
        /// A configuration struct for the application.
        #[derive(Facet)]
        #[allow(dead_code)]
        struct Config {
            /// The name of the configuration.
            name: String,
            /// Maximum number of retries.
            max_retries: u8,
        }

        // With doc comments (default)
        let output = format_shape(Config::SHAPE);
        assert!(
            output.contains("/// A configuration struct"),
            "Should contain struct doc comment: {output}"
        );
        assert!(
            output.contains("/// The name of the configuration"),
            "Should contain field doc comment: {output}"
        );
        assert!(
            output.contains("/// Maximum number of retries"),
            "Should contain field doc comment: {output}"
        );

        // Without doc comments (explicit config)
        let config = ShapeFormatConfig::new();
        let output_without = format_shape_with_config(Config::SHAPE, &config);
        assert!(
            !output_without.contains("///"),
            "Should not contain doc comments when disabled: {output_without}"
        );
    }

    #[test]
    fn test_format_enum_with_doc_comments() {
        /// Status of an operation.
        #[derive(Facet)]
        #[repr(u8)]
        #[allow(dead_code)]
        enum Status {
            /// The operation is active.
            Active,
            /// The operation failed with an error.
            Error {
                /// Error code.
                code: i32,
            },
        }

        let config = ShapeFormatConfig::new().with_doc_comments();
        let output = format_shape_with_config(Status::SHAPE, &config);

        assert!(
            output.contains("/// Status of an operation"),
            "Should contain enum doc comment: {output}"
        );
        assert!(
            output.contains("/// The operation is active"),
            "Should contain variant doc comment: {output}"
        );
        assert!(
            output.contains("/// The operation failed"),
            "Should contain variant doc comment: {output}"
        );
        assert!(
            output.contains("/// Error code"),
            "Should contain variant field doc comment: {output}"
        );
    }
}