-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathall.rs
225 lines (204 loc) · 6.69 KB
/
all.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
//! A small test framework to execute a test function over all files in a
//! directory.
//!
//! Each file in the directory has its own `CHECK-ALL` annotation indicating the
//! expected output of the test. That can be automatically updated with
//! `BLESS=1` in the environment. Otherwise the test are checked against the
//! listed expectation.
use anyhow::{bail, Context, Result};
use rayon::prelude::*;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use walrus::ModuleConfig;
use wast::parser::{Parse, Parser};
fn main() {
run("tests".as_ref(), runtest);
}
fn runtest(test: &Test) -> Result<String> {
let wasm = wat::parse_file(&test.file)?;
let mut walrus = ModuleConfig::new()
.generate_producers_section(false)
.parse(&wasm)?;
let mut exports = Vec::new();
let mut xforms = Vec::new();
for directive in test.directives.iter() {
let export = walrus
.exports
.iter()
.find(|e| e.name == directive.name)
.unwrap();
let id = match export.item {
walrus::ExportItem::Function(id) => id,
_ => panic!("must be function export"),
};
exports.push(export.id());
xforms.push((id, 0, directive.tys.clone()));
}
let memory = walrus.memories.iter().next().unwrap().id();
let stack_pointer = walrus.globals.iter().next().unwrap().id();
let ret = wasm_bindgen_multi_value_xform::run(&mut walrus, memory, stack_pointer, &xforms)?;
for (export, id) in exports.into_iter().zip(ret) {
walrus.exports.get_mut(export).item = walrus::ExportItem::Function(id);
}
walrus::passes::gc::run(&mut walrus);
let printed = wasmprinter::print_bytes(walrus.emit_wasm())?;
Ok(printed)
}
fn run(dir: &Path, run: fn(&Test) -> Result<String>) {
let mut tests = Vec::new();
find_tests(dir, &mut tests);
let filter = std::env::args().nth(1);
let bless = env::var("BLESS").is_ok();
let tests = tests
.iter()
.filter(|test| {
if let Some(filter) = &filter {
if let Some(s) = test.file_name().and_then(|s| s.to_str()) {
if !s.contains(filter) {
return false;
}
}
}
true
})
.collect::<Vec<_>>();
println!("\nrunning {} tests\n", tests.len());
let errors = tests
.par_iter()
.filter_map(|test| run_test(test, bless, run).err())
.collect::<Vec<_>>();
if !errors.is_empty() {
for msg in errors.iter() {
eprintln!("error: {:?}", msg);
}
panic!("{} tests failed", errors.len())
}
println!("test result: ok. {} passed\n", tests.len());
}
fn run_test(test: &Path, bless: bool, run: fn(&Test) -> anyhow::Result<String>) -> Result<()> {
(|| -> Result<_> {
let expected = Test::from_file(test)?;
let actual = run(&expected)?;
expected.check(&actual, bless)?;
Ok(())
})()
.context(format!("test failed - {}", test.display()))?;
Ok(())
}
fn find_tests(path: &Path, tests: &mut Vec<PathBuf>) {
for f in path.read_dir().unwrap() {
let f = f.unwrap();
if f.file_type().unwrap().is_dir() {
find_tests(&f.path(), tests);
continue;
}
match f.path().extension().and_then(|s| s.to_str()) {
Some("wat") => {}
_ => continue,
}
tests.push(f.path());
}
}
struct Test {
file: PathBuf,
directives: Vec<Directive>,
assertion: Option<String>,
}
struct Directive {
name: String,
tys: Vec<walrus::ValType>,
}
impl Test {
fn from_file(path: &Path) -> Result<Test> {
let contents = fs::read_to_string(path)?;
let mut iter = contents.lines();
let mut assertion = None;
let mut directives = Vec::new();
while let Some(line) = iter.next() {
if line.starts_with("(; CHECK-ALL:") {
let mut pattern = String::new();
for line in iter.by_ref() {
if line == ";)" {
break;
}
pattern.push_str(line);
pattern.push('\n');
}
if iter.next().is_some() {
bail!("CHECK-ALL must be at the end of the file");
}
assertion = Some(pattern);
continue;
}
if !line.starts_with(";; @xform") {
continue;
}
let directive = &line[9..];
let buf = wast::parser::ParseBuffer::new(directive)?;
directives.push(wast::parser::parse::<Directive>(&buf)?);
}
Ok(Test {
file: path.to_path_buf(),
directives,
assertion,
})
}
fn check(&self, output: &str, bless: bool) -> Result<()> {
if bless {
update_output(&self.file, output)
} else if let Some(pattern) = &self.assertion {
if output == pattern {
return Ok(());
}
bail!(
"expected\n {}\n\nactual\n {}",
pattern.replace('\n', "\n "),
output.replace('\n', "\n ")
);
} else {
bail!(
"no test assertions were found in this file, but you can \
rerun tests with `BLESS=1` to automatically add assertions \
to this file"
);
}
}
}
fn update_output(path: &Path, output: &str) -> Result<()> {
let contents = fs::read_to_string(path)?;
let start = contents.find("(; CHECK-ALL:").unwrap_or(contents.len());
let mut new_output = String::new();
for line in output.lines() {
new_output.push_str(line);
new_output.push('\n');
}
let new = format!(
"{}\n\n(; CHECK-ALL:\n{}\n;)\n",
contents[..start].trim(),
new_output.trim_end()
);
fs::write(path, new)?;
Ok(())
}
impl<'a> Parse<'a> for Directive {
fn parse(parser: Parser<'a>) -> wast::parser::Result<Self> {
use wast::{core::ValType, kw};
parser.parse::<kw::export>()?;
let name = parser.parse()?;
let mut tys = Vec::new();
parser.parens(|p| {
while !p.is_empty() {
tys.push(match p.parse()? {
ValType::I32 => walrus::ValType::I32,
ValType::I64 => walrus::ValType::I64,
ValType::F32 => walrus::ValType::F32,
ValType::F64 => walrus::ValType::F64,
_ => panic!(),
});
}
Ok(())
})?;
Ok(Directive { name, tys })
}
}