]> git.lizzy.rs Git - rust.git/blob - xtask/src/codegen/gen_diagnostic_docs.rs
Fix mega bug
[rust.git] / xtask / src / codegen / gen_diagnostic_docs.rs
1 //! Generates `assists.md` documentation.
2
3 use std::{fmt, path::PathBuf};
4
5 use crate::{
6     codegen::{self, extract_comment_blocks_with_empty_lines, Location, Mode, PREAMBLE},
7     project_root, rust_files, Result,
8 };
9
10 pub fn generate_diagnostic_docs(mode: Mode) -> Result<()> {
11     let diagnostics = Diagnostic::collect()?;
12     let contents =
13         diagnostics.into_iter().map(|it| it.to_string()).collect::<Vec<_>>().join("\n\n");
14     let contents = format!("//{}\n{}\n", PREAMBLE, contents.trim());
15     let dst = project_root().join("docs/user/generated_diagnostic.adoc");
16     codegen::update(&dst, &contents, mode)?;
17     Ok(())
18 }
19
20 #[derive(Debug)]
21 struct Diagnostic {
22     id: String,
23     location: Location,
24     doc: String,
25 }
26
27 impl Diagnostic {
28     fn collect() -> Result<Vec<Diagnostic>> {
29         let mut res = Vec::new();
30         for path in rust_files() {
31             collect_file(&mut res, path)?;
32         }
33         res.sort_by(|lhs, rhs| lhs.id.cmp(&rhs.id));
34         return Ok(res);
35
36         fn collect_file(acc: &mut Vec<Diagnostic>, path: PathBuf) -> Result<()> {
37             let text = xshell::read_file(&path)?;
38             let comment_blocks = extract_comment_blocks_with_empty_lines("Diagnostic", &text);
39
40             for block in comment_blocks {
41                 let id = block.id;
42                 if let Err(msg) = is_valid_diagnostic_name(&id) {
43                     panic!("invalid diagnostic name: {:?}:\n  {}", id, msg)
44                 }
45                 let doc = block.contents.join("\n");
46                 let location = Location::new(path.clone(), block.line);
47                 acc.push(Diagnostic { id, location, doc })
48             }
49
50             Ok(())
51         }
52     }
53 }
54
55 fn is_valid_diagnostic_name(diagnostic: &str) -> Result<(), String> {
56     let diagnostic = diagnostic.trim();
57     if diagnostic.find(char::is_whitespace).is_some() {
58         return Err("Diagnostic names can't contain whitespace symbols".into());
59     }
60     if diagnostic.chars().any(|c| c.is_ascii_uppercase()) {
61         return Err("Diagnostic names can't contain uppercase symbols".into());
62     }
63     if diagnostic.chars().any(|c| !c.is_ascii()) {
64         return Err("Diagnostic can't contain non-ASCII symbols".into());
65     }
66
67     Ok(())
68 }
69
70 impl fmt::Display for Diagnostic {
71     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72         writeln!(f, "=== {}\n**Source:** {}\n{}", self.id, self.location, self.doc)
73     }
74 }