-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.rs
More file actions
352 lines (296 loc) · 12.5 KB
/
Copy pathbuild.rs
File metadata and controls
352 lines (296 loc) · 12.5 KB
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
use anyhow::{Context, Result};
use herkos::{transpile, TranspileOptions};
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
fn main() -> Result<()> {
// Rerun build script if this file or any data files change
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=data");
// Use cargo's OUT_DIR for generated files (parallel-build safe)
let out_dir = PathBuf::from(env::var("OUT_DIR").context("OUT_DIR not set")?);
eprintln!(
"Generating WASM and transpiled modules to: {}",
out_dir.display()
);
let options = TranspileOptions::default();
let mut module_names = Vec::new();
// 1. WAT test cases from data/wat/*.wat
let wat_names = process_wat_files(Path::new("data/wat"), &out_dir, &options)?;
module_names.extend(wat_names);
// 2. Rust → Wasm → Rust end-to-end test cases from data/rust/*.rs
let rust_e2e_names = process_rust_e2e_files(Path::new("data/rust"), &out_dir, &options)?;
module_names.extend(rust_e2e_names);
// 3. C → Wasm → Rust end-to-end test cases from data/c/*.c
let c_e2e_names = process_c_e2e_files(Path::new("data/c"), &out_dir, &options)?;
module_names.extend(c_e2e_names);
// Generate module manifest
let mut manifest = String::from("// Auto-generated module manifest\n");
manifest.push_str("// DO NOT EDIT - generated by build.rs\n\n");
for name in &module_names {
manifest.push_str(&format!("pub mod {};\n", name));
}
fs::write(out_dir.join("mod.rs"), manifest).context("failed to write mod.rs")?;
eprintln!("Transpilation complete! ({} modules)", module_names.len());
Ok(())
}
// ─── WAT processing ─────────────────────────────────────────────────────────
/// Scan `data/wat/*.wat`, parse each to Wasm, transpile to Rust.
fn process_wat_files(
wat_dir: &Path,
out_dir: &Path,
options: &TranspileOptions,
) -> Result<Vec<String>> {
let mut entries = collect_files_with_ext(wat_dir, "wat")?;
entries.sort(); // deterministic build order
eprintln!(
"Processing {} WAT test cases from {}...",
entries.len(),
wat_dir.display()
);
let mut names = Vec::new();
for path in &entries {
let name = file_stem(path)?;
eprintln!(" WAT: {} ...", name);
let wat_source = fs::read_to_string(path)
.with_context(|| format!("failed to read {}", path.display()))?;
let wasm_bytes = wat::parse_str(&wat_source)
.with_context(|| format!("failed to parse WAT for {}", name))?;
let wasm_path = out_dir.join(format!("{}.wasm", name));
fs::write(&wasm_path, &wasm_bytes)
.with_context(|| format!("failed to write {}.wasm", name))?;
let rust_code = transpile(&wasm_bytes, options)
.with_context(|| format!("failed to transpile {}", name))?;
let module_path = out_dir.join(format!("{}.rs", name));
fs::write(&module_path, &rust_code)
.with_context(|| format!("failed to write {}.rs", name))?;
names.push(name);
}
Ok(names)
}
// ─── Rust E2E processing ────────────────────────────────────────────────────
/// Scan `data/rust/*.rs`, compile each to Wasm via rustc, then transpile.
///
/// Gracefully skips if the wasm32-unknown-unknown target is not installed.
fn process_rust_e2e_files(
rust_dir: &Path,
out_dir: &Path,
options: &TranspileOptions,
) -> Result<Vec<String>> {
// Check if wasm32-unknown-unknown sysroot exists
let sysroot_output = std::process::Command::new("rustc")
.args(["--print", "sysroot"])
.output()
.context("failed to run rustc --print sysroot")?;
let sysroot = String::from_utf8_lossy(&sysroot_output.stdout);
let sysroot = sysroot.trim();
let target_dir = PathBuf::from(sysroot).join("lib/rustlib/wasm32-unknown-unknown");
if !target_dir.exists() {
eprintln!(
"cargo:warning=wasm32-unknown-unknown target not installed; \
skipping Rust E2E tests. Run: rustup target add wasm32-unknown-unknown"
);
return Ok(Vec::new());
}
// Copy common include files to OUT_DIR so include!() paths resolve
// when rustc compiles the copied sources.
let common_dir = rust_dir.join("common");
if common_dir.exists() {
let out_common = out_dir.join("common");
fs::create_dir_all(&out_common).context("failed to create common/ in OUT_DIR")?;
for entry in fs::read_dir(&common_dir).context("failed to read data/rust/common/")? {
let entry = entry?;
let path = entry.path();
if path.is_file() {
let dest = out_common.join(path.file_name().unwrap());
fs::copy(&path, &dest).with_context(|| {
format!("failed to copy {} to OUT_DIR/common/", path.display())
})?;
}
}
}
let mut entries = collect_files_with_ext(rust_dir, "rs")?;
entries.sort();
eprintln!(
"Processing {} Rust E2E test cases (Rust → Wasm → Rust)...",
entries.len()
);
// Transpile options: max_pages=2 to keep IsolatedMemory small enough
// for test thread stacks (8 MiB in debug mode).
let e2e_options = TranspileOptions {
max_pages: 2,
..options.clone()
};
let mut names = Vec::new();
for path in &entries {
let name = file_stem(path)?;
eprintln!(" Rust E2E: {} ...", name);
// Copy source to OUT_DIR for rustc
let rs_src_path = out_dir.join(format!("{}_src.rs", name));
fs::copy(path, &rs_src_path)
.with_context(|| format!("failed to copy {} to OUT_DIR", path.display()))?;
// Compile to Wasm
let wasm_path = out_dir.join(format!("{}.wasm", name));
let compile_output = std::process::Command::new("rustc")
.args([
"--target",
"wasm32-unknown-unknown",
"--crate-type",
"cdylib",
"--edition",
"2021",
"-C",
"opt-level=3",
"-C",
"lto=yes",
// Reduce the Wasm stack size from the default 1 MiB to 64 KiB,
// then set initial/max memory to 2 pages (128 KiB).
// This keeps the transpiled IsolatedMemory small enough for
// test thread stacks (8 MiB in debug mode).
"-C",
"link-arg=-zstack-size=65536",
"-C",
"link-arg=--initial-memory=131072",
"-C",
"link-arg=--max-memory=131072",
])
.arg(&rs_src_path)
.arg("-o")
.arg(&wasm_path)
.output()
.with_context(|| format!("failed to invoke rustc for {}", name))?;
if !compile_output.status.success() {
let stderr = String::from_utf8_lossy(&compile_output.stderr);
eprintln!(
"cargo:warning=Failed to compile {} to Wasm: {}",
name, stderr
);
continue;
}
// Read, transpile, write
let wasm_bytes =
fs::read(&wasm_path).with_context(|| format!("failed to read {}.wasm", name))?;
let rust_code = transpile(&wasm_bytes, &e2e_options)
.with_context(|| format!("failed to transpile {} from Rust-compiled Wasm", name))?;
let module_path = out_dir.join(format!("{}.rs", name));
fs::write(&module_path, &rust_code)
.with_context(|| format!("failed to write {}.rs", name))?;
names.push(name);
}
Ok(names)
}
// ─── C E2E processing ───────────────────────────────────────────────────────
/// Scan `data/c/*.c`, compile each to Wasm via clang, then transpile.
///
/// Gracefully skips if `clang` (with wasm32 target support) is not available.
fn process_c_e2e_files(
c_dir: &Path,
out_dir: &Path,
options: &TranspileOptions,
) -> Result<Vec<String>> {
// Try clang-19 first, then fall back to clang
let clang = if command_succeeds("clang-19", &["--version"]) {
"clang-19"
} else if command_succeeds("clang", &["--version"]) {
"clang"
} else {
eprintln!(
"cargo:warning=clang not found; skipping C E2E tests. \
Install with: apt-get install clang lld"
);
return Ok(Vec::new());
};
let mut entries = collect_files_with_ext(c_dir, "c")?;
entries.sort();
eprintln!(
"Processing {} C E2E test cases (C → Wasm → Rust) using {}...",
entries.len(),
clang
);
// Transpile options: max_pages=2 to match --max-memory=131072
let e2e_options = TranspileOptions {
max_pages: 2,
..options.clone()
};
let mut names = Vec::new();
for path in &entries {
let name = file_stem(path)?;
eprintln!(" C E2E: {} ...", name);
// Copy source to OUT_DIR for clang
let c_src_path = out_dir.join(format!("{}_src.c", name));
fs::copy(path, &c_src_path)
.with_context(|| format!("failed to copy {} to OUT_DIR", path.display()))?;
// Compile C → Wasm using clang with freestanding settings
let wasm_path = out_dir.join(format!("{}.wasm", name));
let compile_output = std::process::Command::new(clang)
.args([
"--target=wasm32-unknown-unknown",
"-nostdlib",
"-Oz",
// Linker flags: no entry point, export all symbols
"-Wl,--no-entry",
"-Wl,--export-all",
// Reduce the Wasm stack from the default 1 MiB to 64 KiB,
// then set initial/max memory to 2 pages (128 KiB).
// This keeps the transpiled IsolatedMemory small enough
// for test thread stacks (8 MiB in debug mode).
"-Wl,-zstack-size=65536",
"-Wl,--initial-memory=131072",
"-Wl,--max-memory=131072",
])
.arg(&c_src_path)
.arg("-o")
.arg(&wasm_path)
.output()
.with_context(|| format!("failed to invoke {} for {}", clang, name))?;
if !compile_output.status.success() {
let stderr = String::from_utf8_lossy(&compile_output.stderr);
eprintln!(
"cargo:warning=Failed to compile {} to Wasm: {}",
name, stderr
);
continue;
}
// Read, transpile, write
let wasm_bytes =
fs::read(&wasm_path).with_context(|| format!("failed to read {}.wasm", name))?;
let rust_code = transpile(&wasm_bytes, &e2e_options)
.with_context(|| format!("failed to transpile {} from C-compiled Wasm", name))?;
let module_path = out_dir.join(format!("{}.rs", name));
fs::write(&module_path, &rust_code)
.with_context(|| format!("failed to write {}.rs", name))?;
names.push(name);
}
Ok(names)
}
// ─── Helpers ────────────────────────────────────────────────────────────────
/// Collect all files with the given extension from a directory.
fn collect_files_with_ext(dir: &Path, ext: &str) -> Result<Vec<PathBuf>> {
if !dir.exists() {
return Ok(Vec::new());
}
let mut files = Vec::new();
for entry in fs::read_dir(dir).with_context(|| format!("failed to read {}", dir.display()))? {
let entry = entry?;
let path = entry.path();
if path.extension().and_then(|e| e.to_str()) == Some(ext) {
files.push(path);
}
}
Ok(files)
}
/// Extract the file stem as a String (used as module name).
fn file_stem(path: &Path) -> Result<String> {
path.file_stem()
.and_then(|s| s.to_str())
.map(|s| s.to_string())
.with_context(|| format!("invalid file name: {}", path.display()))
}
/// Check if a command runs successfully.
fn command_succeeds(cmd: &str, args: &[&str]) -> bool {
std::process::Command::new(cmd)
.args(args)
.output()
.map(|o| o.status.success())
.unwrap_or(false)
}