forked from argotorg/fe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel.rs
More file actions
1243 lines (1135 loc) · 44.9 KB
/
Copy pathmodel.rs
File metadata and controls
1243 lines (1135 loc) · 44.9 KB
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
//! Documentation data model
//!
//! These types represent extracted documentation in a format suitable for rendering.
//! They are designed to be serializable for static site generation and cacheable
//! for dynamic serving.
use serde::{Deserialize, Serialize};
/// Current schema version for the docs.json envelope.
///
/// SERIALIZATION CONTRACT: Bump this number whenever you change the
/// serialization shape of DocIndex, DocItem, DocChild, DocModuleTree, or
/// any type reachable from them. When you bump it, you MUST also:
/// 1. Update the snapshot test in this module (cargo test, accept new snap).
/// 2. Add a migration case in fe-scip-store.js feMigrate().
pub const SCHEMA_VERSION: u32 = 4;
// ============================================================================
// Rich Signature Types (for rendering signatures with embedded links)
// ============================================================================
/// A part of a signature - either plain text or a linkable reference
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(test, derive(schemars::JsonSchema))]
pub struct SignaturePart {
/// The display text
pub text: String,
/// If Some, render as a link to this doc path (e.g., "hoverable::Numbers/struct")
#[serde(default, skip_serializing_if = "Option::is_none")]
pub link: Option<String>,
}
impl SignaturePart {
/// Create a plain text part
pub fn text(s: impl Into<String>) -> Self {
Self {
text: s.into(),
link: None,
}
}
/// Create a linked part
pub fn link(text: impl Into<String>, path: impl Into<String>) -> Self {
Self {
text: text.into(),
link: Some(path.into()),
}
}
}
/// A rich signature with embedded links
pub type RichSignature = Vec<SignaturePart>;
/// Helper to create a RichSignature from a plain string (no links)
pub fn plain_signature(s: impl Into<String>) -> RichSignature {
vec![SignaturePart::text(s)]
}
/// Source location of a signature in its file, used to overlay SCIP occurrences.
///
/// Byte offsets are exact: `file_text[byte_start..byte_end] == signature_text`.
/// Skipped during serialization — only used in-memory during doc generation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SignatureSpanData {
/// Absolute file URL (file:// scheme), used to compute relative path for
/// matching against SCIP document `relative_path` fields.
pub file_url: String,
/// Start byte offset in the file text.
pub byte_start: usize,
/// End byte offset in the file text.
pub byte_end: usize,
}
// ============================================================================
// Core Documentation Types
// ============================================================================
/// A documented item in the Fe codebase
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(test, derive(schemars::JsonSchema))]
pub struct DocItem {
/// Unique path identifier (e.g., "std::option::Option")
pub path: String,
/// Short name of the item
pub name: String,
/// What kind of item this is
pub kind: DocItemKind,
/// The item's visibility
pub visibility: DocVisibility,
/// Parsed documentation content
pub docs: Option<DocContent>,
/// The item's signature/definition (plain text for backward compat)
pub signature: String,
/// Rich signature with embedded links (for rendering)
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub rich_signature: RichSignature,
/// Source span of the signature (for SCIP occurrence overlay, not serialized)
#[serde(skip)]
pub signature_span: Option<SignatureSpanData>,
/// SCIP scope path for this signature (set during enrich_signatures)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sig_scope: Option<String>,
/// Generic parameters, if any
pub generics: Vec<DocGenericParam>,
/// Where clause bounds, if any
pub where_bounds: Vec<String>,
/// Child items (methods, fields, variants, etc.)
pub children: Vec<DocChild>,
/// Source location for "view source" links
pub source: Option<DocSourceLoc>,
/// Full source text of the item definition (for inline "view source")
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source_text: Option<String>,
/// Trait implementations for this type (structs, enums, contracts)
#[serde(default)]
pub trait_impls: Vec<DocTraitImpl>,
/// Types that implement this trait (for trait pages)
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub implementors: Vec<DocImplementor>,
}
/// A type that implements a trait
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(test, derive(schemars::JsonSchema))]
pub struct DocImplementor {
/// The implementing type name
pub type_name: String,
/// Path to the type's documentation
pub type_url: String,
/// The trait name (for linking to the impl block)
pub trait_name: String,
/// The full impl signature (plain text)
pub signature: String,
/// Rich signature with embedded links
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub rich_signature: RichSignature,
/// Source span for the full impl signature (for SCIP positional linking).
/// In-memory only; not serialized to JSON.
#[serde(skip)]
pub signature_span: Option<SignatureSpanData>,
/// SCIP scope path for this implementor signature
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sig_scope: Option<String>,
}
impl DocItem {
/// Get the URL path for this item (includes kind suffix)
pub fn url_path(&self) -> String {
format!("{}/{}", self.path, self.kind.as_str())
}
}
/// The kind of documented item
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(test, derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum DocItemKind {
Module,
Function,
Struct,
Enum,
Trait,
Contract,
TypeAlias,
Const,
Impl,
ImplTrait,
/// A `msg` block (desugared to module internally).
Msg,
/// A variant of a `msg` block (desugared to struct internally).
MsgVariant,
}
impl DocItemKind {
pub fn as_str(&self) -> &'static str {
match self {
DocItemKind::Module => "mod",
DocItemKind::Function => "fn",
DocItemKind::Struct => "struct",
DocItemKind::Enum => "enum",
DocItemKind::Trait => "trait",
DocItemKind::Contract => "contract",
DocItemKind::TypeAlias => "type",
DocItemKind::Const => "const",
DocItemKind::Impl => "impl",
DocItemKind::ImplTrait => "impl",
DocItemKind::Msg => "msg",
DocItemKind::MsgVariant => "msg_variant",
}
}
/// Parse kind from URL suffix string
pub fn parse(s: &str) -> Option<Self> {
match s {
"mod" | "module" => Some(DocItemKind::Module),
"fn" | "function" => Some(DocItemKind::Function),
"struct" => Some(DocItemKind::Struct),
"enum" => Some(DocItemKind::Enum),
"trait" => Some(DocItemKind::Trait),
"contract" => Some(DocItemKind::Contract),
"type" => Some(DocItemKind::TypeAlias),
"const" => Some(DocItemKind::Const),
"impl" => Some(DocItemKind::Impl),
"msg" => Some(DocItemKind::Msg),
"msg_variant" => Some(DocItemKind::MsgVariant),
_ => None,
}
}
pub fn display_name(&self) -> &'static str {
match self {
DocItemKind::Module => "Module",
DocItemKind::Function => "Function",
DocItemKind::Struct => "Struct",
DocItemKind::Enum => "Enum",
DocItemKind::Trait => "Trait",
DocItemKind::Contract => "Contract",
DocItemKind::TypeAlias => "Type Alias",
DocItemKind::Const => "Constant",
DocItemKind::Impl => "Implementation",
DocItemKind::ImplTrait => "Trait Implementation",
DocItemKind::Msg => "Message",
DocItemKind::MsgVariant => "Message Variant",
}
}
/// Plural display name for section headers
pub fn plural_name(&self) -> &'static str {
match self {
DocItemKind::Module => "Modules",
DocItemKind::Function => "Functions",
DocItemKind::Struct => "Structs",
DocItemKind::Enum => "Enums",
DocItemKind::Trait => "Traits",
DocItemKind::Contract => "Contracts",
DocItemKind::TypeAlias => "Type Aliases",
DocItemKind::Const => "Constants",
DocItemKind::Impl => "Implementations",
DocItemKind::ImplTrait => "Trait Implementations",
DocItemKind::Msg => "Messages",
DocItemKind::MsgVariant => "Message Variants",
}
}
/// Display order for sidebar grouping (lower = first)
pub fn display_order(&self) -> u8 {
match self {
DocItemKind::Module => 0,
DocItemKind::Msg => 1,
DocItemKind::Trait => 2,
DocItemKind::Contract => 3,
DocItemKind::Struct => 4,
DocItemKind::Enum => 5,
DocItemKind::TypeAlias => 6,
DocItemKind::Function => 7,
DocItemKind::Const => 8,
DocItemKind::Impl => 9,
DocItemKind::ImplTrait => 10,
DocItemKind::MsgVariant => 11,
}
}
}
/// Visibility of a documented item
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(test, derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum DocVisibility {
Public,
Private,
}
/// Parsed documentation content with sections
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(test, derive(schemars::JsonSchema))]
pub struct DocContent {
/// The main summary (first paragraph)
pub summary: String,
/// Full documentation body (markdown)
pub body: String,
/// Extracted sections like # Examples, # Panics, etc.
pub sections: Vec<DocSection>,
}
impl DocContent {
pub fn from_raw(raw: &str) -> Self {
let trimmed = raw.trim();
// Split into summary (first paragraph) and body
let (summary, body) = if let Some(idx) = trimmed.find("\n\n") {
(trimmed[..idx].to_string(), trimmed.to_string())
} else {
(trimmed.to_string(), trimmed.to_string())
};
// Extract known sections
let sections = Self::extract_sections(trimmed);
DocContent {
summary,
body,
sections,
}
}
fn extract_sections(text: &str) -> Vec<DocSection> {
let mut sections = Vec::new();
let mut current_section: Option<(String, String)> = None;
for line in text.lines() {
if let Some(header) = line.strip_prefix("# ") {
// Save previous section if any
if let Some((name, content)) = current_section.take() {
sections.push(DocSection {
name,
content: content.trim().to_string(),
});
}
// Start new section
let name = header.trim().to_string();
current_section = Some((name, String::new()));
} else if let Some((_, ref mut content)) = current_section {
content.push_str(line);
content.push('\n');
}
}
// Save final section
if let Some((name, content)) = current_section {
sections.push(DocSection {
name,
content: content.trim().to_string(),
});
}
sections
}
}
/// A named section within documentation (e.g., "Examples", "Panics")
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(test, derive(schemars::JsonSchema))]
pub struct DocSection {
pub name: String,
pub content: String,
}
/// A generic parameter with its bounds
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(test, derive(schemars::JsonSchema))]
pub struct DocGenericParam {
pub name: String,
pub bounds: Vec<String>,
pub default: Option<String>,
}
/// A child of a documented item
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(test, derive(schemars::JsonSchema))]
pub struct DocChild {
pub kind: DocChildKind,
pub name: String,
pub docs: Option<DocContent>,
pub signature: String,
/// Rich signature with embedded links
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub rich_signature: RichSignature,
/// Source span of the signature (for SCIP occurrence overlay, not serialized)
#[serde(skip)]
pub signature_span: Option<SignatureSpanData>,
/// SCIP scope path for this signature
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sig_scope: Option<String>,
pub visibility: DocVisibility,
}
/// Kind of child item
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(test, derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum DocChildKind {
Field,
Variant,
Method,
AssocType,
AssocConst,
/// A contract `init(...)` block.
Init,
/// A single arm of a contract `recv Msg { Variant ... }` block.
RecvHandler,
}
impl DocChildKind {
pub fn display_name(&self) -> &'static str {
match self {
DocChildKind::Field => "Field",
DocChildKind::Variant => "Variant",
DocChildKind::Method => "Method",
DocChildKind::AssocType => "Associated Type",
DocChildKind::AssocConst => "Associated Constant",
DocChildKind::Init => "Initializer",
DocChildKind::RecvHandler => "Handler",
}
}
/// Plural display name for section headers
pub fn plural_name(&self) -> &'static str {
match self {
DocChildKind::Field => "Fields",
DocChildKind::Variant => "Variants",
DocChildKind::Method => "Methods",
DocChildKind::AssocType => "Associated Types",
DocChildKind::AssocConst => "Associated Constants",
DocChildKind::Init => "Initializer",
DocChildKind::RecvHandler => "Message Handlers",
}
}
/// Display order for grouping (lower = first)
pub fn display_order(&self) -> u8 {
match self {
DocChildKind::Variant => 0,
DocChildKind::Field => 1,
DocChildKind::Init => 2,
DocChildKind::RecvHandler => 3,
DocChildKind::AssocType => 4,
DocChildKind::AssocConst => 5,
DocChildKind::Method => 6,
}
}
/// Anchor prefix for linking (rustdoc-style)
pub fn anchor_prefix(&self) -> &'static str {
match self {
DocChildKind::Field => "field",
DocChildKind::Variant => "variant",
DocChildKind::Method => "tymethod",
DocChildKind::AssocType => "associatedtype",
DocChildKind::AssocConst => "associatedconstant",
DocChildKind::Init => "init",
DocChildKind::RecvHandler => "handler",
}
}
}
/// Source location for linking to source code
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(test, derive(schemars::JsonSchema))]
pub struct DocSourceLoc {
/// Absolute file path — used only in-memory by LSP for "goto source".
/// Never serialized to JSON (avoids leaking machine paths into static output).
#[serde(skip)]
pub file: String,
/// Relative display path (shown in UI)
pub display_file: String,
pub line: u32,
pub column: u32,
}
/// A trait implementation reference (shown on type pages)
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(test, derive(schemars::JsonSchema))]
pub struct DocTraitImpl {
/// The name of the trait being implemented (e.g., "Clone"). Empty for inherent impls.
pub trait_name: String,
/// URL path to the impl item's documentation
pub impl_url: String,
/// The full signature of the impl (e.g., "impl Clone for MyStruct")
pub signature: String,
/// Rich signature with embedded links
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub rich_signature: RichSignature,
/// Source span of the signature (for SCIP occurrence overlay, not serialized)
#[serde(skip)]
pub signature_span: Option<SignatureSpanData>,
/// SCIP scope path for this impl signature
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sig_scope: Option<String>,
/// Methods defined in this impl block (displayed inline on type pages)
#[serde(default)]
pub methods: Vec<DocImplMethod>,
}
/// A method in an impl block (for inline display on type pages)
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(test, derive(schemars::JsonSchema))]
pub struct DocImplMethod {
/// Method name
pub name: String,
/// Method signature (e.g., "pub fn foo(&self) -> u32")
pub signature: String,
/// Rich signature with embedded links
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub rich_signature: RichSignature,
/// Source span of the signature (for SCIP occurrence overlay, not serialized)
#[serde(skip)]
pub signature_span: Option<SignatureSpanData>,
/// SCIP scope path for this method signature
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sig_scope: Option<String>,
/// Parsed documentation content
pub docs: Option<DocContent>,
}
/// A collection of documented items forming a documentation index
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[cfg_attr(test, derive(schemars::JsonSchema))]
pub struct DocIndex {
/// All documented items, keyed by path
pub items: Vec<DocItem>,
/// Module hierarchy for navigation
pub modules: Vec<DocModuleTree>,
/// Builtin library modules (core, std), rendered separately in sidebar
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub builtin_modules: Vec<DocModuleTree>,
}
impl DocIndex {
pub fn new() -> Self {
Self::default()
}
pub fn add_item(&mut self, item: DocItem) {
self.items.push(item);
}
/// Find an item by its path (without kind suffix)
pub fn find_by_path(&self, path: &str) -> Option<&DocItem> {
self.items.iter().find(|item| item.path == path)
}
/// Find an item by path and kind
pub fn find_by_path_and_kind(&self, path: &str, kind: DocItemKind) -> Option<&DocItem> {
self.items
.iter()
.find(|item| item.path == path && item.kind == kind)
}
/// Parse a URL path (potentially with kind suffix) and find the item.
/// URL format: "path::to::item" or "path::to::item/kind"
/// Returns the item if found, handling both formats.
pub fn find_by_url(&self, url_path: &str) -> Option<&DocItem> {
// Try to parse kind suffix (e.g., "lib::foo/fn" -> path="lib::foo", kind="fn")
if let Some((path, kind_str)) = url_path.rsplit_once('/')
&& let Some(kind) = DocItemKind::parse(kind_str)
{
// URL has valid kind suffix - find by path and kind
return self.find_by_path_and_kind(path, kind);
}
// No valid kind suffix - find by path alone (may be ambiguous)
self.find_by_path(url_path)
}
/// Find all items with a given path (for disambiguation)
pub fn find_all_by_path(&self, path: &str) -> Vec<&DocItem> {
self.items.iter().filter(|item| item.path == path).collect()
}
/// Build a searchable index of items
pub fn search(&self, query: &str) -> Vec<&DocItem> {
let query_lower = query.to_lowercase();
self.items
.iter()
.filter(|item| {
item.name.to_lowercase().contains(&query_lower)
|| item.path.to_lowercase().contains(&query_lower)
})
.collect()
}
/// Link trait implementations to their target types and implementors to traits.
/// `links` is a list of (target_type_path, DocTraitImpl) pairs extracted
/// from the HIR using semantic helpers.
pub fn link_trait_impls(&mut self, links: Vec<(String, DocTraitImpl)>) {
// Build lookup maps keyed by full path to avoid collisions between
// same-named types in different modules (e.g. a::Foo vs b::Foo).
// Maps own their strings so we can mutably borrow self.items later.
let type_items: std::collections::HashMap<String, (String, DocItemKind)> = self
.items
.iter()
.filter(|item| {
matches!(
item.kind,
DocItemKind::Struct | DocItemKind::Enum | DocItemKind::Contract
)
})
.map(|item| (item.path.clone(), (item.path.clone(), item.kind)))
.collect();
let trait_items: std::collections::HashMap<String, String> = self
.items
.iter()
.filter(|item| item.kind == DocItemKind::Trait)
.map(|item| (item.path.clone(), item.path.clone()))
.collect();
/// Look up a type by path: try exact path first, then fall back to
/// simple-name scan (for unqualified paths from older extractors).
fn lookup_type(
map: &std::collections::HashMap<String, (String, DocItemKind)>,
target: &str,
) -> Option<(String, String)> {
if let Some((path, kind)) = map.get(target) {
return Some((path.clone(), kind.as_str().to_string()));
}
// Simple-name fallback when target has no `::`
if !target.contains("::") {
for (path, kind) in map.values() {
let simple = extract_simple_type_name(path);
if simple == target {
return Some((path.clone(), kind.as_str().to_string()));
}
}
}
None
}
/// Look up a trait by path: try exact path first, then simple-name scan.
fn lookup_trait(
map: &std::collections::HashMap<String, String>,
target: &str,
) -> Option<String> {
if let Some(path) = map.get(target) {
return Some(path.clone());
}
if !target.contains("::") {
for path in map.values() {
let simple = extract_simple_type_name(path);
if simple == target {
return Some(path.clone());
}
}
}
None
}
// First pass: collect implementors for each trait (keyed by trait path)
let mut trait_implementors: std::collections::HashMap<String, Vec<DocImplementor>> =
std::collections::HashMap::new();
for (target_type, trait_impl) in &links {
// Skip inherent impls (empty trait_name)
if trait_impl.trait_name.is_empty() {
continue;
}
let trait_simple_name = extract_simple_type_name(&trait_impl.trait_name);
let type_simple_name = extract_simple_type_name(target_type);
// Look up the actual type item to get the correct path and kind
let (type_path, type_kind_suffix) =
if let Some((path, kind)) = lookup_type(&type_items, target_type) {
(path, kind)
} else {
// Fallback to the target_type path with struct suffix
(target_type.clone(), "struct".to_string())
};
// Look up the actual trait to get the correct path
let trait_path = lookup_trait(&trait_items, &trait_impl.trait_name)
.unwrap_or_else(|| trait_impl.trait_name.clone());
// Build rich signature: "impl Trait for Type"
let rich_signature = vec![
SignaturePart::text("impl "),
SignaturePart::link(&trait_simple_name, format!("{}/trait", trait_path)),
SignaturePart::text(" for "),
SignaturePart::link(
&type_simple_name,
format!("{}/{}", type_path, type_kind_suffix),
),
];
// Create implementor entry with correct URL and rich signature
let implementor = DocImplementor {
type_name: type_simple_name.clone(),
type_url: format!("{}/{}", type_path, type_kind_suffix),
trait_name: trait_simple_name.clone(),
signature: trait_impl.signature.clone(),
rich_signature,
signature_span: trait_impl.signature_span.clone(),
sig_scope: None,
};
// Key by trait path (not simple name) to avoid cross-module collisions
let trait_key = trait_path.to_string();
trait_implementors
.entry(trait_key)
.or_default()
.push(implementor);
}
// Second pass: link trait impls to types and implementors to traits
for (target_type, mut trait_impl) in links {
let target_simple_name = extract_simple_type_name(&target_type);
let trait_simple_name = extract_simple_type_name(&trait_impl.trait_name);
for item in &mut self.items {
// Link trait impls to types (structs, enums, contracts)
let is_type = matches!(
item.kind,
DocItemKind::Struct | DocItemKind::Enum | DocItemKind::Contract
);
if is_type {
// Prefer exact canonical path match; only fall back to
// simple-name matching when the caller didn't provide a
// fully qualified path (e.g. from older extractors).
let matches = item.path == target_type
|| (!target_type.contains("::")
&& (item.name == target_simple_name
|| item.path.ends_with(&format!("::{}", target_simple_name))));
if matches {
// Build rich signature for this trait impl if it's a trait impl (not inherent)
if !trait_impl.trait_name.is_empty() && trait_impl.rich_signature.is_empty()
{
// Look up the trait URL
let trait_url = lookup_trait(&trait_items, &trait_impl.trait_name)
.map(|p| format!("{}/trait", p))
.unwrap_or_else(|| format!("{}/trait", trait_impl.trait_name));
// Use the target item's path and kind for the type URL
let type_url = format!("{}/{}", item.path, item.kind.as_str());
trait_impl.rich_signature = vec![
SignaturePart::text("impl "),
SignaturePart::link(&trait_simple_name, trait_url),
SignaturePart::text(" for "),
SignaturePart::link(&target_simple_name, type_url),
];
}
item.trait_impls.push(trait_impl.clone());
}
}
// Link implementors to traits
if item.kind == DocItemKind::Trait && !trait_impl.trait_name.is_empty() {
let trait_matches = item.path == trait_impl.trait_name
|| item.name == trait_simple_name
|| item.path.ends_with(&format!("::{}", trait_simple_name));
// Look up by item's full path first, then by simple name
let impls = trait_implementors
.get(item.path.as_str())
.or_else(|| trait_implementors.get(&trait_simple_name));
if trait_matches && let Some(impls) = impls {
// Only add if not already present (dedup by type_url, not name)
for imp in impls {
if !item.implementors.iter().any(|i| i.type_url == imp.type_url) {
item.implementors.push(imp.clone());
}
}
}
}
}
}
}
}
/// Extract the simple type name from a potentially qualified/generic path.
/// "mod::MyStruct<T>" -> "MyStruct"
/// "MyStruct" -> "MyStruct"
fn extract_simple_type_name(type_str: &str) -> String {
let without_generics = type_str.split('<').next().unwrap_or(type_str);
without_generics
.rsplit("::")
.next()
.unwrap_or(without_generics)
.trim()
.to_string()
}
/// Module tree for navigation sidebar
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(test, derive(schemars::JsonSchema))]
pub struct DocModuleTree {
pub name: String,
pub path: String,
pub children: Vec<DocModuleTree>,
/// Direct items in this module (non-module children)
pub items: Vec<DocModuleItem>,
}
impl DocModuleTree {
/// Get the URL path for this module (includes kind suffix)
pub fn url_path(&self) -> String {
format!("{}/mod", self.path)
}
}
/// A reference to an item within a module
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(test, derive(schemars::JsonSchema))]
pub struct DocModuleItem {
pub name: String,
pub path: String,
pub kind: DocItemKind,
/// Brief summary (first sentence of docs)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub summary: Option<String>,
}
impl DocModuleItem {
/// Get the URL path for this item (includes kind suffix)
pub fn url_path(&self) -> String {
format!("{}/{}", self.path, self.kind.as_str())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn sample_index() -> DocIndex {
let mut index = DocIndex::new();
index.add_item(DocItem {
path: "mylib::Point".into(),
name: "Point".into(),
kind: DocItemKind::Struct,
visibility: DocVisibility::Public,
docs: Some(DocContent::from_raw("A 2D point.\n\nUsed for coordinates.")),
signature: "pub struct Point".into(),
rich_signature: vec![],
signature_span: None,
sig_scope: None,
generics: vec![DocGenericParam {
name: "T".into(),
bounds: vec![],
default: None,
}],
where_bounds: vec![],
children: vec![DocChild {
kind: DocChildKind::Field,
name: "x".into(),
docs: Some(DocContent::from_raw("The x coordinate")),
signature: "x: u256".into(),
rich_signature: vec![],
signature_span: None,
sig_scope: None,
visibility: DocVisibility::Public,
}],
source: Some(DocSourceLoc {
file: "/src/lib.fe".into(),
display_file: "lib.fe".into(),
line: 1,
column: 0,
}),
source_text: None,
trait_impls: vec![],
implementors: vec![],
});
index.add_item(DocItem {
path: "mylib::Color".into(),
name: "Color".into(),
kind: DocItemKind::Enum,
visibility: DocVisibility::Public,
docs: None,
signature: "pub enum Color".into(),
rich_signature: vec![],
signature_span: None,
sig_scope: None,
generics: vec![],
where_bounds: vec![],
children: vec![
DocChild {
kind: DocChildKind::Variant,
name: "Red".into(),
docs: None,
signature: "Red".into(),
rich_signature: vec![],
signature_span: None,
sig_scope: None,
visibility: DocVisibility::Public,
},
DocChild {
kind: DocChildKind::Variant,
name: "Green".into(),
docs: None,
signature: "Green".into(),
rich_signature: vec![],
signature_span: None,
sig_scope: None,
visibility: DocVisibility::Public,
},
],
source: None,
source_text: None,
trait_impls: vec![],
implementors: vec![],
});
index.add_item(DocItem {
path: "mylib::add".into(),
name: "add".into(),
kind: DocItemKind::Function,
visibility: DocVisibility::Public,
docs: Some(DocContent::from_raw("Add two numbers.")),
signature: "pub fn add(a: u256, b: u256) -> u256".into(),
rich_signature: vec![],
signature_span: None,
sig_scope: None,
generics: vec![],
where_bounds: vec![],
children: vec![],
source: None,
source_text: None,
trait_impls: vec![],
implementors: vec![],
});
index.add_item(DocItem {
path: "mylib::TokenMsg".into(),
name: "TokenMsg".into(),
kind: DocItemKind::Msg,
visibility: DocVisibility::Public,
docs: None,
signature: "pub msg TokenMsg".into(),
rich_signature: vec![],
signature_span: None,
sig_scope: None,
generics: vec![],
where_bounds: vec![],
children: vec![],
source: None,
source_text: None,
trait_impls: vec![],
implementors: vec![],
});
index.add_item(DocItem {
path: "mylib::TokenMsg::Transfer".into(),
name: "Transfer".into(),
kind: DocItemKind::MsgVariant,
visibility: DocVisibility::Public,
docs: None,
signature: "Transfer { to: Address } -> bool".into(),
rich_signature: vec![],
signature_span: None,
sig_scope: None,
generics: vec![],
where_bounds: vec![],
children: vec![],
source: None,
source_text: None,
trait_impls: vec![],
implementors: vec![],
});
index
}
#[test]
fn json_round_trip() {
let index = sample_index();
let json = serde_json::to_string_pretty(&index).expect("serialize");
let deserialized: DocIndex = serde_json::from_str(&json).expect("deserialize");
assert_eq!(index.items.len(), deserialized.items.len());
for (a, b) in index.items.iter().zip(deserialized.items.iter()) {
assert_eq!(a.path, b.path);
assert_eq!(a.name, b.name);
assert_eq!(a.kind, b.kind);
assert_eq!(a.visibility, b.visibility);
assert_eq!(a.docs, b.docs);
assert_eq!(a.signature, b.signature);
assert_eq!(a.generics, b.generics);
assert_eq!(a.children, b.children);
// source.file is #[serde(skip)] — verify it's dropped on round-trip
if let (Some(sa), Some(sb)) = (&a.source, &b.source) {
assert!(
sb.file.is_empty(),
"source.file should not survive serialization"
);
assert_eq!(sa.display_file, sb.display_file);
assert_eq!(sa.line, sb.line);
assert_eq!(sa.column, sb.column);
} else {
assert_eq!(a.source.is_some(), b.source.is_some());
}
}
}
#[test]
fn find_by_url_with_kind() {
let index = sample_index();
let item = index.find_by_url("mylib::Point/struct");
assert!(item.is_some());
assert_eq!(item.unwrap().name, "Point");
}
#[test]
fn find_by_url_without_kind() {
let index = sample_index();
let item = index.find_by_url("mylib::Color");
assert!(item.is_some());
assert_eq!(item.unwrap().name, "Color");
}
#[test]
fn find_by_url_not_found() {
let index = sample_index();
assert!(index.find_by_url("mylib::Missing/struct").is_none());
}