]> git.lizzy.rs Git - rust.git/blob - xtask/src/codegen/gen_assists_docs.rs
Fix mega bug
[rust.git] / xtask / src / codegen / gen_assists_docs.rs
1 //! Generates `assists.md` documentation.
2
3 use std::{fmt, path::Path};
4
5 use crate::{
6     codegen::{self, extract_comment_blocks_with_empty_lines, reformat, Location, Mode, PREAMBLE},
7     project_root, rust_files_in, Result,
8 };
9
10 pub fn generate_assists_tests(mode: Mode) -> Result<()> {
11     let assists = Assist::collect()?;
12     generate_tests(&assists, mode)
13 }
14
15 pub fn generate_assists_docs(mode: Mode) -> Result<()> {
16     let assists = Assist::collect()?;
17     let contents = assists.into_iter().map(|it| it.to_string()).collect::<Vec<_>>().join("\n\n");
18     let contents = format!("//{}\n{}\n", PREAMBLE, contents.trim());
19     let dst = project_root().join("docs/user/generated_assists.adoc");
20     codegen::update(&dst, &contents, mode)
21 }
22
23 #[derive(Debug)]
24 struct Assist {
25     id: String,
26     location: Location,
27     doc: String,
28     before: String,
29     after: String,
30 }
31
32 impl Assist {
33     fn collect() -> Result<Vec<Assist>> {
34         let mut res = Vec::new();
35         for path in rust_files_in(&project_root().join("crates/assists/src/handlers")) {
36             collect_file(&mut res, path.as_path())?;
37         }
38         res.sort_by(|lhs, rhs| lhs.id.cmp(&rhs.id));
39         return Ok(res);
40
41         fn collect_file(acc: &mut Vec<Assist>, path: &Path) -> Result<()> {
42             let text = xshell::read_file(path)?;
43             let comment_blocks = extract_comment_blocks_with_empty_lines("Assist", &text);
44
45             for block in comment_blocks {
46                 // FIXME: doesn't support blank lines yet, need to tweak
47                 // `extract_comment_blocks` for that.
48                 let id = block.id;
49                 assert!(
50                     id.chars().all(|it| it.is_ascii_lowercase() || it == '_'),
51                     "invalid assist id: {:?}",
52                     id
53                 );
54                 let mut lines = block.contents.iter();
55
56                 let doc = take_until(lines.by_ref(), "```").trim().to_string();
57                 assert!(
58                     doc.chars().next().unwrap().is_ascii_uppercase() && doc.ends_with('.'),
59                     "\n\n{}: assist docs should be proper sentences, with capitalization and a full stop at the end.\n\n{}\n\n",
60                     id, doc,
61                 );
62
63                 let before = take_until(lines.by_ref(), "```");
64
65                 assert_eq!(lines.next().unwrap().as_str(), "->");
66                 assert_eq!(lines.next().unwrap().as_str(), "```");
67                 let after = take_until(lines.by_ref(), "```");
68                 let location = Location::new(path.to_path_buf(), block.line);
69                 acc.push(Assist { id, location, doc, before, after })
70             }
71
72             fn take_until<'a>(lines: impl Iterator<Item = &'a String>, marker: &str) -> String {
73                 let mut buf = Vec::new();
74                 for line in lines {
75                     if line == marker {
76                         break;
77                     }
78                     buf.push(line.clone());
79                 }
80                 buf.join("\n")
81             }
82             Ok(())
83         }
84     }
85 }
86
87 impl fmt::Display for Assist {
88     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89         let before = self.before.replace("$0", "┃"); // Unicode pseudo-graphics bar
90         let after = self.after.replace("$0", "┃");
91         writeln!(
92             f,
93             "[discrete]\n=== `{}`
94 **Source:** {}
95
96 {}
97
98 .Before
99 ```rust
100 {}```
101
102 .After
103 ```rust
104 {}```",
105             self.id,
106             self.location,
107             self.doc,
108             hide_hash_comments(&before),
109             hide_hash_comments(&after)
110         )
111     }
112 }
113
114 fn generate_tests(assists: &[Assist], mode: Mode) -> Result<()> {
115     let mut buf = String::from("use super::check_doc_test;\n");
116
117     for assist in assists.iter() {
118         let test = format!(
119             r######"
120 #[test]
121 fn doctest_{}() {{
122     check_doc_test(
123         "{}",
124 r#####"
125 {}"#####, r#####"
126 {}"#####)
127 }}
128 "######,
129             assist.id,
130             assist.id,
131             reveal_hash_comments(&assist.before),
132             reveal_hash_comments(&assist.after)
133         );
134
135         buf.push_str(&test)
136     }
137     let buf = reformat(&buf)?;
138     codegen::update(&project_root().join("crates/assists/src/tests/generated.rs"), &buf, mode)
139 }
140
141 fn hide_hash_comments(text: &str) -> String {
142     text.split('\n') // want final newline
143         .filter(|&it| !(it.starts_with("# ") || it == "#"))
144         .map(|it| format!("{}\n", it))
145         .collect()
146 }
147
148 fn reveal_hash_comments(text: &str) -> String {
149     text.split('\n') // want final newline
150         .map(|it| {
151             if it.starts_with("# ") {
152                 &it[2..]
153             } else if it == "#" {
154                 ""
155             } else {
156                 it
157             }
158         })
159         .map(|it| format!("{}\n", it))
160         .collect()
161 }