aboutsummaryrefslogtreecommitdiff
path: root/tools/src/bin/main.rs
diff options
context:
space:
mode:
authorAleksey Kladov <[email protected]>2018-07-30 12:06:22 +0100
committerAleksey Kladov <[email protected]>2018-07-30 12:06:22 +0100
commit6983091d6d255bcfd17c4f8c14015d8abc77928d (patch)
tree153359a05ca3fd887b59fe47ee84a60be0e6dfaf /tools/src/bin/main.rs
parent9a4957d143397256dc04f715660f758a65fcb9d1 (diff)
Cleanup tools
Diffstat (limited to 'tools/src/bin/main.rs')
-rw-r--r--tools/src/bin/main.rs184
1 files changed, 184 insertions, 0 deletions
diff --git a/tools/src/bin/main.rs b/tools/src/bin/main.rs
new file mode 100644
index 000000000..6a9793fff
--- /dev/null
+++ b/tools/src/bin/main.rs
@@ -0,0 +1,184 @@
1extern crate clap;
2#[macro_use]
3extern crate failure;
4extern crate tera;
5extern crate ron;
6extern crate walkdir;
7extern crate itertools;
8
9use std::{
10 fs,
11 path::{Path},
12 collections::HashSet,
13};
14use clap::{App, Arg, SubCommand};
15use itertools::Itertools;
16
17type Result<T> = ::std::result::Result<T, failure::Error>;
18
19const GRAMMAR_DIR: &str = "./src/parser/grammar";
20const INLINE_TESTS_DIR: &str = "tests/data/parser/inline";
21const GRAMMAR: &str = "./src/grammar.ron";
22const SYNTAX_KINDS: &str = "./src/syntax_kinds/generated.rs";
23const SYNTAX_KINDS_TEMPLATE: &str = "./src/syntax_kinds/generated.rs.tera";
24
25fn main() -> Result<()> {
26 let matches = App::new("tasks")
27 .setting(clap::AppSettings::SubcommandRequiredElseHelp)
28 .arg(
29 Arg::with_name("verify")
30 .long("--verify")
31 .help("Verify that generated code is up-to-date")
32 .global(true)
33 )
34 .subcommand(SubCommand::with_name("gen-kinds"))
35 .subcommand(SubCommand::with_name("gen-tests"))
36 .get_matches();
37 match matches.subcommand() {
38 (name, Some(matches)) => run_gen_command(name, matches.is_present("verify"))?,
39 _ => unreachable!(),
40 }
41 Ok(())
42}
43
44fn run_gen_command(name: &str, verify: bool) -> Result<()> {
45 match name {
46 "gen-kinds" => update(Path::new(SYNTAX_KINDS), &get_kinds()?, verify),
47 "gen-tests" => gen_tests(verify),
48 _ => unreachable!(),
49 }
50}
51
52fn update(path: &Path, contents: &str, verify: bool) -> Result<()> {
53 match fs::read_to_string(path) {
54 Ok(ref old_contents) if old_contents == contents => {
55 return Ok(());
56 }
57 _ => (),
58 }
59 if verify {
60 bail!("`{}` is not up-to-date", path.display());
61 }
62 fs::write(path, contents)?;
63 Ok(())
64}
65
66fn get_kinds() -> Result<String> {
67 let grammar = grammar()?;
68 let template = fs::read_to_string(SYNTAX_KINDS_TEMPLATE)?;
69 let ret = tera::Tera::one_off(&template, &grammar, false).map_err(|e| {
70 format_err!("template error: {}", e)
71 })?;
72 Ok(ret)
73}
74
75fn grammar() -> Result<ron::value::Value> {
76 let text = fs::read_to_string(GRAMMAR)?;
77 let ret = ron::de::from_str(&text)?;
78 Ok(ret)
79}
80
81fn gen_tests(verify: bool) -> Result<()> {
82 let tests = tests_from_dir(Path::new(GRAMMAR_DIR))?;
83
84 let inline_tests_dir = Path::new(INLINE_TESTS_DIR);
85 if !inline_tests_dir.is_dir() {
86 fs::create_dir_all(inline_tests_dir)?;
87 }
88 let existing = existing_tests(inline_tests_dir)?;
89
90 for t in existing.difference(&tests) {
91 panic!("Test is deleted: {}\n{}", t.name, t.text);
92 }
93
94 let new_tests = tests.difference(&existing);
95 for (i, t) in new_tests.enumerate() {
96 let name = format!("{:04}_{}.rs", existing.len() + i + 1, t.name);
97 let path = inline_tests_dir.join(name);
98 update(&path, &t.text, verify)?;
99 }
100 Ok(())
101}
102
103#[derive(Debug, Eq)]
104struct Test {
105 name: String,
106 text: String,
107}
108
109impl PartialEq for Test {
110 fn eq(&self, other: &Test) -> bool {
111 self.name.eq(&other.name)
112 }
113}
114
115impl ::std::hash::Hash for Test {
116 fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
117 self.name.hash(state)
118 }
119}
120
121fn tests_from_dir(dir: &Path) -> Result<HashSet<Test>> {
122 let mut res = HashSet::new();
123 for entry in ::walkdir::WalkDir::new(dir) {
124 let entry = entry.unwrap();
125 if !entry.file_type().is_file() {
126 continue;
127 }
128 if entry.path().extension().unwrap_or_default() != "rs" {
129 continue;
130 }
131 let text = fs::read_to_string(entry.path())?;
132
133 for test in collect_tests(&text) {
134 if let Some(old_test) = res.replace(test) {
135 bail!("Duplicate test: {}", old_test.name)
136 }
137 }
138 }
139 Ok(res)
140}
141
142fn collect_tests(s: &str) -> Vec<Test> {
143 let mut res = vec![];
144 let prefix = "// ";
145 let comment_blocks = s.lines()
146 .map(str::trim_left)
147 .group_by(|line| line.starts_with(prefix));
148
149 'outer: for (is_comment, block) in comment_blocks.into_iter() {
150 if !is_comment {
151 continue;
152 }
153 let mut block = block.map(|line| &line[prefix.len()..]);
154
155 let name = loop {
156 match block.next() {
157 Some(line) if line.starts_with("test ") => break line["test ".len()..].to_string(),
158 Some(_) => (),
159 None => continue 'outer,
160 }
161 };
162 let text: String = itertools::join(block.chain(::std::iter::once("")), "\n");
163 assert!(!text.trim().is_empty() && text.ends_with("\n"));
164 res.push(Test { name, text })
165 }
166 res
167}
168
169fn existing_tests(dir: &Path) -> Result<HashSet<Test>> {
170 let mut res = HashSet::new();
171 for file in fs::read_dir(dir)? {
172 let file = file?;
173 let path = file.path();
174 if path.extension().unwrap_or_default() != "rs" {
175 continue;
176 }
177 let name = path.file_name().unwrap().to_str().unwrap();
178 let name = name["0000_".len()..name.len() - 3].to_string();
179 let text = fs::read_to_string(&path)?;
180 res.insert(Test { name, text });
181 }
182 Ok(res)
183}
184