forked from stacks-network/stacks-core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextract_docs.rs
More file actions
2779 lines (2422 loc) · 99.1 KB
/
extract_docs.rs
File metadata and controls
2779 lines (2422 loc) · 99.1 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
// Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020-2025 Stacks Open Internet Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use std::collections::{HashMap, HashSet};
use std::fs;
use std::process::Command as StdCommand;
use anyhow::{Context, Result};
use clap::{Arg, Command as ClapCommand};
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
// Static regex for finding constant references in documentation
static CONSTANT_REFERENCE_REGEX: Lazy<regex::Regex> =
Lazy::new(|| regex::Regex::new(r"\[`([A-Z_][A-Z0-9_]*)`\]").unwrap());
#[derive(Debug, Serialize, Deserialize)]
pub struct FieldDoc {
pub name: String,
pub description: String,
pub default_value: Option<String>,
pub notes: Option<Vec<String>>,
pub deprecated: Option<String>,
pub toml_example: Option<String>,
pub required: Option<bool>,
pub units: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct StructDoc {
pub name: String,
pub description: Option<String>,
pub fields: Vec<FieldDoc>,
}
#[derive(Debug, Serialize, Deserialize)]
struct ConfigDocs {
structs: Vec<StructDoc>,
referenced_constants: HashMap<String, Option<String>>, // Name -> Resolved Value (or None)
}
// JSON navigation helper functions
/// Navigate through nested JSON structure using an array of keys
/// Returns None if any part of the path doesn't exist
///
/// Example: get_json_path(value, &["inner", "struct", "kind"])
/// is equivalent to value.get("inner")?.get("struct")?.get("kind")
fn get_json_path<'a>(value: &'a serde_json::Value, path: &[&str]) -> Option<&'a serde_json::Value> {
let mut current = value;
for &key in path {
current = current.get(key)?;
}
Some(current)
}
/// Navigate to an array at the given JSON path
/// Returns None if the path doesn't exist or the value is not an array
fn get_json_array<'a>(
value: &'a serde_json::Value,
path: &[&str],
) -> Option<&'a Vec<serde_json::Value>> {
get_json_path(value, path)?.as_array()
}
/// Navigate to an object at the given JSON path
/// Returns None if the path doesn't exist or the value is not an object
fn get_json_object<'a>(
value: &'a serde_json::Value,
path: &[&str],
) -> Option<&'a serde_json::Map<String, serde_json::Value>> {
get_json_path(value, path)?.as_object()
}
/// Navigate to a string at the given JSON path
/// Returns None if the path doesn't exist or the value is not a string
fn get_json_string<'a>(value: &'a serde_json::Value, path: &[&str]) -> Option<&'a str> {
get_json_path(value, path)?.as_str()
}
fn main() -> Result<()> {
let matches = ClapCommand::new("extract-docs")
.about("Extract documentation from Rust source code using rustdoc JSON")
.arg(
Arg::new("package")
.long("package")
.short('p')
.value_name("PACKAGE")
.help("Package to extract docs for")
.required(true),
)
.arg(
Arg::new("output")
.long("output")
.short('o')
.value_name("FILE")
.help("Output JSON file")
.required(true),
)
.arg(
Arg::new("structs")
.long("structs")
.value_name("NAMES")
.help("Comma-separated list of struct names to extract")
.required(true),
)
.get_matches();
let package = matches.get_one::<String>("package").unwrap();
let output_file = matches.get_one::<String>("output").unwrap();
let target_structs: Option<Vec<String>> = matches
.get_one::<String>("structs")
.map(|s| s.split(',').map(|s| s.trim().to_string()).collect());
// Generate rustdoc JSON
let rustdoc_json = generate_rustdoc_json(package)?;
// Extract configuration documentation from the rustdoc JSON
let config_docs = extract_config_docs_from_rustdoc(&rustdoc_json, &target_structs)?;
// Write the extracted docs to file
fs::write(output_file, serde_json::to_string_pretty(&config_docs)?)?;
println!("Successfully extracted documentation to {output_file}");
println!(
"Found {} structs with documentation",
config_docs.structs.len()
);
Ok(())
}
fn generate_rustdoc_json(package: &str) -> Result<serde_json::Value> {
// List of crates to generate rustdoc for (in addition to the main package)
// These crates contain constants that might be referenced in documentation
// NOTE: This list must be manually updated if new dependencies containing
// constants referenced in doc comments are added to the project
let additional_crates = ["stacks-common"];
// Respect CARGO_TARGET_DIR environment variable for rustdoc output
let rustdoc_target_dir = std::env::var("CARGO_TARGET_DIR")
.unwrap_or_else(|_| "target".to_string())
+ "/rustdoc-json";
// WARNING: This tool relies on nightly rustdoc JSON output (-Z unstable-options --output-format json)
// The JSON format is subject to change with new Rust nightly versions and could break this tool.
// Use cargo rustdoc with nightly to generate JSON for the main package
let output = StdCommand::new("cargo")
.args([
"+nightly",
"rustdoc",
"--lib",
"-p",
package,
"--target-dir",
&rustdoc_target_dir,
"--",
"-Z",
"unstable-options",
"--output-format",
"json",
"--document-private-items",
])
.output()
.context("Failed to run cargo rustdoc command")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
anyhow::bail!("cargo rustdoc failed: {}", stderr);
}
// Generate rustdoc for additional crates that might contain referenced constants
for additional_crate in &additional_crates {
let error_msg = format!("Failed to run cargo rustdoc command for {additional_crate}");
let output = StdCommand::new("cargo")
.args([
"+nightly",
"rustdoc",
"--lib",
"-p",
additional_crate,
"--target-dir",
&rustdoc_target_dir,
"--",
"-Z",
"unstable-options",
"--output-format",
"json",
"--document-private-items",
])
.output()
.context(error_msg)?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
eprintln!("Warning: Failed to generate rustdoc for {additional_crate}: {stderr}");
}
}
// Map package names to their library names if different
// For most packages, the library name is the same as package name with hyphens replaced by underscores
// But some packages have custom library names defined in Cargo.toml
// NOTE: This mapping must be updated if new packages with different library names are processed
let lib_name = match package {
"stackslib" => "blockstack_lib".to_string(),
_ => package.replace('-', "_"),
};
// Read the generated JSON file - rustdoc generates it based on library name
let json_file_path = format!("{rustdoc_target_dir}/doc/{lib_name}.json");
let json_content = std::fs::read_to_string(json_file_path)
.context("Failed to read generated rustdoc JSON file")?;
serde_json::from_str(&json_content).context("Failed to parse rustdoc JSON output")
}
fn extract_config_docs_from_rustdoc(
rustdoc_json: &serde_json::Value,
target_structs: &Option<Vec<String>>,
) -> Result<ConfigDocs> {
let mut structs = Vec::new();
let mut all_referenced_constants = std::collections::HashSet::new();
// Access the main index containing all items from the rustdoc JSON output
let index = get_json_object(rustdoc_json, &["index"])
.context("Missing 'index' field in rustdoc JSON")?;
for (_item_id, item) in index {
// Extract the item's name from rustdoc JSON structure
if let Some(name) = get_json_string(item, &["name"]) {
// Check if this item is a struct by looking for the "struct" field
if get_json_object(item, &["inner", "struct"]).is_some() {
// Check if this struct is in our target list (if specified)
if let Some(targets) = target_structs
&& !targets.contains(&name.to_string())
{
continue;
}
let (struct_doc_opt, referenced_constants) =
extract_struct_from_rustdoc_index(index, name, item)?;
if let Some(struct_doc) = struct_doc_opt {
structs.push(struct_doc);
}
all_referenced_constants.extend(referenced_constants);
}
}
}
// Resolve all collected constant references
let mut referenced_constants = HashMap::new();
for constant_name in all_referenced_constants {
let resolved_value = resolve_constant_reference(&constant_name, index);
referenced_constants.insert(constant_name, resolved_value);
}
Ok(ConfigDocs {
structs,
referenced_constants,
})
}
fn extract_struct_from_rustdoc_index(
index: &serde_json::Map<String, serde_json::Value>,
struct_name: &str,
struct_item: &serde_json::Value,
) -> Result<(Option<StructDoc>, HashSet<String>)> {
let mut all_referenced_constants = std::collections::HashSet::new();
// Extract struct documentation
let description = get_json_string(struct_item, &["docs"]).map(|s| s.to_string());
// Collect constant references from struct description
if let Some(desc) = &description {
all_referenced_constants.extend(find_constant_references(desc));
}
// Extract fields
let (fields, referenced_constants) = extract_struct_fields(index, struct_item)?;
// Extend referenced constants
all_referenced_constants.extend(referenced_constants);
if !fields.is_empty() || description.is_some() {
let struct_doc = StructDoc {
name: struct_name.to_string(),
description,
fields,
};
Ok((Some(struct_doc), all_referenced_constants))
} else {
Ok((None, all_referenced_constants))
}
}
fn extract_struct_fields(
index: &serde_json::Map<String, serde_json::Value>,
struct_item: &serde_json::Value,
) -> Result<(Vec<FieldDoc>, std::collections::HashSet<String>)> {
let mut fields = Vec::new();
let mut all_referenced_constants = std::collections::HashSet::new();
// Navigate through rustdoc JSON structure to access struct fields
// Path: item.inner.struct.kind.plain.fields[]
if let Some(field_ids) =
get_json_array(struct_item, &["inner", "struct", "kind", "plain", "fields"])
{
for field_id in field_ids {
// Field IDs can be either integers or strings in rustdoc JSON, try both formats
let field_item = if let Some(field_id_num) = field_id.as_u64() {
// Numeric field ID - convert to string for index lookup
index.get(&field_id_num.to_string())
} else if let Some(field_id_str) = field_id.as_str() {
// String field ID - use directly for index lookup
index.get(field_id_str)
} else {
None
};
if let Some(field_item) = field_item {
// Extract the field's name from the rustdoc item
let field_name = get_json_string(field_item, &["name"])
.unwrap_or("unknown")
.to_string();
// Extract the field's documentation text from rustdoc
let field_docs = get_json_string(field_item, &["docs"])
.unwrap_or("")
.to_string();
// Parse the structured documentation
let (field_doc, referenced_constants) =
parse_field_documentation(&field_docs, &field_name)?;
// Only include fields that have documentation
if !field_doc.description.is_empty() || field_doc.default_value.is_some() {
fields.push(field_doc);
}
// Extend referenced constants
all_referenced_constants.extend(referenced_constants);
}
}
}
Ok((fields, all_referenced_constants))
}
fn parse_field_documentation(
doc_text: &str,
field_name: &str,
) -> Result<(FieldDoc, std::collections::HashSet<String>)> {
let mut default_value = None;
let mut notes = None;
let mut deprecated = None;
let mut toml_example = None;
let mut required = None;
let mut units = None;
let mut referenced_constants = std::collections::HashSet::new();
// Split on --- separator if present
let parts: Vec<&str> = doc_text.split("---").collect();
let description = parts[0].trim().to_string();
// Collect constant references from description
referenced_constants.extend(find_constant_references(&description));
// Parse metadata section if present
if parts.len() >= 2 {
let metadata_section = parts[1];
// Parse @default: annotations
if let Some(default_match) = extract_annotation(metadata_section, "default") {
// Collect constant references from default value
referenced_constants.extend(find_constant_references(&default_match));
default_value = Some(default_match);
}
// Parse @notes: annotations
if let Some(notes_text) = extract_annotation(metadata_section, "notes") {
// Collect constant references from notes
referenced_constants.extend(find_constant_references(¬es_text));
let mut note_items: Vec<String> = Vec::new();
let mut current_note = String::new();
let mut in_note = false;
for line in notes_text.lines() {
let trimmed = line.trim();
// Skip empty lines
if trimmed.is_empty() {
continue;
}
// Check if this line starts a new note (bullet point)
if trimmed.starts_with("- ") || trimmed.starts_with("* ") {
// If we were building a previous note, save it
if in_note && !current_note.trim().is_empty() {
note_items.push(current_note.trim().to_string());
}
// Start a new note (remove the bullet point)
current_note = trimmed[2..].trim().to_string();
in_note = true;
} else if in_note {
// This is a continuation line for the current note
if !current_note.is_empty() {
current_note.push(' ');
}
current_note.push_str(trimmed);
}
// If not in_note and doesn't start with bullet, ignore the line
}
// Don't forget the last note
if in_note && !current_note.trim().is_empty() {
note_items.push(current_note.trim().to_string());
}
if !note_items.is_empty() {
notes = Some(note_items);
}
}
// Parse @deprecated: annotations
if let Some(deprecated_text) = extract_annotation(metadata_section, "deprecated") {
// Collect constant references from deprecated text
referenced_constants.extend(find_constant_references(&deprecated_text));
deprecated = Some(deprecated_text);
}
// Parse @toml_example: annotations
if let Some(example_text) = extract_annotation(metadata_section, "toml_example") {
// Note: We typically don't expect constant references in TOML examples,
// but we'll check anyway for completeness
referenced_constants.extend(find_constant_references(&example_text));
toml_example = Some(example_text);
}
// Parse @required: annotations
if let Some(required_text) = extract_annotation(metadata_section, "required") {
let required_bool = match required_text.trim() {
"" => false, // Empty string defaults to false
text => text.parse::<bool>().unwrap_or_else(|_| {
eprintln!(
"Warning: Invalid @required value '{text}' for field '{field_name}', defaulting to false"
);
false
}),
};
required = Some(required_bool);
}
// Parse @units: annotations
if let Some(units_text) = extract_annotation(metadata_section, "units") {
// Collect constant references from units text
referenced_constants.extend(find_constant_references(&units_text));
units = Some(units_text);
}
}
let field_doc = FieldDoc {
name: field_name.to_string(),
description,
default_value,
notes,
deprecated,
toml_example,
required,
units,
};
Ok((field_doc, referenced_constants))
}
/// Parse a YAML-style literal block scalar (|) from comment lines
/// Preserves newlines and internal indentation relative to the block base indentation
fn parse_literal_block_scalar(lines: &[&str], _base_indent: usize) -> String {
if lines.is_empty() {
return String::new();
}
// Find the first non-empty content line to determine block indentation
let content_lines: Vec<&str> = lines
.iter()
.skip_while(|line| line.trim().is_empty())
.copied()
.collect();
if content_lines.is_empty() {
return String::new();
}
// Determine block indentation from the first content line
let block_indent = content_lines[0].len() - content_lines[0].trim_start().len();
// Process all lines, preserving relative indentation within the block
let mut result_lines = Vec::new();
for line in lines {
if line.trim().is_empty() {
// Preserve empty lines
result_lines.push(String::new());
} else {
let line_indent = line.len() - line.trim_start().len();
if line_indent >= block_indent {
// Remove only the common block indentation, preserving relative indentation
let content = &line[block_indent.min(line.len())..];
result_lines.push(content.to_string());
} else {
// Line is less indented than block base - should not happen in well-formed blocks
result_lines.push(line.trim_start().to_string());
}
}
}
// Remove trailing empty lines (clip chomping style)
while let Some(last) = result_lines.last() {
if last.is_empty() {
result_lines.pop();
} else {
break;
}
}
result_lines.join("\n")
}
/// Parse a YAML-style folded block scalar (>)
/// Folds lines into paragraphs, preserving more-indented lines as literal blocks
fn parse_folded_block_scalar(lines: &[&str], _base_indent: usize) -> String {
if lines.is_empty() {
return String::new();
}
// Find the first non-empty content line to determine block indentation
let content_lines: Vec<&str> = lines
.iter()
.skip_while(|line| line.trim().is_empty())
.copied()
.collect();
if content_lines.is_empty() {
return String::new();
}
// Determine block indentation from the first content line
let block_indent = content_lines[0].len() - content_lines[0].trim_start().len();
let mut result = String::new();
let mut current_paragraph = Vec::new();
let mut in_literal_block = false;
for line in lines {
if line.trim().is_empty() {
if in_literal_block {
// Empty line in literal block - preserve it
result.push('\n');
} else if !current_paragraph.is_empty() {
// End current paragraph
result.push_str(¤t_paragraph.join(" "));
result.push_str("\n\n");
current_paragraph.clear();
}
continue;
}
let line_indent = line.len() - line.trim_start().len();
let content = if line_indent >= block_indent {
&line[block_indent.min(line.len())..]
} else {
line.trim_start()
};
let relative_indent = line_indent.saturating_sub(block_indent);
if relative_indent > 0 {
// More indented line - start or continue literal block
if !in_literal_block {
// Finish current paragraph before starting literal block
if !current_paragraph.is_empty() {
result.push_str(¤t_paragraph.join(" "));
result.push('\n');
current_paragraph.clear();
}
in_literal_block = true;
}
// Add literal line with preserved indentation
result.push_str(content);
result.push('\n');
} else {
// Normal indentation - folded content
if in_literal_block {
// Exit literal block
in_literal_block = false;
if !result.is_empty() && !result.ends_with('\n') {
result.push('\n');
}
}
// Add to current paragraph
current_paragraph.push(content);
}
}
// Finish any remaining paragraph
if !current_paragraph.is_empty() {
result.push_str(¤t_paragraph.join(" "));
}
// Apply "clip" chomping style (consistent with literal parser)
// Remove trailing empty lines but preserve a single trailing newline if content exists
let trimmed = result.trim_end_matches('\n');
if !trimmed.is_empty() && result.ends_with('\n') {
format!("{trimmed}\n")
} else {
trimmed.to_string()
}
}
fn extract_annotation(metadata_section: &str, annotation_name: &str) -> Option<String> {
let annotation_pattern = format!("@{annotation_name}:");
if let Some(_start_pos) = metadata_section.find(&annotation_pattern) {
// Split the metadata section into lines for processing
let all_lines: Vec<&str> = metadata_section.lines().collect();
// Find which line contains our annotation
let mut annotation_line_idx = None;
for (idx, line) in all_lines.iter().enumerate() {
if line.contains(&annotation_pattern) {
annotation_line_idx = Some(idx);
break;
}
}
let annotation_line_idx = annotation_line_idx?;
let annotation_line = all_lines[annotation_line_idx];
// Find the position of the annotation pattern within this line
let pattern_pos = annotation_line.find(&annotation_pattern)?;
let after_colon = &annotation_line[pattern_pos + annotation_pattern.len()..];
// Check for multiline indicators immediately after the colon
let trimmed_after_colon = after_colon.trim_start();
if trimmed_after_colon.starts_with('|') {
// Literal block scalar mode (|)
// Content starts from the next line, ignoring any text after | on the same line
let block_lines = collect_annotation_block_lines(
&all_lines,
annotation_line_idx + 1,
annotation_line,
);
// Convert to owned strings for the parser
let owned_lines: Vec<String> = block_lines.iter().map(|s| s.to_string()).collect();
// Convert back to string slices for the parser
let string_refs: Vec<&str> = owned_lines.iter().map(|s| s.as_str()).collect();
let base_indent = annotation_line.len() - annotation_line.trim_start().len();
let result = parse_literal_block_scalar(&string_refs, base_indent);
if result.trim().is_empty() {
return None;
} else {
return Some(result);
}
} else if trimmed_after_colon.starts_with('>') {
// Folded block scalar mode (>)
// Content starts from the next line, ignoring any text after > on the same line
let block_lines = collect_annotation_block_lines(
&all_lines,
annotation_line_idx + 1,
annotation_line,
);
// Convert to owned strings for the parser
let owned_lines: Vec<String> = block_lines.iter().map(|s| s.to_string()).collect();
// Convert back to string slices for the parser
let string_refs: Vec<&str> = owned_lines.iter().map(|s| s.as_str()).collect();
let base_indent = annotation_line.len() - annotation_line.trim_start().len();
let result = parse_folded_block_scalar(&string_refs, base_indent);
if result.trim().is_empty() {
return None;
} else {
return Some(result);
}
} else {
// Default literal-like multiline mode
// Content can start on the same line or the next line
let mut content_lines = Vec::new();
// Check if there's content on the same line after the colon
if !trimmed_after_colon.is_empty() {
content_lines.push(trimmed_after_colon);
}
// Collect subsequent lines that belong to this annotation
let block_lines = collect_annotation_block_lines(
&all_lines,
annotation_line_idx + 1,
annotation_line,
);
// For default mode, preserve relative indentation within the block
if !block_lines.is_empty() {
// Find the base indentation from the first non-empty content line
let mut base_indent = None;
for line in &block_lines {
let trimmed = line.trim();
if !trimmed.is_empty() {
base_indent = Some(line.len() - line.trim_start().len());
break;
}
}
// Process lines preserving relative indentation
for line in block_lines {
let trimmed = line.trim();
if !trimmed.is_empty() {
if let Some(base) = base_indent {
let line_indent = line.len() - line.trim_start().len();
if line_indent >= base {
// Remove only the common base indentation, preserving relative indentation
let content = &line[base.min(line.len())..];
content_lines.push(content);
} else {
// Line is less indented than base - use trimmed content
content_lines.push(trimmed);
}
} else {
content_lines.push(trimmed);
}
}
}
}
if content_lines.is_empty() {
return None;
}
// Join lines preserving the structure - this maintains internal newlines and relative indentation
let result = content_lines.join("\n");
// Apply standard trimming and return if not empty
let cleaned = result.trim();
if !cleaned.is_empty() {
return Some(cleaned.to_string());
}
}
}
None
}
/// Collect lines that belong to an annotation block, stopping at the next annotation or end
fn collect_annotation_block_lines<'a>(
all_lines: &[&'a str],
start_idx: usize,
annotation_line: &str,
) -> Vec<&'a str> {
let mut block_lines = Vec::new();
let annotation_indent = annotation_line.len() - annotation_line.trim_start().len();
for &line in all_lines.iter().skip(start_idx) {
let trimmed = line.trim();
// Stop if we hit another annotation at the same or lesser indentation level
if trimmed.starts_with('@') && trimmed.contains(':') {
let line_indent = line.len() - line.trim_start().len();
if line_indent <= annotation_indent {
break;
}
}
// Stop if we hit a line that's clearly not part of the comment block
// (very different indentation or structure)
let line_indent = line.len() - line.trim_start().len();
if !trimmed.is_empty() && line_indent < annotation_indent {
break;
}
block_lines.push(line);
}
block_lines
}
fn resolve_constant_reference(
name: &str,
rustdoc_index: &serde_json::Map<String, serde_json::Value>,
) -> Option<String> {
// First, try to find the constant in the main rustdoc index
if let Some(value) = resolve_constant_in_index(name, rustdoc_index) {
return Some(value);
}
// If not found in main index, try additional crates
let additional_crate_libs = ["stacks_common"]; // Library names for additional crates
for lib_name in &additional_crate_libs {
let json_file_path = format!("target/rustdoc-json/doc/{lib_name}.json");
if let Ok(json_content) = std::fs::read_to_string(&json_file_path)
&& let Ok(rustdoc_json) = serde_json::from_str::<serde_json::Value>(&json_content)
&& let Some(index) = get_json_object(&rustdoc_json, &["index"])
&& let Some(value) = resolve_constant_in_index(name, index)
{
return Some(value);
}
}
None
}
fn resolve_constant_in_index(
name: &str,
rustdoc_index: &serde_json::Map<String, serde_json::Value>,
) -> Option<String> {
// Look for a constant with the given name in the rustdoc index
for (_item_id, item) in rustdoc_index {
// Check if this item's name matches the constant we're looking for
if let Some(item_name) = get_json_string(item, &["name"])
&& item_name == name
{
// Check if this item is a constant by looking for the "constant" field
if let Some(constant_data) = get_json_object(item, &["inner", "constant"]) {
// Try newer rustdoc JSON structure first (with nested 'const' field)
let constant_data_value = serde_json::Value::Object(constant_data.clone());
if get_json_object(&constant_data_value, &["const"]).is_some() {
// For literal constants, prefer expr which doesn't have type suffix
if get_json_path(&constant_data_value, &["const", "is_literal"])
.and_then(|v| v.as_bool())
== Some(true)
{
// Access the expression field for literal constant values
if let Some(expr) =
get_json_string(&constant_data_value, &["const", "expr"])
&& expr != "_"
{
return Some(expr.to_string());
}
}
// For computed constants or when expr is "_", use value but strip type suffix
if let Some(value) = get_json_string(&constant_data_value, &["const", "value"])
{
return Some(strip_type_suffix(value));
}
// Fallback to expr if value is not available
if let Some(expr) = get_json_string(&constant_data_value, &["const", "expr"])
&& expr != "_"
{
return Some(expr.to_string());
}
}
// Fall back to older rustdoc JSON structure for compatibility
if let Some(value) = get_json_string(&constant_data_value, &["value"]) {
return Some(strip_type_suffix(value));
}
if let Some(expr) = get_json_string(&constant_data_value, &["expr"])
&& expr != "_"
{
return Some(expr.to_string());
}
// For some constants, the value might be in the type field if it's a simple literal
if let Some(type_str) = get_json_string(&constant_data_value, &["type"]) {
// Handle simple numeric or string literals embedded in type
return Some(type_str.to_string());
}
}
}
}
None
}
/// Strip type suffixes from rustdoc constant values (e.g., "50u64" -> "50", "402_653_196u32" -> "402_653_196")
fn strip_type_suffix(value: &str) -> String {
// Common Rust integer type suffixes
let suffixes = [
"u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize",
"f32", "f64",
];
for suffix in &suffixes {
if let Some(without_suffix) = value.strip_suffix(suffix) {
// Only strip if the remaining part looks like a numeric literal
// (contains only digits, underscores, dots, minus signs, or quotes for string literals)
if !without_suffix.is_empty()
&& (without_suffix
.chars()
.all(|c| c.is_ascii_digit() || c == '_' || c == '.' || c == '-')
|| (without_suffix.starts_with('"') && without_suffix.ends_with('"')))
{
return without_suffix.to_string();
}
}
}
// If no valid suffix found, return as-is
value.to_string()
}
fn find_constant_references(text: &str) -> std::collections::HashSet<String> {
let mut constants = std::collections::HashSet::new();
for captures in CONSTANT_REFERENCE_REGEX.captures_iter(text) {
if let Some(constant_name) = captures.get(1) {
constants.insert(constant_name.as_str().to_string());
}
}
constants
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
#[test]
fn test_parse_field_documentation_basic() {
let doc_text = "This is a basic field description.";
let result = parse_field_documentation(doc_text, "test_field").unwrap();
assert_eq!(result.0.name, "test_field");
assert_eq!(result.0.description, "This is a basic field description.");
assert_eq!(result.0.default_value, None);
assert_eq!(result.0.notes, None);
assert_eq!(result.0.deprecated, None);
assert_eq!(result.0.toml_example, None);
}
#[test]
fn test_parse_field_documentation_with_metadata() {
let doc_text = r#"This is a field with metadata.
---
@default: `"test_value"`
@notes:
- This is a note.
- This is another note.
@deprecated: This field is deprecated.
@toml_example: |
key = "value"
other = 123"#;
let result = parse_field_documentation(doc_text, "test_field").unwrap();
assert_eq!(result.0.name, "test_field");
assert_eq!(result.0.description, "This is a field with metadata.");
assert_eq!(result.0.default_value, Some("`\"test_value\"`".to_string()));
assert_eq!(
result.0.notes,
Some(vec![
"This is a note.".to_string(),
"This is another note.".to_string()
])
);
assert_eq!(
result.0.deprecated,
Some("This field is deprecated.".to_string())
);
assert_eq!(
result.0.toml_example,
Some("key = \"value\"\nother = 123".to_string())
);
}
#[test]
fn test_parse_field_documentation_multiline_default() {
let doc_text = r#"Multi-line field description.
---
@default: Derived from [`BurnchainConfig::mode`] ([`CHAIN_ID_MAINNET`] for `mainnet`,
[`CHAIN_ID_TESTNET`] otherwise).
@notes:
- Warning: Do not modify this unless you really know what you're doing."#;
let result = parse_field_documentation(doc_text, "test_field").unwrap();
assert_eq!(result.0.name, "test_field");
assert_eq!(result.0.description, "Multi-line field description.");
assert!(result.0.default_value.is_some());
let default_val = result.0.default_value.unwrap();