weaveffi-core 0.14.0

Generator trait, orchestrator, validation, and shared utilities for WeaveFFI
Documentation
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! Shared rendering of the **C ABI declarations** from a
//! [`BindingModel`](crate::model::BindingModel).
//!
//! Both the C generator (which emits the canonical `{prefix}.h`) and the C++
//! generator (whose idiomatic wrapper opens an `extern "C"` block re-declaring
//! the same symbols) render their C declarations through this module. Before it
//! existed the two re-derived the ABI independently and drifted. Most visibly,
//! the C++ `extern "C"` block lowered `iter<T>` as a list and omitted callbacks
//! and listeners entirely. Routing both through one model-driven renderer makes
//! that class of drift impossible.

use std::fmt::Write;

use crate::abi::AbiParam;
use crate::codegen::common::{emit_doc as common_emit_doc, DocCommentStyle};
use crate::codegen::CodeWriter;
use crate::model::{AbiFn, CallShape, EnumBinding, ModuleBinding, StructBinding};

/// Emit a `/** ... */` doc comment at `indent`.
pub fn emit_doc(out: &mut String, doc: &Option<String>, indent: &str) {
    common_emit_doc(out, doc, indent, DocCommentStyle::Javadoc);
}

/// Join lowered ABI slots into a `"<c-type> <name>, ..."` declaration string.
pub fn params_str(params: &[AbiParam], prefix: &str) -> String {
    params
        .iter()
        .map(|p| format!("{} {}", p.ty.render_c(prefix), p.name))
        .collect::<Vec<_>>()
        .join(", ")
}

/// The export-visibility macro name for `prefix`, for example `WEAVEFFI_API`.
///
/// Every exported function prototype is tagged with this macro so a non-Rust
/// producer that implements the header can export the symbols under hidden
/// default visibility, and Windows consumers import them through `dllimport`.
/// See [`render_visibility_macros`] for the macro's definition.
fn export_macro(prefix: &str) -> String {
    format!("{}_API", prefix.to_uppercase())
}

/// The deprecation macro name for `prefix`, for example `WEAVEFFI_DEPRECATED`.
///
/// Used in place of a bare `__attribute__((deprecated))` so the marker also
/// compiles under MSVC (which spells it `__declspec(deprecated(...))`).
fn deprecated_macro(prefix: &str) -> String {
    format!("{}_DEPRECATED", prefix.to_uppercase())
}

/// Render the portable export-visibility and deprecation macros that the C ABI
/// declarations are tagged with.
///
/// The C ABI header is both consumed (callers link the prebuilt library) and,
/// for non-Rust producers, implemented directly (C, C++, or Zig supply the
/// symbols). A bare prototype exports nothing under hidden default visibility
/// (`-fvisibility=hidden`, the norm for release builds and the MSVC default),
/// so an implementing library compiled that way ships no usable symbols. These
/// macros fix that portably:
///
/// - `{PREFIX}_API` expands to `__declspec(dllexport)` when the producer
///   defines `{PREFIX}_BUILD`, `__declspec(dllimport)` otherwise on Windows,
///   `__attribute__((used, visibility("default")))` under Emscripten,
///   `__attribute__((visibility("default")))` on GCC and Clang, and nothing
///   elsewhere. The Emscripten spelling matches `EMSCRIPTEN_KEEPALIVE`: the
///   `used` attribute keeps every tagged symbol alive through Emscripten's
///   aggressive dead-code elimination, so the exports survive without the
///   producer enumerating them in `-sEXPORTED_FUNCTIONS`.
/// - `{PREFIX}_DEPRECATED(msg)` expands to the compiler's deprecation marker.
///
/// Both definitions are wrapped in `#ifndef` guards so a translation unit that
/// includes both the C header and the C++ header (which inlines the same
/// declarations) defines each macro only once. The names are derived from the
/// configured symbol prefix so two WeaveFFI libraries included together never
/// collide.
pub fn render_visibility_macros(out: &mut String, prefix: &str) {
    let body = r#"#ifndef @U@_API
#  if defined(_WIN32) || defined(__CYGWIN__)
#    ifdef @U@_BUILD
#      define @U@_API __declspec(dllexport)
#    else
#      define @U@_API __declspec(dllimport)
#    endif
#  elif defined(__EMSCRIPTEN__)
#    define @U@_API __attribute__((used, visibility("default")))
#  elif defined(__GNUC__) && (__GNUC__ >= 4)
#    define @U@_API __attribute__((visibility("default")))
#  else
#    define @U@_API
#  endif
#endif

#ifndef @U@_DEPRECATED
#  if defined(_MSC_VER)
#    define @U@_DEPRECATED(msg) __declspec(deprecated(msg))
#  elif defined(__GNUC__) || defined(__clang__)
#    define @U@_DEPRECATED(msg) __attribute__((deprecated(msg)))
#  else
#    define @U@_DEPRECATED(msg)
#  endif
#endif

"#;
    out.push_str(&body.replace("@U@", &prefix.to_uppercase()));
}

/// Render a full `{API} {ret} {symbol}({params});` declaration for a lowered
/// symbol, tagged with the export-visibility macro (see
/// [`render_visibility_macros`]).
pub fn fn_decl(out: &mut String, f: &AbiFn, prefix: &str) {
    let _ = writeln!(
        out,
        "{} {} {}({});",
        export_macro(prefix),
        f.ret.render_c(prefix),
        f.symbol,
        params_str(&f.params, prefix)
    );
}

/// Render the runtime typedefs and helper prototypes (`handle_t`, `error`,
/// `free_*`, `alloc`/`dealloc`, `cancel_token`) that every WeaveFFI C surface
/// depends on.
///
/// `alloc`/`dealloc` back the WASM JavaScript glue, which stages strings,
/// bytes, and arrays into linear memory before each call. Native consumers
/// never call them, but a producer targeting WebAssembly (for example a C
/// library built with Emscripten) must export them; the generated
/// `{prefix}.c` scaffold provides malloc/free-backed defaults.
pub fn render_runtime_decls(out: &mut String, prefix: &str) {
    let api = export_macro(prefix);
    let _ = write!(
        out,
        "typedef uint64_t {prefix}_handle_t;\n\n\
         typedef struct {prefix}_error {{ int32_t code; const char* message; }} {prefix}_error;\n\n\
         {api} void {prefix}_error_clear({prefix}_error* err);\n\
         {api} void {prefix}_free_string(const char* ptr);\n\
         {api} void {prefix}_free_bytes(uint8_t* ptr, size_t len);\n\n\
         /* Linear-memory allocator used by the WASM JS glue to stage call\n   \
           arguments. Native consumers never call these; producers targeting\n   \
           WebAssembly must export them (the generated {prefix}.c provides\n   \
           malloc/free-backed defaults). */\n\
         {api} uint8_t* {prefix}_alloc(uint32_t size);\n\
         {api} void {prefix}_dealloc(uint8_t* ptr, uint32_t size);\n\n\
         typedef struct {prefix}_cancel_token {prefix}_cancel_token;\n\
         {api} {prefix}_cancel_token* {prefix}_cancel_token_create(void);\n\
         {api} void {prefix}_cancel_token_cancel({prefix}_cancel_token* token);\n\
         {api} bool {prefix}_cancel_token_is_cancelled(const {prefix}_cancel_token* token);\n\
         {api} void {prefix}_cancel_token_destroy({prefix}_cancel_token* token);\n\n",
    );
}

/// Render an enum's discriminant constants as a C `typedef enum` named
/// `type_name`. Multi-line when any variant is documented.
fn render_enum_constants(out: &mut String, e: &EnumBinding, type_name: &str) {
    let mut w = CodeWriter::four_space();
    w.doc(&e.doc, DocCommentStyle::Javadoc);
    if e.variants.iter().any(|v| v.doc.is_some()) {
        w.block("typedef enum {", format!("}} {type_name};"), |w| {
            let last = e.variants.len();
            for (i, v) in e.variants.iter().enumerate() {
                w.doc(&v.doc, DocCommentStyle::Javadoc);
                let comma = if i + 1 == last { "" } else { "," };
                w.line(format!("{} = {}{comma}", v.c_const, v.value));
            }
        });
    } else {
        let variants: Vec<String> = e
            .variants
            .iter()
            .map(|v| format!("{} = {}", v.c_const, v.value))
            .collect();
        w.line(format!(
            "typedef enum {{ {} }} {type_name};",
            variants.join(", ")
        ));
    }
    out.push_str(&w.finish());
}

/// Render a C-style enum typedef. Multi-line when any variant is documented.
pub fn render_enum_decl(out: &mut String, e: &EnumBinding) {
    render_enum_constants(out, e, &e.c_tag);
}

/// Render the *discriminant* enum of a rich (algebraic) enum, named
/// `{c_tag}_Tag`. The payload-carrying value itself is an opaque struct
/// `{c_tag}` (forward-declared via [`render_module_type_tags`]); the tag getter
/// returns one of these discriminant constants as `int32_t`.
fn render_rich_enum_tag_decl(out: &mut String, e: &EnumBinding) {
    let tag_enum = format!("{}_Tag", e.c_tag);
    render_enum_constants(out, e, &tag_enum);
}

/// Render the function surface of a rich (algebraic) enum: the tag getter, each
/// variant's constructor and field getters, then the destructor. Assumes the
/// opaque object tag and every referenced type tag are already forward-declared.
fn render_rich_enum_fn_decls(out: &mut String, e: &EnumBinding, prefix: &str) {
    let Some(rich) = &e.rich else {
        return;
    };
    let api = export_macro(prefix);
    let tag = &e.c_tag;
    emit_doc(out, &e.doc, "");
    let _ = writeln!(out, "{api} int32_t {}(const {tag}* self);", rich.tag_symbol);
    for v in &rich.variants {
        emit_doc(out, &v.doc, "");
        fn_decl(out, &v.create, prefix);
        for field in &v.fields {
            emit_doc(out, &field.doc, "");
            let mut parts = vec![format!("const {tag}* self")];
            parts.extend(
                field
                    .getter_out_params
                    .iter()
                    .map(|p| format!("{} {}", p.ty.render_c(prefix), p.name)),
            );
            let _ = writeln!(
                out,
                "{api} {} {}({});",
                field.getter_ret.render_c(prefix),
                field.getter_symbol,
                parts.join(", ")
            );
        }
    }
    let _ = writeln!(out, "{api} void {}({tag}* self);", rich.destroy_symbol);
    out.push('\n');
}

/// Render the opaque struct/builder *tags* (forward typedefs) for one struct.
///
/// These reference no other types, so emitting every struct's tags before any
/// function declaration lets a function in one module accept or return a struct
/// declared in *another* module (a parent module referencing a child's type).
fn render_struct_tags(out: &mut String, s: &StructBinding) {
    let tag = &s.c_tag;
    let _ = writeln!(out, "typedef struct {tag} {tag};");
    if let Some(b) = &s.builder {
        let bt = &b.builder_tag;
        let _ = writeln!(out, "typedef struct {bt} {bt};");
    }
}

/// Render the function declarations for one struct: create/destroy/getters and,
/// if present, the fluent builder's new/setters/build/destroy. Assumes the
/// struct (and every other struct it may reference) already has a forward
/// typedef emitted via [`render_struct_tags`].
fn render_struct_fn_decls(out: &mut String, s: &StructBinding, prefix: &str) {
    let api = export_macro(prefix);
    let tag = &s.c_tag;
    emit_doc(out, &s.doc, "");
    fn_decl(out, &s.create, prefix);
    let _ = writeln!(out, "{api} void {}({tag}* ptr);", s.destroy_symbol);
    for field in &s.fields {
        emit_doc(out, &field.doc, "");
        let mut parts = vec![format!("const {tag}* ptr")];
        parts.extend(
            field
                .getter_out_params
                .iter()
                .map(|p| format!("{} {}", p.ty.render_c(prefix), p.name)),
        );
        let _ = writeln!(
            out,
            "{api} {} {}({});",
            field.getter_ret.render_c(prefix),
            field.getter_symbol,
            parts.join(", ")
        );
    }
    out.push('\n');

    if let Some(b) = &s.builder {
        let bt = &b.builder_tag;
        let _ = writeln!(out, "{api} {bt}* {}(void);", b.new_symbol);
        for (field, (_, setter)) in s.fields.iter().zip(&b.setters) {
            emit_doc(out, &field.doc, "");
            let _ = writeln!(
                out,
                "{api} void {setter}({bt}* builder, {});",
                params_str(&field.value_params, prefix)
            );
        }
        let _ = writeln!(
            out,
            "{api} {tag}* {}({bt}* builder, {prefix}_error* out_err);",
            b.build_symbol
        );
        let _ = writeln!(out, "{api} void {}({bt}* builder);", b.destroy_symbol);
        out.push('\n');
    }
}

/// Phase 1a: enum definitions for one module. Enums reference no other types,
/// so they are emitted first across all modules.
pub fn render_module_enum_defs(out: &mut String, module: &ModuleBinding) {
    for e in &module.enums {
        if e.is_rich() {
            render_rich_enum_tag_decl(out, e);
        } else {
            render_enum_decl(out, e);
        }
    }
}

/// Phase 1b: opaque struct/builder/iterator forward typedefs for one module.
/// Pointers to these are all the C ABI ever uses, so a forward typedef is
/// sufficient and lets declarations in any module reference any struct.
pub fn render_module_type_tags(out: &mut String, module: &ModuleBinding) {
    // A rich (algebraic) enum is an opaque object, declared like a struct tag.
    for e in &module.enums {
        if e.is_rich() {
            let t = &e.c_tag;
            let _ = writeln!(out, "typedef struct {t} {t};");
        }
    }
    for s in &module.structs {
        render_struct_tags(out, s);
    }
    for f in &module.functions {
        if let CallShape::Iterator(it) = &f.shape {
            let t = &it.iter_tag;
            let _ = writeln!(out, "typedef struct {t} {t};");
        }
    }
}

/// Phase 1c: callback / async-callback function-pointer typedefs for one
/// module. These may reference enums (by value) and structs (by pointer), so
/// they are emitted after every module's enums and type tags.
pub fn render_module_callback_types(out: &mut String, module: &ModuleBinding, prefix: &str) {
    for cb in &module.callbacks {
        emit_doc(out, &cb.doc, "");
        let _ = writeln!(
            out,
            "typedef void (*{})({});",
            cb.c_fn_type,
            params_str(&cb.abi_params, prefix)
        );
    }
    for f in &module.functions {
        if let CallShape::Async(a) = &f.shape {
            let _ = writeln!(
                out,
                "typedef void (*{})({});",
                a.callback_type,
                params_str(&a.callback_params, prefix)
            );
        }
    }
}

/// Phase 2: every function prototype for one module: struct create/destroy/
/// getters and builders, listeners, then sync/async/iterator functions. All
/// type tags and callback typedefs are assumed already emitted (phases 1a–1c).
/// Caller controls the leading `// Module:` comment and any framing.
pub fn render_module_fn_decls(out: &mut String, module: &ModuleBinding, prefix: &str) {
    let api = export_macro(prefix);
    let deprecated = deprecated_macro(prefix);
    for e in &module.enums {
        render_rich_enum_fn_decls(out, e, prefix);
    }
    for s in &module.structs {
        render_struct_fn_decls(out, s, prefix);
    }
    for l in &module.listeners {
        emit_doc(out, &l.doc, "");
        let _ = writeln!(
            out,
            "{api} uint64_t {}({} callback, void* context);",
            l.register_symbol, l.callback_c_fn_type
        );
        emit_doc(out, &l.doc, "");
        let _ = writeln!(out, "{api} void {}(uint64_t id);", l.unregister_symbol);
    }
    for f in &module.functions {
        emit_doc(out, &f.doc, "");
        if let Some(msg) = &f.deprecated {
            let _ = writeln!(out, "{deprecated}(\"{}\")", msg.replace('"', "\\\""));
        }
        match &f.shape {
            CallShape::Iterator(it) => {
                let t = &it.iter_tag;
                fn_decl(out, &it.launch, prefix);
                fn_decl(out, &it.next, prefix);
                let _ = writeln!(out, "{api} void {}({t}* iter);", it.destroy_symbol);
            }
            CallShape::Async(a) => {
                fn_decl(out, &a.launch, prefix);
            }
            CallShape::Sync(abi) => {
                fn_decl(out, abi, prefix);
            }
        }
    }
}

/// Render the complete C ABI declaration surface for `modules` in
/// dependency-safe order: all enum definitions, then all opaque type tags, then
/// all callback typedefs, then per-module function prototypes. Emitting every
/// type tag before any function lets a parent module's function reference a
/// child module's struct: cross-module forward references the previous
/// per-module interleaving could not express.
///
/// The runtime decls (`handle_t`, `error`, `free_*`, cancel token) are *not*
/// emitted here; callers render those first (the C generator inserts its map
/// convention comment in between).
pub fn render_decls(
    out: &mut String,
    modules: &[ModuleBinding],
    prefix: &str,
    module_comments: bool,
) {
    for m in modules {
        render_module_enum_defs(out, m);
    }
    for m in modules {
        render_module_type_tags(out, m);
    }
    for m in modules {
        render_module_callback_types(out, m, prefix);
    }
    out.push('\n');
    for m in modules {
        if module_comments {
            let _ = writeln!(out, "// Module: {}", m.path);
        }
        render_module_fn_decls(out, m, prefix);
        out.push('\n');
    }
}