1 //! We use code generation heavily in rust-analyzer.
3 //! Rather then doing it via proc-macros, we use old-school way of just dumping
6 //! This module's submodules define specific bits that we generate.
12 mod gen_lint_completions;
13 mod gen_diagnostic_docs;
17 path::{Path, PathBuf},
19 use xshell::{cmd, pushenv, read_file, write_file};
21 use crate::{ensure_rustfmt, flags, project_root, Result};
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,
32 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
33 pub(crate) enum Mode {
39 pub(crate) fn run(self) -> Result<()> {
41 generate_lint_completions(Mode::Overwrite)?;
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)?;
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) => {
62 let return_error = match mode {
63 Mode::Overwrite => false,
66 eprintln!("updating {}", path.display());
67 write_file(path, contents)?;
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());
76 fn normalize(s: &str) -> String {
77 s.replace("\r\n", "\n")
81 const PREAMBLE: &str = "Generated file, do not edit by hand, see `xtask/src/codegen`";
83 fn reformat(text: &str) -> Result<String> {
84 let _e = pushenv("RUSTUP_TOOLCHAIN", "stable");
86 let rustfmt_toml = project_root().join("rustfmt.toml");
87 let stdout = cmd!("rustfmt --config-path {rustfmt_toml} --config fn_single_line=true")
90 Ok(format!("//! {}\n\n{}\n", PREAMBLE, stdout))
93 fn extract_comment_blocks(text: &str) -> Vec<Vec<String>> {
94 do_extract_comment_blocks(text, false).into_iter().map(|(_line, block)| block).collect()
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 };
112 struct CommentBlock {
115 contents: Vec<String>,
118 fn do_extract_comment_blocks(
120 allow_blocks_with_empty_lines: bool,
121 ) -> Vec<(usize, Vec<String>)> {
122 let mut res = Vec::new();
125 let lines = text.lines().map(str::trim_start);
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());
134 let is_comment = line.starts_with(prefix);
136 block.1.push(line[prefix.len()..].to_string());
138 if !block.1.is_empty() {
139 res.push(mem::take(&mut block));
141 block.0 = line_num + 2;
144 if !block.1.is_empty() {
157 fn new(file: PathBuf, line: usize) -> Self {
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();
169 "https://github.com/rust-analyzer/rust-analyzer/blob/master/{}#L{}[{}]",
172 name.to_str().unwrap()