1use quote::ToTokens;
2use regex::Regex;
3use std::error::Error;
4use std::fs;
5use std::path::{Path, PathBuf};
6use std::process::Command;
7use std::{collections::HashSet, env};
8use syn::{
9 Attribute, File, Item, ItemEnum, ItemImpl, ItemStruct, ItemTrait, ItemType, ItemUse, Type,
10 TypePath, UseRename, UseTree,
11};
12
13#[derive(Debug)]
14struct CodeExample {
15 input_code: String,
16 output_start: usize,
17 output_end: usize,
18}
19
20#[derive(Debug)]
21struct ExtractedCode {
22 use_statements: Vec<ItemUse>,
23 trait_definitions: Vec<ItemTrait>,
24 type_aliases: Vec<ItemType>,
25 struct_definitions: Vec<ItemStruct>,
26 enum_definitions: Vec<ItemEnum>,
27 fieldwork_impls: Vec<ItemImpl>,
28}
29
30fn main() -> Result<(), Box<dyn Error>> {
31 let verbose = env::args().any(|arg| arg == "--verbose" || arg == "-v");
32 let verify = env::args().any(|arg| arg == "--verify");
33
34 let docs_dir = env::args()
35 .skip(1)
36 .find(|arg| !arg.starts_with("--"))
37 .unwrap_or_else(|| "docs".to_string());
38
39 let md_files = find_markdown_files(Path::new(&docs_dir))?;
40 println!("Found {} markdown files in {docs_dir}/", md_files.len());
41
42 let example_file = env::current_dir()?.join("examples/docs-expansion.rs");
43 let mut any_changed = false;
44 let mut any_failed = false;
45
46 for path in &md_files {
47 match process_file(path, &example_file, verbose, verify) {
48 Ok(changed) => any_changed |= changed,
49 Err(e) => {
50 eprintln!("❌ {e}");
51 any_failed = true;
52 }
53 }
54 }
55
56 if any_failed {
57 eprintln!("❌ Some examples could not be processed; see errors above.");
58 std::process::exit(1);
59 }
60
61 if verify && any_changed {
62 eprintln!("❌ Documentation is out of date! Run `cargo docs-gen` to update.");
63 std::process::exit(1);
64 } else if verify {
65 println!("✅ Documentation is up to date.");
66 }
67
68 Ok(())
69}
70
71fn find_markdown_files(dir: &Path) -> Result<Vec<PathBuf>, Box<dyn Error>> {
72 let mut files = Vec::new();
73 if !dir.exists() {
74 return Ok(files);
75 }
76 collect_markdown_files(dir, &mut files)?;
77 files.sort();
78 Ok(files)
79}
80
81fn collect_markdown_files(dir: &Path, files: &mut Vec<PathBuf>) -> Result<(), Box<dyn Error>> {
82 for entry in fs::read_dir(dir)? {
83 let entry = entry?;
84 let path = entry.path();
85 if path.is_dir() {
86 collect_markdown_files(&path, files)?;
87 } else if path.extension().and_then(|e| e.to_str()) == Some("md") {
88 files.push(path);
89 }
90 }
91 Ok(())
92}
93
94fn process_file(
95 path: &Path,
96 example_file: &Path,
97 verbose: bool,
98 verify: bool,
99) -> Result<bool, Box<dyn Error>> {
100 let display = path.display();
101 let content = fs::read_to_string(path)?;
102
103 println!("Looking for examples in {display}...");
104 let examples = find_expandable_examples(&content)?;
105
106 if examples.is_empty() {
107 return Ok(false);
108 }
109
110 println!("Found {} examples", examples.len());
111
112 let mut new_content = content.clone();
113 let mut updated_count = 0;
114 let mut failed_count = 0;
115
116 for (i, example) in examples.iter().rev().enumerate() {
117 println!("🔄 Processing example {i} of {}...", examples.len());
118
119 match process_example(&example.input_code, example_file) {
120 Ok(formatted) => {
121 if verbose {
122 println!("Generated output ({} chars):", formatted.len());
123 let lines: Vec<&str> = formatted.lines().collect();
124 for (i, line) in lines.iter().take(5).enumerate() {
125 println!(" {}: {}", i + 1, line);
126 }
127 if lines.len() > 5 {
128 println!(" ... ({} more lines)", lines.len() - 5);
129 }
130 }
131
132 let start = example.output_start;
133 let end = example.output_end;
134
135 let safe_start = if start >= new_content.len() {
136 new_content.len()
137 } else if new_content.is_char_boundary(start) {
138 start
139 } else {
140 (0..=start)
141 .rev()
142 .find(|&i| new_content.is_char_boundary(i))
143 .unwrap_or(0)
144 };
145
146 let safe_end = if end > new_content.len() {
147 new_content.len()
148 } else if new_content.is_char_boundary(end) {
149 end
150 } else {
151 (end..new_content.len())
152 .find(|&i| new_content.is_char_boundary(i))
153 .unwrap_or(new_content.len())
154 };
155
156 if safe_start <= safe_end {
157 new_content.replace_range(safe_start..safe_end, &formatted);
158 } else {
159 eprintln!("⚠️ Invalid range for example {i}, skipping replacement");
160 }
161
162 updated_count += 1;
163 println!("✅ Example {i} updated successfully");
164 }
165 Err(e) => {
166 eprintln!("❌ Failed to process example {i}: {e}");
167 if verbose {
168 eprintln!("Input code was:\n{}", example.input_code);
169 }
170 failed_count += 1;
171 }
172 }
173 }
174
175 let changed = new_content != content;
176
177 if !verify && updated_count > 0 {
178 fs::write(path, new_content)?;
179 println!("📝 Updated {updated_count} examples in {display}");
180 }
181
182 if failed_count > 0 {
183 return Err(format!("{failed_count} examples failed to process in {display}").into());
184 }
185
186 Ok(changed)
187}
188
189fn find_expandable_examples(content: &str) -> Result<Vec<CodeExample>, Box<dyn Error>> {
190 let mut examples = Vec::new();
191 let block_pattern = Regex::new(r"(?s)```rust\n(.*?)\n```")?;
192 let blocks: Vec<_> = block_pattern.captures_iter(content).collect();
193
194 for (i, block_match) in blocks.iter().enumerate() {
195 let block_content = block_match.get(1).unwrap().as_str();
196
197 if block_content.contains("#[derive(") && !block_content.contains("// docgen-skip") {
198 let input_code = block_content
199 .lines()
200 .map(|line| {
201 if let Some(stripped) = line.strip_prefix("# ") {
202 stripped
203 } else if line == "#" {
204 ""
205 } else {
206 line
207 }
208 })
209 .collect::<Vec<_>>()
210 .join("\n");
211
212 if let Some(next_block) = blocks.get(i + 1) {
213 let next_full = next_block.get(0).unwrap();
214 let output_start = next_full.start() + 8; let output_end = next_full.end() - 4; examples.push(CodeExample {
218 input_code,
219 output_start,
220 output_end,
221 });
222 }
223 }
224 }
225
226 Ok(examples)
227}
228
229fn process_example(input: &str, example_file: &Path) -> Result<String, Box<dyn Error>> {
230 let target_items = extract_item_names_from_input(input)?;
231 let expanded = expand_single_example(input, example_file)?;
232 let extracted = extract_fieldwork_code(&expanded, &target_items)?;
233 format_extracted_code(&extracted)
234}
235
236fn extract_item_names_from_input(input: &str) -> Result<HashSet<String>, Box<dyn Error>> {
237 let parsed: File = syn::parse_str(input)?;
238 let mut item_names = HashSet::new();
239
240 for item in parsed.items {
241 match item {
242 Item::Struct(s) => {
243 item_names.insert(s.ident.to_string());
244 }
245 Item::Enum(e) => {
246 item_names.insert(e.ident.to_string());
247 }
248 _ => {}
249 }
250 }
251
252 Ok(item_names)
253}
254
255fn extract_fieldwork_code(
256 expanded: &str,
257 target_items: &HashSet<String>,
258) -> Result<ExtractedCode, Box<dyn Error>> {
259 let parsed: File = syn::parse_str(expanded)?;
260
261 let mut use_statements = vec![];
262 let mut trait_definitions = vec![];
263 let mut type_aliases = vec![];
264 let mut struct_definitions = vec![];
265 let mut enum_definitions = vec![];
266 let mut fieldwork_impls = vec![];
267
268 for item in parsed.items {
269 match item {
270 Item::Use(use_item) if !is_delegation_reexport(&use_item) => {
271 use_statements.push(use_item);
272 }
273 Item::Trait(item_trait) => {
274 trait_definitions.push(item_trait);
275 }
276 Item::Type(item_type) => {
277 type_aliases.push(item_type);
278 }
279 Item::Struct(item_struct) => {
280 if target_items.contains(&item_struct.ident.to_string()) {
281 struct_definitions.push(item_struct);
282 }
283 }
284 Item::Enum(item_enum) => {
285 if target_items.contains(&item_enum.ident.to_string()) {
286 enum_definitions.push(item_enum);
287 }
288 }
289 Item::Impl(item_impl) => {
290 if is_fieldwork_impl(&item_impl, target_items) {
291 fieldwork_impls.push(item_impl);
292 }
293 }
294 _ => {}
295 }
296 }
297
298 Ok(ExtractedCode {
299 trait_definitions,
300 type_aliases,
301 struct_definitions,
302 enum_definitions,
303 fieldwork_impls,
304 use_statements,
305 })
306}
307
308fn is_delegation_reexport(use_item: &ItemUse) -> bool {
311 matches!(
312 &use_item.tree,
313 UseTree::Rename(UseRename { ident, .. })
314 if ident.to_string().starts_with("__fieldwork_delegate_")
315 )
316}
317
318fn is_fieldwork_impl(item_impl: &ItemImpl, target_items: &HashSet<String>) -> bool {
319 if item_impl.trait_.is_some() {
320 return false;
321 }
322
323 if let Type::Path(TypePath { path, .. }) = &*item_impl.self_ty {
324 if let Some(segment) = path.segments.last() {
325 let type_name = segment.ident.to_string();
326 return target_items.contains(&type_name);
327 }
328 }
329
330 false
331}
332
333fn format_extracted_code(extracted: &ExtractedCode) -> Result<String, Box<dyn Error>> {
334 let mut result = vec!["// GENERATED".to_string()];
335
336 for use_statement in &extracted.use_statements {
337 let formatted_use = concise_format(&use_statement.to_token_stream().to_string());
338 for line in formatted_use.lines() {
339 if !line.trim().is_empty() && !line.starts_with("#[prelude_import]") {
340 result.push(format!("# {line}"));
341 }
342 }
343 }
344
345 for trait_def in &extracted.trait_definitions {
346 let formatted_trait = concise_format(&trait_def.to_token_stream().to_string());
347 for line in formatted_trait.lines() {
348 if !line.trim().is_empty() {
349 result.push(format!("# {line}"));
350 }
351 }
352 }
353
354 for type_alias in &extracted.type_aliases {
355 let formatted_alias = concise_format(&type_alias.to_token_stream().to_string());
356 result.push(format!("# {formatted_alias}"));
357 }
358
359 for struct_def in &extracted.struct_definitions {
360 let mut cleaned_struct = struct_def.clone();
361 cleaned_struct
362 .attrs
363 .retain(|attr| !is_fieldwork_attr(attr) && !attr.path().is_ident("doc"));
364
365 for field in &mut cleaned_struct.fields {
366 field
367 .attrs
368 .retain(|attr| !is_fieldwork_attr(attr) && !attr.path().is_ident("doc"));
369 }
370
371 let formatted_struct = concise_format(&cleaned_struct.into_token_stream().to_string());
372 for line in formatted_struct.lines() {
373 if !line.trim().is_empty() {
374 result.push(format!("# {line}"));
375 }
376 }
377 }
378
379 for enum_def in &extracted.enum_definitions {
380 let mut cleaned_enum = enum_def.clone();
381 cleaned_enum
382 .attrs
383 .retain(|attr| !is_fieldwork_attr(attr) && !attr.path().is_ident("doc"));
384
385 for variant in &mut cleaned_enum.variants {
386 variant.attrs.retain(|attr| !is_fieldwork_attr(attr));
387 for field in &mut variant.fields {
388 field.attrs.retain(|attr| !is_fieldwork_attr(attr));
389 }
390 }
391
392 let formatted_enum = concise_format(&cleaned_enum.into_token_stream().to_string());
393 for line in formatted_enum.lines() {
394 if !line.trim().is_empty() {
395 result.push(format!("# {line}"));
396 }
397 }
398 }
399
400 for impl_block in &extracted.fieldwork_impls {
401 let formatted_impl = prettyplease::unparse(&syn::parse_quote! { #impl_block });
402 result.push(formatted_impl);
403 }
404
405 Ok(result.join("\n"))
406}
407
408fn is_fieldwork_attr(attr: &Attribute) -> bool {
409 let path = attr.path();
410 path.is_ident("fieldwork") || path.is_ident("field") || path.is_ident("variant")
411}
412
413fn concise_format(s: &str) -> String {
414 s.replace(" : ", ": ")
415 .replace(" < ", "<")
416 .replace(" > ", ">")
417 .replace(" , ", ", ")
418 .replace(" ; ", "; ")
419 .replace(" :: ", "::")
420 .replace("# ", "#")
421 .replace(" ;", ";")
422}
423
424fn expand_single_example(input: &str, example_file: &Path) -> Result<String, Box<dyn Error>> {
425 fs::write(example_file, input)?;
426
427 let output = Command::new("cargo")
428 .current_dir(env::current_dir()?)
429 .args(["expand", "--example", "docs-expansion"])
430 .output()?;
431
432 if output.status.success() {
433 fs::remove_file(example_file)?;
434 } else {
435 return Err(format!(
436 "cargo expand failed: {}",
437 String::from_utf8_lossy(&output.stderr)
438 )
439 .into());
440 }
441
442 if output.stdout.is_empty() {
443 return Err("cargo expand was empty, that's probably not right".into());
444 }
445
446 Ok(String::from_utf8(output.stdout)?)
447}
448
449#[cfg(test)]
450mod tests {
451 use super::*;
452
453 #[test]
454 fn test_extract_item_names() {
455 let input = r#"
456 #[derive(fieldwork::Fieldwork)]
457 struct User { name: String }
458
459 #[derive(fieldwork::Fieldwork)]
460 struct Post { title: String }
461
462 #[derive(fieldwork::Fieldwork)]
463 enum Status { Active { name: String }, Inactive { name: String } }
464 "#;
465
466 let names = extract_item_names_from_input(input).unwrap();
467 assert!(names.contains("User"));
468 assert!(names.contains("Post"));
469 assert!(names.contains("Status"));
470 assert_eq!(names.len(), 3);
471 }
472}