aboutsummaryrefslogtreecommitdiff
path: root/xtask
diff options
context:
space:
mode:
authorSeivan Heidari <[email protected]>2019-10-31 08:43:20 +0000
committerSeivan Heidari <[email protected]>2019-10-31 08:43:20 +0000
commit8edda0e7b164009d6c03bb3d4be603fb38ad2e2a (patch)
tree744cf81075d394e2f9c06afb07642a2601800dda /xtask
parent49562d36b97ddde34cf7585a8c2e8f232519b657 (diff)
parentd067afb064a7fa67b172abf561b7d80740cd6f18 (diff)
Merge branch 'master' into feature/themes
Diffstat (limited to 'xtask')
-rw-r--r--xtask/src/codegen.rs72
-rw-r--r--xtask/src/codegen/gen_assists_docs.rs137
-rw-r--r--xtask/src/codegen/gen_parser_tests.rs71
-rw-r--r--xtask/src/codegen/gen_syntax.rs25
-rw-r--r--xtask/src/main.rs26
-rw-r--r--xtask/tests/tidy-tests/cli.rs7
-rw-r--r--xtask/tests/tidy-tests/docs.rs6
7 files changed, 267 insertions, 77 deletions
diff --git a/xtask/src/codegen.rs b/xtask/src/codegen.rs
index 948b86719..4ec8ab75a 100644
--- a/xtask/src/codegen.rs
+++ b/xtask/src/codegen.rs
@@ -7,12 +7,22 @@
7 7
8mod gen_syntax; 8mod gen_syntax;
9mod gen_parser_tests; 9mod gen_parser_tests;
10mod gen_assists_docs;
10 11
11use std::{fs, path::Path}; 12use std::{
13 fs,
14 io::Write,
15 mem,
16 path::Path,
17 process::{Command, Stdio},
18};
12 19
13use crate::Result; 20use crate::{project_root, Result};
14 21
15pub use self::{gen_parser_tests::generate_parser_tests, gen_syntax::generate_syntax}; 22pub use self::{
23 gen_assists_docs::generate_assists_docs, gen_parser_tests::generate_parser_tests,
24 gen_syntax::generate_syntax,
25};
16 26
17pub const GRAMMAR: &str = "crates/ra_syntax/src/grammar.ron"; 27pub const GRAMMAR: &str = "crates/ra_syntax/src/grammar.ron";
18const GRAMMAR_DIR: &str = "crates/ra_parser/src/grammar"; 28const GRAMMAR_DIR: &str = "crates/ra_parser/src/grammar";
@@ -22,6 +32,10 @@ const ERR_INLINE_TESTS_DIR: &str = "crates/ra_syntax/test_data/parser/inline/err
22pub const SYNTAX_KINDS: &str = "crates/ra_parser/src/syntax_kind/generated.rs"; 32pub const SYNTAX_KINDS: &str = "crates/ra_parser/src/syntax_kind/generated.rs";
23pub const AST: &str = "crates/ra_syntax/src/ast/generated.rs"; 33pub const AST: &str = "crates/ra_syntax/src/ast/generated.rs";
24 34
35const ASSISTS_DIR: &str = "crates/ra_assists/src/assists";
36const ASSISTS_TESTS: &str = "crates/ra_assists/src/doc_tests/generated.rs";
37const ASSISTS_DOCS: &str = "docs/user/assists.md";
38
25#[derive(Debug, PartialEq, Eq, Clone, Copy)] 39#[derive(Debug, PartialEq, Eq, Clone, Copy)]
26pub enum Mode { 40pub enum Mode {
27 Overwrite, 41 Overwrite,
@@ -30,7 +44,7 @@ pub enum Mode {
30 44
31/// A helper to update file on disk if it has changed. 45/// A helper to update file on disk if it has changed.
32/// With verify = false, 46/// With verify = false,
33pub fn update(path: &Path, contents: &str, mode: Mode) -> Result<()> { 47fn update(path: &Path, contents: &str, mode: Mode) -> Result<()> {
34 match fs::read_to_string(path) { 48 match fs::read_to_string(path) {
35 Ok(ref old_contents) if old_contents == contents => { 49 Ok(ref old_contents) if old_contents == contents => {
36 return Ok(()); 50 return Ok(());
@@ -44,3 +58,53 @@ pub fn update(path: &Path, contents: &str, mode: Mode) -> Result<()> {
44 fs::write(path, contents)?; 58 fs::write(path, contents)?;
45 Ok(()) 59 Ok(())
46} 60}
61
62fn reformat(text: impl std::fmt::Display) -> Result<String> {
63 let mut rustfmt = Command::new("rustfmt")
64 .arg("--config-path")
65 .arg(project_root().join("rustfmt.toml"))
66 .stdin(Stdio::piped())
67 .stdout(Stdio::piped())
68 .spawn()?;
69 write!(rustfmt.stdin.take().unwrap(), "{}", text)?;
70 let output = rustfmt.wait_with_output()?;
71 let stdout = String::from_utf8(output.stdout)?;
72 let preamble = "Generated file, do not edit by hand, see `crate/ra_tools/src/codegen`";
73 Ok(format!("//! {}\n\n{}", preamble, stdout))
74}
75
76fn extract_comment_blocks(text: &str) -> Vec<Vec<String>> {
77 do_extract_comment_blocks(text, false)
78}
79
80fn extract_comment_blocks_with_empty_lines(text: &str) -> Vec<Vec<String>> {
81 do_extract_comment_blocks(text, true)
82}
83
84fn do_extract_comment_blocks(text: &str, allow_blocks_with_empty_lins: bool) -> Vec<Vec<String>> {
85 let mut res = Vec::new();
86
87 let prefix = "// ";
88 let lines = text.lines().map(str::trim_start);
89
90 let mut block = vec![];
91 for line in lines {
92 if line == "//" && allow_blocks_with_empty_lins {
93 block.push(String::new());
94 continue;
95 }
96
97 let is_comment = line.starts_with(prefix);
98 if is_comment {
99 block.push(line[prefix.len()..].to_string());
100 } else {
101 if !block.is_empty() {
102 res.push(mem::replace(&mut block, Vec::new()))
103 }
104 }
105 }
106 if !block.is_empty() {
107 res.push(mem::replace(&mut block, Vec::new()))
108 }
109 res
110}
diff --git a/xtask/src/codegen/gen_assists_docs.rs b/xtask/src/codegen/gen_assists_docs.rs
new file mode 100644
index 000000000..05afda8f1
--- /dev/null
+++ b/xtask/src/codegen/gen_assists_docs.rs
@@ -0,0 +1,137 @@
1use std::{fs, path::Path};
2
3use crate::{
4 codegen::{self, extract_comment_blocks_with_empty_lines, Mode},
5 project_root, Result,
6};
7
8pub fn generate_assists_docs(mode: Mode) -> Result<()> {
9 let assists = collect_assists()?;
10 generate_tests(&assists, mode)?;
11 generate_docs(&assists, mode)?;
12 Ok(())
13}
14
15#[derive(Debug)]
16struct Assist {
17 id: String,
18 doc: String,
19 before: String,
20 after: String,
21}
22
23fn collect_assists() -> Result<Vec<Assist>> {
24 let mut res = Vec::new();
25 for entry in fs::read_dir(project_root().join(codegen::ASSISTS_DIR))? {
26 let entry = entry?;
27 let path = entry.path();
28 if path.is_file() {
29 collect_file(&mut res, path.as_path())?;
30 }
31 }
32 res.sort_by(|lhs, rhs| lhs.id.cmp(&rhs.id));
33 return Ok(res);
34
35 fn collect_file(acc: &mut Vec<Assist>, path: &Path) -> Result<()> {
36 let text = fs::read_to_string(path)?;
37 let comment_blocks = extract_comment_blocks_with_empty_lines(&text);
38
39 for block in comment_blocks {
40 // FIXME: doesn't support blank lines yet, need to tweak
41 // `extract_comment_blocks` for that.
42 let mut lines = block.iter();
43 let first_line = lines.next().unwrap();
44 if !first_line.starts_with("Assist: ") {
45 continue;
46 }
47 let id = first_line["Assist: ".len()..].to_string();
48 assert!(
49 id.chars().all(|it| it.is_ascii_lowercase() || it == '_'),
50 "invalid assist id: {:?}",
51 id
52 );
53
54 let doc = take_until(lines.by_ref(), "```").trim().to_string();
55 assert!(
56 doc.chars().next().unwrap().is_ascii_uppercase() && doc.ends_with('.'),
57 "\n\n{}: assist docs should be proper sentences, with capitalization and a full stop at the end.\n\n{}\n\n",
58 id, doc,
59 );
60
61 let before = take_until(lines.by_ref(), "```");
62
63 assert_eq!(lines.next().unwrap().as_str(), "->");
64 assert_eq!(lines.next().unwrap().as_str(), "```");
65 let after = take_until(lines.by_ref(), "```");
66 acc.push(Assist { id, doc, before, after })
67 }
68
69 fn take_until<'a>(lines: impl Iterator<Item = &'a String>, marker: &str) -> String {
70 let mut buf = Vec::new();
71 for line in lines {
72 if line == marker {
73 break;
74 }
75 buf.push(line.clone());
76 }
77 buf.join("\n")
78 }
79 Ok(())
80 }
81}
82
83fn generate_tests(assists: &[Assist], mode: Mode) -> Result<()> {
84 let mut buf = String::from("use super::check;\n");
85
86 for assist in assists.iter() {
87 let test = format!(
88 r######"
89#[test]
90fn doctest_{}() {{
91 check(
92 "{}",
93r#####"
94{}
95"#####, r#####"
96{}
97"#####)
98}}
99"######,
100 assist.id, assist.id, assist.before, assist.after
101 );
102
103 buf.push_str(&test)
104 }
105 let buf = codegen::reformat(buf)?;
106 codegen::update(&project_root().join(codegen::ASSISTS_TESTS), &buf, mode)
107}
108
109fn generate_docs(assists: &[Assist], mode: Mode) -> Result<()> {
110 let mut buf = String::from(
111 "# Assists\n\nCursor position or selection is signified by `┃` character.\n\n",
112 );
113
114 for assist in assists {
115 let before = assist.before.replace("<|>", "┃"); // Unicode pseudo-graphics bar
116 let after = assist.after.replace("<|>", "┃");
117 let docs = format!(
118 "
119## `{}`
120
121{}
122
123```rust
124// BEFORE
125{}
126
127// AFTER
128{}
129```
130",
131 assist.id, assist.doc, before, after
132 );
133 buf.push_str(&docs);
134 }
135
136 codegen::update(&project_root().join(codegen::ASSISTS_DOCS), &buf, mode)
137}
diff --git a/xtask/src/codegen/gen_parser_tests.rs b/xtask/src/codegen/gen_parser_tests.rs
index 0f550d948..d0f0f683b 100644
--- a/xtask/src/codegen/gen_parser_tests.rs
+++ b/xtask/src/codegen/gen_parser_tests.rs
@@ -3,12 +3,12 @@
3 3
4use std::{ 4use std::{
5 collections::HashMap, 5 collections::HashMap,
6 fs, 6 fs, iter,
7 path::{Path, PathBuf}, 7 path::{Path, PathBuf},
8}; 8};
9 9
10use crate::{ 10use crate::{
11 codegen::{self, update, Mode}, 11 codegen::{self, extract_comment_blocks, update, Mode},
12 project_root, Result, 12 project_root, Result,
13}; 13};
14 14
@@ -56,48 +56,29 @@ struct Tests {
56 pub err: HashMap<String, Test>, 56 pub err: HashMap<String, Test>,
57} 57}
58 58
59fn collect_tests(s: &str) -> Vec<(usize, Test)> { 59fn collect_tests(s: &str) -> Vec<Test> {
60 let mut res = vec![]; 60 let mut res = Vec::new();
61 let prefix = "// "; 61 for comment_block in extract_comment_blocks(s) {
62 let lines = s.lines().map(str::trim_start).enumerate(); 62 let first_line = &comment_block[0];
63 63 let (name, ok) = if first_line.starts_with("test ") {
64 let mut block = vec![]; 64 let name = first_line["test ".len()..].to_string();
65 for (line_idx, line) in lines { 65 (name, true)
66 let is_comment = line.starts_with(prefix); 66 } else if first_line.starts_with("test_err ") {
67 if is_comment { 67 let name = first_line["test_err ".len()..].to_string();
68 block.push((line_idx, &line[prefix.len()..])); 68 (name, false)
69 } else { 69 } else {
70 process_block(&mut res, &block); 70 continue;
71 block.clear();
72 }
73 }
74 process_block(&mut res, &block);
75 return res;
76
77 fn process_block(acc: &mut Vec<(usize, Test)>, block: &[(usize, &str)]) {
78 if block.is_empty() {
79 return;
80 }
81 let mut ok = true;
82 let mut block = block.iter();
83 let (start_line, name) = loop {
84 match block.next() {
85 Some(&(idx, line)) if line.starts_with("test ") => {
86 break (idx, line["test ".len()..].to_string());
87 }
88 Some(&(idx, line)) if line.starts_with("test_err ") => {
89 ok = false;
90 break (idx, line["test_err ".len()..].to_string());
91 }
92 Some(_) => (),
93 None => return,
94 }
95 }; 71 };
96 let text: String = 72 let text: String = comment_block[1..]
97 block.map(|(_, line)| *line).chain(std::iter::once("")).collect::<Vec<_>>().join("\n"); 73 .iter()
74 .cloned()
75 .chain(iter::once(String::new()))
76 .collect::<Vec<_>>()
77 .join("\n");
98 assert!(!text.trim().is_empty() && text.ends_with('\n')); 78 assert!(!text.trim().is_empty() && text.ends_with('\n'));
99 acc.push((start_line, Test { name, text, ok })) 79 res.push(Test { name, text, ok })
100 } 80 }
81 res
101} 82}
102 83
103fn tests_from_dir(dir: &Path) -> Result<Tests> { 84fn tests_from_dir(dir: &Path) -> Result<Tests> {
@@ -118,15 +99,13 @@ fn tests_from_dir(dir: &Path) -> Result<Tests> {
118 fn process_file(res: &mut Tests, path: &Path) -> Result<()> { 99 fn process_file(res: &mut Tests, path: &Path) -> Result<()> {
119 let text = fs::read_to_string(path)?; 100 let text = fs::read_to_string(path)?;
120 101
121 for (_, test) in collect_tests(&text) { 102 for test in collect_tests(&text) {
122 if test.ok { 103 if test.ok {
123 if let Some(old_test) = res.ok.insert(test.name.clone(), test) { 104 if let Some(old_test) = res.ok.insert(test.name.clone(), test) {
124 Err(format!("Duplicate test: {}", old_test.name))? 105 return Err(format!("Duplicate test: {}", old_test.name).into());
125 }
126 } else {
127 if let Some(old_test) = res.err.insert(test.name.clone(), test) {
128 Err(format!("Duplicate test: {}", old_test.name))?
129 } 106 }
107 } else if let Some(old_test) = res.err.insert(test.name.clone(), test) {
108 return Err(format!("Duplicate test: {}", old_test.name).into());
130 } 109 }
131 } 110 }
132 Ok(()) 111 Ok(())
diff --git a/xtask/src/codegen/gen_syntax.rs b/xtask/src/codegen/gen_syntax.rs
index 6a81c0e4d..88f2ac0e3 100644
--- a/xtask/src/codegen/gen_syntax.rs
+++ b/xtask/src/codegen/gen_syntax.rs
@@ -3,12 +3,7 @@
3//! Specifically, it generates the `SyntaxKind` enum and a number of newtype 3//! Specifically, it generates the `SyntaxKind` enum and a number of newtype
4//! wrappers around `SyntaxNode` which implement `ra_syntax::AstNode`. 4//! wrappers around `SyntaxNode` which implement `ra_syntax::AstNode`.
5 5
6use std::{ 6use std::{collections::BTreeMap, fs};
7 collections::BTreeMap,
8 fs,
9 io::Write,
10 process::{Command, Stdio},
11};
12 7
13use proc_macro2::{Punct, Spacing}; 8use proc_macro2::{Punct, Spacing};
14use quote::{format_ident, quote}; 9use quote::{format_ident, quote};
@@ -163,7 +158,7 @@ fn generate_ast(grammar: &Grammar) -> Result<String> {
163 #(#nodes)* 158 #(#nodes)*
164 }; 159 };
165 160
166 let pretty = reformat(ast)?; 161 let pretty = codegen::reformat(ast)?;
167 Ok(pretty) 162 Ok(pretty)
168} 163}
169 164
@@ -276,21 +271,7 @@ fn generate_syntax_kinds(grammar: &Grammar) -> Result<String> {
276 } 271 }
277 }; 272 };
278 273
279 reformat(ast) 274 codegen::reformat(ast)
280}
281
282fn reformat(text: impl std::fmt::Display) -> Result<String> {
283 let mut rustfmt = Command::new("rustfmt")
284 .arg("--config-path")
285 .arg(project_root().join("rustfmt.toml"))
286 .stdin(Stdio::piped())
287 .stdout(Stdio::piped())
288 .spawn()?;
289 write!(rustfmt.stdin.take().unwrap(), "{}", text)?;
290 let output = rustfmt.wait_with_output()?;
291 let stdout = String::from_utf8(output.stdout)?;
292 let preamble = "Generated file, do not edit by hand, see `crate/ra_tools/src/codegen`";
293 Ok(format!("//! {}\n\n{}", preamble, stdout))
294} 275}
295 276
296#[derive(Deserialize, Debug)] 277#[derive(Deserialize, Debug)]
diff --git a/xtask/src/main.rs b/xtask/src/main.rs
index db901ced2..e04e45f15 100644
--- a/xtask/src/main.rs
+++ b/xtask/src/main.rs
@@ -1,5 +1,12 @@
1//! FIXME: write short doc here 1//! See https://github.com/matklad/cargo-xtask/.
2 2//!
3//! This binary defines various auxiliary build commands, which are not
4//! expressible with just `cargo`. Notably, it provides `cargo xtask codegen`
5//! for code generation and `cargo xtask install` for installation of
6//! rust-analyzer server and client.
7//!
8//! This binary is integrated into the `cargo` command line by using an alias in
9//! `.cargo/config`.
3mod help; 10mod help;
4 11
5use core::fmt::Write; 12use core::fmt::Write;
@@ -53,7 +60,7 @@ fn main() -> Result<()> {
53 matches.finish().or_else(handle_extra_flags)?; 60 matches.finish().or_else(handle_extra_flags)?;
54 let opts = InstallOpt { 61 let opts = InstallOpt {
55 client: if server { None } else { Some(ClientOpt::VsCode) }, 62 client: if server { None } else { Some(ClientOpt::VsCode) },
56 server: if client_code { None } else { Some(ServerOpt { jemalloc: jemalloc }) }, 63 server: if client_code { None } else { Some(ServerOpt { jemalloc }) },
57 }; 64 };
58 install(opts)? 65 install(opts)?
59 } 66 }
@@ -64,6 +71,7 @@ fn main() -> Result<()> {
64 } 71 }
65 codegen::generate_syntax(Mode::Overwrite)?; 72 codegen::generate_syntax(Mode::Overwrite)?;
66 codegen::generate_parser_tests(Mode::Overwrite)?; 73 codegen::generate_parser_tests(Mode::Overwrite)?;
74 codegen::generate_assists_docs(Mode::Overwrite)?;
67 } 75 }
68 "format" => { 76 "format" => {
69 if matches.contains(["-h", "--help"]) { 77 if matches.contains(["-h", "--help"]) {
@@ -158,6 +166,17 @@ fn fix_path_for_mac() -> Result<()> {
158} 166}
159 167
160fn install_client(ClientOpt::VsCode: ClientOpt) -> Result<()> { 168fn install_client(ClientOpt::VsCode: ClientOpt) -> Result<()> {
169 let npm_version = Cmd {
170 unix: r"npm --version",
171 windows: r"cmd.exe /c npm.cmd --version",
172 work_dir: "./editors/code",
173 }
174 .run();
175
176 if npm_version.is_err() {
177 eprintln!("\nERROR: `npm --version` failed, `npm` is required to build the VS Code plugin")
178 }
179
161 Cmd { unix: r"npm ci", windows: r"cmd.exe /c npm.cmd ci", work_dir: "./editors/code" }.run()?; 180 Cmd { unix: r"npm ci", windows: r"cmd.exe /c npm.cmd ci", work_dir: "./editors/code" }.run()?;
162 Cmd { 181 Cmd {
163 unix: r"npm run package", 182 unix: r"npm run package",
@@ -210,6 +229,7 @@ fn install_server(opts: ServerOpt) -> Result<()> {
210 let mut old_rust = false; 229 let mut old_rust = false;
211 if let Ok(output) = run_with_output("cargo --version", ".") { 230 if let Ok(output) = run_with_output("cargo --version", ".") {
212 if let Ok(stdout) = String::from_utf8(output.stdout) { 231 if let Ok(stdout) = String::from_utf8(output.stdout) {
232 println!("{}", stdout);
213 if !check_version(&stdout, REQUIRED_RUST_VERSION) { 233 if !check_version(&stdout, REQUIRED_RUST_VERSION) {
214 old_rust = true; 234 old_rust = true;
215 } 235 }
diff --git a/xtask/tests/tidy-tests/cli.rs b/xtask/tests/tidy-tests/cli.rs
index 543c7d7c4..573ffadbf 100644
--- a/xtask/tests/tidy-tests/cli.rs
+++ b/xtask/tests/tidy-tests/cli.rs
@@ -19,6 +19,13 @@ fn generated_tests_are_fresh() {
19} 19}
20 20
21#[test] 21#[test]
22fn generated_assists_are_fresh() {
23 if let Err(error) = codegen::generate_assists_docs(Mode::Verify) {
24 panic!("{}. Please update assists by running `cargo xtask codegen`", error);
25 }
26}
27
28#[test]
22fn check_code_formatting() { 29fn check_code_formatting() {
23 if let Err(error) = run_rustfmt(Mode::Verify) { 30 if let Err(error) = run_rustfmt(Mode::Verify) {
24 panic!("{}. Please format the code by running `cargo format`", error); 31 panic!("{}. Please format the code by running `cargo format`", error);
diff --git a/xtask/tests/tidy-tests/docs.rs b/xtask/tests/tidy-tests/docs.rs
index fe5852bc6..6a629ce63 100644
--- a/xtask/tests/tidy-tests/docs.rs
+++ b/xtask/tests/tidy-tests/docs.rs
@@ -8,7 +8,9 @@ use walkdir::{DirEntry, WalkDir};
8use xtask::project_root; 8use xtask::project_root;
9 9
10fn is_exclude_dir(p: &Path) -> bool { 10fn is_exclude_dir(p: &Path) -> bool {
11 let exclude_dirs = ["tests", "test_data"]; 11 // Test hopefully don't really need comments, and for assists we already
12 // have special comments which are source of doc tests and user docs.
13 let exclude_dirs = ["tests", "test_data", "assists"];
12 let mut cur_path = p; 14 let mut cur_path = p;
13 while let Some(path) = cur_path.parent() { 15 while let Some(path) = cur_path.parent() {
14 if exclude_dirs.iter().any(|dir| path.ends_with(dir)) { 16 if exclude_dirs.iter().any(|dir| path.ends_with(dir)) {
@@ -27,7 +29,7 @@ fn is_exclude_file(d: &DirEntry) -> bool {
27} 29}
28 30
29fn is_hidden(entry: &DirEntry) -> bool { 31fn is_hidden(entry: &DirEntry) -> bool {
30 entry.file_name().to_str().map(|s| s.starts_with(".")).unwrap_or(false) 32 entry.file_name().to_str().map(|s| s.starts_with('.')).unwrap_or(false)
31} 33}
32 34
33#[test] 35#[test]