wit-bindgen-d 0.61.1

D bindings generator for WIT and the component model, typically used through the `wit-bindgen-cli` crate.
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
import core.attribute : mustuse;
import ldc.attributes : llvmAttr;

alias wasmImport(string mod, string name) = AliasSeq!(
    llvmAttr("wasm-import-module", mod),
    llvmAttr("wasm-import-name", name)
);

enum wasmExport(string name) = llvmAttr("wasm-export-name", name);

struct witExport { string mod; string name; }

/// Thin CABI compliant wrapper over `T[]`
struct WitList(T) {
@safe @nogc pure nothrow:
    T* ptr;
    size_t length;

    this(inout T[] slice) inout @trusted {
        ptr = slice.ptr;
        length = slice.length;
    }

    void opAssign(T[] slice) @trusted {
        ptr = slice.ptr;
        length = slice.length;
    }

    alias asSlice this;
    inout(T)[] asSlice() @trusted inout {
        return (ptr && length) ? ptr[0..length] : null;
    }

    bool opEquals(in T[] other) const => this[] == other;
    size_t toHash() const => this[].hashOf;
}
auto witList(T)(inout T[] slice) => inout WitList!T(slice);

// WIT ABI for string matches List,
// except list<char> in WIT is actually List!(dchar)
//
// We assume UTF-8 data (as D native strings are UTF-8)
alias WitString = WitList!(char);

// TODO: split this file up and give Tuple a full port of the Phobos version?
/// adapted from Phobos std.typecons.Tuple
/// No support for naming members.
struct Tuple(Types...) if (is(Types)) {
    Types expand;
    alias expand this;
}

inout(Tuple!Types) tuple(Types...)(inout Types vals) => inout Tuple!Types(vals);

mixin template WitFlags(T) if (__traits(isUnsigned, T)) {
    private alias F = typeof(this);

    T bits;

    @safe nothrow @nogc pure:

    static typeof(this) opIndex(size_t i)
    in(i < T.sizeof*8) => F(cast(T)(1 << i));

    auto opUnary(string op : "~")() const => F(~bits);

    auto ref opOpAssign(string op)(F rhs)
    if (op == "|" || op == "&" || op == "^")
    {
        mixin("bits "~op~"= rhs.bits;");
        return this;
    }

    auto opBinary(string op)(F flags) const
    if (op == "|" || op == "&" || op == "^")
    {
        F result = this;
        result.opOpAssign!op(flags);
        return result;
    }

    typeof(this) witClone() const { return this; }
}


mixin template WitVariant(Types...) {
private:
    static assert(is(typeof(this).Tag));
    static assert(is(Tag U == enum) && __traits(isIntegral, U));

    static assert(__traits(allMembers, Tag).length == Types.length);
    static foreach (i, M; __traits(allMembers, Tag)) {
        static assert(i == __traits(getMember, Tag, M));
    }

    union Storage {
        template ReplacedTypes() {
            alias ReplacedTypes = AliasSeq!();

            static foreach (T; Types) {
                static if (is(T == void))
                    ReplacedTypes = AliasSeq!(ReplacedTypes, void[0]);
                else
                    ReplacedTypes = AliasSeq!(ReplacedTypes, T);
            }
        }

        ubyte __zeroinit = 0;
        ReplacedTypes!() members;
    }

    Tag _tag;
    Storage _storage;


    @disable this();

    this(Tag tag, inout Storage storage = Storage.init) inout @nogc nothrow @trusted {
      _tag = tag;
      _storage = storage;
    }


    static auto _create(Tag tag)() if (is(Types[tag] == void)) {
        return typeof(this)(tag);
    }
    static auto _create(Tag tag)(inout Types[tag] val) if (!is(Types[tag] == void)) {
        Storage storage = Storage.init;
        storage.tupleof[tag+1] = cast(Types[tag])val;
        return inout typeof(this)(tag, cast(inout(Storage))storage);
    }

    ref auto _get(Tag tag)() inout return if (!is(Types[tag] == void))
    in (_tag == tag) do { return cast(inout)_storage.tupleof[tag+1]; }
}

/// Based on Rust's Option
struct Option(T) {
private:
    bool _present = false;
    T _value;

    this(bool present, inout T value) inout @safe @nogc nothrow {
        _present = present;
        _value = value;
    }
public:
    static inout(Option) makeSome(inout T value) @safe @nogc nothrow {
        return inout Option(true, value);
    }

    static Option makeNone() @safe @nogc nothrow {
        return Option(false, T.init);
    }

    bool isSome() const @safe @nogc nothrow => _present;
    alias isSome this; // implicit conversion to bool

    bool isNone() const @safe @nogc nothrow => !_present;

    ref inout(T) unwrap() inout @trusted @nogc nothrow return
    in (_present) do { return _value; }

    T unwrapOr(T fallback) @trusted @nogc nothrow => _present ? _value : fallback;

    T unwrapOrElse(D)(scope D fallback)
    if (is(D R == return) && is(R : T) && is(D == __parameters))
    { return _present ? _value : fallback(); }

    bool opEquals(in Option rhs) const {
        if (isSome != rhs.isSome) return false;

        if (isSome) return unwrap == rhs.unwrap;
        else return true;
    }

    size_t toHash() const @safe pure nothrow
    {
        if (isSome) return this.unwrap.hashOf(true.hashOf);
        return false.hashOf;
    }
}

auto some(T)(inout T value) @safe @nogc nothrow {
    return Option!T.makeSome(value);
}

auto none(T)() @safe @nogc nothrow {
    return Option!T.makeNone;
}

/// Based on Rust's Result
@mustuse
struct Result(T = void, E = void) {
private:
    bool _hasError;
    union Storage {
        ubyte __zeroinit = 0;
        static if (!is(T == void)) {
            T value;
        }
        static if (!is(E == void)) {
            E error;
        }
    }
    Storage _storage;

    this(bool hasError, inout(Storage) storage) inout @safe @nogc nothrow {
        _hasError = hasError;
        _storage = storage;
    }

public:
    static if (is(T == void)) {
        static Result makeOk() @safe @nogc nothrow => Result(false, Storage.init);
    } else {
        static inout(Result) makeOk(inout(T) value) @trusted @nogc nothrow {
            Storage newStorage = Storage.init;
            newStorage.value = cast(T)value;

            return inout Result(false, cast(inout Storage)newStorage);
        }
    }

    static if (is(E == void)) {
        static Result makeErr() @safe @nogc nothrow => Result(true, Storage.init);
    } else {
        static inout(Result) makeErr(inout(E) error) @trusted @nogc nothrow {
            Storage newStorage = Storage.init;
            newStorage.error = cast(E)error;

            return inout Result(true, cast(inout Storage)newStorage);
        }
    }

    bool isOk() const @safe @nogc nothrow => !_hasError;

    bool isErr() const @safe @nogc nothrow => _hasError;
    alias isErr this; // implicit conversion to bool

    static if (!is(T == void)) {
        ref inout(T) unwrap() inout @trusted @nogc nothrow return
        in (isOk) do { return _storage.value; }

        T unwrapOr(T fallback) @trusted @nogc nothrow => isOk ? _storage.value : fallback;

        T unwrapOrElse(D)(scope D fallback)
        if (is(D R == return) && is(R : T) && is(D == __parameters))
        { return isOk ? _storage.value : fallback(); }
    }

    static if (!is(E == void)) {
        ref inout(E) unwrapErr() inout @trusted @nogc nothrow return
        in (isErr) do { return _storage.error; }
    }

    bool opEquals(in Result rhs) const {
        if (isErr != rhs.isErr) return false;

        if (isErr) {
            static if (!is(E == void)) return unwrapErr == rhs.unwrapErr;
            else return true;
        }

        static if (!is(T == void)) return unwrap == rhs.unwrap;
        else return true;
    }

    size_t toHash() const @safe pure nothrow
    {
        if (isErr) {
            static if (!is(E == void)) return this.unwrapErr.hashOf(true.hashOf);
            return true.hashOf;
        }

        static if (!is(T == void)) return this.unwrap.hashOf(false.hashOf);
        else return false.hashOf;
    }
}

auto ok(E, T)(inout T value) @safe @nogc nothrow {
    return Result!(T, E).makeOk(value);
}
auto ok(E)() @safe @nogc nothrow {
    return Result!(void, E).makeOk();
}

auto err(T, E)(inout E value) @safe @nogc nothrow {
    return Result!(T, E).makeErr(value);
}
auto err(T)() @safe @nogc nothrow {
    return Result!(T, void).makeErr();
}

void witFree(T)(scope ref T val) if (__traits(isArithmetic, T)) {
    // no-op
}
void witDrop(T)(scope ref T val) if (__traits(isArithmetic, T)) {
    // no-op
}
T witClone(T)(in T val) if (__traits(isArithmetic, T)) {
    return val;
}

void witFree(T : Option!U, U)(scope ref T val) {
    static if (!is(U == void)) if (val.isSome) val.unwrap.witFree;
}
void witDrop(T : Option!U, U)(scope ref T val) {
    static if (!is(U == void)) if (val.isSome) val.unwrap.witDrop;
}
T witClone(T : Option!U, U)(in T val) {
    if (val.isSome) {
        static if (!is(U == void)) {
            return T.makeSome(val.unwrap.witClone);
        } else {
            return T.makeSome;
        }
    } else {
        return T.makeNone;
    }
}

void witFree(T : Result!(U, V), U, V)(scope ref T val) {
    if (val.isErr) {
        static if (!is(V == void)) val.unwrapErr.witFree;
    } else {
        static if (!is(U == void)) val.unwrap.witFree;
    }
}
void witDrop(T : Result!(U, V), U, V)(scope ref T val) {
    if (val.isErr) {
        static if (!is(V == void)) val.unwrapErr.witDrop;
    } else {
        static if (!is(U == void)) val.unwrap.witDrop;
    }
}
T witClone(T : Result!(U, V), U, V)(in T val) {
    if (val.isErr) {
        static if (!is(V == void)) {
            return T.makeErr(val.unwrapErr.witClone);
        } else {
            return T.makeErr;
        }
    } else {
        static if (!is(U == void)) {
            return T.makeOk(val.unwrap.witClone);
        } else {
            return T.makeOk;
        }
    }
}

void witFree(T : WitList!U, U)(scope ref T val) {
    foreach (ref e; val) {
        e.witFree;
    }
    if (val.ptr && val.length) free(val.ptr);
    val = null;
}
void witDrop(T : WitList!U, U)(scope ref T val) {
    foreach (ref e; val) {
        e.witDrop;
    }
    val = null;
}
T witClone(T : WitList!U, U)(in T val) @trusted {
    if (val.ptr == null || val.length == 0) return T(null);

    auto clone = mallocSlice!U(val.length);

    foreach (i, ref e; clone) {
        e = val[i].witClone;
    }

    return clone.witList;
}

void witFree(T : Tuple!U, U...)(scope ref T val) {
    static foreach (F; T.tupleof) {
        __traits(child, val, F).witFree;
    }
}
void witDrop(T : Tuple!U, U...)(scope ref T val) {
    static foreach (F; T.tupleof) {
        __traits(child, val, F).witDrop;
    }
}
T witClone(T : Tuple!U, U...)(in T val) {
    T clone = void;
    static foreach (F; T.tupleof) {
        __traits(child, clone, F) = __traits(child, val, F).witClone;
    }
    return clone;
}


void witFree(T, size_t L)(scope ref T[L] val) {
    foreach (ref e; val) {
        e.witFree;
    }
}
void witDrop(T, size_t L)(scope ref T[L] val) {
    foreach (ref e; val) {
        e.witDrop;
    }
}
T[L] witClone(T, size_t L)(in T[L] val) {
    T[L] clone;
    foreach (i, ref e; clone) {
        e = val[i].witClone;
    }
    return clone;
}

package:

extern(C) @nogc nothrow {
    void*    malloc(size_t size);
    void*    realloc(void* ptr, size_t newSize);
    void     free(void* ptr);
    noreturn abort();
}

// from https://github.com/Inochi2D/numem/blob/main/source/numem/casting.d
// Copyright © 2023-2025, Kitsunebi Games
// Copyright © 2023-2025, Inochi2D Project
// License:   $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
// Authors:   Luna Nielsen
pragma(inline, true)
auto ref T reinterpretCast(T, U)(auto ref U from) @trusted if (T.sizeof == U.sizeof) {
    union tmp { U from; T to; }
    return tmp(from).to;
}

T[] mallocSlice(T)(size_t count) @nogc nothrow {
    if (count == 0) return [];
    auto ptr = malloc(count*T.sizeof);
    if (ptr is null) return [];

    return (cast(T*)ptr)[0..count];
}

// from std.meta
alias AliasSeq(T...) = T;


template findWitExportFunc(string mod, string name, Sig, bool implicitSelf, Impl...) {
    static foreach(Func; Impl) {
        static foreach(uda; __traits(getAttributes, Func)) {
            static if (!is(uda) && is(typeof(uda) == witExport) && uda == witExport(mod, name)) {
                static assert(
                    !is(Func) &&
                    (is(typeof(Func) == function)),
                    "The implementation of '", mod, "#", name, "' ",
                    "`", __traits(fullyQualifiedName, findWitExportFunc), "` ",
                    "must be a function or method."
                );

                static assert(
                    !is(typeof(findWitExportFunc) == void) || __traits(isSame, findWitExportFunc, Func),
                    "There must be only one implementation of '", mod, "#", name, "'. ",
                    "Found at least `", __traits(fullyQualifiedName, findWitExportFunc),
                    "` and `", __traits(fullyQualifiedName, Func), "`."
                );
                alias findWitExportFunc = Func;
            }
        }
    }

    static assert(
        !is(typeof(findWitExportFunc) == void),
        "Could not find implementation for '", mod, "#", name, "'"
    );

    static assert(
        is(typeof(&findWitExportFunc) : Sig) && __traits(isStaticFunction, findWitExportFunc) != implicitSelf,
        "The implementation of '", mod, "#", name, "' ",
        "`", __traits(fullyQualifiedName, findWitExportFunc), "` ",
        "must conform to the necessary signature. ",
        "Found `", typeof(&findWitExportFunc), "`",
        ", but expected `", Sig, "`"
    );
}

template findWitExportResource(string mod, string name, Impl...) {
    static foreach(Resource; Impl) {
        static foreach(uda; __traits(getAttributes, Resource)) {
            static if (!is(uda) && is(typeof(uda) == witExport) && uda == witExport(mod, name)) {
                static assert(
                    is(Resource == struct),
                    "The implementation of '", mod, "#", name, "' ",
                    "`", __traits(fullyQualifiedName, findWitExportResource), "` ",
                    "must be a struct."
                );

                static assert(
                    !is(typeof(findWitExportResource) == void) || __traits(isSame, findWitExportResource, Resource),
                    "There must be only one implementation of '", mod, "#", name, "'. ",
                    "Found at least `", __traits(fullyQualifiedName, findWitExportResource),
                    "` and `", __traits(fullyQualifiedName, Resource), "`."
                );
                alias findWitExportResource = Resource;
            }
        }
    }

    static assert(
        !is(typeof(findWitExportResource) == void),
        "Could not find implementation for '", mod, "#", name, "'"
    );
}


template witExportsIn(T) {
    alias witExportsIn = AliasSeq!();

    static foreach(M; __traits(allMembers, T)) {
        static foreach(Export; __traits(getOverloads, T, M)) {
            static foreach(uda; __traits(getAttributes, Export)) {
                static if (!is(uda) && is(typeof(uda) == witExport)) {
                    witExportsIn = AliasSeq!(witExportsIn, Export);
                }
            }
        }
    }
}

struct DeallocateBuffer {
    @nogc nothrow:
    struct Page {
        void*[32] slots;
        static assert(slots.length < 256);

        ubyte cursor;
        Page* next;
    }

    Page first;
    Page* head;

    @disable this(this);

    private void allocNewPage() {
        Page* page = cast(Page*)malloc(Page.sizeof);
        if (page is null) abort();

        *page = Page.init;
        page.next = head;
        head = page;
    }

    void opOpAssign(string op: "~")(void* ptr) {
        import core.builtins : unlikely;

        if (unlikely(ptr is null)) return;
        if (/*unlikely?*/(head is null)) head = &first;

        if (head.cursor >= head.slots.length) allocNewPage();

        head.slots[head.cursor++] = ptr;
    }

    void purge() {
        auto page = head;
        while (page) {
            foreach (ptr; page.slots[0..page.cursor]) free(ptr);

            auto next = page.next;
            if (page != &first) free(page);
            page = next;
        }

        first = Page.init;
        head = null;
    }

    ~this() {
        purge();
    }
}

version (CRuntime_WASI) {
    version (WASIp1) {}
    else version = LibcDefinesCABIRealloc;
}

version (LibcDefinesCABIRealloc) {}
else
@wasmExport!("cabi_realloc")
void* cabi_realloc(void *ptr, size_t oldSize, size_t alignment, size_t newSize) {
    if (newSize == 0) return cast(void*)alignment;
    void *ret = realloc(ptr, newSize);
    if (!ret) abort();
    return ret;
}