-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwasm_gen.rs
More file actions
271 lines (244 loc) · 10 KB
/
Copy pathwasm_gen.rs
File metadata and controls
271 lines (244 loc) · 10 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
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) 2026 Jonathan D.A. Jewell <j.d.a.jewell@open.ac.uk>
//
// WASM generation module for affinescriptiser — Produces WASM compilation configuration files
// and entry point declarations from the manifest's WASM settings and the generated AffineScript
// module. The output includes a build configuration (target, optimisation flags, size constraints)
// and an entry point source file that wires up the safe resource wrappers for WASM export.
use crate::abi::{Violation, ViolationType, WasmConfig, WasmTarget};
use crate::codegen::affine_gen::AffineModule;
use std::fmt::Write;
/// Generated WASM build artefacts: a build configuration file and a WASM entry point module.
#[derive(Debug, Clone)]
pub struct WasmOutput {
/// WASM build configuration (target, flags, constraints) as TOML content.
pub build_config: String,
/// WASM entry point source code that imports and re-exports the safe wrappers.
pub entry_point: String,
/// Any WASM-specific violations (e.g. size constraint failures).
pub violations: Vec<Violation>,
}
/// Generate WASM build configuration and entry point from the AffineScript module
/// and WASM settings declared in the manifest.
///
/// The build configuration is emitted as a TOML file suitable for consumption by
/// WASM build tools (wasm-pack, cargo-wasi, or custom AffineScript compiler).
/// The entry point re-exports each resource's safe allocation/deallocation functions
/// as WASM-exported symbols.
pub fn generate_wasm_output(affine_module: &AffineModule, wasm_config: &WasmConfig) -> WasmOutput {
let build_config = generate_build_config(wasm_config, &affine_module.module_name);
let entry_point = generate_entry_point(affine_module);
let violations = Vec::new(); // Size checks happen at build time, not codegen time.
WasmOutput {
build_config,
entry_point,
violations,
}
}
/// Generate a TOML build configuration for the WASM target.
fn generate_build_config(config: &WasmConfig, module_name: &str) -> String {
let mut out = String::new();
writeln!(
out,
"# WASM build configuration generated by affinescriptiser"
)
.expect("TODO: handle error");
writeln!(out, "# SPDX-License-Identifier: MPL-2.0").expect("TODO: handle error");
writeln!(out).expect("TODO: handle error");
writeln!(out, "[build]").expect("TODO: handle error");
writeln!(out, "module = \"{}\"", module_name).expect("TODO: handle error");
writeln!(out, "target = \"{}\"", config.target).expect("TODO: handle error");
writeln!(out, "optimize = {}", config.optimize).expect("TODO: handle error");
if let Some(limit) = config.size_limit_kb {
writeln!(out, "size-limit-kb = {}", limit).expect("TODO: handle error");
}
writeln!(out).expect("TODO: handle error");
writeln!(out, "[build.flags]").expect("TODO: handle error");
// Target-specific flags.
match config.target {
WasmTarget::Wasm32Unknown => {
writeln!(out, "# Browser-compatible WASM (no WASI)").expect("TODO: handle error");
writeln!(out, "no-wasi = true").expect("TODO: handle error");
}
WasmTarget::Wasm32Wasi => {
writeln!(out, "# WASI-enabled WASM (filesystem, env access)")
.expect("TODO: handle error");
writeln!(out, "wasi = true").expect("TODO: handle error");
}
}
if config.optimize {
writeln!(out, "wasm-opt = true").expect("TODO: handle error");
writeln!(out, "strip-debug = true").expect("TODO: handle error");
writeln!(out, "lto = true").expect("TODO: handle error");
}
out
}
/// Generate the WASM entry point module that imports and re-exports safe resource wrappers.
fn generate_entry_point(affine_module: &AffineModule) -> String {
let mut out = String::new();
writeln!(out, "// WASM entry point generated by affinescriptiser").expect("TODO: handle error");
writeln!(out, "// SPDX-License-Identifier: MPL-2.0").expect("TODO: handle error");
writeln!(out).expect("TODO: handle error");
writeln!(
out,
"import {{ * }} from \"{}\";",
affine_module.module_name
)
.expect("TODO: handle error");
writeln!(out).expect("TODO: handle error");
// Extract and re-export all safe_create_* and safe_destroy_* functions.
for line in affine_module.source.lines() {
let trimmed = line.trim();
if trimmed.starts_with("fn safe_create_") || trimmed.starts_with("fn safe_destroy_") {
// Extract the function name.
if let Some(name) = extract_function_name(trimmed) {
writeln!(out, "@wasm_export").expect("TODO: handle error");
writeln!(
out,
"pub fn {}(/* forwarded params */) -> /* forwarded return */ {{",
name
)
.expect("TODO: handle error");
writeln!(
out,
" {}.{}(/* forwarded args */)",
affine_module.module_name, name
)
.expect("TODO: handle error");
writeln!(out, "}}").expect("TODO: handle error");
writeln!(out).expect("TODO: handle error");
}
}
}
// Export a health-check function for WASM module validation.
writeln!(out, "@wasm_export").expect("TODO: handle error");
writeln!(out, "pub fn affinescriptiser_health() -> i32 {{").expect("TODO: handle error");
writeln!(out, " // Returns 0 if all resource invariants hold").expect("TODO: handle error");
writeln!(out, " 0").expect("TODO: handle error");
writeln!(out, "}}").expect("TODO: handle error");
out
}
/// Extract a function name from a line like `fn safe_create_gpu_buffer(params: ...) -> ... {`.
fn extract_function_name(line: &str) -> Option<String> {
let after_fn = line.strip_prefix("fn ")?;
let paren_pos = after_fn.find('(')?;
Some(after_fn[..paren_pos].to_string())
}
/// Check whether a WASM binary (represented by its size) exceeds the configured limit.
/// Returns a SizeExceeded violation if the limit is exceeded, or None if within bounds.
pub fn check_size_limit(actual_bytes: u64, config: &WasmConfig) -> Option<Violation> {
if let Some(limit_kb) = config.size_limit_kb {
let actual_kb = actual_bytes / 1024;
if actual_kb > limit_kb {
return Some(Violation::new(ViolationType::SizeExceeded {
actual_kb,
limit_kb,
}));
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
use crate::abi::{AffineResource, AffinityKind};
use crate::codegen::affine_gen::generate_affine_module;
fn sample_module() -> AffineModule {
let resources = vec![
AffineResource {
name: "GpuBuffer".into(),
allocator: "create_buffer".into(),
deallocator: "release_buffer".into(),
affinity: AffinityKind::Affine,
},
AffineResource {
name: "SessionToken".into(),
allocator: "create_session".into(),
deallocator: "revoke_session".into(),
affinity: AffinityKind::Linear,
},
];
generate_affine_module("wasm_safe", &resources, &[])
}
#[test]
fn test_generate_build_config() {
let config = WasmConfig {
target: WasmTarget::Wasm32Unknown,
optimize: true,
size_limit_kb: Some(512),
};
let out = generate_build_config(&config, "test");
assert!(out.contains("target = \"wasm32-unknown-unknown\""));
assert!(out.contains("optimize = true"));
assert!(out.contains("size-limit-kb = 512"));
assert!(out.contains("wasm-opt = true"));
}
#[test]
fn test_generate_build_config_wasi() {
let config = WasmConfig {
target: WasmTarget::Wasm32Wasi,
optimize: false,
size_limit_kb: None,
};
let out = generate_build_config(&config, "test");
assert!(out.contains("target = \"wasm32-wasi\""));
assert!(out.contains("wasi = true"));
assert!(!out.contains("wasm-opt"));
}
#[test]
fn test_generate_entry_point_exports() {
let module = sample_module();
let config = WasmConfig::default();
let output = generate_wasm_output(&module, &config);
assert!(output.entry_point.contains("@wasm_export"));
assert!(output.entry_point.contains("affinescriptiser_health"));
}
#[test]
fn test_check_size_limit_within_bounds() {
let config = WasmConfig {
target: WasmTarget::default(),
optimize: false,
size_limit_kb: Some(512),
};
// 256KB = 262144 bytes — within the 512KB limit.
assert!(check_size_limit(262144, &config).is_none());
}
#[test]
fn test_check_size_limit_exceeded() {
let config = WasmConfig {
target: WasmTarget::default(),
optimize: false,
size_limit_kb: Some(512),
};
// 1MB = 1048576 bytes — exceeds the 512KB limit.
let violation = check_size_limit(1048576, &config);
assert!(violation.is_some());
assert!(
violation
.expect("TODO: handle error")
.violation
.to_string()
.contains("SIZE-EXCEEDED")
);
}
#[test]
fn test_check_size_limit_no_limit() {
let config = WasmConfig {
target: WasmTarget::default(),
optimize: false,
size_limit_kb: None,
};
// No limit configured — any size is fine.
assert!(check_size_limit(999999999, &config).is_none());
}
#[test]
fn test_extract_function_name() {
assert_eq!(
extract_function_name(
"fn safe_create_gpu_buffer(params: AllocParams) -> GpuBuffer<Affine> {"
),
Some("safe_create_gpu_buffer".into())
);
assert_eq!(extract_function_name("let x = 1;"), None);
}
}