-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaffine_gen.rs
More file actions
373 lines (342 loc) · 13.2 KB
/
Copy pathaffine_gen.rs
File metadata and controls
373 lines (342 loc) · 13.2 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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) 2026 Jonathan D.A. Jewell <j.d.a.jewell@open.ac.uk>
//
// AffineScript type annotation generator — Takes parsed resource sites and manifest resource
// declarations and produces AffineScript wrapper modules. Each tracked resource gets a wrapper
// type that enforces its affinity discipline (affine = at-most-once, linear = exactly-once)
// at compile time. The generated code also includes violation checks that can be statically
// verified or emitted as runtime assertions for the WASM target.
use crate::abi::{AffineResource, AffinityKind, Violation, ViolationType};
use crate::codegen::parser::{ResourceSite, SiteKind};
use std::collections::HashMap;
use std::fmt::Write;
/// Generated AffineScript module containing type wrappers for a set of tracked resources.
#[derive(Debug, Clone)]
pub struct AffineModule {
/// Module name (derived from the project name).
pub module_name: String,
/// The generated AffineScript source code.
pub source: String,
/// Any violations detected during static analysis of the resource sites.
pub violations: Vec<Violation>,
}
/// Generate an AffineScript wrapper module from the manifest's resource declarations and
/// the parsed resource sites. The module contains:
/// 1. Type declarations for each resource with affine/linear wrappers.
/// 2. Safe allocation functions that return wrapped handles.
/// 3. Safe deallocation functions that consume wrapped handles.
/// 4. Static violation reports for detected misuse patterns.
pub fn generate_affine_module(
module_name: &str,
resources: &[AffineResource],
sites: &[ResourceSite],
) -> AffineModule {
let mut source = String::new();
let mut violations = Vec::new();
// Module header.
writeln!(
source,
"// AffineScript module generated by affinescriptiser"
)
.expect("TODO: handle error");
writeln!(source, "// SPDX-License-Identifier: MPL-2.0").expect("TODO: handle error");
writeln!(source, "// Module: {}", module_name).expect("TODO: handle error");
writeln!(source).expect("TODO: handle error");
writeln!(source, "module {} {{", module_name).expect("TODO: handle error");
writeln!(source).expect("TODO: handle error");
// Generate wrapper types and safe API for each resource.
for resource in resources {
generate_resource_wrapper(&mut source, resource);
writeln!(source).expect("TODO: handle error");
}
// Perform static violation analysis on the parsed sites.
let detected = analyse_sites(resources, sites);
for v in &detected {
// Emit violation as a compile-time error annotation.
writeln!(source, " // @error: {}", v.violation).expect("TODO: handle error");
}
violations.extend(detected);
writeln!(source, "}}").expect("TODO: handle error");
AffineModule {
module_name: module_name.to_string(),
source,
violations,
}
}
/// Generate the AffineScript type wrapper for a single resource. Produces:
/// - An opaque wrapper type with the appropriate affinity marker.
/// - A safe `create_*` function that wraps the raw allocator.
/// - A safe `destroy_*` function that consumes the wrapper.
fn generate_resource_wrapper(out: &mut String, resource: &AffineResource) {
let type_name = &resource.name;
let affinity_marker = match resource.affinity {
AffinityKind::Affine => "Affine",
AffinityKind::Linear => "Linear",
};
// Type declaration with affinity annotation.
writeln!(
out,
" // {} resource — {} discipline",
type_name, resource.affinity
)
.expect("TODO: handle error");
writeln!(
out,
" // Allocated by: {} Deallocated by: {}",
resource.allocator, resource.deallocator
)
.expect("TODO: handle error");
writeln!(
out,
" type {}<{}> = opaque handle;",
type_name, affinity_marker
)
.expect("TODO: handle error");
writeln!(out).expect("TODO: handle error");
// Safe allocator — returns a wrapped handle.
writeln!(
out,
" // Safe wrapper for {} — returns an affine-tracked handle",
resource.allocator
)
.expect("TODO: handle error");
writeln!(
out,
" fn safe_create_{name}(params: AllocParams) -> {type_name}<{marker}> {{",
name = to_snake_case(type_name),
type_name = type_name,
marker = affinity_marker
)
.expect("TODO: handle error");
writeln!(out, " let raw = @ffi::{}(params);", resource.allocator)
.expect("TODO: handle error");
writeln!(out, " {}<{}>::wrap(raw)", type_name, affinity_marker).expect("TODO: handle error");
writeln!(out, " }}").expect("TODO: handle error");
writeln!(out).expect("TODO: handle error");
// Safe deallocator — consumes the wrapped handle.
writeln!(
out,
" // Safe wrapper for {} — consumes the handle (cannot be used again)",
resource.deallocator
)
.expect("TODO: handle error");
writeln!(
out,
" fn safe_destroy_{name}(handle: {type_name}<{marker}>) -> () {{",
name = to_snake_case(type_name),
type_name = type_name,
marker = affinity_marker
)
.expect("TODO: handle error");
writeln!(
out,
" let raw = {}<{}>::unwrap(handle);",
type_name, affinity_marker
)
.expect("TODO: handle error");
writeln!(out, " @ffi::{}(raw);", resource.deallocator).expect("TODO: handle error");
writeln!(out, " }}").expect("TODO: handle error");
// Linear resources get a must-consume annotation.
if resource.affinity == AffinityKind::Linear {
writeln!(out).expect("TODO: handle error");
writeln!(
out,
" // LINEAR INVARIANT: {} must be consumed exactly once.",
type_name
)
.expect("TODO: handle error");
writeln!(
out,
" #[must_consume(\"{} is linear — must be explicitly deallocated\")]",
type_name
)
.expect("TODO: handle error");
writeln!(out, " impl MustConsume for {}<Linear> {{}}", type_name)
.expect("TODO: handle error");
}
}
/// Analyse parsed resource sites to detect affine/linear type violations:
/// - Double-free: two deallocation sites for the same resource within the same file scope.
/// - Leaked linear resources: allocation without a corresponding deallocation.
///
/// This is a conservative heuristic analysis (not a full control-flow analysis).
/// It groups sites by file and resource, then checks for imbalanced alloc/dealloc counts
/// and duplicate deallocation sequences.
fn analyse_sites(resources: &[AffineResource], sites: &[ResourceSite]) -> Vec<Violation> {
let mut violations = Vec::new();
// Build a lookup map: resource name -> AffineResource.
let resource_map: HashMap<&str, &AffineResource> =
resources.iter().map(|r| (r.name.as_str(), r)).collect();
// Group sites by (file, resource_name).
let mut grouped: HashMap<(&str, &str), Vec<&ResourceSite>> = HashMap::new();
for site in sites {
grouped
.entry((site.file.as_str(), site.resource_name.as_str()))
.or_default()
.push(site);
}
for ((file, res_name), file_sites) in &grouped {
let resource = match resource_map.get(res_name) {
Some(r) => r,
None => continue,
};
let allocs: Vec<_> = file_sites
.iter()
.filter(|s| s.kind == SiteKind::Allocation)
.collect();
let deallocs: Vec<_> = file_sites
.iter()
.filter(|s| s.kind == SiteKind::Deallocation)
.collect();
// Check for double-free: more than one deallocation site.
if deallocs.len() > 1 {
for i in 1..deallocs.len() {
violations.push(Violation::new(ViolationType::DoubleFree {
resource: res_name.to_string(),
first_free_at: format!("{}:{}", file, deallocs[0].line),
second_free_at: format!("{}:{}", file, deallocs[i].line),
}));
}
}
// Check for leaked linear resources: allocation with no deallocation.
if resource.affinity == AffinityKind::Linear && !allocs.is_empty() && deallocs.is_empty() {
for alloc in &allocs {
violations.push(Violation::new(ViolationType::Leaked {
resource: res_name.to_string(),
allocated_at: format!("{}:{}", file, alloc.line),
}));
}
}
}
violations
}
/// Convert a PascalCase or camelCase name to snake_case for generated function names.
fn to_snake_case(s: &str) -> String {
let mut result = String::with_capacity(s.len() + 4);
for (i, c) in s.chars().enumerate() {
if c.is_uppercase() {
if i > 0 {
result.push('_');
}
result.push(c.to_lowercase().next().expect("TODO: handle error"));
} else {
result.push(c);
}
}
result
}
#[cfg(test)]
mod tests {
use super::*;
fn gpu_resource() -> AffineResource {
AffineResource {
name: "GpuBuffer".into(),
allocator: "create_buffer".into(),
deallocator: "release_buffer".into(),
affinity: AffinityKind::Affine,
}
}
fn session_resource() -> AffineResource {
AffineResource {
name: "SessionToken".into(),
allocator: "create_session".into(),
deallocator: "revoke_session".into(),
affinity: AffinityKind::Linear,
}
}
#[test]
fn test_to_snake_case() {
assert_eq!(to_snake_case("GpuBuffer"), "gpu_buffer");
assert_eq!(to_snake_case("SessionToken"), "session_token");
assert_eq!(to_snake_case("X"), "x");
}
#[test]
fn test_generate_affine_module_produces_output() {
let resources = vec![gpu_resource()];
let sites = vec![];
let module = generate_affine_module("test_module", &resources, &sites);
assert!(module.source.contains("module test_module"));
assert!(module.source.contains("type GpuBuffer<Affine>"));
assert!(module.source.contains("safe_create_gpu_buffer"));
assert!(module.source.contains("safe_destroy_gpu_buffer"));
}
#[test]
fn test_linear_resource_gets_must_consume() {
let resources = vec![session_resource()];
let module = generate_affine_module("test", &resources, &[]);
assert!(module.source.contains("#[must_consume"));
assert!(module.source.contains("Linear"));
}
#[test]
fn test_double_free_detection() {
let resources = vec![gpu_resource()];
let sites = vec![
ResourceSite {
resource_name: "GpuBuffer".into(),
function: "create_buffer".into(),
kind: SiteKind::Allocation,
file: "test.rs".into(),
line: 1,
context: "create_buffer(64)".into(),
},
ResourceSite {
resource_name: "GpuBuffer".into(),
function: "release_buffer".into(),
kind: SiteKind::Deallocation,
file: "test.rs".into(),
line: 3,
context: "release_buffer(buf)".into(),
},
ResourceSite {
resource_name: "GpuBuffer".into(),
function: "release_buffer".into(),
kind: SiteKind::Deallocation,
file: "test.rs".into(),
line: 5,
context: "release_buffer(buf)".into(),
},
];
let module = generate_affine_module("test", &resources, &sites);
assert_eq!(module.violations.len(), 1);
assert!(
module.violations[0]
.violation
.to_string()
.contains("DOUBLE-FREE")
);
}
#[test]
fn test_linear_leak_detection() {
let resources = vec![session_resource()];
let sites = vec![ResourceSite {
resource_name: "SessionToken".into(),
function: "create_session".into(),
kind: SiteKind::Allocation,
file: "test.rs".into(),
line: 1,
context: "create_session()".into(),
}];
// No deallocation site — should detect a leak for the linear resource.
let module = generate_affine_module("test", &resources, &sites);
assert_eq!(module.violations.len(), 1);
assert!(module.violations[0].violation.to_string().contains("LEAK"));
}
#[test]
fn test_affine_resource_no_leak_violation() {
// Affine resources are allowed to be dropped without deallocation.
let resources = vec![gpu_resource()];
let sites = vec![ResourceSite {
resource_name: "GpuBuffer".into(),
function: "create_buffer".into(),
kind: SiteKind::Allocation,
file: "test.rs".into(),
line: 1,
context: "create_buffer(64)".into(),
}];
let module = generate_affine_module("test", &resources, &sites);
assert!(
module.violations.is_empty(),
"Affine resources should not report leaks"
);
}
}