forked from bytecodealliance/ComponentizeJS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsplicer.rs
More file actions
252 lines (213 loc) · 7.36 KB
/
splicer.rs
File metadata and controls
252 lines (213 loc) · 7.36 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
use std::fs;
use std::path::PathBuf;
use std::str::FromStr;
use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use spidermonkey_embedding_splicer::wit::exports::local::spidermonkey_embedding_splicer::splicer::{
CoreFn, CoreTy, Feature,
};
use spidermonkey_embedding_splicer::{splice, stub_wasi};
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand, Debug, Clone)]
enum Commands {
/// Stub WASI imports in a WebAssembly module
StubWasi {
/// Input WebAssembly file path
#[arg(short, long)]
input: PathBuf,
/// Output WebAssembly file path
#[arg(short, long)]
output: PathBuf,
/// Features to enable (multiple allowed)
#[arg(short, long)]
features: Vec<String>,
/// Path to WIT file or directory
#[arg(long)]
wit_path: Option<PathBuf>,
/// World name to use
#[arg(long)]
world_name: Option<String>,
},
/// Splice bindings into a WebAssembly module
SpliceBindings {
/// Input engine WebAssembly file path
#[arg(short, long)]
input: PathBuf,
/// Output directory
#[arg(short, long)]
out_dir: PathBuf,
/// Features to enable (multiple allowed)
#[arg(short, long)]
features: Vec<String>,
/// Path to WIT file or directory
#[arg(long)]
wit_path: Option<PathBuf>,
/// World name to use
#[arg(long)]
world_name: Option<String>,
/// Enable debug mode
#[arg(long)]
debug: bool,
},
}
fn main() -> Result<()> {
let cli = Cli::parse();
match cli.command {
Commands::StubWasi {
input,
output,
features,
wit_path,
world_name,
} => {
let wasm = fs::read(&input)
.with_context(|| format!("Failed to read input file: {}", input.display()))?;
let wit_path_str = wit_path.as_ref().map(|p| p.to_string_lossy().to_string());
let features = features
.iter()
.map(|v| Feature::from_str(v))
.collect::<Result<Vec<_>>>()?;
let result = stub_wasi::stub_wasi(wasm, features, None, wit_path_str, world_name)
.map_err(|e| anyhow::anyhow!(e))?;
fs::write(&output, result)
.with_context(|| format!("Failed to write output file: {}", output.display()))?;
println!(
"Successfully stubbed WASI imports and saved to {}",
output.display()
);
}
Commands::SpliceBindings {
input,
out_dir,
features,
wit_path,
world_name,
debug,
} => {
if !out_dir.exists() {
fs::create_dir_all(&out_dir).with_context(|| {
format!("Failed to create output directory: {}", out_dir.display())
})?;
}
let engine = fs::read(&input)
.with_context(|| format!("Failed to read input file: {}", input.display()))?;
let wit_path_str = wit_path.as_ref().map(|p| p.to_string_lossy().to_string());
let features = features
.iter()
.map(|v| Feature::from_str(v))
.collect::<Result<Vec<_>>>()?;
let result =
splice::splice_bindings(engine, features, None, wit_path_str, world_name, debug)
.map_err(|e| anyhow::anyhow!(e))?;
fs::write(out_dir.join("component.wasm"), result.wasm).with_context(|| {
format!(
"Failed to write output file: {}",
out_dir.join("component.wasm").display()
)
})?;
fs::write(out_dir.join("initializer.js"), result.js_bindings).with_context(|| {
format!(
"Failed to write output file: {}",
out_dir.join("initializer.js").display()
)
})?;
// Write exports and imports as JSON (manual serialization)
let exports_json = serialize_exports(&result.exports);
fs::write(out_dir.join("exports.json"), exports_json).with_context(|| {
format!(
"Failed to write exports file: {}",
out_dir.join("exports.json").display()
)
})?;
let imports_json = serialize_imports(&result.imports);
fs::write(out_dir.join("imports.json"), imports_json).with_context(|| {
format!(
"Failed to write imports file: {}",
out_dir.join("imports.json").display()
)
})?;
println!(
"Successfully generated bindings and saved to {}",
out_dir.display()
);
}
}
Ok(())
}
/// Manually serialize exports to JSON
fn serialize_exports(exports: &[(String, CoreFn)]) -> String {
let mut result = String::from("[\n");
for (i, (name, core_fn)) in exports.iter().enumerate() {
if i > 0 {
result.push_str(",\n");
}
result.push_str(" [\"");
result.push_str(&name.replace('\\', "\\\\").replace('"', "\\\""));
result.push_str("\", ");
result.push_str(&serialize_core_fn(core_fn));
result.push(']');
}
result.push_str("\n]");
result
}
/// Manually serialize imports to JSON
fn serialize_imports(imports: &[(String, String, u32)]) -> String {
let mut result = String::from("[\n");
for (i, (specifier, name, arg_count)) in imports.iter().enumerate() {
if i > 0 {
result.push_str(",\n");
}
result.push_str(" [\"");
result.push_str(&specifier.replace('\\', "\\\\").replace('"', "\\\""));
result.push_str("\", \"");
result.push_str(&name.replace('\\', "\\\\").replace('"', "\\\""));
result.push_str("\", ");
result.push_str(&arg_count.to_string());
result.push(']');
}
result.push_str("\n]");
result
}
/// Manually serialize CoreFn to JSON
fn serialize_core_fn(core_fn: &CoreFn) -> String {
let mut result = String::from("{");
// params
result.push_str("\"params\": [");
for (i, param) in core_fn.params.iter().enumerate() {
if i > 0 {
result.push_str(", ");
}
result.push_str(&serialize_core_ty(param));
}
result.push_str("], ");
// ret
result.push_str("\"ret\": ");
if let Some(ref ret) = core_fn.ret {
result.push_str(&serialize_core_ty(ret));
} else {
result.push_str("null");
}
result.push_str(", ");
// retptr
result.push_str(&format!("\"retptr\": {}, ", core_fn.retptr));
// retsize
result.push_str(&format!("\"retsize\": {}, ", core_fn.retsize));
// paramptr
result.push_str(&format!("\"paramptr\": {}", core_fn.paramptr));
result.push('}');
result
}
/// Manually serialize CoreTy to JSON
fn serialize_core_ty(core_ty: &CoreTy) -> String {
match core_ty {
CoreTy::I32 => "\"i32\"".to_string(),
CoreTy::I64 => "\"i64\"".to_string(),
CoreTy::F32 => "\"f32\"".to_string(),
CoreTy::F64 => "\"f64\"".to_string(),
}
}