-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.zig
More file actions
296 lines (238 loc) · 8.35 KB
/
Copy pathmain.zig
File metadata and controls
296 lines (238 loc) · 8.35 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
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) 2026 Jonathan D.A. Jewell <j.d.a.jewell@open.ac.uk>
//
// TYPED_WASM FFI Implementation
//
// This module is the C-compatible Zig FFI surface. Types and result codes
// are hand-maintained in parallel with the Idris2 ABI spread across
// src/abi/{Region,TypedAccess,Pointer,Effects,Lifetime,Linear,
// MultiModule}.idr and src/abi/Layout/*.idr. There is no automated
// Idris2 -> C header pipeline yet; see docs/architecture/ABI-PIPELINE.adoc
// for the gap analysis and the plan for closing it.
//
// SPDX-License-Identifier: MPL-2.0
const std = @import("std");
// Version information (keep in sync with project)
const VERSION = "0.1.0";
const BUILD_INFO = "TYPED_WASM built with Zig " ++ @import("builtin").zig_version_string;
/// Thread-local error storage
threadlocal var last_error: ?[]const u8 = null;
/// Set the last error message
fn setError(msg: []const u8) void {
last_error = msg;
}
/// Clear the last error
fn clearError() void {
last_error = null;
}
//==============================================================================
// Core Types (must match src/abi/Types.idr)
//==============================================================================
/// Result codes (must match Idris2 Result type)
pub const Result = enum(c_int) {
ok = 0,
@"error" = 1,
invalid_param = 2,
out_of_memory = 3,
null_pointer = 4,
};
/// Library handle: *truly* opaque to C — a pointer-only incomplete type
/// (FILE*-style). zig 0.15 forbids fields on `opaque`, which is correct: an
/// opaque type has no known size/alignment/layout, so it cannot carry fields.
/// The real state lives in `HandleImpl`, hidden behind the pointer; C only
/// ever holds a `*Handle` and never sees the implementation's size or fields.
/// This preserves the original "opaque to prevent direct access" intent
/// rather than downgrading to a plain struct.
pub const Handle = opaque {};
/// The concrete state behind a `*Handle`. Internal; never exposed across the
/// C ABI. Conjured/recovered via `impl()`.
const HandleImpl = struct {
allocator: std.mem.Allocator,
initialized: bool,
// Add further fields here.
};
/// Recover the implementation struct from an opaque handle pointer.
inline fn impl(handle: *Handle) *HandleImpl {
return @ptrCast(@alignCast(handle));
}
//==============================================================================
// Library Lifecycle
//==============================================================================
/// Initialize the library
/// Returns a handle, or null on failure
export fn typed_wasm_init() ?*Handle {
const allocator = std.heap.c_allocator;
const self = allocator.create(HandleImpl) catch {
setError("Failed to allocate handle");
return null;
};
// Initialize state
self.* = .{
.allocator = allocator,
.initialized = true,
};
clearError();
return @ptrCast(self);
}
/// Free the library handle
export fn typed_wasm_free(handle: ?*Handle) void {
const h = impl(handle orelse return);
const allocator = h.allocator;
// Clean up resources
h.initialized = false;
allocator.destroy(h);
clearError();
}
//==============================================================================
// Core Operations
//==============================================================================
/// Process data (example operation)
export fn typed_wasm_process(handle: ?*Handle, input: u32) Result {
const h = impl(handle orelse {
setError("Null handle");
return .null_pointer;
});
if (!h.initialized) {
setError("Handle not initialized");
return .@"error";
}
// Example processing logic
_ = input;
clearError();
return .ok;
}
//==============================================================================
// String Operations
//==============================================================================
/// Get a string result (example)
/// Caller must free the returned string
export fn typed_wasm_get_string(handle: ?*Handle) ?[*:0]const u8 {
const h = impl(handle orelse {
setError("Null handle");
return null;
});
if (!h.initialized) {
setError("Handle not initialized");
return null;
}
// Example: allocate and return a string
const result = h.allocator.dupeZ(u8, "Example result") catch {
setError("Failed to allocate string");
return null;
};
clearError();
return result.ptr;
}
/// Free a string allocated by the library
export fn typed_wasm_free_string(str: ?[*:0]const u8) void {
const s = str orelse return;
const allocator = std.heap.c_allocator;
const slice = std.mem.span(s);
allocator.free(slice);
}
//==============================================================================
// Array/Buffer Operations
//==============================================================================
/// Process an array of data
export fn typed_wasm_process_array(
handle: ?*Handle,
buffer: ?[*]const u8,
len: u32,
) Result {
const h = impl(handle orelse {
setError("Null handle");
return .null_pointer;
});
const buf = buffer orelse {
setError("Null buffer");
return .null_pointer;
};
if (!h.initialized) {
setError("Handle not initialized");
return .@"error";
}
// Access the buffer
const data = buf[0..len];
_ = data;
// Process data here
clearError();
return .ok;
}
//==============================================================================
// Error Handling
//==============================================================================
/// Get the last error message
/// Returns null if no error
export fn typed_wasm_last_error() ?[*:0]const u8 {
const err = last_error orelse return null;
// Return C string (static storage, no need to free)
const allocator = std.heap.c_allocator;
const c_str = allocator.dupeZ(u8, err) catch return null;
return c_str.ptr;
}
//==============================================================================
// Version Information
//==============================================================================
/// Get the library version
export fn typed_wasm_version() [*:0]const u8 {
return VERSION.ptr;
}
/// Get build information
export fn typed_wasm_build_info() [*:0]const u8 {
return BUILD_INFO.ptr;
}
//==============================================================================
// Callback Support
//==============================================================================
/// Callback function type (C ABI). zig 0.15 renamed the calling-convention
/// tag `.C` to `.c` (CallingConvention became a union to carry per-CC params).
pub const Callback = *const fn (u64, u32) callconv(.c) u32;
/// Register a callback
export fn typed_wasm_register_callback(
handle: ?*Handle,
callback: ?Callback,
) Result {
const h = impl(handle orelse {
setError("Null handle");
return .null_pointer;
});
const cb = callback orelse {
setError("Null callback");
return .null_pointer;
};
if (!h.initialized) {
setError("Handle not initialized");
return .@"error";
}
// Store callback for later use
_ = cb;
clearError();
return .ok;
}
//==============================================================================
// Utility Functions
//==============================================================================
/// Check if handle is initialized
export fn typed_wasm_is_initialized(handle: ?*Handle) u32 {
const h = impl(handle orelse return 0);
return if (h.initialized) 1 else 0;
}
//==============================================================================
// Tests
//==============================================================================
test "lifecycle" {
const handle = typed_wasm_init() orelse return error.InitFailed;
defer typed_wasm_free(handle);
try std.testing.expect(typed_wasm_is_initialized(handle) == 1);
}
test "error handling" {
const result = typed_wasm_process(null, 0);
try std.testing.expectEqual(Result.null_pointer, result);
const err = typed_wasm_last_error();
try std.testing.expect(err != null);
}
test "version" {
const ver = typed_wasm_version();
const ver_str = std.mem.span(ver);
try std.testing.expectEqualStrings(VERSION, ver_str);
}