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