]> git.lizzy.rs Git - rust.git/blob - xtask/src/codegen.rs
Make working with codegen less annoying
[rust.git] / xtask / src / codegen.rs
1 //! We use code generation heavily in rust-analyzer.
2 //!
3 //! Rather then doing it via proc-macros, we use old-school way of just dumping
4 //! the source code.
5 //!
6 //! This module's submodules define specific bits that we generate.
7
8 mod gen_syntax;
9 mod gen_parser_tests;
10 mod gen_assists_docs;
11 mod gen_feature_docs;
12 mod gen_lint_completions;
13 mod gen_diagnostic_docs;
14
15 use std::{
16     fmt, mem,
17     path::{Path, PathBuf},
18 };
19 use xshell::{cmd, pushenv, read_file, write_file};
20
21 use crate::{ensure_rustfmt, flags, project_root, Result};
22
23 pub(crate) use self::{
24     gen_assists_docs::{generate_assists_docs, generate_assists_tests},
25     gen_diagnostic_docs::generate_diagnostic_docs,
26     gen_feature_docs::generate_feature_docs,
27     gen_lint_completions::generate_lint_completions,
28     gen_parser_tests::generate_parser_tests,
29     gen_syntax::generate_syntax,
30 };
31
32 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
33 pub(crate) enum Mode {
34     Overwrite,
35     Ensure,
36 }
37
38 impl flags::Codegen {
39     pub(crate) fn run(self) -> Result<()> {
40         if self.features {
41             generate_lint_completions(Mode::Overwrite)?;
42         }
43         generate_syntax(Mode::Overwrite)?;
44         generate_parser_tests(Mode::Overwrite)?;
45         generate_assists_tests(Mode::Overwrite)?;
46         generate_assists_docs(Mode::Overwrite)?;
47         generate_feature_docs(Mode::Overwrite)?;
48         generate_diagnostic_docs(Mode::Overwrite)?;
49         Ok(())
50     }
51 }
52
53 /// A helper to update file on disk if it has changed.
54 /// With verify = false,
55 fn update(path: &Path, contents: &str, mode: Mode) -> Result<()> {
56     match read_file(path) {
57         Ok(old_contents) if normalize(&old_contents) == normalize(contents) => {
58             return Ok(());
59         }
60         _ => (),
61     }
62     let return_error = match mode {
63         Mode::Overwrite => false,
64         Mode::Ensure => true,
65     };
66     eprintln!("updating {}", path.display());
67     write_file(path, contents)?;
68
69     return if return_error {
70         let path = path.strip_prefix(&project_root()).unwrap_or(path);
71         anyhow::bail!("`{}` was not up-to-date, updating", path.display());
72     } else {
73         Ok(())
74     };
75
76     fn normalize(s: &str) -> String {
77         s.replace("\r\n", "\n")
78     }
79 }
80
81 const PREAMBLE: &str = "Generated file, do not edit by hand, see `xtask/src/codegen`";
82
83 fn reformat(text: &str) -> Result<String> {
84     let _e = pushenv("RUSTUP_TOOLCHAIN", "stable");
85     ensure_rustfmt()?;
86     let rustfmt_toml = project_root().join("rustfmt.toml");
87     let stdout = cmd!("rustfmt --config-path {rustfmt_toml} --config fn_single_line=true")
88         .stdin(text)
89         .read()?;
90     Ok(format!("//! {}\n\n{}\n", PREAMBLE, stdout))
91 }
92
93 fn extract_comment_blocks(text: &str) -> Vec<Vec<String>> {
94     do_extract_comment_blocks(text, false).into_iter().map(|(_line, block)| block).collect()
95 }
96
97 fn extract_comment_blocks_with_empty_lines(tag: &str, text: &str) -> Vec<CommentBlock> {
98     assert!(tag.starts_with(char::is_uppercase));
99     let tag = format!("{}:", tag);
100     let mut res = Vec::new();
101     for (line, mut block) in do_extract_comment_blocks(text, true) {
102         let first = block.remove(0);
103         if first.starts_with(&tag) {
104             let id = first[tag.len()..].trim().to_string();
105             let block = CommentBlock { id, line, contents: block };
106             res.push(block);
107         }
108     }
109     res
110 }
111
112 struct CommentBlock {
113     id: String,
114     line: usize,
115     contents: Vec<String>,
116 }
117
118 fn do_extract_comment_blocks(
119     text: &str,
120     allow_blocks_with_empty_lines: bool,
121 ) -> Vec<(usize, Vec<String>)> {
122     let mut res = Vec::new();
123
124     let prefix = "// ";
125     let lines = text.lines().map(str::trim_start);
126
127     let mut block = (0, vec![]);
128     for (line_num, line) in lines.enumerate() {
129         if line == "//" && allow_blocks_with_empty_lines {
130             block.1.push(String::new());
131             continue;
132         }
133
134         let is_comment = line.starts_with(prefix);
135         if is_comment {
136             block.1.push(line[prefix.len()..].to_string());
137         } else {
138             if !block.1.is_empty() {
139                 res.push(mem::take(&mut block));
140             }
141             block.0 = line_num + 2;
142         }
143     }
144     if !block.1.is_empty() {
145         res.push(block)
146     }
147     res
148 }
149
150 #[derive(Debug)]
151 struct Location {
152     file: PathBuf,
153     line: usize,
154 }
155
156 impl Location {
157     fn new(file: PathBuf, line: usize) -> Self {
158         Self { file, line }
159     }
160 }
161
162 impl fmt::Display for Location {
163     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164         let path = self.file.strip_prefix(&project_root()).unwrap().display().to_string();
165         let path = path.replace('\\', "/");
166         let name = self.file.file_name().unwrap();
167         write!(
168             f,
169             "https://github.com/rust-analyzer/rust-analyzer/blob/master/{}#L{}[{}]",
170             path,
171             self.line,
172             name.to_str().unwrap()
173         )
174     }
175 }