zig¶
The Zig target, zig, generates a module binding the API, into
<output>/zig:
<prefix>.zigThe bindings, in two layers.
<prefix>_check.zigThe check, not part of the API: it asserts at compile time that every record has the size, alignment and field offsets recorded in the IR, then prints a zeroed instance of every record, as YAML or JSON.
<prefix>_compile.zigWhat has all of the module compiled, as Zig compiles only what is referenced.
<prefix>_signatures.zigThe check of the signatures, not part of the API: it imports the headers the IR was parsed from, by Zig’s own translation of C, and asserts at compile time that each extern function of the bindings takes and returns what the header’s does, as the C ABI sees it: as many parameters, and each one, and the return, of the same class, pointer, float or other, size and alignment, field by field for a record passed by value. A function the headers do not declare fails.
The module needs Zig 0.16, as Zig’s standard library changes between releases,
and libc, as the C API does. yace compiles all of the module, with
$ZIG, by default zig, then builds and runs the check, and parses what it
printed, as YAML and as JSON. As for the C API, the layout is asserted only on
the platform it was recorded on.
The check of the signatures is compiled with the include directories, as for the C API, and where a header is not found, yace warns that the signatures are not checked. It warns the same where Zig cannot import the headers, as where a header asserts the size of a record of bit-fields, which Zig translates as opaque.
The raw layer¶
The raw layer is the C API as C has it, by its C names, as Zig’s own
translation of C headers gives it: records as extern struct and
extern union, named in CamelCase, struct foo_point as FooPoint,
which typedef struct foo_point foo_point; also names; a packed record with
each field align(1); opaque records as opaque; functions as
extern fn; pointers as C pointers, [*c]T, except to opaque types,
void and functions, which are optional pointers; constants by their names.
Each enum is a non-exhaustive enum, as C does not restrict an enum to its
values, its members in lower case without the prefix of the enum, with
cName() the C name of a value; the members are also constants by their C
names.
Every struct and union has the pretty-printers: fpr(w, obj, flags),
printing to a *std.Io.Writer as the C API’s <name>_fpr() does, and
format(), for "{f}", printing YAML. Floats are formatted by libc’s
snprintf(): Zig rounds a float from its shortest decimal form, C from its
binary one, and the two differ.
Each part of a field of bits, see The C Subset, has a getter and a
setter, codeType() and setCodeType(value), taking and giving an
integer of the part’s own width, such as u3, so a value that does not fit
is a compile error, or a checked cast, rather than one written into the bits
beside it. The field itself is there as before. A name the struct has already,
as a field or a printer, gets a trailing underscore.
The idiomatic layer¶
The idiomatic layer is built over the raw one, from what the header says
beyond C, see The C Subset, and as derived in
yace.targets.idiom. Its functions are named in camelCase, without
the prefix:
- Handles
An opaque record is a struct holding the pointer, named without the prefix:
struct foo_handleisHandle. Its constructor is a function of it,Handle.open(), returning an optional where it has no@errno; its destructor a method, also asdeinit, fordefer handle.deinit(), unless a method has that name; the functions taking it first are its methods. A handle given otherwise is its struct.- Buffers
A buffer that
<stem>_allocallocates, see the buffer pattern in The C Subset, is returned as aBuffer, an optional where@nullable, and otherwiseerror.OutOfMemorywhere C returned NULL:dev.bufAlloc(4096).ptrandlenare its address and size in bytes, andrealloc(nbytes)resizes it with<stem>_realloc.deinit(), fordefer buf.deinit(), frees it with<stem>_free; neither has a name of its own in the module. Zig has no closures, so theBufferkeeps the pointer of the handle it was allocated with, which must outlive it, and the pattern is bound so only where<stem>_freetakes no other argument than one handle. The memory may be a device’s, such as GPU memory, which the CPU cannot read, and nothing in the API says which;slice()is for memory of the host only. The struct isBuffer_where the module has the nameBuffer.- Registrations
Memory that
<stem>_registerregisters, see the registration pattern in The C Subset, is given as a[]u8, whose length is the size:dev.bufRegister(&memory). The function returns aRegistration, whosememoryis the slice.unregister()unregisters the memory with<stem>_unregister, which has no name of its own in the module, anddeinit()does so without the error. The memory, and the handle it was registered with, must outlive it. The struct isRegistration_where the module has the nameRegistration.- Errors
A function documented
@errnoreturns an error union, the error that of the errno’s name:-EINVALiserror.INVAL.errnoOf()is the errno of such an error. One returningintreturnsvoidotherwise; one returning another integer, such as a count, ausize.- Results
What a function writes through an
[out]pointer is returned rather than passed. An[out]array is written to a slice the caller gives, as Zig does not allocate behind a caller’s back, and the part written is returned. A returned string is a[:0]const u8, borrowed; a returned pointer to a record a copy of it, optional where@nullable.- Arguments
A string is a
[*:0]const u8, optional where@nullable; a string with a length, which C reads as bytes rather than to a NUL, is a[]const u8, and the length is that of the slice. An array read through a pointer is a slice; slices sharing one length must be as long, or the call panics; a@nullableone is optional,nullpassing NULL. Avoid *@arrparamis a slice ofu8. The size of a@recparamrecord is not given; the layer passes@sizeOfof the record’s type. A pointer to a record or value is a pointer to one, optional where@nullable. A callback is a context pointer and a comptime function taking it, called through a generated trampoline with thevoid *; the caller keeps the context as long as the callback’s@lifetimesays (see Callback lifetimes), which its documentation repeats. One that is@nullableis not optional here, the raw function passing NULL.
A function named as a declaration of the module, such as std, as a
parameter of its own functions, such as flags, or as a primitive type, such
as u8, gets the suffix _. A parameter that would shadow a declaration, a
local or a primitive type, which Zig does not allow, that is named _, or
that ends in _arg and underscores, gets the suffix _arg, and _ until
it shadows nothing. A local of the module’s own code, such as ret or w,
gets _ while the C API declares its name, as an enumerator may. A name that
is a keyword is quoted, @"type".
Example¶
yace output/foo.yaml --emit zig --output output
output/zig
├── check.json
├── check.yaml
├── foo.zig
├── foo_check
├── foo_check.zig
├── foo_compile.zig
├── foo_signatures.zig
├── signatures.log
└── zig.log
1 directory, 9 files
The fixture library is called through the idiomatic layer, and the raw one for
what the idiomatic one does not take, by
examples/libfoo/checks/zig/check.zig:
//! The check of the Zig bindings of libfoo: calls the library through the
//! idiomatic layer, its handle, errors and returned values, and prints what it
//! got back, as YAML documents, or with argument "json" as JSON objects, each
//! holding what 'expected.yaml' says. An error is printed as the negative errno
//! the C function returned; what the layer does not take, a NULL where none is
//! allowed, is called raw.
const std = @import("std");
const foo = @import("foo");
const Writer = std.Io.Writer;
var as_json = false;
const Field = struct { []const u8, Value };
const Value = union(enum) {
int: i64,
str: []const u8,
names: []const []const u8,
fn write(self: Value, w: *Writer) Writer.Error!void {
switch (self) {
.int => |v| try w.print("{d}", .{v}),
.str => |s| try w.print("\"{s}\"", .{s}),
.names => |list| {
try w.writeAll("[");
for (list, 0..) |name, idx| {
if (idx > 0) try w.writeAll(", ");
try w.print("\"{s}\"", .{name});
}
try w.writeAll("]");
},
}
}
};
fn document(w: *Writer, name: []const u8, fields: []const Field) Writer.Error!void {
if (as_json) {
try w.print("{{\"{s}\": {{", .{name});
for (fields, 0..) |field, idx| {
if (idx > 0) try w.writeAll(", ");
try w.print("\"{s}\": ", .{field[0]});
try field[1].write(w);
}
return w.writeAll("}}\n");
}
try w.print("---\n{s}:\n", .{name});
for (fields) |field| {
try w.print(" {s}: ", .{field[0]});
try field[1].write(w);
try w.writeAll("\n");
}
}
/// Print a record, or none, with the pretty-printer generated for it
fn record(w: *Writer, comptime T: type, name: []const u8, obj: ?T) Writer.Error!void {
const flags = if (as_json) foo.FOO_PR_JSON else foo.FOO_PR_YAML;
if (as_json) {
try w.print("{{\"{s}\": ", .{name});
try T.fpr(w, if (obj) |*o| o else null, flags);
return w.writeAll("}\n");
}
try w.writeAll("---\n");
try T.fpr(w, if (obj) |*o| o else null, flags);
}
/// The value, 0 for void, or the negative errno of the error
fn errno(result: anytype) i64 {
if (result) |value| {
return switch (@typeInfo(@TypeOf(value))) {
.int, .comptime_int => @intCast(value),
else => 0,
};
} else |err| {
return -@as(i64, foo.errnoOf(err));
}
}
fn names(comptime E: type, comptime values: []const c_int) [values.len][]const u8 {
var found: [values.len][]const u8 = undefined;
for (values, 0..) |value, idx| {
const e: E = @enumFromInt(value);
found[idx] = e.cName() orelse "UNKNOWN";
}
return found;
}
const Sum = struct {
x: i64 = 0,
y: i64 = 0,
visited: usize = 0,
stop_after: usize = 0,
fn visit(self: *Sum, point: *const foo.FooPoint) c_int {
self.x += point.x;
self.y += point.y;
self.visited += 1;
return @intFromBool(self.visited == self.stop_after);
}
};
const Watched = struct {
count: usize = 0,
x: i64 = 0,
fn added(self: *Watched, point: *const foo.FooPoint) void {
self.count += 1;
self.x += point.x;
}
};
const Done = struct {
count: usize = 0,
fn set(self: *Done, count: usize) void {
self.count = count;
}
};
fn addX(arg: ?*anyopaque, point: [*c]const foo.FooPoint) callconv(.c) c_int {
const sum: *i64 = @ptrCast(@alignCast(arg));
sum.* += point[0].x;
return 0;
}
pub fn main(init: std.process.Init) !void {
var buf: [4096]u8 = undefined;
var stdout = std.Io.File.stdout().writer(init.io, &buf);
const w = &stdout.interface;
var args = init.minimal.args.iterate();
_ = args.next();
as_json = if (args.next()) |arg| std.mem.eql(u8, arg, "json") else false;
try document(w, "defines", &.{
.{ "FOO_NAME", .{ .str = foo.FOO_NAME } },
.{ "FOO_MAGIC", .{ .int = foo.FOO_MAGIC } },
.{ "FOO_VERSION_MAJOR", .{ .int = foo.FOO_VERSION_MAJOR } },
.{ "FOO_VERSION_MINOR", .{ .int = foo.FOO_VERSION_MINOR } },
.{ "FOO_VERSION_PATCH", .{ .int = foo.FOO_VERSION_PATCH } },
.{ "FOO_POINTS_MAX", .{ .int = foo.FOO_POINTS_MAX } },
.{ "FOO_DEFAULT_SHAPE_SIDES", .{ .int = foo.FOO_DEFAULT_SHAPE_SIDES } },
});
const shapes = names(foo.FooShape, &.{ -1, 0, 1, 2, 3 });
const options = names(foo.FooOption, &.{ 1, 2, 3 });
try document(w, "enums", &.{
.{ "foo_shape", .{ .names = &shapes } },
.{ "foo_option", .{ .names = &options } },
});
const points = [_]foo.FooPoint{ .{ .x = 1, .y = 2 }, .{ .x = 3, .y = 4 }, .{ .x = 5, .y = 6 } };
var handle = try foo.Handle.open("points");
defer handle.deinit();
var unopened: ?*foo.FooHandle = null;
const open_without_name = foo.foo_open(null, &unopened);
var watched = Watched{};
const watch = errno(handle.pointWatch(&watched, Watched.added));
var busy = Watched{};
const watch_busy = errno(handle.pointWatch(&busy, Watched.added));
var added: i64 = 0;
for (&points) |*point| added += @intFromBool(errno(handle.pointAdd(point)) == 0);
const count = handle.pointCount();
var every = Sum{};
const visit = errno(handle.pointVisit(&every, Sum.visit));
var first_two = Sum{ .stop_after = 2 };
const stopped = errno(handle.pointVisit(&first_two, Sum.visit));
const without = foo.foo_point_visit(handle.ptr, null, null);
var with_x: i64 = 0;
const visitor = foo.FooVisitor{ .visit = &addX, .arg = &with_x };
const visit_with = errno(handle.pointVisitWith(&visitor));
const unknown = errno(foo.figureFill(3));
const add_many = errno(handle.pointAddMany(&points));
const count_after = handle.pointCount();
const watched_after = watched;
var copied_buf: [4]foo.FooPoint = undefined;
const copied = try handle.pointCopy(&copied_buf);
var copied_x: i64 = 0;
for (copied) |p| copied_x += p.x;
var done = Done{};
const submit = errno(handle.countSubmit(&done, Done.set));
const submit_busy = errno(handle.countSubmit(&done, Done.set));
const complete = handle.countComplete();
const complete_again = handle.countComplete();
try document(w, "calls", &.{
.{ "version", .{ .str = foo.version() } },
.{ "open", .{ .int = 0 } },
.{ "open_without_name", .{ .int = open_without_name } },
.{ "name", .{ .str = handle.name() } },
.{ "watch", .{ .int = watch } },
.{ "watch_busy", .{ .int = watch_busy } },
.{ "added", .{ .int = added } },
.{ "count", .{ .int = @intCast(count) } },
.{ "visit", .{ .int = visit } },
.{ "visit_sum_x", .{ .int = every.x } },
.{ "visit_sum_y", .{ .int = every.y } },
.{ "visit_stopped", .{ .int = stopped } },
.{ "visit_without_callback", .{ .int = without } },
.{ "visit_with", .{ .int = visit_with } },
.{ "visit_with_sum_x", .{ .int = with_x } },
.{ "figure_of_unknown_shape", .{ .int = unknown } },
.{ "add_many", .{ .int = add_many } },
.{ "count_after_add_many", .{ .int = @intCast(count_after) } },
.{ "watched", .{ .int = @intCast(watched_after.count) } },
.{ "watched_sum_x", .{ .int = watched_after.x } },
.{ "points_copied", .{ .int = @intCast(copied.len) } },
.{ "points_sum_x", .{ .int = copied_x } },
.{ "submit", .{ .int = submit } },
.{ "submit_busy", .{ .int = submit_busy } },
.{ "complete", .{ .int = @intCast(complete) } },
.{ "done_count", .{ .int = @intCast(done.count) } },
.{ "complete_again", .{ .int = @intCast(complete_again) } },
});
try record(w, foo.FooPoint, "foo_point", handle.pointGet(1));
try record(w, foo.FooPoint, "foo_point", handle.pointGet(6));
while (errno(handle.pointAdd(&points[0])) == 0) {}
try document(w, "full", &.{
.{ "count", .{ .int = @intCast(handle.pointCount()) } },
.{ "add", .{ .int = errno(handle.pointAdd(&points[0])) } },
.{ "add_many", .{ .int = errno(handle.pointAddMany(points[0..1])) } },
.{ "watched", .{ .int = @intCast(watched.count) } },
});
const status = handle.statusGet();
try record(w, foo.FooStatus, "foo_status", status);
try document(w, "status", &.{
.{ "pending", .{ .int = status.codePending() } },
.{ "points", .{ .int = status.codePoints() } },
.{ "full", .{ .int = status.codeFull() } },
});
var made = foo.FooStatus{ .code = 0, .max = foo.FOO_POINTS_MAX };
made.setCodePoints(5);
made.setCodePending(1);
try record(w, foo.FooStatus, "foo_status", made);
try record(w, foo.FooScalars, "foo_scalars", foo.scalarsFill());
for ([_]foo.FooShape{ .point, .line, .polygon }) |shape| {
const figure = try foo.figureFill(@intCast(@intFromEnum(shape)));
try record(w, foo.FooFigure, "foo_figure", figure);
}
try record(w, foo.FooValue, "foo_value", foo.valueSet(-1));
try record(w, foo.FooWire, "foo_wire", foo.wireFill());
try w.flush();
}
Bindings¶
//! libfoo: An example library described in the C subset of yace
//!
//! Zig bindings generated by yace from foo.h; do not
//! edit. The raw layer declares the C API as C has it, with C names; the
//! idiomatic layer, after it, is what the header says beyond C. Every struct
//! and union with fields, but for one with bit-fields, prints itself as the C
//! API's pretty-printers do. Needs Zig 0.16.
//!
//! SPDX-License-Identifier: GPL-2.0-only
const std = @import("std");
/// Output formats of the pretty-printers: the default, YAML
pub const FOO_PR_DEF: c_int = 0x0;
/// YAML
pub const FOO_PR_YAML: c_int = 0x1;
/// Terse; the generated printers print YAML
pub const FOO_PR_TERSE: c_int = 0x2;
/// JSON, on one line
pub const FOO_PR_JSON: c_int = 0x4;
// Its names are qualified, as a declaration of the C API may share them
const yace_pp = struct {
fn strn(w: *std.Io.Writer, chars: []const u8) std.Io.Writer.Error!void {
try w.writeAll("\"");
for (chars) |chr| {
if (chr == 0) break;
switch (chr) {
'"', '\\' => {
try w.writeByte('\\');
try w.writeByte(chr);
},
0x01...0x1f, 0x7f => try w.print("\\u{x:0>4}", .{chr}),
else => try w.writeByte(chr),
}
}
try w.writeAll("\"");
}
fn str(w: *std.Io.Writer, chars: [*c]const u8) std.Io.Writer.Error!void {
if (chars == null) return w.writeAll("null");
return yace_pp.strn(w, std.mem.span(@as([*:0]const u8, @ptrCast(chars))));
}
fn ptr(w: *std.Io.Writer, addr: usize) std.Io.Writer.Error!void {
if (addr == 0) return w.writeAll("null");
return w.print("\"0x{x}\"", .{addr});
}
extern fn snprintf(buf: [*]u8, len: usize, fmt: [*:0]const u8, ...) c_int;
/// 'value' as C's printf() prints it with "%g", through C's snprintf(), as
/// Zig rounds a value from its shortest decimal form, C from its binary one
fn g(w: *std.Io.Writer, value: f64) std.Io.Writer.Error!void {
var buf: [64]u8 = undefined;
const len = yace_pp.snprintf(&buf, buf.len, "%g", value);
return w.writeAll(buf[0..@intCast(len)]);
}
};
/// Name of the library
pub const FOO_NAME = "foo";
/// A hexadecimal constant
pub const FOO_MAGIC = 0xacdc;
/// Major version
pub const FOO_VERSION_MAJOR = 1;
/// Minor version
pub const FOO_VERSION_MINOR = 2;
/// Patch version
pub const FOO_VERSION_PATCH = 3;
/// Points a handle holds at most
pub const FOO_POINTS_MAX = 8;
/// A constant, by name
pub const FOO_DEFAULT_SHAPE_SIDES = 8;
/// A count is submitted and not yet completed; bit 0 of 'code'
pub const FOO_STATUS_CODE_PENDING = 0x1;
/// Points held; bits 11:4 of 'code'
pub const FOO_STATUS_CODE_POINTS = 0xff0;
/// The handle holds FOO_POINTS_MAX points; bit 15 of 'code'
pub const FOO_STATUS_CODE_FULL = 0x8000;
/// Kinds of figure
///
/// Non-exhaustive, as C does not restrict an enum to the values it names.
pub const FooShape = enum(c_int) {
/// No figure
none = -1,
/// A single point
point = 0,
/// Two points
line = 1,
/// Three points or more
polygon = 2,
_,
/// The C name of the value, null when it is none of those named
pub fn cName(self: @This()) ?[]const u8 {
return switch (self) {
.none => "FOO_SHAPE_NONE",
.point => "FOO_SHAPE_POINT",
.line => "FOO_SHAPE_LINE",
.polygon => "FOO_SHAPE_POLYGON",
_ => null,
};
}
};
pub const FOO_SHAPE_NONE: c_int = -1;
pub const FOO_SHAPE_POINT: c_int = 0;
pub const FOO_SHAPE_LINE: c_int = 1;
pub const FOO_SHAPE_POLYGON: c_int = 2;
/// Options of a figure, combined as bits
///
/// Non-exhaustive, as C does not restrict an enum to the values it names.
pub const FooOption = enum(c_uint) {
/// The last corner connects to the first
closed = 1,
/// The inside is filled
filled = 2,
_,
/// The C name of the value, null when it is none of those named
pub fn cName(self: @This()) ?[]const u8 {
return switch (self) {
.closed => "FOO_OPTION_CLOSED",
.filled => "FOO_OPTION_FILLED",
_ => null,
};
}
};
pub const FOO_OPTION_CLOSED: c_uint = 1;
pub const FOO_OPTION_FILLED: c_uint = 2;
/// A collection of points, opened with foo_open() and closed with foo_close()
pub const FooHandle = opaque {};
/// A point on the plane
pub const FooPoint = extern struct {
/// Horizontal position
x: i32,
/// Vertical position
y: i32,
fn json(self: @This(), w: *std.Io.Writer) std.Io.Writer.Error!void {
try w.writeAll("{");
try w.writeAll("\"x\": ");
try w.print("{d}", .{self.x});
try w.writeAll(", \"y\": ");
try w.print("{d}", .{self.y});
try w.writeAll("}");
}
fn yaml(self: @This(), w: *std.Io.Writer, indent: usize) std.Io.Writer.Error!void {
try w.splatByteAll(' ', indent);
try w.writeAll("x: ");
try w.print("{d}", .{self.x});
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("y: ");
try w.print("{d}", .{self.y});
try w.writeAll("\n");
}
/// Print 'obj', or null, as YAML, or as JSON on one line, as foo_point_fpr()
pub fn fpr(w: *std.Io.Writer, obj: ?*const @This(), flags: c_int) std.Io.Writer.Error!void {
if (flags & FOO_PR_JSON != 0) {
if (obj) |o| try o.json(w) else try w.writeAll("null");
return w.writeAll("\n");
}
if (obj) |o| {
try w.writeAll("foo_point:\n");
return o.yaml(w, 2);
}
return w.writeAll("foo_point: ~\n");
}
/// The YAML, for "{f}"
pub fn format(self: @This(), w: *std.Io.Writer) std.Io.Writer.Error!void {
return @This().fpr(w, &self, FOO_PR_YAML);
}
};
/// A callback and its argument
pub const FooVisitor = extern struct {
/// Called for each point
visit: FooVisitCb,
/// Given to 'visit'
arg: ?*anyopaque,
fn json(self: @This(), w: *std.Io.Writer) std.Io.Writer.Error!void {
try w.writeAll("{");
try w.writeAll("\"visit\": ");
try yace_pp.ptr(w, if (self.visit) |p| @intFromPtr(p) else 0);
try w.writeAll(", \"arg\": ");
try yace_pp.ptr(w, if (self.arg) |p| @intFromPtr(p) else 0);
try w.writeAll("}");
}
fn yaml(self: @This(), w: *std.Io.Writer, indent: usize) std.Io.Writer.Error!void {
try w.splatByteAll(' ', indent);
try w.writeAll("visit: ");
try yace_pp.ptr(w, if (self.visit) |p| @intFromPtr(p) else 0);
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("arg: ");
try yace_pp.ptr(w, if (self.arg) |p| @intFromPtr(p) else 0);
try w.writeAll("\n");
}
/// Print 'obj', or null, as YAML, or as JSON on one line, as foo_visitor_fpr()
pub fn fpr(w: *std.Io.Writer, obj: ?*const @This(), flags: c_int) std.Io.Writer.Error!void {
if (flags & FOO_PR_JSON != 0) {
if (obj) |o| try o.json(w) else try w.writeAll("null");
return w.writeAll("\n");
}
if (obj) |o| {
try w.writeAll("foo_visitor:\n");
return o.yaml(w, 2);
}
return w.writeAll("foo_visitor: ~\n");
}
/// The YAML, for "{f}"
pub fn format(self: @This(), w: *std.Io.Writer) std.Io.Writer.Error!void {
return @This().fpr(w, &self, FOO_PR_YAML);
}
};
/// A value of every kind of scalar
pub const FooScalars = extern struct {
/// bool
flag: bool,
/// char
letter: u8,
/// signed char
schar: i8,
/// unsigned char
uchar: u8,
/// short
s: c_short,
/// unsigned short
us: c_ushort,
/// int
i: c_int,
/// unsigned int
ui: c_uint,
/// long
l: c_long,
/// unsigned long
ul: c_ulong,
/// long long
ll: c_longlong,
/// unsigned long long
ull: c_ulonglong,
/// float
f: f32,
/// double
d: f64,
/// int8_t
i8: i8,
/// int16_t
i16: i16,
/// int32_t
i32: i32,
/// int64_t
i64: i64,
/// uint8_t
u8: u8,
/// uint16_t
u16: u16,
/// uint32_t
u32: u32,
/// uint64_t
u64: u64,
/// intptr_t
iptr: isize,
/// uintptr_t
uptr: usize,
/// size_t
size: usize,
/// ssize_t
ssize: isize,
/// ptrdiff_t
diff: isize,
fn json(self: @This(), w: *std.Io.Writer) std.Io.Writer.Error!void {
try w.writeAll("{");
try w.writeAll("\"flag\": ");
try w.writeAll(if (self.flag) "true" else "false");
try w.writeAll(", \"letter\": ");
try w.print("{d}", .{self.letter});
try w.writeAll(", \"schar\": ");
try w.print("{d}", .{self.schar});
try w.writeAll(", \"uchar\": ");
try w.print("{d}", .{self.uchar});
try w.writeAll(", \"s\": ");
try w.print("{d}", .{self.s});
try w.writeAll(", \"us\": ");
try w.print("{d}", .{self.us});
try w.writeAll(", \"i\": ");
try w.print("{d}", .{self.i});
try w.writeAll(", \"ui\": ");
try w.print("{d}", .{self.ui});
try w.writeAll(", \"l\": ");
try w.print("{d}", .{self.l});
try w.writeAll(", \"ul\": ");
try w.print("{d}", .{self.ul});
try w.writeAll(", \"ll\": ");
try w.print("{d}", .{self.ll});
try w.writeAll(", \"ull\": ");
try w.print("{d}", .{self.ull});
try w.writeAll(", \"f\": ");
try yace_pp.g(w, self.f);
try w.writeAll(", \"d\": ");
try yace_pp.g(w, self.d);
try w.writeAll(", \"i8\": ");
try w.print("{d}", .{self.i8});
try w.writeAll(", \"i16\": ");
try w.print("{d}", .{self.i16});
try w.writeAll(", \"i32\": ");
try w.print("{d}", .{self.i32});
try w.writeAll(", \"i64\": ");
try w.print("{d}", .{self.i64});
try w.writeAll(", \"u8\": ");
try w.print("{d}", .{self.u8});
try w.writeAll(", \"u16\": ");
try w.print("{d}", .{self.u16});
try w.writeAll(", \"u32\": ");
try w.print("{d}", .{self.u32});
try w.writeAll(", \"u64\": ");
try w.print("{d}", .{self.u64});
try w.writeAll(", \"iptr\": ");
try w.print("{d}", .{self.iptr});
try w.writeAll(", \"uptr\": ");
try w.print("{d}", .{self.uptr});
try w.writeAll(", \"size\": ");
try w.print("{d}", .{self.size});
try w.writeAll(", \"ssize\": ");
try w.print("{d}", .{self.ssize});
try w.writeAll(", \"diff\": ");
try w.print("{d}", .{self.diff});
try w.writeAll("}");
}
fn yaml(self: @This(), w: *std.Io.Writer, indent: usize) std.Io.Writer.Error!void {
try w.splatByteAll(' ', indent);
try w.writeAll("flag: ");
try w.writeAll(if (self.flag) "true" else "false");
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("letter: ");
try w.print("{d}", .{self.letter});
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("schar: ");
try w.print("{d}", .{self.schar});
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("uchar: ");
try w.print("{d}", .{self.uchar});
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("s: ");
try w.print("{d}", .{self.s});
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("us: ");
try w.print("{d}", .{self.us});
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("i: ");
try w.print("{d}", .{self.i});
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("ui: ");
try w.print("{d}", .{self.ui});
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("l: ");
try w.print("{d}", .{self.l});
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("ul: ");
try w.print("{d}", .{self.ul});
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("ll: ");
try w.print("{d}", .{self.ll});
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("ull: ");
try w.print("{d}", .{self.ull});
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("f: ");
try yace_pp.g(w, self.f);
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("d: ");
try yace_pp.g(w, self.d);
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("i8: ");
try w.print("{d}", .{self.i8});
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("i16: ");
try w.print("{d}", .{self.i16});
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("i32: ");
try w.print("{d}", .{self.i32});
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("i64: ");
try w.print("{d}", .{self.i64});
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("u8: ");
try w.print("{d}", .{self.u8});
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("u16: ");
try w.print("{d}", .{self.u16});
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("u32: ");
try w.print("{d}", .{self.u32});
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("u64: ");
try w.print("{d}", .{self.u64});
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("iptr: ");
try w.print("{d}", .{self.iptr});
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("uptr: ");
try w.print("{d}", .{self.uptr});
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("size: ");
try w.print("{d}", .{self.size});
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("ssize: ");
try w.print("{d}", .{self.ssize});
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("diff: ");
try w.print("{d}", .{self.diff});
try w.writeAll("\n");
}
/// Print 'obj', or null, as YAML, or as JSON on one line, as foo_scalars_fpr()
pub fn fpr(w: *std.Io.Writer, obj: ?*const @This(), flags: c_int) std.Io.Writer.Error!void {
if (flags & FOO_PR_JSON != 0) {
if (obj) |o| try o.json(w) else try w.writeAll("null");
return w.writeAll("\n");
}
if (obj) |o| {
try w.writeAll("foo_scalars:\n");
return o.yaml(w, 2);
}
return w.writeAll("foo_scalars: ~\n");
}
/// The YAML, for "{f}"
pub fn format(self: @This(), w: *std.Io.Writer) std.Io.Writer.Error!void {
return @This().fpr(w, &self, FOO_PR_YAML);
}
};
/// A figure: its kind, where it is, and its corners
pub const FooFigure = extern struct {
/// One of enum foo_shape
shape: u32,
/// Bits of enum foo_option
options: u32,
/// Where the figure is
origin: FooPoint,
/// The corners, relative to 'origin'
corners: [4]FooPoint,
/// How many of 'corners' are used
ncorners: u8,
/// Name of the figure
name: [16]u8,
/// A two-dimensional array
grid: [2][3]i16,
/// A string, NULL when there is none
label: [*c]const u8,
/// Scale of the figure
scale: f32,
/// Area of the figure
area: f64,
fn json(self: @This(), w: *std.Io.Writer) std.Io.Writer.Error!void {
try w.writeAll("{");
try w.writeAll("\"shape\": ");
try w.print("{d}", .{self.shape});
try w.writeAll(", \"options\": ");
try w.print("{d}", .{self.options});
try w.writeAll(", \"origin\": ");
try self.origin.json(w);
try w.writeAll(", \"corners\": ");
try w.writeAll("[");
for (self.corners, 0..) |item0, idx0| {
if (idx0 > 0) try w.writeAll(", ");
try item0.json(w);
}
try w.writeAll("]");
try w.writeAll(", \"ncorners\": ");
try w.print("{d}", .{self.ncorners});
try w.writeAll(", \"name\": ");
try yace_pp.strn(w, &self.name);
try w.writeAll(", \"grid\": ");
try w.writeAll("[");
for (self.grid, 0..) |item0, idx0| {
if (idx0 > 0) try w.writeAll(", ");
try w.writeAll("[");
for (item0, 0..) |item1, idx1| {
if (idx1 > 0) try w.writeAll(", ");
try w.print("{d}", .{item1});
}
try w.writeAll("]");
}
try w.writeAll("]");
try w.writeAll(", \"label\": ");
try yace_pp.str(w, self.label);
try w.writeAll(", \"scale\": ");
try yace_pp.g(w, self.scale);
try w.writeAll(", \"area\": ");
try yace_pp.g(w, self.area);
try w.writeAll("}");
}
fn yaml(self: @This(), w: *std.Io.Writer, indent: usize) std.Io.Writer.Error!void {
try w.splatByteAll(' ', indent);
try w.writeAll("shape: ");
try w.print("{d}", .{self.shape});
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("options: ");
try w.print("{d}", .{self.options});
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("origin:\n");
try self.origin.yaml(w, indent + 2);
try w.splatByteAll(' ', indent);
try w.writeAll("corners: ");
try w.writeAll("[");
for (self.corners, 0..) |item0, idx0| {
if (idx0 > 0) try w.writeAll(", ");
try item0.json(w);
}
try w.writeAll("]");
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("ncorners: ");
try w.print("{d}", .{self.ncorners});
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("name: ");
try yace_pp.strn(w, &self.name);
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("grid: ");
try w.writeAll("[");
for (self.grid, 0..) |item0, idx0| {
if (idx0 > 0) try w.writeAll(", ");
try w.writeAll("[");
for (item0, 0..) |item1, idx1| {
if (idx1 > 0) try w.writeAll(", ");
try w.print("{d}", .{item1});
}
try w.writeAll("]");
}
try w.writeAll("]");
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("label: ");
try yace_pp.str(w, self.label);
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("scale: ");
try yace_pp.g(w, self.scale);
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("area: ");
try yace_pp.g(w, self.area);
try w.writeAll("\n");
}
/// Print 'obj', or null, as YAML, or as JSON on one line, as foo_figure_fpr()
pub fn fpr(w: *std.Io.Writer, obj: ?*const @This(), flags: c_int) std.Io.Writer.Error!void {
if (flags & FOO_PR_JSON != 0) {
if (obj) |o| try o.json(w) else try w.writeAll("null");
return w.writeAll("\n");
}
if (obj) |o| {
try w.writeAll("foo_figure:\n");
return o.yaml(w, 2);
}
return w.writeAll("foo_figure: ~\n");
}
/// The YAML, for "{f}"
pub fn format(self: @This(), w: *std.Io.Writer) std.Io.Writer.Error!void {
return @This().fpr(w, &self, FOO_PR_YAML);
}
};
/// A 32-bit value, read as signed, as unsigned, or as the 'x' of a point
pub const FooValue = extern union {
/// Signed
i: i32,
/// Unsigned
u: u32,
/// A point, its 'x' sharing the bits of 'i'
point: FooPoint,
fn json(self: @This(), w: *std.Io.Writer) std.Io.Writer.Error!void {
try w.writeAll("{");
try w.writeAll("\"i\": ");
try w.print("{d}", .{self.i});
try w.writeAll(", \"u\": ");
try w.print("{d}", .{self.u});
try w.writeAll(", \"point\": ");
try self.point.json(w);
try w.writeAll("}");
}
fn yaml(self: @This(), w: *std.Io.Writer, indent: usize) std.Io.Writer.Error!void {
try w.splatByteAll(' ', indent);
try w.writeAll("i: ");
try w.print("{d}", .{self.i});
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("u: ");
try w.print("{d}", .{self.u});
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("point:\n");
try self.point.yaml(w, indent + 2);
}
/// Print 'obj', or null, as YAML, or as JSON on one line, as foo_value_fpr()
pub fn fpr(w: *std.Io.Writer, obj: ?*const @This(), flags: c_int) std.Io.Writer.Error!void {
if (flags & FOO_PR_JSON != 0) {
if (obj) |o| try o.json(w) else try w.writeAll("null");
return w.writeAll("\n");
}
if (obj) |o| {
try w.writeAll("foo_value:\n");
return o.yaml(w, 2);
}
return w.writeAll("foo_value: ~\n");
}
/// The YAML, for "{f}"
pub fn format(self: @This(), w: *std.Io.Writer) std.Io.Writer.Error!void {
return @This().fpr(w, &self, FOO_PR_YAML);
}
};
/// A record laid out without padding, as a wire format is: no field after the first is aligned
pub const FooWire = extern struct {
/// One of enum foo_shape
kind: u8 align(1),
/// At offset 1
length: u32 align(1),
/// A point, at offset 5
at: FooPoint align(1),
/// An array, at offset 13
pair: [2]u16 align(1),
fn json(self: @This(), w: *std.Io.Writer) std.Io.Writer.Error!void {
try w.writeAll("{");
try w.writeAll("\"kind\": ");
try w.print("{d}", .{self.kind});
try w.writeAll(", \"length\": ");
try w.print("{d}", .{self.length});
try w.writeAll(", \"at\": ");
try self.at.json(w);
try w.writeAll(", \"pair\": ");
try w.writeAll("[");
for (self.pair, 0..) |item0, idx0| {
if (idx0 > 0) try w.writeAll(", ");
try w.print("{d}", .{item0});
}
try w.writeAll("]");
try w.writeAll("}");
}
fn yaml(self: @This(), w: *std.Io.Writer, indent: usize) std.Io.Writer.Error!void {
try w.splatByteAll(' ', indent);
try w.writeAll("kind: ");
try w.print("{d}", .{self.kind});
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("length: ");
try w.print("{d}", .{self.length});
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("at:\n");
try self.at.yaml(w, indent + 2);
try w.splatByteAll(' ', indent);
try w.writeAll("pair: ");
try w.writeAll("[");
for (self.pair, 0..) |item0, idx0| {
if (idx0 > 0) try w.writeAll(", ");
try w.print("{d}", .{item0});
}
try w.writeAll("]");
try w.writeAll("\n");
}
/// Print 'obj', or null, as YAML, or as JSON on one line, as foo_wire_fpr()
pub fn fpr(w: *std.Io.Writer, obj: ?*const @This(), flags: c_int) std.Io.Writer.Error!void {
if (flags & FOO_PR_JSON != 0) {
if (obj) |o| try o.json(w) else try w.writeAll("null");
return w.writeAll("\n");
}
if (obj) |o| {
try w.writeAll("foo_wire:\n");
return o.yaml(w, 2);
}
return w.writeAll("foo_wire: ~\n");
}
/// The YAML, for "{f}"
pub fn format(self: @This(), w: *std.Io.Writer) std.Io.Writer.Error!void {
return @This().fpr(w, &self, FOO_PR_YAML);
}
};
/// The status of a handle, its code a field of bits
pub const FooStatus = extern struct {
/// Status code, see FOO_STATUS_CODE_*
code: u16,
/// Points the handle holds at most
max: u16,
fn json(self: @This(), w: *std.Io.Writer) std.Io.Writer.Error!void {
try w.writeAll("{");
try w.writeAll("\"code\": ");
try w.print("{{\"val\": {d}", .{self.code});
try w.print(", \"pending\": {d}", .{(self.code & 0x1) >> 0});
try w.print(", \"points\": {d}", .{(self.code & 0xff0) >> 4});
try w.print(", \"full\": {d}", .{(self.code & 0x8000) >> 15});
try w.writeAll("}");
try w.writeAll(", \"max\": ");
try w.print("{d}", .{self.max});
try w.writeAll("}");
}
fn yaml(self: @This(), w: *std.Io.Writer, indent: usize) std.Io.Writer.Error!void {
try w.splatByteAll(' ', indent);
try w.writeAll("code: ");
try w.print("{{val: 0x{x}", .{self.code});
try w.print(", pending: 0x{x}", .{(self.code & 0x1) >> 0});
try w.print(", points: 0x{x}", .{(self.code & 0xff0) >> 4});
try w.print(", full: 0x{x}", .{(self.code & 0x8000) >> 15});
try w.writeAll("}");
try w.writeAll("\n");
try w.splatByteAll(' ', indent);
try w.writeAll("max: ");
try w.print("{d}", .{self.max});
try w.writeAll("\n");
}
/// Print 'obj', or null, as YAML, or as JSON on one line, as foo_status_fpr()
pub fn fpr(w: *std.Io.Writer, obj: ?*const @This(), flags: c_int) std.Io.Writer.Error!void {
if (flags & FOO_PR_JSON != 0) {
if (obj) |o| try o.json(w) else try w.writeAll("null");
return w.writeAll("\n");
}
if (obj) |o| {
try w.writeAll("foo_status:\n");
return o.yaml(w, 2);
}
return w.writeAll("foo_status: ~\n");
}
/// The YAML, for "{f}"
pub fn format(self: @This(), w: *std.Io.Writer) std.Io.Writer.Error!void {
return @This().fpr(w, &self, FOO_PR_YAML);
}
/// A count is submitted and not yet completed; bit 0 of 'code'
pub fn codePending(self: @This()) u1 {
return @truncate((self.code & 0x1) >> 0);
}
/// Set the part of 'code' that codePending() reads
pub fn setCodePending(self: *@This(), value: u1) void {
self.code = (self.code & ~@as(u16, 0x1)) | (@as(u16, value) << 0);
}
/// Points held; bits 11:4 of 'code'
pub fn codePoints(self: @This()) u8 {
return @truncate((self.code & 0xff0) >> 4);
}
/// Set the part of 'code' that codePoints() reads
pub fn setCodePoints(self: *@This(), value: u8) void {
self.code = (self.code & ~@as(u16, 0xff0)) | (@as(u16, value) << 4);
}
/// The handle holds FOO_POINTS_MAX points; bit 15 of 'code'
pub fn codeFull(self: @This()) u1 {
return @truncate((self.code & 0x8000) >> 15);
}
/// Set the part of 'code' that codeFull() reads
pub fn setCodeFull(self: *@This(), value: u1) void {
self.code = (self.code & ~@as(u16, 0x8000)) | (@as(u16, value) << 15);
}
};
/// Called back with each point visited
///
/// Parameters:
///
/// * `arg`: The argument given along with the callback
/// * `point`: The point visited
///
/// Returns 0 to go on, anything else to stop
pub const FooVisitCb = ?*const fn (?*anyopaque, [*c]const FooPoint) callconv(.c) c_int;
/// Called back when a count submitted completes
///
/// Parameters:
///
/// * `arg`: The argument given along with the callback
/// * `count`: The number of points when it completed
pub const FooDoneCb = ?*const fn (?*anyopaque, usize) callconv(.c) void;
/// Called back with each point added to a handle watched
///
/// Parameters:
///
/// * `arg`: The argument given along with the callback
/// * `point`: The point added
pub const FooAddedCb = ?*const fn (?*anyopaque, [*c]const FooPoint) callconv(.c) void;
/// The version of the library
///
/// Returns The version, as "MAJOR.MINOR.PATCH"
pub extern fn foo_version() [*c]const u8;
/// Why the call that failed last on the calling thread failed
///
/// A function that returns a negative errno keeps a message saying what the errno does not, such as the name of the handle that is full. The meta names this function as 'errmsg', so that the error of a binding holds the message.
///
/// Returns The message, owned by the library and valid until the next call fails on the calling thread; "" when no call has failed
pub extern fn foo_errmsg() [*c]const u8;
/// Open a handle holding no points
///
/// Parameters:
///
/// * `name`: Name of the handle, copied
/// * `handle`: Set to the handle opened
///
/// Returns 0 on success, -EINVAL when 'name' or 'handle' is NULL, -ENOMEM when memory ran out
pub extern fn foo_open(name: [*c]const u8, handle: [*c]?*FooHandle) c_int;
/// Close a handle
///
/// Parameters:
///
/// * `handle`: The handle to close, NULL is ignored
pub extern fn foo_close(handle: ?*FooHandle) void;
/// The name the handle was opened with
///
/// Parameters:
///
/// * `handle`: The handle
///
/// Returns The name, owned by the handle
pub extern fn foo_name(handle: ?*const FooHandle) [*c]const u8;
/// Add a point to the handle
///
/// Parameters:
///
/// * `handle`: The handle
/// * `point`: The point to add, copied
///
/// Returns 0 on success, -ENOSPC when the handle holds FOO_POINTS_MAX points
pub extern fn foo_point_add(handle: ?*FooHandle, point: [*c]const FooPoint) c_int;
/// Add points to the handle, as many as it has room for
///
/// Parameters:
///
/// * `handle`: The handle
/// * `points`: The points to add, copied
/// * `points_len`: The number of points
///
/// Returns The number of points added, -ENOSPC when there was room for none
pub extern fn foo_point_add_many(handle: ?*FooHandle, points: [*c]const FooPoint, points_len: usize) isize;
/// The number of points held
///
/// Parameters:
///
/// * `handle`: The handle
///
/// Returns The number of points
pub extern fn foo_point_count(handle: ?*const FooHandle) usize;
/// A point held by the handle
///
/// Parameters:
///
/// * `handle`: The handle
/// * `idx`: Index of the point
///
/// Returns The point, NULL when 'idx' is past the last one
pub extern fn foo_point_get(handle: ?*const FooHandle, idx: usize) [*c]const FooPoint;
/// Copy the points held, as many as fit
///
/// Parameters:
///
/// * `handle`: The handle
/// * `points`: Where to copy the points to
/// * `points_len`: The number of points that fit
///
/// Returns The number of points copied
pub extern fn foo_point_copy(handle: ?*const FooHandle, points: [*c]FooPoint, points_len: usize) isize;
/// Watch the points added to the handle, from now until it is closed
///
/// Parameters:
///
/// * `handle`: The handle
/// * `added`: Called with each point added, until the handle is closed
/// * `arg`: Given to 'added'
///
/// Returns 0 on success, -EBUSY when the handle is watched already
pub extern fn foo_point_watch(handle: ?*FooHandle, added: FooAddedCb, arg: ?*anyopaque) c_int;
/// Visit the points in the order they were added
///
/// Parameters:
///
/// * `handle`: The handle
/// * `visit`: Called for each point, until it returns non-zero
/// * `arg`: Given to 'visit'
///
/// Returns The number of points visited, -EINVAL when 'visit' is NULL
pub extern fn foo_point_visit(handle: ?*FooHandle, visit: FooVisitCb, arg: ?*anyopaque) isize;
/// Visit the points with a visitor; as foo_point_visit()
///
/// Parameters:
///
/// * `handle`: The handle
/// * `visitor`: The callback and its argument
///
/// Returns The number of points visited, -EINVAL when the callback is NULL
pub extern fn foo_point_visit_with(handle: ?*FooHandle, visitor: [*c]const FooVisitor) isize;
/// Submit a count of the points, completed by foo_count_complete()
///
/// Parameters:
///
/// * `handle`: The handle
/// * `done`: Called once, by foo_count_complete(), with the number of points
/// * `arg`: Given to 'done'
///
/// Returns 0, -EBUSY when a count is submitted and not yet completed
pub extern fn foo_count_submit(handle: ?*FooHandle, done: FooDoneCb, arg: ?*anyopaque) c_int;
/// Complete the count submitted, if any, calling its callback
///
/// Parameters:
///
/// * `handle`: The handle
///
/// Returns The number of counts completed, 0 or 1
pub extern fn foo_count_complete(handle: ?*FooHandle) usize;
/// The status of the handle
///
/// Parameters:
///
/// * `handle`: The handle
/// * `status`: The status to fill in
pub extern fn foo_status_get(handle: ?*const FooHandle, status: [*c]FooStatus) void;
/// Fill in a value of every kind of scalar, the limits of the fixed-width ones
///
/// Parameters:
///
/// * `scalars`: The values to fill in
pub extern fn foo_scalars_fill(scalars: [*c]FooScalars) void;
/// Fill in a figure of the given shape
///
/// Parameters:
///
/// * `figure`: The figure to fill in
/// * `shape`: One of enum foo_shape
///
/// Returns 0 on success, -EINVAL when 'shape' is none of enum foo_shape
pub extern fn foo_figure_fill(figure: [*c]FooFigure, shape: u32) c_int;
/// Set a value, clearing the bits it does not use
///
/// Parameters:
///
/// * `value`: The value to set
/// * `i`: What to set it to
pub extern fn foo_value_set(value: [*c]FooValue, i: i32) void;
/// Fill in a packed record
///
/// Parameters:
///
/// * `wire`: The record to fill in
pub extern fn foo_wire_fill(wire: [*c]FooWire) void;
/// The error of a negative errno: the Zig error of the same name
pub fn errnoError(ret: c_int) anyerror {
return switch (@as(std.posix.E, @enumFromInt(-ret))) {
inline else => |tag| @field(anyerror, @tagName(tag)),
_ => error.Unexpected,
};
}
/// The errno of an error of errnoError(), 0 for any other
pub fn errnoOf(err: anyerror) c_int {
inline for (@typeInfo(std.posix.E).@"enum".fields) |field| {
if (err == @field(anyerror, field.name))
return @intCast(field.value);
}
return 0;
}
/// A collection of points, opened with foo_open() and closed with foo_close()
pub const Handle = struct {
ptr: *FooHandle,
/// Open a handle holding no points
///
/// Parameters:
///
/// * `name_arg`: Name of the handle, copied
///
/// Errors: foo_open() returns: 0 on success, -EINVAL when 'name' or 'handle' is NULL, -ENOMEM when memory ran out
///
/// Calls `foo_open`.
pub fn open(name_arg: [*:0]const u8) anyerror!Handle {
var handle_out: ?*FooHandle = null;
const ret = foo_open(name_arg, &handle_out);
if (ret < 0) return errnoError(@intCast(ret));
return Handle{ .ptr = handle_out orelse return error.Unexpected };
}
/// The name the handle was opened with
///
/// Returns The name, owned by the handle
///
/// Calls `foo_name`.
pub fn name(self: Handle) [:0]const u8 {
const ret = foo_name(self.ptr);
return std.mem.span(@as([*:0]const u8, @ptrCast(ret)));
}
/// Add a point to the handle
///
/// Parameters:
///
/// * `point`: The point to add, copied
///
/// Errors: foo_point_add() returns: 0 on success, -ENOSPC when the handle holds FOO_POINTS_MAX points
///
/// Calls `foo_point_add`.
pub fn pointAdd(self: Handle, point: *const FooPoint) anyerror!void {
const ret = foo_point_add(self.ptr, point);
if (ret < 0) return errnoError(@intCast(ret));
}
/// Add points to the handle, as many as it has room for
///
/// Parameters:
///
/// * `points`: The points to add, copied
///
/// Errors: foo_point_add_many() returns: The number of points added, -ENOSPC when there was room for none
///
/// Calls `foo_point_add_many`.
pub fn pointAddMany(self: Handle, points: []const FooPoint) anyerror!usize {
const ret = foo_point_add_many(self.ptr, points.ptr, @intCast(points.len));
if (ret < 0) return errnoError(@intCast(ret));
return @intCast(ret);
}
/// The number of points held
///
/// Returns The number of points
///
/// Calls `foo_point_count`.
pub fn pointCount(self: Handle) usize {
const ret = foo_point_count(self.ptr);
return ret;
}
/// A point held by the handle
///
/// Parameters:
///
/// * `idx`: Index of the point
///
/// Returns The point, NULL when 'idx' is past the last one
///
/// Calls `foo_point_get`.
pub fn pointGet(self: Handle, idx: usize) ?FooPoint {
const ret = foo_point_get(self.ptr, idx);
return if (ret == null) null else ret.*;
}
/// Copy the points held, as many as fit
///
/// Parameters:
///
/// * `points`: Where to copy the points to
///
/// Errors: foo_point_copy() returns: The number of points copied
///
/// Calls `foo_point_copy`.
pub fn pointCopy(self: Handle, points: []FooPoint) anyerror![]FooPoint {
const ret = foo_point_copy(self.ptr, @ptrCast(points.ptr), @intCast(points.len));
if (ret < 0) return errnoError(@intCast(ret));
return points[0..@intCast(ret)];
}
/// Watch the points added to the handle, from now until it is closed
///
/// Parameters:
///
/// * `added`: Called with each point added, until the handle is closed
///
/// Errors: foo_point_watch() returns: 0 on success, -EBUSY when the handle is watched already
///
/// Calls `foo_point_watch`.
///
/// `added_context` must live until the handle is destroyed.
pub fn pointWatch(self: Handle, added_context: anytype, comptime added: fn (@TypeOf(added_context), *const FooPoint) void) anyerror!void {
const added_trampoline = struct {
fn call(a0: ?*anyopaque, a1: [*c]const FooPoint) callconv(.c) void {
const context: @TypeOf(added_context) = @ptrCast(@alignCast(a0));
return added(context, a1);
}
};
const ret = foo_point_watch(self.ptr, &added_trampoline.call, @ptrCast(@constCast(added_context)));
if (ret < 0) return errnoError(@intCast(ret));
}
/// Visit the points in the order they were added
///
/// Parameters:
///
/// * `visit`: Called for each point, until it returns non-zero
///
/// Errors: foo_point_visit() returns: The number of points visited, -EINVAL when 'visit' is NULL
///
/// Calls `foo_point_visit`.
pub fn pointVisit(self: Handle, visit_context: anytype, comptime visit: fn (@TypeOf(visit_context), *const FooPoint) c_int) anyerror!usize {
const visit_trampoline = struct {
fn call(a0: ?*anyopaque, a1: [*c]const FooPoint) callconv(.c) c_int {
const context: @TypeOf(visit_context) = @ptrCast(@alignCast(a0));
return visit(context, a1);
}
};
const ret = foo_point_visit(self.ptr, &visit_trampoline.call, @ptrCast(@constCast(visit_context)));
if (ret < 0) return errnoError(@intCast(ret));
return @intCast(ret);
}
/// Visit the points with a visitor; as foo_point_visit()
///
/// Parameters:
///
/// * `visitor`: The callback and its argument
///
/// Errors: foo_point_visit_with() returns: The number of points visited, -EINVAL when the callback is NULL
///
/// Calls `foo_point_visit_with`.
pub fn pointVisitWith(self: Handle, visitor: *const FooVisitor) anyerror!usize {
const ret = foo_point_visit_with(self.ptr, visitor);
if (ret < 0) return errnoError(@intCast(ret));
return @intCast(ret);
}
/// Submit a count of the points, completed by foo_count_complete()
///
/// Parameters:
///
/// * `done`: Called once, by foo_count_complete(), with the number of points
///
/// Errors: foo_count_submit() returns: 0, -EBUSY when a count is submitted and not yet completed
///
/// Calls `foo_count_submit`.
///
/// `done_context` must live until it has been called, once.
pub fn countSubmit(self: Handle, done_context: anytype, comptime done: fn (@TypeOf(done_context), usize) void) anyerror!void {
const done_trampoline = struct {
fn call(a0: ?*anyopaque, a1: usize) callconv(.c) void {
const context: @TypeOf(done_context) = @ptrCast(@alignCast(a0));
return done(context, a1);
}
};
const ret = foo_count_submit(self.ptr, &done_trampoline.call, @ptrCast(@constCast(done_context)));
if (ret < 0) return errnoError(@intCast(ret));
}
/// Complete the count submitted, if any, calling its callback
///
/// Returns The number of counts completed, 0 or 1
///
/// Calls `foo_count_complete`.
pub fn countComplete(self: Handle) usize {
const ret = foo_count_complete(self.ptr);
return ret;
}
/// The status of the handle
///
/// Calls `foo_status_get`.
pub fn statusGet(self: Handle) FooStatus {
var status_out: FooStatus = std.mem.zeroes(FooStatus);
foo_status_get(self.ptr, &status_out);
return status_out;
}
/// Close a handle
///
/// Calls `foo_close`.
pub fn close(self: Handle) void {
foo_close(self.ptr);
}
/// As close(), for `defer handle.deinit()`
pub const deinit = close;
};
/// The version of the library
///
/// Returns The version, as "MAJOR.MINOR.PATCH"
///
/// Calls `foo_version`.
pub fn version() [:0]const u8 {
const ret = foo_version();
return std.mem.span(@as([*:0]const u8, @ptrCast(ret)));
}
/// Why the call that failed last on the calling thread failed
///
/// A function that returns a negative errno keeps a message saying what the errno does not, such as the name of the handle that is full. The meta names this function as 'errmsg', so that the error of a binding holds the message.
///
/// Returns The message, owned by the library and valid until the next call fails on the calling thread; "" when no call has failed
///
/// Calls `foo_errmsg`.
pub fn errmsg() [:0]const u8 {
const ret = foo_errmsg();
return std.mem.span(@as([*:0]const u8, @ptrCast(ret)));
}
/// Fill in a value of every kind of scalar, the limits of the fixed-width ones
///
/// Calls `foo_scalars_fill`.
pub fn scalarsFill() FooScalars {
var scalars_out: FooScalars = std.mem.zeroes(FooScalars);
foo_scalars_fill(&scalars_out);
return scalars_out;
}
/// Fill in a figure of the given shape
///
/// Parameters:
///
/// * `shape`: One of enum foo_shape
///
/// Errors: foo_figure_fill() returns: 0 on success, -EINVAL when 'shape' is none of enum foo_shape
///
/// Calls `foo_figure_fill`.
pub fn figureFill(shape: u32) anyerror!FooFigure {
var figure_out: FooFigure = std.mem.zeroes(FooFigure);
const ret = foo_figure_fill(&figure_out, shape);
if (ret < 0) return errnoError(@intCast(ret));
return figure_out;
}
/// Set a value, clearing the bits it does not use
///
/// Parameters:
///
/// * `i`: What to set it to
///
/// Calls `foo_value_set`.
pub fn valueSet(i: i32) FooValue {
var value_out: FooValue = std.mem.zeroes(FooValue);
foo_value_set(&value_out, i);
return value_out;
}
/// Fill in a packed record
///
/// Calls `foo_wire_fill`.
pub fn wireFill() FooWire {
var wire_out: FooWire = std.mem.zeroes(FooWire);
foo_wire_fill(&wire_out);
return wire_out;
}
Implementation¶
The Zig target: a module binding the API, in two layers, the raw one declaring the C API as C has it and the idiomatic one over it, with pretty-printers for every struct and union, and a check of what it generated
Emits, into <output>/zig:
<prefix>.zig, the bindings<prefix>_check.zig, the check program<prefix>_compile.zig, what has all of the module compiled<prefix>_signatures.zig, the check of the signatures against the headers
The module needs Zig 0.16, as Zig’s standard library changes between releases
and the printers use its std.Io.Writer, and libc, as the C API does.
- class yace.targets.zig.target.Zig(output: Path, include: List[Path] | None = None, options: Dict[str, str] | None = None)¶
-
- signatures(model: Model, zig: str, cache: list) list¶
Compile the check of the signatures with the headers the IR was parsed from, found in the include directories, so that an extern function the header does not declare alike fails; where a header is not found, it warns that the signatures are not checked, and fails nothing
Zig code for the IR: names, the Zig type of each IR type, and the statements of
the pretty-printers. The raw layer uses the types C has, as Zig’s own
translation of C headers does: C pointers, [*c]T, that may be NULL and point
to any number of elements, optional pointers to opaque types and functions.
- class yace.targets.zig.zgen.Locals(declared: set)¶
The names the module’s own code binds, each renamed with ‘_’ while the module declares it, as Zig forbids a local to shadow a declaration; the C API may declare any name, as an enumerator such as ‘ret’ or ‘w’
- rename(text: str, part: str) str¶
‘text’, a ‘part’ of the module, with the names it binds renamed, other than in a doc comment, a string, after ‘.’ or before ‘(’, where the name is not a local’s
- renamed() set¶
What the names declared too are renamed to
- class yace.targets.zig.zgen.Namer(model: Model)¶
The Zig names of the IR’s types: CamelCase of the C name, or the C name itself where two would get the same one
- is_opaque(typ) bool¶
Whether ‘typ’ is a type Zig only knows as opaque
- is_optional(typ) bool¶
Whether the Zig type of ‘typ’ is an optional, rather than
[*c]
- ztype(typ, param: bool = False) str¶
The Zig type of ‘typ’; a parameter’s arrays are pointers, as in C
- class yace.targets.zig.zgen.Printer(namer: Namer, printable: dict)¶
The Zig statements printing a value of a type as JSON
- accessors(record) List[str]¶
The methods reading and writing the parts of the fields of bits of ‘record’, each part an integer of its own width, so Zig does not compile passing a value that does not fit without a cast
- method(record, name: str) str¶
The name of the printer ‘name’ of ‘record’, other than that of a field, as Zig lets no declaration share a field’s name
- parts(field, expr: str, fmt: str, quote: str) List[str]¶
The value of a field of bits and of each of its parts, as a mapping on one line, with the keys quoted by ‘quote’, the values by ‘fmt’
- yace.targets.zig.zgen.doc_lines(doc, errors: str = '') List[str]¶
‘doc’ as the lines of a doc comment, without the ‘///’; ‘errors’ says when the function documented returns an error
- yace.targets.zig.zgen.ident(name: str) str¶
‘name’, usable as a Zig identifier
- yace.targets.zig.zgen.lower_camel(name: str) str¶
Zig names functions in camelCase
- yace.targets.zig.zgen.used(lines: List[str]) List[str]¶
The body of a printer, ‘lines’, discarding ‘self’ where they print none of its fields, as Zig reports an unused parameter as an error
The idiomatic Zig layer of the bindings, over the raw externs: handles as
structs with their methods and a deinit, errors as Zig errors named for the
errno, what is written through [out] pointers returned, slices for arrays,
a caller’s buffer for those written, [*:0]const u8 and [:0]const u8 for
strings, optionals where NULL is allowed, and a context pointer with a comptime
function for callbacks. See yace.targets.idiom for what is derived
from where. Names are camelCase for functions, without the prefix.