aboutsummaryrefslogtreecommitdiff
path: root/xtask/src/codegen
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/src/codegen
parent49562d36b97ddde34cf7585a8c2e8f232519b657 (diff)
parentd067afb064a7fa67b172abf561b7d80740cd6f18 (diff)
Merge branch 'master' into feature/themes
Diffstat (limited to 'xtask/src/codegen')
-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
3 files changed, 165 insertions, 68 deletions
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)]