groxide 0.1.0

Query Rust crate documentation from the terminal
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
use std::collections::{HashMap, HashSet};

use rustdoc_types::{Crate, Id, ItemEnum, Visibility};
use serde::Deserialize;

use crate::signature::render_signature;
use crate::types::{ChildRef, DocIndex, IndexItem, ItemKind, SourceSpan, TraitImplInfo};

/// Parses rustdoc JSON with disabled recursion limit.
///
/// Uses `serde_json::Deserializer::from_str` with recursion limit disabled
/// to handle deeply nested types (e.g., `typenum`). Safe because the input
/// is trusted output from `cargo rustdoc`.
pub(crate) fn parse_rustdoc_json(json: &str) -> crate::error::Result<Crate> {
    let mut deserializer = serde_json::Deserializer::from_str(json);
    deserializer.disable_recursion_limit();
    Crate::deserialize(&mut deserializer).map_err(|e| crate::error::GroxError::JsonParseFailed {
        details: e.to_string(),
    })
}

/// Builds a `DocIndex` from a parsed rustdoc `Crate`.
///
/// Runs four sequential passes:
/// 1. Parent map construction (child → parent reverse lookup)
/// 2. Path computation (seed from `krate.paths`, glob re-export hoisting, impl/trait paths, fallback)
/// 3. Item conversion (`ItemEnum` → `IndexItem`, visibility, re-exports, feature gates)
/// 4. Children & relationships (impl methods, trait impls, module children)
pub(crate) fn build_index(krate: &Crate, crate_name: &str, crate_version: &str) -> DocIndex {
    let mut builder = IndexBuilder {
        krate,
        index: DocIndex::new(crate_name.to_string(), crate_version.to_string()),
        id_to_index: HashMap::new(),
        id_to_path: HashMap::new(),
        blanket_impl_items: HashSet::new(),
        child_to_parent: HashMap::new(),
    };

    builder.pass1_build_parent_map();
    builder.pass2_compute_paths();
    builder.pass3_convert_items();
    builder.pass4_link_relationships();
    builder.collect_cross_crate_globs();

    builder.index
}

struct IndexBuilder<'a> {
    krate: &'a Crate,
    index: DocIndex,
    id_to_index: HashMap<Id, usize>,
    id_to_path: HashMap<Id, String>,
    blanket_impl_items: HashSet<Id>,
    child_to_parent: HashMap<Id, Id>,
}

impl IndexBuilder<'_> {
    // ---- Pass 1: Parent Map ----

    fn pass1_build_parent_map(&mut self) {
        for (parent_id, item) in &self.krate.index {
            let child_ids = self.collect_child_ids_for_parent(item);
            for child_id in child_ids {
                self.child_to_parent.insert(child_id, *parent_id);
            }
        }
    }

    fn collect_child_ids_for_parent(&self, item: &rustdoc_types::Item) -> Vec<Id> {
        match &item.inner {
            ItemEnum::Module(m) => m.items.clone(),
            ItemEnum::Struct(s) => {
                let mut ids = struct_field_ids(s);
                self.extend_with_impl_items(&mut ids, &s.impls);
                ids
            }
            ItemEnum::Enum(e) => {
                let mut ids = e.variants.clone();
                self.extend_with_impl_items(&mut ids, &e.impls);
                ids
            }
            ItemEnum::Union(u) => {
                let mut ids = Vec::new();
                self.extend_with_impl_items(&mut ids, &u.impls);
                ids
            }
            ItemEnum::Trait(t) => t.items.clone(),
            ItemEnum::Impl(i) => i.items.clone(),
            _ => Vec::new(),
        }
    }

    fn extend_with_impl_items(&self, ids: &mut Vec<Id>, impls: &[Id]) {
        for impl_id in impls {
            if let Some(impl_item) = self.krate.index.get(impl_id) {
                if let ItemEnum::Impl(impl_data) = &impl_item.inner {
                    ids.extend(impl_data.items.iter().copied());
                }
            }
        }
    }

    // ---- Pass 2: Path Computation ----

    fn pass2_compute_paths(&mut self) {
        // 2.1: Seed from krate.paths
        for (id, summary) in &self.krate.paths {
            self.id_to_path.insert(*id, summary.path.join("::"));
        }

        // 2.2: Glob re-export hoisting (must run before impl path computation)
        self.hoist_glob_reexport_paths();

        // 2.3: Impl block path computation
        self.compute_descendant_paths(|_id, inner, id_to_path| {
            let ItemEnum::Impl(impl_data) = inner else {
                return None;
            };
            let parent_path = Self::resolve_type_path_from(id_to_path, &impl_data.for_)?;
            Some((parent_path, impl_data.items.clone()))
        });

        // 2.4: Trait item path computation
        self.compute_descendant_paths(|id, inner, id_to_path| {
            let ItemEnum::Trait(t) = inner else {
                return None;
            };
            let parent_path = id_to_path.get(id)?.clone();
            Some((parent_path, t.items.clone()))
        });

        // 2.5: Fallback — reconstruct remaining paths via parent chain
        let missing_ids: Vec<(Id, String)> = self
            .krate
            .index
            .iter()
            .filter(|(id, _)| !self.id_to_path.contains_key(*id))
            .filter_map(|(id, item)| self.reconstruct_path(*id, item).map(|path| (*id, path)))
            .collect();

        for (id, path) in missing_ids {
            self.id_to_path.entry(id).or_insert(path);
        }
    }

    fn hoist_glob_reexport_paths(&mut self) {
        let mut overrides = Vec::new();

        for (id, item) in &self.krate.index {
            let ItemEnum::Module(m) = &item.inner else {
                continue;
            };
            let Some(parent_path) = self.id_to_path.get(id) else {
                continue;
            };
            let parent_path = parent_path.clone();

            let mut sorted_children: Vec<_> = m.items.clone();
            sorted_children.sort();

            for child_id in &sorted_children {
                let Some(child) = self.krate.index.get(child_id) else {
                    continue;
                };
                let ItemEnum::Use(use_item) = &child.inner else {
                    continue;
                };
                if !use_item.is_glob {
                    continue;
                }
                let Some(target_id) = &use_item.id else {
                    continue;
                };
                let Some(target) = self.krate.index.get(target_id) else {
                    continue;
                };
                let ItemEnum::Module(target_module) = &target.inner else {
                    continue;
                };

                let mut sorted_target_children: Vec<_> = target_module.items.clone();
                sorted_target_children.sort();

                for tc_id in &sorted_target_children {
                    let Some(tc) = self.krate.index.get(tc_id) else {
                        continue;
                    };
                    let Some(tc_name) = &tc.name else {
                        continue;
                    };
                    overrides.push((*tc_id, format!("{parent_path}::{tc_name}")));
                }
            }
        }

        for (id, path) in overrides {
            self.id_to_path.insert(id, path);
        }
    }

    /// Computes paths for descendant items (e.g. methods in impl blocks, items in traits).
    ///
    /// `extract` receives each item's ID, inner enum, and the current path map, returning
    /// the parent path and child IDs if the item is a relevant parent kind.
    fn compute_descendant_paths(
        &mut self,
        extract: impl Fn(&Id, &ItemEnum, &HashMap<Id, String>) -> Option<(String, Vec<Id>)>,
    ) {
        let mut new_paths = Vec::new();

        for (id, item) in &self.krate.index {
            let Some((parent_path, child_ids)) = extract(id, &item.inner, &self.id_to_path) else {
                continue;
            };

            for child_id in &child_ids {
                if self.id_to_path.contains_key(child_id) {
                    continue;
                }
                let Some(child) = self.krate.index.get(child_id) else {
                    continue;
                };
                let Some(child_name) = &child.name else {
                    continue;
                };
                new_paths.push((*child_id, format!("{parent_path}::{child_name}")));
            }
        }

        for (id, path) in new_paths {
            self.id_to_path.entry(id).or_insert(path);
        }
    }

    fn resolve_type_path_from(
        id_to_path: &HashMap<Id, String>,
        ty: &rustdoc_types::Type,
    ) -> Option<String> {
        match ty {
            rustdoc_types::Type::ResolvedPath(path) => id_to_path
                .get(&path.id)
                .cloned()
                .or_else(|| Some(path.path.clone())),
            _ => None,
        }
    }

    fn reconstruct_path(&self, id: Id, item: &rustdoc_types::Item) -> Option<String> {
        let item_name = item.name.as_deref()?;
        let mut segments = vec![item_name.to_string()];
        let mut current_id = id;
        let mut depth = 0;

        loop {
            depth += 1;
            if depth > 20 {
                break;
            }

            let Some(&parent_id) = self.child_to_parent.get(&current_id) else {
                break;
            };
            let Some(parent_item) = self.krate.index.get(&parent_id) else {
                break;
            };

            if let Some(parent_path) = self.id_to_path.get(&parent_id) {
                segments.reverse();
                return Some(format!("{}::{}", parent_path, segments.join("::")));
            }

            let Some(parent_name) = &parent_item.name else {
                break;
            };
            segments.push(parent_name.clone());
            current_id = parent_id;
        }

        segments.reverse();
        Some(segments.join("::"))
    }

    // ---- Pass 3: Item Conversion ----

    fn pass3_convert_items(&mut self) {
        self.collect_blanket_impl_items();

        // Sort items by ID for deterministic order
        let mut sorted_items: Vec<_> = self.krate.index.iter().collect();
        sorted_items.sort_by_key(|(a, _)| *a);

        for (id, item) in sorted_items {
            if self.blanket_impl_items.contains(id) {
                continue;
            }

            let index_item = if let ItemEnum::Use(_) = &item.inner {
                self.convert_use_item(*id, item)
            } else {
                self.convert_regular_item(*id, item)
            };

            if let Some(index_item) = index_item {
                let idx = self.index.items.len();
                self.id_to_index.insert(*id, idx);
                self.index.add_item(index_item);
            }
        }
    }

    fn collect_blanket_impl_items(&mut self) {
        for item in self.krate.index.values() {
            if let ItemEnum::Impl(impl_data) = &item.inner {
                if impl_data.trait_.is_some()
                    && (impl_data.blanket_impl.is_some() || impl_data.is_synthetic)
                {
                    for child_id in &impl_data.items {
                        self.blanket_impl_items.insert(*child_id);
                    }
                }
            }
        }
    }

    fn convert_regular_item(&self, id: Id, item: &rustdoc_types::Item) -> Option<IndexItem> {
        let path = self.id_to_path.get(&id)?.clone();
        let name = item.name.as_deref()?.to_string();
        let kind = convert_item_kind(&item.inner)?;
        let signature = render_signature(item, self.krate)
            .unwrap_or_else(|| fallback_signature(&item.visibility, kind, &name));
        let docs = item.docs.clone().unwrap_or_default();
        let summary = extract_summary(&docs);
        let span = extract_span(item);
        let is_public = check_visibility(item);
        let has_body = matches!(&item.inner, ItemEnum::Function(f) if f.has_body);
        let feature_gate = extract_feature_gate(item);

        Some(IndexItem {
            path,
            name,
            kind,
            signature,
            docs,
            summary,
            span,
            children: Vec::new(),
            is_public,
            has_body,
            feature_gate,
            reexport_source: None,
        })
    }

    fn convert_use_item(&self, id: Id, item: &rustdoc_types::Item) -> Option<IndexItem> {
        let ItemEnum::Use(use_item) = &item.inner else {
            return None;
        };

        // Skip glob re-exports (handled by path hoisting and module child resolution)
        if use_item.is_glob {
            return None;
        }

        // Skip non-public items
        if !matches!(item.visibility, Visibility::Public) {
            return None;
        }

        let name = use_item.name.clone();
        if name.is_empty() {
            return None;
        }

        // Deduplication: if the referenced item already has the same path, skip
        if let Some(ref_id) = &use_item.id {
            if let Some(existing_path) = self.id_to_path.get(ref_id) {
                if let Some(this_path) = self.id_to_path.get(&id) {
                    if this_path == existing_path {
                        return None;
                    }
                }
            }
        }

        // Build path: try id_to_path, then parent module, then crate root
        let path = self.id_to_path.get(&id).cloned().unwrap_or_else(|| {
            // Try parent module path
            if let Some(parent_id) = self.child_to_parent.get(&id) {
                if let Some(parent_path) = self.id_to_path.get(parent_id) {
                    return format!("{parent_path}::{name}");
                }
            }
            // Fallback to crate root
            let root_path = self
                .id_to_path
                .get(&self.krate.root)
                .cloned()
                .unwrap_or_default();
            format!("{root_path}::{name}")
        });

        let kind = self.resolve_use_kind(use_item);

        // Build source path for docs/signature
        let source = use_item
            .id
            .as_ref()
            .and_then(|ref_id| self.id_to_path.get(ref_id))
            .cloned()
            .unwrap_or_else(|| use_item.source.clone());

        // Try to get real signature/docs from the referenced item (in-crate re-export)
        let (signature, docs, summary, has_body) =
            if let Some(ref_item) = use_item.id.as_ref().and_then(|id| self.krate.index.get(id)) {
                // In-crate re-export: use the real signature and docs
                let sig = render_signature(ref_item, self.krate)
                    .unwrap_or_else(|| fallback_signature(&ref_item.visibility, kind, &name));

                // Use the pub use item's own docs if present, otherwise the referenced item's docs
                let docs = if item.docs.is_some() {
                    item.docs.clone().unwrap_or_default()
                } else {
                    ref_item.docs.clone().unwrap_or_default()
                };

                let summary = extract_summary(&docs);
                let has_body = matches!(&ref_item.inner, ItemEnum::Function(f) if f.has_body);
                (sig, docs, summary, has_body)
            } else {
                // Cross-crate re-export: keep stub signature
                let docs = item.docs.clone().unwrap_or_default();
                let summary = extract_summary(&docs);
                let signature = format!("pub use {source} as {name}");
                (signature, docs, summary, false)
            };

        let feature_gate = extract_feature_gate(item);

        Some(IndexItem {
            path,
            name,
            kind,
            signature,
            docs,
            summary,
            span: extract_span(item),
            children: Vec::new(),
            is_public: true,
            has_body,
            feature_gate,
            reexport_source: Some(source),
        })
    }

    fn resolve_use_kind(&self, use_item: &rustdoc_types::Use) -> ItemKind {
        if let Some(ref_id) = &use_item.id {
            if let Some(ref_item) = self.krate.index.get(ref_id) {
                if let Some(kind) = convert_item_kind(&ref_item.inner) {
                    return kind;
                }
            }
            if let Some(summary) = self.krate.paths.get(ref_id) {
                if let Some(kind) = convert_item_summary_kind(summary.kind) {
                    return kind;
                }
            }
        }
        ItemKind::Struct
    }

    // ---- Pass 4: Children & Relationships ----

    fn pass4_link_relationships(&mut self) {
        let krate_items: Vec<_> = self.krate.index.iter().collect();

        for (id, item) in &krate_items {
            let Some(&parent_idx) = self.id_to_index.get(*id) else {
                continue;
            };

            let resolved_ids = match &item.inner {
                ItemEnum::Module(m) => self.resolve_module_children(m),
                ItemEnum::Use(use_item) => {
                    // For in-crate re-exports, copy children from the referenced item
                    self.resolve_use_children(use_item, parent_idx);
                    continue;
                }
                _ => self.collect_item_child_ids(item),
            };

            let mut children = Vec::new();
            for cid in &resolved_ids {
                let Some(&cidx) = self.id_to_index.get(cid) else {
                    continue;
                };
                let child_item = &self.index.items[cidx];
                children.push(ChildRef {
                    index: cidx,
                    kind: child_item.kind,
                    name: child_item.name.clone(),
                });
            }

            if !children.is_empty() {
                self.index.items[parent_idx].children = children;
            }

            let trait_impls = self.extract_trait_impls(item);
            if !trait_impls.is_empty() {
                self.index.trait_impls.insert(parent_idx, trait_impls);
            }
        }
    }

    /// Records `pub use other_crate::*` statements that target items outside
    /// `self.krate.index` (i.e. another crate). Same-crate globs are already
    /// expanded into individual paths by `compute_paths_for_glob_use`.
    fn collect_cross_crate_globs(&mut self) {
        let mut globs = Vec::new();
        for (mod_id, mod_item) in &self.krate.index {
            let ItemEnum::Module(m) = &mod_item.inner else {
                continue;
            };
            let parent_path = self
                .id_to_path
                .get(mod_id)
                .cloned()
                .unwrap_or_else(String::new);

            for child_id in &m.items {
                let Some(child) = self.krate.index.get(child_id) else {
                    continue;
                };
                let ItemEnum::Use(use_item) = &child.inner else {
                    continue;
                };
                if !use_item.is_glob {
                    continue;
                }
                let resolves_in_crate = use_item
                    .id
                    .as_ref()
                    .is_some_and(|id| self.krate.index.contains_key(id));
                if resolves_in_crate {
                    continue; // handled by compute_paths_for_glob_use already
                }
                globs.push(crate::types::GlobUse {
                    parent_path: parent_path.clone(),
                    source_path: use_item.source.clone(),
                });
            }
        }
        // Stable order so caches are deterministic.
        globs.sort_by(|a, b| {
            a.parent_path
                .cmp(&b.parent_path)
                .then_with(|| a.source_path.cmp(&b.source_path))
        });
        globs.dedup();
        self.index.glob_uses = globs;
    }

    fn resolve_module_children(&self, module: &rustdoc_types::Module) -> Vec<Id> {
        let mut result = Vec::new();
        for child_id in &module.items {
            let Some(child) = self.krate.index.get(child_id) else {
                continue;
            };
            if let ItemEnum::Use(use_item) = &child.inner {
                if use_item.is_glob {
                    if let Some(target_id) = &use_item.id {
                        if let Some(target) = self.krate.index.get(target_id) {
                            if let ItemEnum::Module(target_module) = &target.inner {
                                result.extend(target_module.items.iter().copied());
                            }
                        }
                    }
                    continue; // skip the Use item itself
                }
            }
            result.push(*child_id);
        }
        result
    }

    /// Copies children and trait impls from a referenced item to a `Use` re-export.
    fn resolve_use_children(&mut self, use_item: &rustdoc_types::Use, parent_idx: usize) {
        let Some(ref_id) = &use_item.id else {
            return;
        };
        let Some(ref_item) = self.krate.index.get(ref_id) else {
            return;
        };

        // Collect child IDs from the referenced item (struct fields, enum variants, impl methods)
        let child_ids = self.collect_item_child_ids(ref_item);

        let mut children = Vec::new();
        for cid in &child_ids {
            let Some(&cidx) = self.id_to_index.get(cid) else {
                continue;
            };
            let child_item = &self.index.items[cidx];
            children.push(ChildRef {
                index: cidx,
                kind: child_item.kind,
                name: child_item.name.clone(),
            });
        }

        if !children.is_empty() {
            self.index.items[parent_idx].children = children;
        }

        // Also copy trait impls from the referenced item
        let trait_impls = self.extract_trait_impls(ref_item);
        if !trait_impls.is_empty() {
            self.index.trait_impls.insert(parent_idx, trait_impls);
        }
    }

    /// Collects child IDs from a struct, enum, union, or trait item,
    /// including methods from inherent impls.
    fn collect_item_child_ids(&self, item: &rustdoc_types::Item) -> Vec<Id> {
        match &item.inner {
            ItemEnum::Struct(s) => {
                let mut ids = struct_field_ids(s);
                ids.extend(self.resolve_inherent_impl_items(&s.impls));
                ids
            }
            ItemEnum::Enum(e) => {
                let mut ids = e.variants.clone();
                ids.extend(self.resolve_inherent_impl_items(&e.impls));
                ids
            }
            ItemEnum::Union(u) => self.resolve_inherent_impl_items(&u.impls),
            ItemEnum::Trait(t) => t.items.clone(),
            _ => Vec::new(),
        }
    }

    fn resolve_inherent_impl_items(&self, impl_ids: &[Id]) -> Vec<Id> {
        let mut result = Vec::new();
        for impl_id in impl_ids {
            let Some(impl_item) = self.krate.index.get(impl_id) else {
                continue;
            };
            if let ItemEnum::Impl(impl_data) = &impl_item.inner {
                if impl_data.trait_.is_none() {
                    result.extend(impl_data.items.iter().copied());
                }
            }
        }
        result
    }

    fn extract_trait_impls(&self, item: &rustdoc_types::Item) -> Vec<TraitImplInfo> {
        let impls_list = match &item.inner {
            ItemEnum::Struct(s) => &s.impls,
            ItemEnum::Enum(e) => &e.impls,
            ItemEnum::Union(u) => &u.impls,
            _ => return Vec::new(),
        };

        let mut result = Vec::new();
        for impl_id in impls_list {
            let Some(impl_item) = self.krate.index.get(impl_id) else {
                continue;
            };
            let ItemEnum::Impl(impl_data) = &impl_item.inner else {
                continue;
            };
            let Some(trait_ref) = &impl_data.trait_ else {
                continue;
            };
            // Filter out blanket impls
            if impl_data.blanket_impl.is_some() {
                continue;
            }

            result.push(TraitImplInfo {
                trait_path: trait_ref.path.clone(),
                is_synthetic: impl_data.is_synthetic,
            });
        }

        result
    }
}

/// Extracts field IDs from a struct.
fn struct_field_ids(s: &rustdoc_types::Struct) -> Vec<Id> {
    match &s.kind {
        rustdoc_types::StructKind::Plain {
            fields,
            has_stripped_fields: _,
        } => fields.clone(),
        rustdoc_types::StructKind::Tuple(fields) => fields.iter().copied().flatten().collect(),
        rustdoc_types::StructKind::Unit => Vec::new(),
    }
}

/// Converts `ItemEnum` variant to `ItemKind`.
fn convert_item_kind(inner: &ItemEnum) -> Option<ItemKind> {
    match inner {
        ItemEnum::Module(_) => Some(ItemKind::Module),
        ItemEnum::Struct(_) => Some(ItemKind::Struct),
        ItemEnum::Enum(_) => Some(ItemKind::Enum),
        ItemEnum::Union(_) => Some(ItemKind::Union),
        ItemEnum::Trait(_) => Some(ItemKind::Trait),
        ItemEnum::TraitAlias(_) => Some(ItemKind::TraitAlias),
        ItemEnum::Function(_) => Some(ItemKind::Function),
        ItemEnum::TypeAlias(_) => Some(ItemKind::TypeAlias),
        ItemEnum::AssocType { .. } => Some(ItemKind::AssocType),
        ItemEnum::AssocConst { .. } => Some(ItemKind::AssocConst),
        ItemEnum::Constant { .. } => Some(ItemKind::Constant),
        ItemEnum::Static(_) => Some(ItemKind::Static),
        ItemEnum::Macro(_) => Some(ItemKind::Macro),
        ItemEnum::ProcMacro(_) => Some(ItemKind::ProcMacro),
        ItemEnum::Variant(_) => Some(ItemKind::Variant),
        ItemEnum::StructField(_) => Some(ItemKind::Field),
        ItemEnum::ExternType => Some(ItemKind::ForeignType),
        ItemEnum::Primitive(_) => Some(ItemKind::Primitive),
        // Skip: Impl, Use, ExternCrate
        ItemEnum::Impl(_) | ItemEnum::Use(_) | ItemEnum::ExternCrate { .. } => None,
    }
}

/// Converts `rustdoc_types::ItemKind` (from `krate.paths`) to our `ItemKind`.
fn convert_item_summary_kind(kind: rustdoc_types::ItemKind) -> Option<ItemKind> {
    match kind {
        rustdoc_types::ItemKind::Module => Some(ItemKind::Module),
        rustdoc_types::ItemKind::Struct => Some(ItemKind::Struct),
        rustdoc_types::ItemKind::Enum => Some(ItemKind::Enum),
        rustdoc_types::ItemKind::Union => Some(ItemKind::Union),
        rustdoc_types::ItemKind::Trait => Some(ItemKind::Trait),
        rustdoc_types::ItemKind::TraitAlias => Some(ItemKind::TraitAlias),
        rustdoc_types::ItemKind::Function => Some(ItemKind::Function),
        rustdoc_types::ItemKind::TypeAlias => Some(ItemKind::TypeAlias),
        rustdoc_types::ItemKind::AssocType => Some(ItemKind::AssocType),
        rustdoc_types::ItemKind::AssocConst => Some(ItemKind::AssocConst),
        rustdoc_types::ItemKind::Constant => Some(ItemKind::Constant),
        rustdoc_types::ItemKind::Static => Some(ItemKind::Static),
        rustdoc_types::ItemKind::Macro => Some(ItemKind::Macro),
        rustdoc_types::ItemKind::ProcAttribute | rustdoc_types::ItemKind::ProcDerive => {
            Some(ItemKind::ProcMacro)
        }
        rustdoc_types::ItemKind::Variant => Some(ItemKind::Variant),
        rustdoc_types::ItemKind::StructField => Some(ItemKind::Field),
        rustdoc_types::ItemKind::ExternType => Some(ItemKind::ForeignType),
        rustdoc_types::ItemKind::Primitive => Some(ItemKind::Primitive),
        rustdoc_types::ItemKind::ExternCrate
        | rustdoc_types::ItemKind::Use
        | rustdoc_types::ItemKind::Impl
        | rustdoc_types::ItemKind::Keyword
        | rustdoc_types::ItemKind::Attribute => None,
    }
}

/// Checks item visibility according to spec §5.4.
fn check_visibility(item: &rustdoc_types::Item) -> bool {
    match &item.visibility {
        Visibility::Public => true,
        Visibility::Default => {
            // Enum variants are implicitly public; trait methods use Default visibility
            matches!(
                &item.inner,
                ItemEnum::Variant(_) | ItemEnum::Function(_) | ItemEnum::StructField(_)
            )
        }
        Visibility::Crate | Visibility::Restricted { .. } => false,
    }
}

/// Extracts the first sentence from a doc string.
fn extract_summary(docs: &str) -> String {
    if docs.is_empty() {
        return String::new();
    }

    let mut chars = docs.char_indices().peekable();

    while let Some((byte_pos, ch)) = chars.next() {
        if (ch == '!' || ch == '?') && chars.peek().is_none_or(|(_, c)| c.is_whitespace()) {
            return docs[..byte_pos + ch.len_utf8()].to_string();
        }

        if ch == '.' {
            // At end of string
            if chars.peek().is_none() {
                return docs[..=byte_pos].to_string();
            }
            // Followed by whitespace
            if let Some((_, next_ch)) = chars.peek() {
                if next_ch.is_whitespace() {
                    let remaining = &docs[byte_pos + 1..];
                    let next_non_ws = remaining.chars().find(|c| !c.is_whitespace());
                    if next_non_ws.is_none_or(char::is_uppercase) {
                        return docs[..=byte_pos].to_string();
                    }
                }
            }
        }
    }

    // No sentence terminator found: take first line
    let first_line = docs.split('\n').next().unwrap_or(docs);
    if first_line.len() > 100 {
        format!("{}...", &first_line[..100])
    } else {
        first_line.to_string()
    }
}

/// Extracts source span from a rustdoc item.
fn extract_span(item: &rustdoc_types::Item) -> SourceSpan {
    match &item.span {
        Some(span) => SourceSpan {
            file: span.filename.to_string_lossy().to_string(),
            #[allow(clippy::cast_possible_truncation)]
            line_start: span.begin.0 as u32,
            #[allow(clippy::cast_possible_truncation)]
            line_end: span.end.0 as u32,
        },
        None => SourceSpan {
            file: String::new(),
            line_start: 0,
            line_end: 0,
        },
    }
}

/// Extracts a feature gate from item attributes.
fn extract_feature_gate(item: &rustdoc_types::Item) -> Option<String> {
    for attr in &item.attrs {
        if let rustdoc_types::Attribute::Other(s) = attr {
            // Match: #[doc(cfg(feature = "feature_name"))]
            if let Some(start) = s.find("cfg(feature") {
                let rest = &s[start..];
                if let Some(quote_start) = rest.find('"') {
                    let after_quote = &rest[quote_start + 1..];
                    if let Some(quote_end) = after_quote.find('"') {
                        return Some(after_quote[..quote_end].to_string());
                    }
                }
            }
        }
    }
    None
}

/// Generates a fallback signature when `render_signature` returns `None`.
fn fallback_signature(vis: &Visibility, kind: ItemKind, name: &str) -> String {
    let vis_str = match vis {
        Visibility::Public => "pub ",
        _ => "",
    };
    format!("{vis_str}{} {name}", kind.short_name())
}

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

    /// Loads the fixture crate JSON using the recursion-safe parser.
    fn load_fixture() -> Crate {
        let json = std::fs::read_to_string(
            std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
                .join("test-fixtures/groxide_test_api.json"),
        )
        .expect("fixture JSON should exist");
        parse_rustdoc_json(&json).expect("fixture JSON should parse")
    }

    /// Builds the index from the fixture crate.
    fn build_fixture_index() -> DocIndex {
        let krate = load_fixture();
        build_index(&krate, "groxide_test_api", "0.1.0")
    }

    // ---- parse_rustdoc_json ----

    #[test]
    fn parse_succeeds_for_fixture() {
        let json = std::fs::read_to_string(
            std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
                .join("test-fixtures/groxide_test_api.json"),
        )
        .expect("fixture JSON should exist");
        let krate = parse_rustdoc_json(&json);
        assert!(
            krate.is_ok(),
            "parse_rustdoc_json failed: {:?}",
            krate.err()
        );
    }

    #[test]
    fn parse_returns_error_for_invalid_json() {
        let result = parse_rustdoc_json("not valid json");
        assert!(result.is_err());
    }

    // ---- Correct item count ----

    #[test]
    fn build_index_produces_nonzero_items() {
        let index = build_fixture_index();
        assert!(index.len() > 10, "expected >10 items, got {}", index.len());
    }

    // ---- Path map has expected paths ----

    #[test]
    fn path_map_contains_crate_root() {
        let index = build_fixture_index();
        assert!(
            index.path_map.contains_key("groxide_test_api"),
            "path_map should contain crate root"
        );
    }

    #[test]
    fn path_map_contains_top_level_struct() {
        let index = build_fixture_index();
        assert!(
            index
                .path_map
                .contains_key("groxide_test_api::SimpleStruct"),
            "path_map should contain SimpleStruct"
        );
    }

    #[test]
    fn path_map_contains_module() {
        let index = build_fixture_index();
        assert!(
            index.path_map.contains_key("groxide_test_api::containers"),
            "path_map should contain containers module"
        );
    }

    #[test]
    fn path_map_contains_nested_item() {
        let index = build_fixture_index();
        assert!(
            index
                .path_map
                .contains_key("groxide_test_api::containers::Stack"),
            "path_map should contain containers::Stack"
        );
    }

    #[test]
    fn path_map_contains_deeply_nested_function() {
        let index = build_fixture_index();
        assert!(
            index
                .path_map
                .contains_key("groxide_test_api::deeply::nested::deep_fn"),
            "path_map should contain deeply::nested::deep_fn"
        );
    }

    // ---- Suffix map generates correct suffixes ----

    #[test]
    fn suffix_map_contains_simple_name() {
        let index = build_fixture_index();
        assert!(
            index.suffix_map.contains_key("simplestruct"),
            "suffix_map should contain 'simplestruct'"
        );
    }

    #[test]
    fn suffix_map_contains_partial_path_suffix() {
        let index = build_fixture_index();
        assert!(
            index.suffix_map.contains_key("containers::stack"),
            "suffix_map should contain 'containers::stack'"
        );
    }

    #[test]
    fn suffix_map_contains_deeply_nested_suffix() {
        let index = build_fixture_index();
        assert!(
            index.suffix_map.contains_key("nested::deep_fn"),
            "suffix_map should contain 'nested::deep_fn'"
        );
    }

    // ---- Name map is case-insensitive ----

    #[test]
    fn name_map_lowercases_keys() {
        let index = build_fixture_index();
        assert!(
            index.name_map.contains_key("simplestruct"),
            "name_map should contain lowercased 'simplestruct'"
        );
        assert!(
            !index.name_map.contains_key("SimpleStruct"),
            "name_map should NOT contain original-case 'SimpleStruct'"
        );
    }

    #[test]
    fn name_map_contains_function_names() {
        let index = build_fixture_index();
        assert!(
            index.name_map.contains_key("add"),
            "name_map should contain 'add'"
        );
    }

    #[test]
    fn name_map_lookup_finds_items() {
        let index = build_fixture_index();
        let indices = index.name_map.get("stack").expect("should find 'stack'");
        assert!(!indices.is_empty());
        let item = index.get(indices[0]);
        assert_eq!(item.name, "Stack");
    }

    // ---- Re-exported items have correct paths ----

    #[test]
    fn reexport_helper_has_reexports_path() {
        let index = build_fixture_index();
        assert!(
            index
                .path_map
                .contains_key("groxide_test_api::reexports::Helper"),
            "path_map should contain reexported Helper at reexports path"
        );
    }

    #[test]
    fn glob_reexported_items_have_correct_path() {
        let index = build_fixture_index();
        assert!(
            index
                .path_map
                .contains_key("groxide_test_api::reexports::GlobItem"),
            "path_map should contain glob-reexported GlobItem at reexports path"
        );
    }

    // ---- Public vs private items correctly flagged ----

    #[test]
    fn public_items_flagged_correctly() {
        let index = build_fixture_index();
        let indices = index
            .path_map
            .get("groxide_test_api::SimpleStruct")
            .expect("should find SimpleStruct");
        let item = index.get(indices[0]);
        assert!(item.is_public, "SimpleStruct should be public");
    }

    #[test]
    fn public_function_flagged_correctly() {
        let index = build_fixture_index();
        let indices = index
            .path_map
            .get("groxide_test_api::add")
            .expect("should find add");
        let item = index.get(indices[0]);
        assert!(item.is_public, "add function should be public");
    }

    #[test]
    fn enum_variants_flagged_as_public() {
        let index = build_fixture_index();
        let indices = index
            .path_map
            .get("groxide_test_api::Direction::North")
            .expect("should find Direction::North");
        let item = index.get(indices[0]);
        assert!(item.is_public, "enum variant North should be public");
    }

    // ---- Trait impls stored in DocIndex.trait_impls ----

    #[test]
    fn trait_impls_stored_on_docindex() {
        let index = build_fixture_index();
        let stack_indices = index
            .path_map
            .get("groxide_test_api::containers::Stack")
            .expect("should find Stack");
        let stack_idx = stack_indices[0];
        let impls = index.item_trait_impls(stack_idx);
        let trait_names: Vec<&str> = impls.iter().map(|i| i.trait_path.as_str()).collect();
        assert!(
            trait_names.contains(&"Default"),
            "Stack should have Default impl, got: {trait_names:?}"
        );
    }

    #[test]
    fn trait_impls_not_on_index_item() {
        let index = build_fixture_index();
        let stack_indices = index
            .path_map
            .get("groxide_test_api::containers::Stack")
            .expect("should find Stack");
        let stack_item = index.get(stack_indices[0]);
        for child in &stack_item.children {
            assert_ne!(
                child.kind,
                ItemKind::Trait,
                "children should not include traits, found: {}",
                child.name
            );
        }
    }

    // ---- Children correctly linked ----

    #[test]
    fn struct_has_method_children() {
        let index = build_fixture_index();
        let stack_indices = index
            .path_map
            .get("groxide_test_api::containers::Stack")
            .expect("should find Stack");
        let stack_item = index.get(stack_indices[0]);
        let child_names: Vec<&str> = stack_item
            .children
            .iter()
            .map(|c| c.name.as_str())
            .collect();
        assert!(
            child_names.contains(&"new"),
            "Stack should have 'new' method child, got: {child_names:?}"
        );
        assert!(
            child_names.contains(&"push"),
            "Stack should have 'push' method child, got: {child_names:?}"
        );
        assert!(
            child_names.contains(&"pop"),
            "Stack should have 'pop' method child, got: {child_names:?}"
        );
    }

    #[test]
    fn module_has_children() {
        let index = build_fixture_index();
        let containers_indices = index
            .path_map
            .get("groxide_test_api::containers")
            .expect("should find containers module");
        let containers_item = index.get(containers_indices[0]);
        let child_names: Vec<&str> = containers_item
            .children
            .iter()
            .map(|c| c.name.as_str())
            .collect();
        assert!(
            child_names.contains(&"Stack"),
            "containers module should have Stack child, got: {child_names:?}"
        );
        assert!(
            child_names.contains(&"Pair"),
            "containers module should have Pair child, got: {child_names:?}"
        );
    }

    // ---- Enum has variant children ----

    #[test]
    fn enum_has_variant_children() {
        let index = build_fixture_index();
        let direction_indices = index
            .path_map
            .get("groxide_test_api::Direction")
            .expect("should find Direction");
        let direction_item = index.get(direction_indices[0]);
        let variant_names: Vec<&str> = direction_item
            .children
            .iter()
            .filter(|c| c.kind == ItemKind::Variant)
            .map(|c| c.name.as_str())
            .collect();
        assert!(variant_names.contains(&"North"), "should have North");
        assert!(variant_names.contains(&"South"), "should have South");
        assert!(variant_names.contains(&"East"), "should have East");
        assert!(variant_names.contains(&"West"), "should have West");
    }

    #[test]
    fn enum_shape_has_all_variants() {
        let index = build_fixture_index();
        let shape_indices = index
            .path_map
            .get("groxide_test_api::Shape")
            .expect("should find Shape");
        let shape_item = index.get(shape_indices[0]);
        let variant_names: Vec<&str> = shape_item
            .children
            .iter()
            .filter(|c| c.kind == ItemKind::Variant)
            .map(|c| c.name.as_str())
            .collect();
        assert!(variant_names.contains(&"Circle"), "should have Circle");
        assert!(
            variant_names.contains(&"Rectangle"),
            "should have Rectangle"
        );
        assert!(variant_names.contains(&"Point"), "should have Point");
    }

    // ---- Trait has method children ----

    #[test]
    fn trait_has_method_children() {
        let index = build_fixture_index();
        let stringify_indices = index
            .path_map
            .get("groxide_test_api::traits::Stringify")
            .expect("should find Stringify");
        let stringify_item = index.get(stringify_indices[0]);
        let child_names: Vec<&str> = stringify_item
            .children
            .iter()
            .map(|c| c.name.as_str())
            .collect();
        assert!(
            child_names.contains(&"stringify"),
            "Stringify should have 'stringify', got: {child_names:?}"
        );
        assert!(
            child_names.contains(&"debug_string"),
            "Stringify should have 'debug_string', got: {child_names:?}"
        );
    }

    // ---- has_body flag ----

    #[test]
    fn trait_required_method_has_body_false() {
        let index = build_fixture_index();
        let indices = index
            .path_map
            .get("groxide_test_api::traits::Stringify::stringify")
            .expect("should find stringify method");
        let item = index.get(indices[0]);
        assert!(!item.has_body, "required method should have has_body=false");
    }

    #[test]
    fn trait_provided_method_has_body_true() {
        let index = build_fixture_index();
        let indices = index
            .path_map
            .get("groxide_test_api::traits::Stringify::debug_string")
            .expect("should find debug_string method");
        let item = index.get(indices[0]);
        assert!(item.has_body, "provided method should have has_body=true");
    }

    // ---- Summary extraction ----

    #[test]
    fn extract_summary_first_sentence() {
        assert_eq!(
            extract_summary("Adds two numbers together. Returns the sum."),
            "Adds two numbers together."
        );
    }

    #[test]
    fn extract_summary_no_terminator() {
        assert_eq!(
            extract_summary("A simple struct with no generics"),
            "A simple struct with no generics"
        );
    }

    #[test]
    fn extract_summary_empty_docs() {
        assert_eq!(extract_summary(""), "");
    }

    #[test]
    fn extract_summary_truncates_long_first_line() {
        let long_line = "a".repeat(200);
        let result = extract_summary(&long_line);
        assert_eq!(result.len(), 103); // 100 + "..."
        assert!(result.ends_with("..."));
    }

    #[test]
    fn extract_summary_period_in_version_number() {
        assert_eq!(
            extract_summary("Requires version 1.56.0 to compile"),
            "Requires version 1.56.0 to compile"
        );
    }

    // ---- Feature gate extraction ----

    #[test]
    fn extract_feature_gate_from_attrs() {
        let item = rustdoc_types::Item {
            id: Id(0),
            crate_id: 0,
            name: Some("test".to_string()),
            span: None,
            visibility: Visibility::Public,
            docs: None,
            links: HashMap::new(),
            attrs: vec![rustdoc_types::Attribute::Other(
                "#[doc(cfg(feature = \"unstable\"))]".to_string(),
            )],
            deprecation: None,
            inner: ItemEnum::Constant {
                type_: rustdoc_types::Type::Primitive("bool".to_string()),
                const_: rustdoc_types::Constant {
                    expr: String::new(),
                    value: None,
                    is_literal: false,
                },
            },
        };
        assert_eq!(extract_feature_gate(&item), Some("unstable".to_string()));
    }

    #[test]
    fn extract_feature_gate_none_when_absent() {
        let item = rustdoc_types::Item {
            id: Id(0),
            crate_id: 0,
            name: Some("test".to_string()),
            span: None,
            visibility: Visibility::Public,
            docs: None,
            links: HashMap::new(),
            attrs: vec![],
            deprecation: None,
            inner: ItemEnum::Constant {
                type_: rustdoc_types::Type::Primitive("bool".to_string()),
                const_: rustdoc_types::Constant {
                    expr: String::new(),
                    value: None,
                    is_literal: false,
                },
            },
        };
        assert_eq!(extract_feature_gate(&item), None);
    }

    // ---- All maps populated ----

    #[test]
    fn all_maps_populated() {
        let index = build_fixture_index();
        assert!(!index.path_map.is_empty(), "path_map should not be empty");
        assert!(!index.name_map.is_empty(), "name_map should not be empty");
        assert!(
            !index.suffix_map.is_empty(),
            "suffix_map should not be empty"
        );
    }

    // ---- Crate metadata ----

    #[test]
    fn crate_name_and_version_set() {
        let index = build_fixture_index();
        assert_eq!(index.crate_name, "groxide_test_api");
        assert_eq!(index.crate_version, "0.1.0");
    }

    // ---- Item kinds present ----

    #[test]
    fn index_contains_expected_item_kinds() {
        let index = build_fixture_index();
        let kinds: HashSet<ItemKind> = index.items.iter().map(|i| i.kind).collect();

        assert!(kinds.contains(&ItemKind::Module), "should have modules");
        assert!(kinds.contains(&ItemKind::Struct), "should have structs");
        assert!(kinds.contains(&ItemKind::Enum), "should have enums");
        assert!(kinds.contains(&ItemKind::Function), "should have functions");
        assert!(kinds.contains(&ItemKind::Constant), "should have constants");
        assert!(
            kinds.contains(&ItemKind::TypeAlias),
            "should have type aliases"
        );
        assert!(kinds.contains(&ItemKind::Static), "should have statics");
        assert!(kinds.contains(&ItemKind::Macro), "should have macros");
        assert!(kinds.contains(&ItemKind::Trait), "should have traits");
        assert!(kinds.contains(&ItemKind::Union), "should have unions");
        assert!(kinds.contains(&ItemKind::Variant), "should have variants");
        assert!(kinds.contains(&ItemKind::Field), "should have fields");
    }

    // ---- Signatures populated ----

    #[test]
    fn items_have_nonempty_signatures() {
        let index = build_fixture_index();
        for item in &index.items {
            assert!(
                !item.signature.is_empty(),
                "item {} ({:?}) should have non-empty signature",
                item.path,
                item.kind
            );
        }
    }

    // ---- Docs populated ----

    #[test]
    fn documented_items_have_docs() {
        let index = build_fixture_index();
        let add_indices = index
            .path_map
            .get("groxide_test_api::add")
            .expect("should find add");
        let add_item = index.get(add_indices[0]);
        assert!(!add_item.docs.is_empty(), "add should have documentation");
        assert!(!add_item.summary.is_empty(), "add should have a summary");
    }

    // ---- Constant items ----

    #[test]
    fn constants_have_correct_kind() {
        let index = build_fixture_index();
        let indices = index
            .path_map
            .get("groxide_test_api::MAX_BUFFER_SIZE")
            .expect("should find MAX_BUFFER_SIZE");
        let item = index.get(indices[0]);
        assert_eq!(item.kind, ItemKind::Constant);
    }

    // ---- Associated types and consts from traits ----

    #[test]
    fn trait_assoc_type_has_path() {
        let index = build_fixture_index();
        assert!(
            index
                .path_map
                .contains_key("groxide_test_api::traits::Processor::Input"),
            "Processor::Input should have a path"
        );
    }

    #[test]
    fn trait_assoc_const_has_path() {
        let index = build_fixture_index();
        assert!(
            index
                .path_map
                .contains_key("groxide_test_api::traits::Processor::MAX_ITEMS"),
            "Processor::MAX_ITEMS should have a path"
        );
    }
}