]> git.lizzy.rs Git - rust.git/blob - crates/ra_tools/src/lib.rs
d47660369e85081d3fe058d16e205100521b2c34
[rust.git] / crates / ra_tools / src / lib.rs
1 mod boilerplate_gen;
2
3 use std::{
4     collections::HashMap,
5     error::Error,
6     fs,
7     io::{Error as IoError, ErrorKind},
8     path::{Path, PathBuf},
9     process::{Command, Output, Stdio},
10 };
11
12 use itertools::Itertools;
13
14 pub use self::boilerplate_gen::generate_boilerplate;
15
16 pub type Result<T> = std::result::Result<T, Box<dyn Error>>;
17
18 pub const GRAMMAR: &str = "crates/ra_syntax/src/grammar.ron";
19 const GRAMMAR_DIR: &str = "crates/ra_parser/src/grammar";
20 const OK_INLINE_TESTS_DIR: &str = "crates/ra_syntax/test_data/parser/inline/ok";
21 const ERR_INLINE_TESTS_DIR: &str = "crates/ra_syntax/test_data/parser/inline/err";
22
23 pub const SYNTAX_KINDS: &str = "crates/ra_parser/src/syntax_kind/generated.rs";
24 pub const AST: &str = "crates/ra_syntax/src/ast/generated.rs";
25 const TOOLCHAIN: &str = "stable";
26
27 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
28 pub enum Mode {
29     Overwrite,
30     Verify,
31 }
32 pub use Mode::*;
33
34 #[derive(Debug)]
35 pub struct Test {
36     pub name: String,
37     pub text: String,
38     pub ok: bool,
39 }
40
41 pub fn collect_tests(s: &str) -> Vec<(usize, Test)> {
42     let mut res = vec![];
43     let prefix = "// ";
44     let comment_blocks = s
45         .lines()
46         .map(str::trim_start)
47         .enumerate()
48         .group_by(|(_idx, line)| line.starts_with(prefix));
49
50     'outer: for (is_comment, block) in comment_blocks.into_iter() {
51         if !is_comment {
52             continue;
53         }
54         let mut block = block.map(|(idx, line)| (idx, &line[prefix.len()..]));
55
56         let mut ok = true;
57         let (start_line, name) = loop {
58             match block.next() {
59                 Some((idx, line)) if line.starts_with("test ") => {
60                     break (idx, line["test ".len()..].to_string());
61                 }
62                 Some((idx, line)) if line.starts_with("test_err ") => {
63                     ok = false;
64                     break (idx, line["test_err ".len()..].to_string());
65                 }
66                 Some(_) => (),
67                 None => continue 'outer,
68             }
69         };
70         let text: String =
71             itertools::join(block.map(|(_, line)| line).chain(::std::iter::once("")), "\n");
72         assert!(!text.trim().is_empty() && text.ends_with('\n'));
73         res.push((start_line, Test { name, text, ok }))
74     }
75     res
76 }
77
78 pub fn project_root() -> PathBuf {
79     Path::new(&env!("CARGO_MANIFEST_DIR")).ancestors().nth(2).unwrap().to_path_buf()
80 }
81
82 pub struct Cmd {
83     pub unix: &'static str,
84     pub windows: &'static str,
85     pub work_dir: &'static str,
86 }
87
88 impl Cmd {
89     pub fn run(self) -> Result<()> {
90         if cfg!(windows) {
91             run(self.windows, self.work_dir)
92         } else {
93             run(self.unix, self.work_dir)
94         }
95     }
96     pub fn run_with_output(self) -> Result<Output> {
97         if cfg!(windows) {
98             run_with_output(self.windows, self.work_dir)
99         } else {
100             run_with_output(self.unix, self.work_dir)
101         }
102     }
103 }
104
105 pub fn run(cmdline: &str, dir: &str) -> Result<()> {
106     do_run(cmdline, dir, |c| {
107         c.stdout(Stdio::inherit());
108     })
109     .map(|_| ())
110 }
111
112 pub fn run_with_output(cmdline: &str, dir: &str) -> Result<Output> {
113     do_run(cmdline, dir, |_| {})
114 }
115
116 pub fn run_rustfmt(mode: Mode) -> Result<()> {
117     match Command::new("rustup")
118         .args(&["run", TOOLCHAIN, "--", "cargo", "fmt", "--version"])
119         .stderr(Stdio::null())
120         .stdout(Stdio::null())
121         .status()
122     {
123         Ok(status) if status.success() => (),
124         _ => install_rustfmt()?,
125     };
126
127     if mode == Verify {
128         run(&format!("rustup run {} -- cargo fmt -- --check", TOOLCHAIN), ".")?;
129     } else {
130         run(&format!("rustup run {} -- cargo fmt", TOOLCHAIN), ".")?;
131     }
132     Ok(())
133 }
134
135 pub fn install_rustfmt() -> Result<()> {
136     run(&format!("rustup install {}", TOOLCHAIN), ".")?;
137     run(&format!("rustup component add rustfmt --toolchain {}", TOOLCHAIN), ".")
138 }
139
140 pub fn install_format_hook() -> Result<()> {
141     let result_path = Path::new(if cfg!(windows) {
142         "./.git/hooks/pre-commit.exe"
143     } else {
144         "./.git/hooks/pre-commit"
145     });
146     if !result_path.exists() {
147         run("cargo build --package ra_tools --bin pre-commit", ".")?;
148         if cfg!(windows) {
149             fs::copy("./target/debug/pre-commit.exe", result_path)?;
150         } else {
151             fs::copy("./target/debug/pre-commit", result_path)?;
152         }
153     } else {
154         Err(IoError::new(ErrorKind::AlreadyExists, "Git hook already created"))?;
155     }
156     Ok(())
157 }
158
159 pub fn run_clippy() -> Result<()> {
160     match Command::new("rustup")
161         .args(&["run", TOOLCHAIN, "--", "cargo", "clippy", "--version"])
162         .stderr(Stdio::null())
163         .stdout(Stdio::null())
164         .status()
165     {
166         Ok(status) if status.success() => (),
167         _ => install_clippy()?,
168     };
169
170     let allowed_lints = [
171         "clippy::collapsible_if",
172         "clippy::map_clone", // FIXME: remove when Iterator::copied stabilizes (1.36.0)
173         "clippy::needless_pass_by_value",
174         "clippy::nonminimal_bool",
175         "clippy::redundant_pattern_matching",
176     ];
177     run(
178         &format!(
179             "rustup run {} -- cargo clippy --all-features --all-targets -- -A {}",
180             TOOLCHAIN,
181             allowed_lints.join(" -A ")
182         ),
183         ".",
184     )?;
185     Ok(())
186 }
187
188 pub fn install_clippy() -> Result<()> {
189     run(&format!("rustup install {}", TOOLCHAIN), ".")?;
190     run(&format!("rustup component add clippy --toolchain {}", TOOLCHAIN), ".")
191 }
192
193 pub fn run_fuzzer() -> Result<()> {
194     match Command::new("cargo")
195         .args(&["fuzz", "--help"])
196         .stderr(Stdio::null())
197         .stdout(Stdio::null())
198         .status()
199     {
200         Ok(status) if status.success() => (),
201         _ => run("cargo install cargo-fuzz", ".")?,
202     };
203
204     run("rustup run nightly -- cargo fuzz run parser", "./crates/ra_syntax")
205 }
206
207 pub fn gen_tests(mode: Mode) -> Result<()> {
208     let tests = tests_from_dir(&project_root().join(Path::new(GRAMMAR_DIR)))?;
209     fn install_tests(tests: &HashMap<String, Test>, into: &str, mode: Mode) -> Result<()> {
210         let tests_dir = project_root().join(into);
211         if !tests_dir.is_dir() {
212             fs::create_dir_all(&tests_dir)?;
213         }
214         // ok is never actually read, but it needs to be specified to create a Test in existing_tests
215         let existing = existing_tests(&tests_dir, true)?;
216         for t in existing.keys().filter(|&t| !tests.contains_key(t)) {
217             panic!("Test is deleted: {}", t);
218         }
219
220         let mut new_idx = existing.len() + 1;
221         for (name, test) in tests {
222             let path = match existing.get(name) {
223                 Some((path, _test)) => path.clone(),
224                 None => {
225                     let file_name = format!("{:04}_{}.rs", new_idx, name);
226                     new_idx += 1;
227                     tests_dir.join(file_name)
228                 }
229             };
230             update(&path, &test.text, mode)?;
231         }
232         Ok(())
233     }
234     install_tests(&tests.ok, OK_INLINE_TESTS_DIR, mode)?;
235     install_tests(&tests.err, ERR_INLINE_TESTS_DIR, mode)
236 }
237
238 fn do_run<F>(cmdline: &str, dir: &str, mut f: F) -> Result<Output>
239 where
240     F: FnMut(&mut Command),
241 {
242     eprintln!("\nwill run: {}", cmdline);
243     let proj_dir = project_root().join(dir);
244     let mut args = cmdline.split_whitespace();
245     let exec = args.next().unwrap();
246     let mut cmd = Command::new(exec);
247     f(cmd.args(args).current_dir(proj_dir).stderr(Stdio::inherit()));
248     let output = cmd.output()?;
249     if !output.status.success() {
250         Err(format!("`{}` exited with {}", cmdline, output.status))?;
251     }
252     Ok(output)
253 }
254
255 #[derive(Default, Debug)]
256 struct Tests {
257     pub ok: HashMap<String, Test>,
258     pub err: HashMap<String, Test>,
259 }
260
261 fn tests_from_dir(dir: &Path) -> Result<Tests> {
262     let mut res = Tests::default();
263     for entry in ::walkdir::WalkDir::new(dir) {
264         let entry = entry.unwrap();
265         if !entry.file_type().is_file() {
266             continue;
267         }
268         if entry.path().extension().unwrap_or_default() != "rs" {
269             continue;
270         }
271         process_file(&mut res, entry.path())?;
272     }
273     let grammar_rs = dir.parent().unwrap().join("grammar.rs");
274     process_file(&mut res, &grammar_rs)?;
275     return Ok(res);
276     fn process_file(res: &mut Tests, path: &Path) -> Result<()> {
277         let text = fs::read_to_string(path)?;
278
279         for (_, test) in collect_tests(&text) {
280             if test.ok {
281                 if let Some(old_test) = res.ok.insert(test.name.clone(), test) {
282                     Err(format!("Duplicate test: {}", old_test.name))?
283                 }
284             } else {
285                 if let Some(old_test) = res.err.insert(test.name.clone(), test) {
286                     Err(format!("Duplicate test: {}", old_test.name))?
287                 }
288             }
289         }
290         Ok(())
291     }
292 }
293
294 fn existing_tests(dir: &Path, ok: bool) -> Result<HashMap<String, (PathBuf, Test)>> {
295     let mut res = HashMap::new();
296     for file in fs::read_dir(dir)? {
297         let file = file?;
298         let path = file.path();
299         if path.extension().unwrap_or_default() != "rs" {
300             continue;
301         }
302         let name = {
303             let file_name = path.file_name().unwrap().to_str().unwrap();
304             file_name[5..file_name.len() - 3].to_string()
305         };
306         let text = fs::read_to_string(&path)?;
307         let test = Test { name: name.clone(), text, ok };
308         if let Some(old) = res.insert(name, (path, test)) {
309             println!("Duplicate test: {:?}", old);
310         }
311     }
312     Ok(res)
313 }
314
315 /// A helper to update file on disk if it has changed.
316 /// With verify = false,
317 pub fn update(path: &Path, contents: &str, mode: Mode) -> Result<()> {
318     match fs::read_to_string(path) {
319         Ok(ref old_contents) if old_contents == contents => {
320             return Ok(());
321         }
322         _ => (),
323     }
324     if mode == Verify {
325         Err(format!("`{}` is not up-to-date", path.display()))?;
326     }
327     eprintln!("updating {}", path.display());
328     fs::write(path, contents)?;
329     Ok(())
330 }