code
stringlengths 38
801k
| repo_path
stringlengths 6
263
|
---|---|
const std = @import("std");
const big = std.math.big;
const mem = std.mem;
usingnamespace @import("primitive_types.zig");
usingnamespace @import("iterator.zig");
usingnamespace @import("connection.zig");
usingnamespace @import("client.zig");
const testing = @import("testing.zig");
// This files provides helpers to test the client with a real cassandra node.
pub const DDL = [_][]const u8{
\\ CREATE KEYSPACE IF NOT EXISTS foobar WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};
,
\\ CREATE TABLE IF NOT EXISTS foobar.age_to_ids(
\\ age int,
\\ name text,
\\ ids set<tinyint>,
\\ balance varint,
\\ PRIMARY KEY ((age))
\\ );
,
\\ CREATE TABLE IF NOT EXISTS foobar.user(
\\ id bigint,
\\ secondary_id int,
\\ PRIMARY KEY ((id), secondary_id)
\\ );
};
pub const Truncate = [_][]const u8{
\\ TRUNCATE TABLE foobar.age_to_ids;
,
\\ TRUNCATE TABLE foobar.user;
};
pub const Args = struct {
pub const AgeToIDs = struct {
age: u32 = 0,
name: ?[]const u8 = null,
ids: [4]u8 = undefined,
balance: ?big.int.Const = null,
};
pub const User = struct {
id: u64 = 0,
secondary_id: u32 = 0,
};
};
// Define a Row struct with a 1:1 mapping with the fields selected.
pub const Row = struct {
pub const AgeToIDs = struct {
age: u32,
name: []const u8,
ids: []u8,
balance: big.int.Const,
};
pub const User = struct {
id: u64,
secondary_id: u32,
};
};
pub const Harness = struct {
const Self = @This();
allocator: *mem.Allocator,
positive_varint: big.int.Managed = undefined,
negative_varint: big.int.Managed = undefined,
connection: Connection,
client: Client,
pub fn init(self: *Self, allocator: *mem.Allocator, compression_algorithm: ?CompressionAlgorithm, protocol_version: ?ProtocolVersion) !void {
self.allocator = allocator;
self.connection = undefined;
self.client = undefined;
// Create the varints.
self.positive_varint = try big.int.Managed.init(allocator);
try self.positive_varint.setString(10, "3405245950896869895938539859386968968953285938539111111111111111111111111111111111111111122222222222222222222222222222222");
self.negative_varint = try big.int.Managed.init(allocator);
try self.negative_varint.setString(10, "-3405245950896869895938539859386968968953285938539111111111111111111111111111111111111111122222222222222222222222222222222");
// Create the client.
var address = std.net.Address.initIp4([_]u8{ 127, 0, 0, 1 }, 9042);
var init_options = Connection.InitOptions{};
init_options.protocol_version = protocol_version orelse ProtocolVersion{ .version = @as(u8, 4) };
init_options.compression = compression_algorithm;
init_options.username = "cassandra";
init_options.password = "<PASSWORD>";
var init_diags = Connection.InitOptions.Diagnostics{};
init_options.diags = &init_diags;
std.debug.print("protocol version provided: {} (using {}) compression algorithm: {}\n", .{ protocol_version, init_options.protocol_version, compression_algorithm });
self.connection.initIp4(allocator, address, init_options) catch |err| switch (err) {
error.HandshakeFailed => {
std.debug.panic("unable to handhsake, error: {s}", .{init_diags.message});
},
else => return err,
};
self.client = Client.initWithConnection(allocator, &self.connection, .{});
// Create the keyspace and tables if necessary.
inline for (DDL) |query| {
_ = try self.client.query(allocator, .{}, query, .{});
}
inline for (Truncate) |query| {
_ = try self.client.query(allocator, .{}, query, .{});
}
}
pub fn deinit(self: *Self) void {
self.positive_varint.deinit();
self.negative_varint.deinit();
self.client.deinit();
self.connection.close();
}
pub fn insertTestData(self: *Self, comptime table: Table, n: usize) !void {
var buffer: [16384]u8 = undefined;
var fba = std.heap.FixedBufferAllocator.init(&buffer);
var options = Client.QueryOptions{};
var diags = Client.QueryOptions.Diagnostics{};
options.diags = &diags;
switch (table) {
.AgeToIDs => {
const query_id = self.client.prepare(
self.allocator,
options,
"INSERT INTO foobar.age_to_ids(age, name, ids, balance) VALUES(?, ?, ?, ?)",
Args.AgeToIDs{},
) catch |err| switch (err) {
error.QueryPreparationFailed => {
std.debug.panic("query preparation failed, received cassandra error: {s}\n", .{diags.message});
},
else => return err,
};
var i: usize = 0;
while (i < n) : (i += 1) {
fba.reset();
const name = try std.fmt.allocPrint(&fba.allocator, "Vincent {}", .{i});
var balance = if (i % 2 == 0) self.positive_varint else self.negative_varint;
_ = self.client.execute(
&fba.allocator,
options,
query_id,
Args.AgeToIDs{
.age = @intCast(u32, i),
.ids = [_]u8{ 0, 2, 4, 8 },
.name = if (i % 2 == 0) @as([]const u8, name) else null,
.balance = balance.toConst(),
},
) catch |err| switch (err) {
error.QueryExecutionFailed => {
std.debug.panic("query execution failed, received cassandra error: {s}\n", .{diags.message});
},
else => return err,
};
}
},
.User => {
const query_id = self.client.prepare(
self.allocator,
options,
"INSERT INTO foobar.user(id, secondary_id) VALUES(?, ?)",
Args.User{},
) catch |err| switch (err) {
error.QueryPreparationFailed => {
std.debug.panic("query preparation failed, received cassandra error: {s}\n", .{diags.message});
},
else => return err,
};
var i: usize = 0;
while (i < n) : (i += 1) {
fba.reset();
_ = self.client.execute(
&fba.allocator,
options,
query_id,
Args.User{
.id = 2000,
.secondary_id = @intCast(u32, i + 25),
},
) catch |err| switch (err) {
error.QueryExecutionFailed => {
std.debug.panic("query preparation failed, received cassandra error: {s}\n", .{diags.message});
},
else => return err,
};
}
},
}
}
pub fn selectAndScan(
self: *Self,
comptime RowType: type,
comptime query: []const u8,
args: anytype,
callback: fn (harness: *Self, i: usize, row: *RowType) anyerror!bool,
) !bool {
// Use an arena per query.
var arena = std.heap.ArenaAllocator.init(self.allocator);
defer arena.deinit();
var diags = Client.QueryOptions.Diagnostics{};
var options = Client.QueryOptions{
.diags = &diags,
};
var iter = (self.client.query(&arena.allocator, options, query, args) catch |err| switch (err) {
error.QueryExecutionFailed => {
std.debug.panic("query preparation failed, received cassandra error: {s}\n", .{diags.message});
},
else => return err,
}).?;
var row: RowType = undefined;
var i: usize = 0;
while (true) : (i += 1) {
// Use a single arena per iteration.
var row_arena = std.heap.ArenaAllocator.init(&arena.allocator);
defer row_arena.deinit();
// We want iteration diagnostics in case of failures.
var iter_diags = Iterator.ScanOptions.Diagnostics{};
var scan_options = Iterator.ScanOptions{
.diags = &iter_diags,
};
const scanned = iter.scan(&arena.allocator, scan_options, &row) catch |err| switch (err) {
error.IncompatibleMetadata => blk: {
const im = iter_diags.incompatible_metadata;
const it = im.incompatible_types;
if (it.cql_type_name != null and it.native_type_name != null) {
std.debug.panic("metadata incompatible. CQL type {s} can't be scanned into native type {s}\n", .{
it.cql_type_name, it.native_type_name,
});
} else {
std.debug.panic("metadata incompatible. columns in result: {} fields in struct: {}\n", .{
im.metadata_columns, im.struct_fields,
});
}
break :blk false;
},
else => return err,
};
if (!scanned) {
break;
}
const res = try callback(self, i, &row);
if (!res) {
return res;
}
}
return true;
}
};
pub const Table = enum {
AgeToIDs,
User,
}; | src/casstest.zig |
const std = @import("std");
const assert = std.debug.assert;
const math = @import("utils/math.zig");
const CharacterData = @import("CharacterData.zig");
// Get all active vulnerable hitboxes translated by the character's position.
fn GetVulnerableBoxes(
hitboxPool: []CharacterData.Hitbox, // out parameter
action: CharacterData.ActionProperties,
frame: i32,
position: math.IntVector2D,
) usize {
var poolIndex: usize = 0;
// Find all active hitboxes
for (action.VulnerableHitboxGroups.items) |hitboxGroup| {
if (hitboxGroup.IsActiveOnFrame(frame)) {
for (hitboxGroup.Hitboxes.items) |hitbox| {
assert(poolIndex <= hitboxPool.len);
// If we exceeded the hitbox pool size, return the size of the hitbox pool and write no more hitboxes.
if (poolIndex >= hitboxPool.len) {
return hitboxPool.len;
}
// Translate the hitbox by the character position
hitboxPool[poolIndex] = CharacterData.Hitbox{
.top = hitbox.top + position.y,
.left = hitbox.left + position.x,
.bottom = hitbox.bottom + position.y,
.right = hitbox.right + position.x,
};
poolIndex += 1;
}
}
}
return poolIndex;
}
test "Test getting translated hitboxes from an action" {
var allocator = std.testing.allocator;
var action = try CharacterData.ActionProperties.init(allocator);
defer action.VulnerableHitboxGroups.deinit();
try action.VulnerableHitboxGroups.append(try CharacterData.HitboxGroup.init(allocator));
action.VulnerableHitboxGroups.items[0].StartFrame = 0;
action.VulnerableHitboxGroups.items[0].Duration = 50;
try action.VulnerableHitboxGroups.items[0].Hitboxes.append(CharacterData.Hitbox{ .top = 500, .left = -500, .bottom = 0, .right = 500 });
defer action.VulnerableHitboxGroups.items[0].Hitboxes.deinit();
var hitboxPool: [10]CharacterData.Hitbox = [_]CharacterData.Hitbox{.{}} ** 10;
const frame = 5;
const position = math.IntVector2D{ .x = 200, .y = 400 };
const count = GetVulnerableBoxes(hitboxPool[0..], action, frame, position);
const testingBox = action.VulnerableHitboxGroups.items[0].Hitboxes.items[0];
const hitbox = hitboxPool[0];
try std.testing.expect(count == 1);
try std.testing.expect(action.VulnerableHitboxGroups.items[0].IsActiveOnFrame(5));
try std.testing.expect(hitbox.top == (position.y + testingBox.top));
try std.testing.expect(hitbox.left == (position.x + testingBox.left));
try std.testing.expect(hitbox.bottom == (position.y + testingBox.bottom));
try std.testing.expect(hitbox.right == (position.x + testingBox.right));
} | src/common.zig |
const std = @import("std");
const Instance = @import("instance.zig");
const Op = @import("op.zig");
pub const PostProcess = @import("module/post_process.zig");
const log = std.log.scoped(.wazm);
const magic_number = std.mem.readIntLittle(u32, "\x00asm");
const Module = @This();
arena: std.heap.ArenaAllocator,
/// Code=0
custom: []const struct {
name: []const u8,
payload: []const u8,
} = &.{},
/// Code=1
@"type": []const struct {
form: Type.Form, // TODO: why is this called form?
param_types: []const Type.Value,
return_type: ?Type.Value,
} = &.{},
/// Code=2
import: []const struct {
module: []const u8,
field: []const u8,
kind: union(ExternalKind) {
Function: Index.FuncType,
// TODO: add these types
Table: void,
Memory: void,
Global: void,
},
} = &.{},
/// Code=3
function: []const struct {
type_idx: Index.FuncType,
} = &.{},
/// Code=4
table: []const struct {
element_type: Type.Elem,
limits: ResizableLimits,
} = &.{},
/// Code=5
memory: []const struct {
limits: ResizableLimits,
} = &.{},
/// Code=6
global: []const struct {
@"type": struct {
content_type: Type.Value,
mutability: bool,
},
init: InitExpr,
} = &.{},
/// Code=7
@"export": []const struct {
field: []const u8,
kind: ExternalKind,
index: u32,
} = &.{},
/// Code=8
start: ?struct {
index: Index.Function,
} = null,
/// Code=9
element: []const struct {
index: Index.Table,
offset: InitExpr,
elems: []const Index.Function,
} = &.{},
/// Code=10
code: []const struct {
locals: []const Type.Value,
body: []const Module.Instr,
} = &.{},
/// Code=11
data: []const struct {
index: Index.Memory,
offset: InitExpr,
data: []const u8,
} = &.{},
post_process: ?PostProcess = null,
pub fn init(arena: std.heap.ArenaAllocator) Module {
return Module{ .arena = arena };
}
pub fn deinit(self: *Module) void {
self.arena.deinit();
self.* = undefined;
}
pub fn Section(comptime section: std.wasm.Section) type {
const fields = std.meta.fields(Module);
const num = @enumToInt(section) + 1; // 0 == allocator, 1 == custom, etc.
return std.meta.Child(fields[num].field_type);
}
test "Section" {
const module: Module = undefined;
try std.testing.expectEqual(std.meta.Child(@TypeOf(module.custom)), Section(.custom));
try std.testing.expectEqual(std.meta.Child(@TypeOf(module.memory)), Section(.memory));
try std.testing.expectEqual(std.meta.Child(@TypeOf(module.data)), Section(.data));
}
pub const Index = struct {
pub const FuncType = enum(u32) { _ };
pub const Table = enum(u32) { _ };
pub const Function = enum(u32) { _ };
pub const Memory = enum(u32) { _ };
pub const Global = enum(u32) { _ };
};
pub const Type = struct {
pub const Value = enum(i7) {
I32 = -0x01,
I64 = -0x02,
F32 = -0x03,
F64 = -0x04,
};
pub const Block = enum(i7) {
I32 = -0x01,
I64 = -0x02,
F32 = -0x03,
F64 = -0x04,
Empty = -0x40,
};
pub const Elem = enum(i7) {
Anyfunc = -0x10,
};
pub const Form = enum(i7) {
Func = -0x20,
};
};
pub const ExternalKind = enum(u7) {
Function = 0,
Table = 1,
Memory = 2,
Global = 3,
};
pub const ResizableLimits = struct {
initial: u32,
maximum: ?u32,
};
pub const Instr = struct {
op: std.wasm.Opcode,
pop_len: u8,
arg: Op.Arg,
};
pub const InitExpr = union(enum) {
i32_const: i32,
i64_const: i64,
f32_const: f32,
f64_const: f64,
global_get: u32,
fn parse(reader: anytype) !InitExpr {
const opcode = @intToEnum(std.wasm.Opcode, try reader.readByte());
const result: InitExpr = switch (opcode) {
.i32_const => .{ .i32_const = try readVarint(i32, reader) },
.i64_const => .{ .i64_const = try readVarint(i64, reader) },
.f32_const => .{ .f32_const = @bitCast(f32, try reader.readIntLittle(i32)) },
.f64_const => .{ .f64_const = @bitCast(f64, try reader.readIntLittle(i64)) },
.global_get => .{ .global_get = try readVarint(u32, reader) },
else => return error.UnsupportedInitExpr,
};
if (std.wasm.opcode(.end) != try reader.readByte()) {
return error.InitExprTerminationError;
}
return result;
}
};
pub fn postProcess(self: *Module) !void {
if (self.post_process == null) {
self.post_process = try PostProcess.init(self);
}
}
fn readVarint(comptime T: type, reader: anytype) !T {
const readFn = switch (@typeInfo(T).Int.signedness) {
.signed => std.leb.readILEB128,
.unsigned => std.leb.readULEB128,
};
return try readFn(T, reader);
}
test "readVarint" {
{
var ios = std.io.fixedBufferStream("\xE5\x8E\x26");
try std.testing.expectEqual(@as(u32, 624485), try readVarint(u32, ios.reader()));
ios.pos = 0;
try std.testing.expectEqual(@as(u21, 624485), try readVarint(u21, ios.reader()));
}
{
var ios = std.io.fixedBufferStream("\xC0\xBB\x78");
try std.testing.expectEqual(@as(i32, -123456), try readVarint(i32, ios.reader()));
ios.pos = 0;
try std.testing.expectEqual(@as(i21, -123456), try readVarint(i21, ios.reader()));
}
{
var ios = std.io.fixedBufferStream("\x7F");
try std.testing.expectEqual(@as(i7, -1), try readVarint(i7, ios.reader()));
ios.pos = 0;
try std.testing.expectEqual(@as(i21, -1), try readVarint(i21, ios.reader()));
ios.pos = 0;
try std.testing.expectEqual(@as(i32, -1), try readVarint(i32, ios.reader()));
}
{
var ios = std.io.fixedBufferStream("\xa4\x03");
try std.testing.expectEqual(@as(i21, 420), try readVarint(i21, ios.reader()));
ios.pos = 0;
try std.testing.expectEqual(@as(i32, 420), try readVarint(i32, ios.reader()));
}
}
fn readVarintEnum(comptime E: type, reader: anytype) !E {
const raw = try readVarint(std.meta.TagType(E), reader);
if (@typeInfo(E).Enum.is_exhaustive) {
return try std.meta.intToEnum(E, raw);
} else {
return @intToEnum(E, raw);
}
}
fn expectEos(reader: anytype) !void {
var tmp: [1]u8 = undefined;
const len = try reader.read(&tmp);
if (len != 0) {
return error.NotEndOfStream;
}
}
fn Mut(comptime T: type) type {
var ptr_info = @typeInfo(T).Pointer;
ptr_info.is_const = false;
return @Type(.{ .Pointer = ptr_info });
}
// --- Before ---
// const count = try readVarint(u32, section.reader());
// result.field = arena.allocator.alloc(@TypeOf(result.field), count);
// for (result.field) |*item| {
//
// --- After ---
// const count = try readVarint(u32, section.reader());
// for (self.allocInto(&result.field, count)) |*item| {
fn allocInto(self: *Module, ptr_to_slice: anytype, count: usize) !Mut(std.meta.Child(@TypeOf(ptr_to_slice))) {
const Slice = Mut(std.meta.Child(@TypeOf(ptr_to_slice)));
std.debug.assert(@typeInfo(Slice).Pointer.size == .Slice);
var result = try self.arena.allocator.alloc(std.meta.Child(Slice), count);
ptr_to_slice.* = result;
return result;
}
pub fn parse(allocator: *std.mem.Allocator, reader: anytype) !Module {
const signature = try reader.readIntLittle(u32);
if (signature != magic_number) {
return error.InvalidFormat;
}
const version = try reader.readIntLittle(u32);
if (version != 1) {
return error.InvalidFormat;
}
var result = Module.init(std.heap.ArenaAllocator.init(allocator));
errdefer result.arena.deinit();
var customs = std.ArrayList(Module.Section(.custom)).init(&result.arena.allocator);
errdefer customs.deinit();
while (true) {
const id = reader.readByte() catch |err| switch (err) {
error.EndOfStream => break,
else => return err,
};
const section_len = try readVarint(u32, reader);
var section = std.io.limitedReader(reader, section_len);
switch (try std.meta.intToEnum(std.wasm.Section, id)) {
.type => {
const count = try readVarint(u32, section.reader());
for (try result.allocInto(&result.@"type", count)) |*t| {
t.form = try readVarintEnum(Type.Form, section.reader());
const param_count = try readVarint(u32, section.reader());
for (try result.allocInto(&t.param_types, param_count)) |*param_type| {
param_type.* = try readVarintEnum(Type.Value, section.reader());
}
const return_count = try readVarint(u1, section.reader());
t.return_type = if (return_count == 0) null else try readVarintEnum(Type.Value, section.reader());
}
try expectEos(section.reader());
},
.import => {
const count = try readVarint(u32, section.reader());
for (try result.allocInto(&result.import, count)) |*i| {
const module_len = try readVarint(u32, section.reader());
const module_data = try result.arena.allocator.alloc(u8, module_len);
try section.reader().readNoEof(module_data);
i.module = module_data;
const field_len = try readVarint(u32, section.reader());
const field_data = try result.arena.allocator.alloc(u8, field_len);
try section.reader().readNoEof(field_data);
i.field = field_data;
// TODO: actually test import parsing
const kind = try readVarintEnum(ExternalKind, section.reader());
i.kind = switch (kind) {
.Function => .{ .Function = try readVarintEnum(Index.FuncType, section.reader()) },
.Table => @panic("TODO"),
.Memory => @panic("TODO"),
.Global => @panic("TODO"),
};
}
try expectEos(section.reader());
},
.function => {
const count = try readVarint(u32, section.reader());
for (try result.allocInto(&result.function, count)) |*f| {
f.type_idx = try readVarintEnum(Index.FuncType, section.reader());
}
try expectEos(section.reader());
},
.table => {
const count = try readVarint(u32, section.reader());
for (try result.allocInto(&result.table, count)) |*t| {
t.element_type = try readVarintEnum(Type.Elem, section.reader());
const flags = try readVarint(u1, section.reader());
t.limits.initial = try readVarint(u32, section.reader());
t.limits.maximum = if (flags == 0) null else try readVarint(u32, section.reader());
}
try expectEos(section.reader());
},
.memory => {
const count = try readVarint(u32, section.reader());
for (try result.allocInto(&result.memory, count)) |*m| {
const flags = try readVarint(u1, section.reader());
m.limits.initial = try readVarint(u32, section.reader());
m.limits.maximum = if (flags == 0) null else try readVarint(u32, section.reader());
}
try expectEos(section.reader());
},
.global => {
const count = try readVarint(u32, section.reader());
for (try result.allocInto(&result.global, count)) |*g| {
g.@"type".content_type = try readVarintEnum(Type.Value, section.reader());
g.@"type".mutability = (try readVarint(u1, section.reader())) == 1;
g.init = try InitExpr.parse(section.reader());
}
try expectEos(section.reader());
},
.@"export" => {
const count = try readVarint(u32, section.reader());
for (try result.allocInto(&result.@"export", count)) |*e| {
const field_len = try readVarint(u32, section.reader());
const field_data = try result.arena.allocator.alloc(u8, field_len);
try section.reader().readNoEof(field_data);
e.field = field_data;
e.kind = try readVarintEnum(ExternalKind, section.reader());
e.index = try readVarint(u32, section.reader());
}
try expectEos(section.reader());
},
.start => {
const index = try readVarint(u32, section.reader());
result.start = .{
.index = try readVarintEnum(Index.Function, section.reader()),
};
try expectEos(section.reader());
},
.element => {
const count = try readVarint(u32, section.reader());
for (try result.allocInto(&result.element, count)) |*e| {
e.index = try readVarintEnum(Index.Table, section.reader());
e.offset = try InitExpr.parse(section.reader());
const num_elem = try readVarint(u32, section.reader());
for (try result.allocInto(&e.elems, count)) |*func| {
func.* = try readVarintEnum(Index.Function, section.reader());
}
}
try expectEos(section.reader());
},
.code => {
const count = try readVarint(u32, section.reader());
for (try result.allocInto(&result.code, count)) |*c| {
const body_size = try readVarint(u32, section.reader());
var body = std.io.limitedReader(section.reader(), body_size);
c.locals = blk: {
// TODO: double pass here to preallocate the exact array size
var list = std.ArrayList(Type.Value).init(&result.arena.allocator);
var local_count = try readVarint(u32, body.reader());
while (local_count > 0) : (local_count -= 1) {
var current_count = try readVarint(u32, body.reader());
const typ = try readVarintEnum(Type.Value, body.reader());
while (current_count > 0) : (current_count -= 1) {
try list.append(typ);
}
}
break :blk list.items;
};
c.body = body: {
var list = std.ArrayList(Module.Instr).init(&result.arena.allocator);
while (true) {
const opcode = body.reader().readByte() catch |err| switch (err) {
error.EndOfStream => {
const last = list.popOrNull() orelse return error.MissingFunctionEnd;
if (last.op != .end) {
return error.MissingFunctionEnd;
}
break :body list.items;
},
else => return err,
};
const op_meta = Op.Meta.all[opcode] orelse return error.InvalidOpCode;
try list.append(.{
.op = @intToEnum(std.wasm.Opcode, opcode),
.pop_len = @intCast(u8, op_meta.pop.len),
.arg = switch (op_meta.arg_kind) {
.Void => undefined,
.I32 => .{ .I32 = try readVarint(i32, body.reader()) },
.U32 => .{ .U32 = try readVarint(u32, body.reader()) },
.I64 => .{ .I64 = try readVarint(i64, body.reader()) },
.U64 => .{ .U64 = try readVarint(u64, body.reader()) },
.F32 => .{ .F64 = @bitCast(f32, try body.reader().readIntLittle(i32)) },
.F64 => .{ .F64 = @bitCast(f64, try body.reader().readIntLittle(i64)) },
.Type => .{ .Type = @intToEnum(Op.Arg.Type, try readVarint(u7, body.reader())) },
.U32z => .{
.U32z = .{
.data = try readVarint(u32, body.reader()),
.reserved = try body.reader().readByte(),
},
},
.Mem => .{
.Mem = .{
.align_ = try readVarint(u32, body.reader()),
.offset = try readVarint(u32, body.reader()),
},
},
.Array => blk: {
const target_count = try readVarint(u32, body.reader());
const size = target_count + 1; // Implementation detail: we shove the default into the last element of the array
const data = try result.arena.allocator.alloc(u32, size);
for (data) |*item| {
item.* = try readVarint(u32, body.reader());
}
break :blk .{
.Array = .{
.ptr = data.ptr,
.len = data.len,
},
};
},
},
});
}
};
try expectEos(body.reader());
}
try expectEos(section.reader());
},
.data => {
const count = try readVarint(u32, section.reader());
for (try result.allocInto(&result.data, count)) |*d| {
d.index = try readVarintEnum(Index.Memory, section.reader());
d.offset = try InitExpr.parse(section.reader());
const size = try readVarint(u32, section.reader());
const data = try result.arena.allocator.alloc(u8, size);
try section.reader().readNoEof(data);
d.data = data;
}
try expectEos(section.reader());
},
.custom => {
const custom_section = try customs.addOne();
const name_len = try readVarint(u32, section.reader());
const name = try result.arena.allocator.alloc(u8, name_len);
try section.reader().readNoEof(name);
custom_section.name = name;
const payload = try result.arena.allocator.alloc(u8, section.bytes_left);
try section.reader().readNoEof(payload);
custom_section.payload = payload;
try expectEos(section.reader());
},
}
// Putting this in all the switch paths makes debugging much easier
// Leaving an extra one here in case one of the paths is missing
if (std.builtin.mode == .Debug) {
try expectEos(section.reader());
}
}
result.custom = customs.toOwnedSlice();
result.post_process = try PostProcess.init(&result);
return result;
}
pub const instantiate = Instance.init;
const empty_raw_bytes = &[_]u8{ 0, 'a', 's', 'm', 1, 0, 0, 0 };
test "empty module" {
var ios = std.io.fixedBufferStream(empty_raw_bytes);
var module = try Module.parse(std.testing.allocator, ios.reader());
defer module.deinit();
try std.testing.expectEqual(@as(usize, 0), module.memory.len);
try std.testing.expectEqual(@as(usize, 0), module.@"type".len);
try std.testing.expectEqual(@as(usize, 0), module.function.len);
try std.testing.expectEqual(@as(usize, 0), module.@"export".len);
}
test "module with only type" {
const raw_bytes = empty_raw_bytes ++ // (module
"\x01\x04\x01\x60\x00\x00" ++ // (type (func)))
"";
var ios = std.io.fixedBufferStream(raw_bytes);
var module = try Module.parse(std.testing.allocator, ios.reader());
defer module.deinit();
try std.testing.expectEqual(@as(usize, 1), module.@"type".len);
try std.testing.expectEqual(@as(usize, 0), module.@"type"[0].param_types.len);
try std.testing.expectEqual(@as(?Type.Value, null), module.@"type"[0].return_type);
}
test "module with function body" {
const raw_bytes = empty_raw_bytes ++ // (module
"\x01\x05\x01\x60\x00\x01\x7f" ++ // (type (;0;) (func (result i32)))
"\x03\x02\x01\x00" ++ // (func (;0;) (type 0)
"\x07\x05\x01\x01\x61\x00\x00" ++ // (export "a" (func 0))
"\x0a\x07\x01\x05\x00\x41\xa4\x03\x0b" ++ // i32.const 420
"";
var ios = std.io.fixedBufferStream(raw_bytes);
var module = try Module.parse(std.testing.allocator, ios.reader());
defer module.deinit();
try std.testing.expectEqual(@as(usize, 1), module.@"type".len);
try std.testing.expectEqual(@as(usize, 0), module.@"type"[0].param_types.len);
try std.testing.expectEqual(Type.Value.I32, module.@"type"[0].return_type.?);
try std.testing.expectEqual(@as(usize, 1), module.@"export".len);
try std.testing.expectEqual(@as(usize, 1), module.function.len);
try std.testing.expectEqual(@as(usize, 1), module.code.len);
try std.testing.expectEqual(@as(usize, 1), module.code[0].body.len);
try std.testing.expectEqual(std.wasm.Opcode.i32_const, module.code[0].body[0].op);
}
test "global definitions" {
const raw_bytes = empty_raw_bytes ++ // (module
"\x06\x09\x01\x7f\x01\x41\x80\x80\xc0\x00\x0b" ++ // (global (mut i32) (i32.const 1048576)))
"";
var ios = std.io.fixedBufferStream(raw_bytes);
var module = try Module.parse(std.testing.allocator, ios.reader());
defer module.deinit();
try std.testing.expectEqual(@as(usize, 1), module.global.len);
try std.testing.expectEqual(Type.Value.I32, module.global[0].type.content_type);
try std.testing.expectEqual(true, module.global[0].type.mutability);
} | src/module.zig |
const std = @import("std");
const mem = std.mem;
const Tree = @import("Tree.zig");
const NodeIndex = Tree.NodeIndex;
const TokenIndex = Tree.TokenIndex;
const Attribute = @This();
name: TokenIndex,
params: NodeIndex = .none,
pub const ParseContext = enum {
any,
@"enum",
function,
label,
record,
statement,
typedef,
variable,
};
pub const Tag = enum {
access,
alias,
aligned,
alloc_align,
alloc_size,
always_inline,
artificial,
assume_aligned,
cleanup,
cold,
common,
@"const",
constructor,
copy,
deprecated,
designated_init,
destructor,
@"error",
externally_visible,
fallthrough,
flatten,
format,
format_arg,
gnu_inline,
hot,
ifunc,
interrupt,
interrupt_handler,
leaf,
malloc,
may_alias,
mode,
no_address_safety_analysis,
no_icf,
no_instrument_function,
no_profile_instrument_function,
no_reorder,
no_sanitize,
no_sanitize_address,
no_sanitize_coverage,
no_sanitize_thread,
no_sanitize_undefined,
no_split_stack,
no_stack_limit,
no_stack_protector,
noclone,
nocommon,
noinit,
@"noinline",
noipa,
nonnull,
nonstring,
noplt,
noreturn,
nothrow,
optimize,
@"packed",
patchable_function_entry,
persistent,
pure,
retain,
returns_nonnull,
returns_twice,
scalar_storage_order,
section,
sentinel,
simd,
stack_protect,
symver,
target,
target_clones,
tls_model,
transparent_union,
unavailable,
uninitialized,
unused,
used,
vector_size,
visibility,
warn_if_not_aligned,
warn_unused_result,
warning,
weak,
weakref,
zero_call_used_regs,
fn normalize(name: []const u8) []const u8 {
if (name.len >= 4 and mem.startsWith(u8, name, "__") and mem.endsWith(u8, name, "__")) {
return name[2 .. name.len - 2];
}
return name;
}
pub fn fromString(name: []const u8) ?Tag {
@setEvalBranchQuota(2500);
return std.meta.stringToEnum(Tag, normalize(name));
}
pub fn allowedInContext(tag: Tag, context: ParseContext) bool {
return switch (context) {
.any => true,
.@"enum" => tag.isEnumAttr(),
.function => tag.isFuncAttr(),
.label => tag.isLabelAttr(),
.record => tag.isTypeAttr(),
.statement => tag.isStatementAttr(),
.typedef => tag.isTypeAttr(),
.variable => tag.isVariableAttr(),
};
}
pub fn isVariableAttr(tag: Tag) bool {
return switch (tag) {
.alias,
.aligned,
.alloc_size,
.cleanup,
.common,
.copy,
.deprecated,
.mode,
.nocommon,
.noinit,
.nonstring,
.@"packed",
.persistent,
.retain,
.section,
.tls_model,
.unavailable,
.uninitialized,
.unused,
.used,
.vector_size,
.visibility,
.warn_if_not_aligned,
.weak,
=> true,
else => false,
};
}
pub fn isTypeAttr(tag: Tag) bool {
return switch (tag) {
.aligned,
.alloc_size,
.copy,
.deprecated,
.designated_init,
.may_alias,
.mode,
.@"packed",
.scalar_storage_order,
.transparent_union,
.unavailable,
.unused,
.vector_size,
.warn_if_not_aligned,
=> true,
else => false,
};
}
pub fn isFuncAttr(tag: Tag) bool {
return switch (tag) {
.access,
.alias,
.aligned,
.alloc_align,
.alloc_size,
.always_inline,
.artificial,
.assume_aligned,
.cold,
.@"const",
.constructor,
.copy,
.deprecated,
.destructor,
.@"error",
.externally_visible,
.flatten,
.format,
.format_arg,
.gnu_inline,
.hot,
.ifunc,
.interrupt,
.interrupt_handler,
.leaf,
.malloc,
.no_address_safety_analysis,
.no_icf,
.no_instrument_function,
.no_profile_instrument_function,
.no_reorder,
.no_sanitize,
.no_sanitize_address,
.no_sanitize_coverage,
.no_sanitize_thread,
.no_sanitize_undefined,
.no_split_stack,
.no_stack_limit,
.no_stack_protector,
.noclone,
.@"noinline",
.noipa,
.nonnull,
.noplt,
.noreturn,
.nothrow,
.optimize,
.patchable_function_entry,
.pure,
.retain,
.returns_nonnull,
.returns_twice,
.section,
.sentinel,
.simd,
.stack_protect,
.symver,
.target,
.target_clones,
.unavailable,
.unused,
.used,
.visibility,
.warn_unused_result,
.warning,
.weak,
.weakref,
.zero_call_used_regs,
=> true,
else => false,
};
}
pub fn isLabelAttr(tag: Tag) bool {
return switch (tag) {
.cold, .hot, .unused => true,
else => false,
};
}
pub fn isStatementAttr(tag: Tag) bool {
return tag == .fallthrough;
}
pub fn isEnumAttr(tag: Tag) bool {
return switch (tag) {
.deprecated, .unavailable => true,
else => false,
};
}
}; | src/Attribute.zig |
const builtin = @import("builtin");
const std = @import("../../std.zig");
const testing = std.testing;
const math = std.math;
const cmath = math.complex;
const Complex = cmath.Complex;
const ldexp_cexp = @import("ldexp.zig").ldexp_cexp;
/// Returns e raised to the power of z (e^z).
pub fn exp(z: anytype) @TypeOf(z) {
const T = @TypeOf(z.re);
return switch (T) {
f32 => exp32(z),
f64 => exp64(z),
else => @compileError("exp not implemented for " ++ @typeName(z)),
};
}
fn exp32(z: Complex(f32)) Complex(f32) {
const exp_overflow = 0x42b17218; // max_exp * ln2 ~= 88.72283955
const cexp_overflow = 0x43400074; // (max_exp - min_denom_exp) * ln2
const x = z.re;
const y = z.im;
const hy = @bitCast(u32, y) & 0x7fffffff;
// cexp(x + i0) = exp(x) + i0
if (hy == 0) {
return Complex(f32).new(math.exp(x), y);
}
const hx = @bitCast(u32, x);
// cexp(0 + iy) = cos(y) + isin(y)
if ((hx & 0x7fffffff) == 0) {
return Complex(f32).new(math.cos(y), math.sin(y));
}
if (hy >= 0x7f800000) {
// cexp(finite|nan +- i inf|nan) = nan + i nan
if ((hx & 0x7fffffff) != 0x7f800000) {
return Complex(f32).new(y - y, y - y);
} // cexp(-inf +- i inf|nan) = 0 + i0
else if (hx & 0x80000000 != 0) {
return Complex(f32).new(0, 0);
} // cexp(+inf +- i inf|nan) = inf + i nan
else {
return Complex(f32).new(x, y - y);
}
}
// 88.7 <= x <= 192 so must scale
if (hx >= exp_overflow and hx <= cexp_overflow) {
return ldexp_cexp(z, 0);
} // - x < exp_overflow => exp(x) won't overflow (common)
// - x > cexp_overflow, so exp(x) * s overflows for s > 0
// - x = +-inf
// - x = nan
else {
const exp_x = math.exp(x);
return Complex(f32).new(exp_x * math.cos(y), exp_x * math.sin(y));
}
}
fn exp64(z: Complex(f64)) Complex(f64) {
const exp_overflow = 0x40862e42; // high bits of max_exp * ln2 ~= 710
const cexp_overflow = 0x4096b8e4; // (max_exp - min_denorm_exp) * ln2
const x = z.re;
const y = z.im;
const fy = @bitCast(u64, y);
const hy = @intCast(u32, (fy >> 32) & 0x7fffffff);
const ly = @truncate(u32, fy);
// cexp(x + i0) = exp(x) + i0
if (hy | ly == 0) {
return Complex(f64).new(math.exp(x), y);
}
const fx = @bitCast(u64, x);
const hx = @intCast(u32, fx >> 32);
const lx = @truncate(u32, fx);
// cexp(0 + iy) = cos(y) + isin(y)
if ((hx & 0x7fffffff) | lx == 0) {
return Complex(f64).new(math.cos(y), math.sin(y));
}
if (hy >= 0x7ff00000) {
// cexp(finite|nan +- i inf|nan) = nan + i nan
if (lx != 0 or (hx & 0x7fffffff) != 0x7ff00000) {
return Complex(f64).new(y - y, y - y);
} // cexp(-inf +- i inf|nan) = 0 + i0
else if (hx & 0x80000000 != 0) {
return Complex(f64).new(0, 0);
} // cexp(+inf +- i inf|nan) = inf + i nan
else {
return Complex(f64).new(x, y - y);
}
}
// 709.7 <= x <= 1454.3 so must scale
if (hx >= exp_overflow and hx <= cexp_overflow) {
return ldexp_cexp(z, 0);
} // - x < exp_overflow => exp(x) won't overflow (common)
// - x > cexp_overflow, so exp(x) * s overflows for s > 0
// - x = +-inf
// - x = nan
else {
const exp_x = math.exp(x);
return Complex(f64).new(exp_x * math.cos(y), exp_x * math.sin(y));
}
}
const epsilon = 0.0001;
test "complex.cexp32" {
const a = Complex(f32).new(5, 3);
const c = exp(a);
try testing.expect(math.approxEqAbs(f32, c.re, -146.927917, epsilon));
try testing.expect(math.approxEqAbs(f32, c.im, 20.944065, epsilon));
}
test "complex.cexp64" {
const a = Complex(f64).new(5, 3);
const c = exp(a);
try testing.expect(math.approxEqAbs(f64, c.re, -146.927917, epsilon));
try testing.expect(math.approxEqAbs(f64, c.im, 20.944065, epsilon));
} | lib/std/math/complex/exp.zig |
const builtin = @import("builtin");
const std = @import("../std.zig");
const math = std.math;
const expect = std.testing.expect;
const expo2 = @import("expo2.zig").expo2;
const maxInt = std.math.maxInt;
pub fn sinh(x: var) @typeOf(x) {
const T = @typeOf(x);
return switch (T) {
f32 => sinh32(x),
f64 => sinh64(x),
else => @compileError("sinh not implemented for " ++ @typeName(T)),
};
}
// sinh(x) = (exp(x) - 1 / exp(x)) / 2
// = (exp(x) - 1 + (exp(x) - 1) / exp(x)) / 2
// = x + x^3 / 6 + o(x^5)
fn sinh32(x: f32) f32 {
const u = @bitCast(u32, x);
const ux = u & 0x7FFFFFFF;
const ax = @bitCast(f32, ux);
if (x == 0.0 or math.isNan(x)) {
return x;
}
var h: f32 = 0.5;
if (u >> 31 != 0) {
h = -h;
}
// |x| < log(FLT_MAX)
if (ux < 0x42B17217) {
const t = math.expm1(ax);
if (ux < 0x3F800000) {
if (ux < 0x3F800000 - (12 << 23)) {
return x;
} else {
return h * (2 * t - t * t / (t + 1));
}
}
return h * (t + t / (t + 1));
}
// |x| > log(FLT_MAX) or nan
return 2 * h * expo2(ax);
}
fn sinh64(x: f64) f64 {
const u = @bitCast(u64, x);
const w = @intCast(u32, u >> 32);
const ax = @bitCast(f64, u & (maxInt(u64) >> 1));
if (x == 0.0 or math.isNan(x)) {
return x;
}
var h: f32 = 0.5;
if (u >> 63 != 0) {
h = -h;
}
// |x| < log(FLT_MAX)
if (w < 0x40862E42) {
const t = math.expm1(ax);
if (w < 0x3FF00000) {
if (w < 0x3FF00000 - (26 << 20)) {
return x;
} else {
return h * (2 * t - t * t / (t + 1));
}
}
// NOTE: |x| > log(0x1p26) + eps could be h * exp(x)
return h * (t + t / (t + 1));
}
// |x| > log(DBL_MAX) or nan
return 2 * h * expo2(ax);
}
test "math.sinh" {
expect(sinh(f32(1.5)) == sinh32(1.5));
expect(sinh(f64(1.5)) == sinh64(1.5));
}
test "math.sinh32" {
const epsilon = 0.000001;
expect(math.approxEq(f32, sinh32(0.0), 0.0, epsilon));
expect(math.approxEq(f32, sinh32(0.2), 0.201336, epsilon));
expect(math.approxEq(f32, sinh32(0.8923), 1.015512, epsilon));
expect(math.approxEq(f32, sinh32(1.5), 2.129279, epsilon));
}
test "math.sinh64" {
const epsilon = 0.000001;
expect(math.approxEq(f64, sinh64(0.0), 0.0, epsilon));
expect(math.approxEq(f64, sinh64(0.2), 0.201336, epsilon));
expect(math.approxEq(f64, sinh64(0.8923), 1.015512, epsilon));
expect(math.approxEq(f64, sinh64(1.5), 2.129279, epsilon));
}
test "math.sinh32.special" {
expect(sinh32(0.0) == 0.0);
expect(sinh32(-0.0) == -0.0);
expect(math.isPositiveInf(sinh32(math.inf(f32))));
expect(math.isNegativeInf(sinh32(-math.inf(f32))));
expect(math.isNan(sinh32(math.nan(f32))));
}
test "math.sinh64.special" {
expect(sinh64(0.0) == 0.0);
expect(sinh64(-0.0) == -0.0);
expect(math.isPositiveInf(sinh64(math.inf(f64))));
expect(math.isNegativeInf(sinh64(-math.inf(f64))));
expect(math.isNan(sinh64(math.nan(f64))));
} | std/math/sinh.zig |
const std = @import("std");
const Tree = @import("Tree.zig");
const TokenIndex = Tree.TokenIndex;
const NodeIndex = Tree.NodeIndex;
const Parser = @import("Parser.zig");
const Compilation = @import("Compilation.zig");
const Attribute = @import("Attribute.zig");
const Type = @This();
pub const Qualifiers = packed struct {
@"const": bool = false,
atomic: bool = false,
@"volatile": bool = false,
// for function parameters only, stored here since it fits in the padding
register: bool = false,
restrict: bool = false,
pub fn any(quals: Qualifiers) bool {
return quals.@"const" or quals.restrict or quals.@"volatile" or quals.atomic;
}
pub fn dump(quals: Qualifiers, w: anytype) !void {
if (quals.@"const") try w.writeAll("const ");
if (quals.atomic) try w.writeAll("_Atomic ");
if (quals.@"volatile") try w.writeAll("volatile ");
if (quals.restrict) try w.writeAll("restrict ");
if (quals.register) try w.writeAll("register ");
}
/// Merge the const/volatile qualifiers, used by type resolution
/// of the conditional operator
pub fn mergeCV(a: Qualifiers, b: Qualifiers) Qualifiers {
return .{
.@"const" = a.@"const" or b.@"const",
.@"volatile" = a.@"volatile" or b.@"volatile",
};
}
/// Merge all qualifiers, used by typeof()
fn mergeAll(a: Qualifiers, b: Qualifiers) Qualifiers {
return .{
.@"const" = a.@"const" or b.@"const",
.atomic = a.atomic or b.atomic,
.@"volatile" = a.@"volatile" or b.@"volatile",
.restrict = a.restrict or b.restrict,
.register = a.register or b.register,
};
}
/// Checks if a has all the qualifiers of b
pub fn hasQuals(a: Qualifiers, b: Qualifiers) bool {
if (b.@"const" and !a.@"const") return false;
if (b.@"volatile" and !a.@"volatile") return false;
if (b.atomic and !a.atomic) return false;
return true;
}
/// register is a storage class and not actually a qualifier
/// so it is not preserved by typeof()
pub fn inheritFromTypeof(quals: Qualifiers) Qualifiers {
var res = quals;
res.register = false;
return res;
}
pub const Builder = struct {
@"const": ?TokenIndex = null,
atomic: ?TokenIndex = null,
@"volatile": ?TokenIndex = null,
restrict: ?TokenIndex = null,
pub fn finish(b: Qualifiers.Builder, p: *Parser, ty: *Type) !void {
if (ty.specifier != .pointer and b.restrict != null) {
try p.errStr(.restrict_non_pointer, b.restrict.?, try p.typeStr(ty.*));
}
if (b.atomic) |some| {
if (ty.isArray()) try p.errStr(.atomic_array, some, try p.typeStr(ty.*));
if (ty.isFunc()) try p.errStr(.atomic_func, some, try p.typeStr(ty.*));
if (ty.hasIncompleteSize()) try p.errStr(.atomic_incomplete, some, try p.typeStr(ty.*));
}
ty.qual = .{
.@"const" = b.@"const" != null,
.atomic = b.atomic != null,
.@"volatile" = b.@"volatile" != null,
.restrict = b.restrict != null,
};
}
};
};
// TODO improve memory usage
pub const Func = struct {
return_type: Type,
params: []Param,
pub const Param = struct {
name: []const u8,
ty: Type,
name_tok: TokenIndex,
};
};
pub const Array = struct {
len: u64,
elem: Type,
};
pub const Expr = struct {
node: NodeIndex,
ty: Type,
};
pub const Attributed = struct {
attributes: []Attribute,
base: Type,
fn create(allocator: std.mem.Allocator, base: Type, attributes: []const Attribute) !*Attributed {
var attributed_type = try allocator.create(Attributed);
errdefer allocator.destroy(attributed_type);
attributed_type.* = .{
.attributes = try allocator.dupe(Attribute, attributes),
.base = base,
};
return attributed_type;
}
};
// TODO improve memory usage
pub const Enum = struct {
name: []const u8,
tag_ty: Type,
fields: []Field,
pub const Field = struct {
name: []const u8,
ty: Type,
value: u64,
};
pub fn isIncomplete(e: Enum) bool {
return e.fields.len == std.math.maxInt(usize);
}
pub fn create(allocator: std.mem.Allocator, name: []const u8) !*Enum {
var e = try allocator.create(Enum);
e.name = name;
e.fields.len = std.math.maxInt(usize);
return e;
}
};
// TODO improve memory usage
pub const Record = struct {
name: []const u8,
fields: []Field,
size: u64,
alignment: u29,
pub const Field = struct {
name: []const u8,
ty: Type,
bit_width: u32 = 0,
};
pub fn isIncomplete(r: Record) bool {
return r.fields.len == std.math.maxInt(usize);
}
pub fn create(allocator: std.mem.Allocator, name: []const u8) !*Record {
var r = try allocator.create(Record);
r.name = name;
r.fields.len = std.math.maxInt(usize);
return r;
}
};
pub const Specifier = enum {
void,
bool,
// integers
char,
schar,
uchar,
short,
ushort,
int,
uint,
long,
ulong,
long_long,
ulong_long,
// floating point numbers
float,
double,
long_double,
complex_float,
complex_double,
complex_long_double,
// data.sub_type
pointer,
unspecified_variable_len_array,
decayed_unspecified_variable_len_array,
// data.func
/// int foo(int bar, char baz) and int (void)
func,
/// int foo(int bar, char baz, ...)
var_args_func,
/// int foo(bar, baz) and int foo()
/// is also var args, but we can give warnings about incorrect amounts of parameters
old_style_func,
// data.array
array,
decayed_array,
static_array,
decayed_static_array,
incomplete_array,
decayed_incomplete_array,
// data.expr
variable_len_array,
decayed_variable_len_array,
// data.record
@"struct",
@"union",
// data.enum
@"enum",
/// typeof(type-name)
typeof_type,
/// decayed array created with typeof(type-name)
decayed_typeof_type,
/// typeof(expression)
typeof_expr,
/// decayed array created with typeof(expression)
decayed_typeof_expr,
/// data.attributed
attributed,
};
/// All fields of Type except data may be mutated
data: union {
sub_type: *Type,
func: *Func,
array: *Array,
expr: *Expr,
@"enum": *Enum,
record: *Record,
attributed: *Attributed,
none: void,
} = .{ .none = {} },
/// user requested alignment, to get type alignment use `alignof`
alignment: u29 = 0,
specifier: Specifier,
qual: Qualifiers = .{},
/// Determine if type matches the given specifier, recursing into typeof
/// types if necessary.
pub fn is(ty: Type, specifier: Specifier) bool {
std.debug.assert(specifier != .typeof_type and specifier != .typeof_expr);
return ty.get(specifier) != null;
}
pub fn withAttributes(self: Type, allocator: std.mem.Allocator, attributes: []const Attribute) !Type {
if (attributes.len == 0) return self;
const attributed_type = try Type.Attributed.create(allocator, self, attributes);
return Type{ .specifier = .attributed, .data = .{ .attributed = attributed_type } };
}
pub fn isCallable(ty: Type) ?Type {
return switch (ty.specifier) {
.func, .var_args_func, .old_style_func => ty,
.pointer => if (ty.data.sub_type.isFunc()) ty.data.sub_type.* else null,
.typeof_type => ty.data.sub_type.isCallable(),
.typeof_expr => ty.data.expr.ty.isCallable(),
.attributed => ty.data.attributed.base.isCallable(),
else => null,
};
}
pub fn isFunc(ty: Type) bool {
return switch (ty.specifier) {
.func, .var_args_func, .old_style_func => true,
.typeof_type => ty.data.sub_type.isFunc(),
.typeof_expr => ty.data.expr.ty.isFunc(),
.attributed => ty.data.attributed.base.isFunc(),
else => false,
};
}
pub fn isArray(ty: Type) bool {
return switch (ty.specifier) {
.array, .static_array, .incomplete_array, .variable_len_array, .unspecified_variable_len_array => true,
.typeof_type => ty.data.sub_type.isArray(),
.typeof_expr => ty.data.expr.ty.isArray(),
.attributed => ty.data.attributed.base.isArray(),
else => false,
};
}
pub fn isPtr(ty: Type) bool {
return switch (ty.specifier) {
.pointer,
.decayed_array,
.decayed_static_array,
.decayed_incomplete_array,
.decayed_variable_len_array,
.decayed_unspecified_variable_len_array,
.decayed_typeof_type,
.decayed_typeof_expr,
=> true,
.typeof_type => ty.data.sub_type.isPtr(),
.typeof_expr => ty.data.expr.ty.isPtr(),
.attributed => ty.data.attributed.base.isPtr(),
else => false,
};
}
pub fn isInt(ty: Type) bool {
return switch (ty.specifier) {
.@"enum", .bool, .char, .schar, .uchar, .short, .ushort, .int, .uint, .long, .ulong, .long_long, .ulong_long => true,
.typeof_type => ty.data.sub_type.isInt(),
.typeof_expr => ty.data.expr.ty.isInt(),
.attributed => ty.data.attributed.base.isInt(),
else => false,
};
}
pub fn isFloat(ty: Type) bool {
return switch (ty.specifier) {
.float, .double, .long_double, .complex_float, .complex_double, .complex_long_double => true,
.typeof_type => ty.data.sub_type.isFloat(),
.typeof_expr => ty.data.expr.ty.isFloat(),
.attributed => ty.data.attributed.base.isFloat(),
else => false,
};
}
pub fn isReal(ty: Type) bool {
return switch (ty.specifier) {
.complex_float, .complex_double, .complex_long_double => false,
.typeof_type => ty.data.sub_type.isReal(),
.typeof_expr => ty.data.expr.ty.isReal(),
.attributed => ty.data.attributed.base.isReal(),
else => true,
};
}
pub fn isVoidStar(ty: Type) bool {
return switch (ty.specifier) {
.pointer => ty.data.sub_type.specifier == .void,
.typeof_type => ty.data.sub_type.isVoidStar(),
.typeof_expr => ty.data.expr.ty.isVoidStar(),
.attributed => ty.data.attributed.base.isVoidStar(),
else => false,
};
}
pub fn isTypeof(ty: Type) bool {
return switch (ty.specifier) {
.typeof_type, .typeof_expr, .decayed_typeof_type, .decayed_typeof_expr => true,
else => false,
};
}
pub fn isConst(ty: Type) bool {
return switch (ty.specifier) {
.typeof_type, .decayed_typeof_type => ty.qual.@"const" or ty.data.sub_type.isConst(),
.typeof_expr, .decayed_typeof_expr => ty.qual.@"const" or ty.data.expr.ty.isConst(),
.attributed => ty.data.attributed.base.isConst(),
else => ty.qual.@"const",
};
}
pub fn isUnsignedInt(ty: Type, comp: *Compilation) bool {
return switch (ty.specifier) {
.char => return getCharSignedness(comp) == .unsigned,
.uchar, .ushort, .uint, .ulong, .ulong_long => return true,
.typeof_type => ty.data.sub_type.isUnsignedInt(comp),
.typeof_expr => ty.data.expr.ty.isUnsignedInt(comp),
.attributed => ty.data.attributed.base.isUnsignedInt(comp),
else => false,
};
}
pub fn isEnumOrRecord(ty: Type) bool {
return switch (ty.specifier) {
.@"enum", .@"struct", .@"union" => true,
.typeof_type => ty.data.sub_type.isEnumOrRecord(),
.typeof_expr => ty.data.expr.ty.isEnumOrRecord(),
.attributed => ty.data.attributed.base.isEnumOrRecord(),
else => false,
};
}
pub fn isRecord(ty: Type) bool {
return switch (ty.specifier) {
.@"struct", .@"union" => true,
.typeof_type => ty.data.sub_type.isRecord(),
.typeof_expr => ty.data.expr.ty.isRecord(),
.attributed => ty.data.attributed.base.isRecord(),
else => false,
};
}
pub fn isAnonymousRecord(ty: Type) bool {
return switch (ty.specifier) {
// anonymous records can be recognized by their names which are in
// the format "(anonymous TAG at path:line:col)".
.@"struct", .@"union" => ty.data.record.name[0] == '(',
.typeof_type => ty.data.sub_type.isAnonymousRecord(),
.typeof_expr => ty.data.expr.ty.isAnonymousRecord(),
.attributed => ty.data.attributed.base.isAnonymousRecord(),
else => false,
};
}
pub fn elemType(ty: Type) Type {
return switch (ty.specifier) {
.pointer, .unspecified_variable_len_array, .decayed_unspecified_variable_len_array => ty.data.sub_type.*,
.array, .static_array, .incomplete_array, .decayed_array, .decayed_static_array, .decayed_incomplete_array => ty.data.array.elem,
.variable_len_array, .decayed_variable_len_array => ty.data.expr.ty,
.typeof_type, .decayed_typeof_type, .typeof_expr, .decayed_typeof_expr, .attributed => {
const unwrapped = ty.canonicalize(.preserve_quals);
var elem = unwrapped.elemType();
elem.qual = elem.qual.mergeAll(unwrapped.qual);
return elem;
},
else => unreachable,
};
}
pub fn returnType(ty: Type) Type {
return switch (ty.specifier) {
.func, .var_args_func, .old_style_func => ty.data.func.return_type,
.typeof_type, .decayed_typeof_type, .typeof_expr, .decayed_typeof_expr, .attributed => {
const unwrapped = ty.canonicalize(.preserve_quals);
var elem = unwrapped.elemType();
elem.qual = elem.qual.mergeAll(unwrapped.qual);
return elem;
},
else => unreachable,
};
}
pub fn arrayLen(ty: Type) ?usize {
return switch (ty.specifier) {
.array, .static_array, .decayed_array, .decayed_static_array => ty.data.array.len,
.typeof_type, .decayed_typeof_type => ty.data.sub_type.arrayLen(),
.typeof_expr, .decayed_typeof_expr => ty.data.expr.ty.arrayLen(),
.attributed => ty.data.attributed.base.arrayLen(),
else => null,
};
}
pub fn anyQual(ty: Type) bool {
return switch (ty.specifier) {
.typeof_type => ty.qual.any() or ty.data.sub_type.anyQual(),
.typeof_expr => ty.qual.any() or ty.data.expr.ty.anyQual(),
else => ty.qual.any(),
};
}
pub fn eitherLongDouble(a: Type, b: Type) ?Type {
if (a.is(.long_double) or a.is(.complex_long_double)) return a;
if (b.is(.long_double) or b.is(.complex_long_double)) return b;
return null;
}
pub fn eitherDouble(a: Type, b: Type) ?Type {
if (a.is(.double) or a.is(.complex_double)) return a;
if (b.is(.double) or b.is(.complex_double)) return b;
return null;
}
pub fn eitherFloat(a: Type, b: Type) ?Type {
if (a.is(.float) or a.is(.complex_float)) return a;
if (b.is(.float) or b.is(.complex_float)) return b;
return null;
}
pub fn integerPromotion(ty: Type, comp: *Compilation) Type {
var specifier = ty.specifier;
if (specifier == .@"enum") specifier = ty.data.@"enum".tag_ty.specifier;
return .{
.specifier = switch (specifier) {
.bool, .char, .schar, .uchar, .short => .int,
.ushort => if (ty.sizeof(comp).? == sizeof(.{ .specifier = .int }, comp)) Specifier.uint else .int,
.int => .int,
.uint => .uint,
.long => .long,
.ulong => .ulong,
.long_long => .long_long,
.ulong_long => .ulong_long,
.typeof_type => return ty.data.sub_type.integerPromotion(comp),
.typeof_expr => return ty.data.expr.ty.integerPromotion(comp),
.attributed => return ty.data.attributed.base.integerPromotion(comp),
else => unreachable, // not an integer type
},
};
}
pub fn wideChar(comp: *Compilation) Type {
const os = comp.target.os.tag;
return switch (comp.target.cpu.arch) {
.xcore => .{ .specifier = .uchar },
.ve => .{ .specifier = .uint },
.arm, .armeb, .thumb, .thumbeb => .{
.specifier = if (os != .windows and os != .netbsd and os != .openbsd) .uint else .int,
},
.aarch64, .aarch64_be, .aarch64_32 => .{
.specifier = if (!os.isDarwin() and os != .netbsd) .uint else .int,
},
.x86_64, .i386 => .{ .specifier = if (os == .windows) .ushort else .int },
else => .{ .specifier = .int },
};
}
pub fn ptrDiffT(comp: *Compilation) Type {
if (comp.target.os.tag == .windows and comp.target.cpu.arch.ptrBitWidth() == 64)
return .{ .specifier = .long_long };
return switch (comp.target.cpu.arch.ptrBitWidth()) {
32 => .{ .specifier = .int },
64 => .{ .specifier = .long },
else => unreachable,
};
}
pub fn sizeT(comp: *Compilation) Type {
if (comp.target.os.tag == .windows and comp.target.cpu.arch.ptrBitWidth() == 64)
return .{ .specifier = .ulong_long };
return switch (comp.target.cpu.arch.ptrBitWidth()) {
32 => .{ .specifier = .uint },
64 => .{ .specifier = .ulong },
else => unreachable,
};
}
pub fn hasIncompleteSize(ty: Type) bool {
return switch (ty.specifier) {
.void, .incomplete_array => true,
.@"enum" => ty.data.@"enum".isIncomplete(),
.@"struct", .@"union" => ty.data.record.isIncomplete(),
.typeof_type => ty.data.sub_type.hasIncompleteSize(),
.typeof_expr => ty.data.expr.ty.hasIncompleteSize(),
.attributed => ty.data.attributed.base.hasIncompleteSize(),
else => false,
};
}
pub fn hasUnboundVLA(ty: Type) bool {
var cur = ty;
while (true) {
switch (cur.specifier) {
.unspecified_variable_len_array,
.decayed_unspecified_variable_len_array,
=> return true,
.array,
.static_array,
.incomplete_array,
.variable_len_array,
.decayed_array,
.decayed_static_array,
.decayed_incomplete_array,
.decayed_variable_len_array,
=> cur = cur.elemType(),
.typeof_type, .decayed_typeof_type => cur = cur.data.sub_type.*,
.typeof_expr, .decayed_typeof_expr => cur = cur.data.expr.ty,
.attributed => cur = cur.data.attributed.base,
else => return false,
}
}
}
const FieldAndIndex = struct { f: Record.Field, i: usize };
pub fn getField(ty: Type, name: []const u8) ?FieldAndIndex {
// TODO deal with anonymous struct
switch (ty.specifier) {
.@"struct" => {
std.debug.assert(!ty.data.record.isIncomplete());
for (ty.data.record.fields) |f, i| {
if (std.mem.eql(u8, name, f.name)) return FieldAndIndex{ .f = f, .i = i };
}
},
.@"union" => {
std.debug.assert(!ty.data.record.isIncomplete());
for (ty.data.record.fields) |f, i| {
if (std.mem.eql(u8, name, f.name)) return FieldAndIndex{ .f = f, .i = i };
}
},
.typeof_type => return ty.data.sub_type.getField(name),
.typeof_expr => return ty.data.expr.ty.getField(name),
.attributed => return ty.data.attributed.base.getField(name),
else => unreachable,
}
return null;
}
pub fn getCharSignedness(comp: *Compilation) std.builtin.Signedness {
switch (comp.target.cpu.arch) {
.aarch64,
.aarch64_32,
.aarch64_be,
.arm,
.armeb,
.thumb,
.thumbeb,
=> return if (comp.target.os.tag.isDarwin() or comp.target.os.tag == .windows) .signed else .unsigned,
.powerpc, .powerpc64 => return if (comp.target.os.tag.isDarwin()) .signed else .unsigned,
.powerpc64le,
.s390x,
.xcore,
.arc,
=> return .unsigned,
else => return .signed,
}
}
/// Size of type as reported by sizeof
pub fn sizeof(ty: Type, comp: *Compilation) ?u64 {
// TODO get target from compilation
return switch (ty.specifier) {
.variable_len_array, .unspecified_variable_len_array, .incomplete_array => return null,
.func, .var_args_func, .old_style_func, .void, .bool => 1,
.char, .schar, .uchar => 1,
.short, .ushort => 2,
.int, .uint => 4,
.long, .ulong => switch (comp.target.os.tag) {
.linux,
.macos,
.freebsd,
.netbsd,
.dragonfly,
.openbsd,
.wasi,
.emscripten,
=> comp.target.cpu.arch.ptrBitWidth() >> 3,
.windows, .uefi => 4,
else => 4,
},
.long_long, .ulong_long => 8,
.float => 4,
.double => 8,
.long_double => 16,
.complex_float => 8,
.complex_double => 16,
.complex_long_double => 32,
.pointer,
.decayed_array,
.decayed_static_array,
.decayed_incomplete_array,
.decayed_variable_len_array,
.decayed_unspecified_variable_len_array,
.decayed_typeof_type,
.decayed_typeof_expr,
.static_array,
=> comp.target.cpu.arch.ptrBitWidth() >> 3,
.array => ty.data.array.elem.sizeof(comp).? * ty.data.array.len,
.@"struct", .@"union" => if (ty.data.record.isIncomplete()) null else ty.data.record.size,
.@"enum" => if (ty.data.@"enum".isIncomplete()) null else ty.data.@"enum".tag_ty.sizeof(comp),
.typeof_type => ty.data.sub_type.sizeof(comp),
.typeof_expr => ty.data.expr.ty.sizeof(comp),
.attributed => ty.data.attributed.base.sizeof(comp),
};
}
pub fn bitSizeof(ty: Type, comp: *Compilation) ?u64 {
return switch (ty.specifier) {
.bool => 1,
.typeof_type, .decayed_typeof_type => ty.data.sub_type.bitSizeof(comp),
.typeof_expr, .decayed_typeof_expr => ty.data.expr.ty.bitSizeof(comp),
.attributed => ty.data.attributed.base.bitSizeof(comp),
else => 8 * (ty.sizeof(comp) orelse return null),
};
}
/// Get the alignment of a type
pub fn alignof(ty: Type, comp: *Compilation) u29 {
if (ty.alignment != 0) return ty.alignment;
// TODO get target from compilation
return switch (ty.specifier) {
.unspecified_variable_len_array => unreachable, // must be bound in function definition
.variable_len_array, .incomplete_array => ty.elemType().alignof(comp),
.func, .var_args_func, .old_style_func => 4, // TODO check target
.char, .schar, .uchar, .void, .bool => 1,
.short, .ushort => 2,
.int, .uint => 4,
.long, .ulong => switch (comp.target.os.tag) {
.linux,
.macos,
.freebsd,
.netbsd,
.dragonfly,
.openbsd,
.wasi,
.emscripten,
=> comp.target.cpu.arch.ptrBitWidth() >> 3,
.windows, .uefi => 4,
else => 4,
},
.long_long, .ulong_long => 8,
.float, .complex_float => 4,
.double, .complex_double => 8,
.long_double, .complex_long_double => 16,
.pointer,
.decayed_array,
.decayed_static_array,
.decayed_incomplete_array,
.decayed_variable_len_array,
.decayed_unspecified_variable_len_array,
.static_array,
=> comp.target.cpu.arch.ptrBitWidth() >> 3,
.array => ty.data.array.elem.alignof(comp),
.@"struct", .@"union" => if (ty.data.record.isIncomplete()) 0 else ty.data.record.alignment,
.@"enum" => if (ty.data.@"enum".isIncomplete()) 0 else ty.data.@"enum".tag_ty.alignof(comp),
.typeof_type, .decayed_typeof_type => ty.data.sub_type.alignof(comp),
.typeof_expr, .decayed_typeof_expr => ty.data.expr.ty.alignof(comp),
.attributed => ty.data.attributed.base.alignof(comp),
};
}
/// Canonicalize a possibly-typeof() type. If the type is not a typeof() type, simply
/// return it. Otherwise, determine the actual qualified type.
/// The `qual_handling` parameter can be used to return the full set of qualifiers
/// added by typeof() operations, which is useful when determining the elemType of
/// arrays and pointers.
pub fn canonicalize(ty: Type, qual_handling: enum { standard, preserve_quals }) Type {
var cur = ty;
if (cur.specifier == .attributed) cur = cur.data.attributed.base;
if (!cur.isTypeof()) return cur;
var qual = cur.qual;
while (true) {
switch (cur.specifier) {
.typeof_type => cur = cur.data.sub_type.*,
.typeof_expr => cur = cur.data.expr.ty,
.decayed_typeof_type => {
cur = cur.data.sub_type.*;
cur.decayArray();
},
.decayed_typeof_expr => {
cur = cur.data.expr.ty;
cur.decayArray();
},
else => break,
}
qual = qual.mergeAll(cur.qual);
}
if ((cur.isArray() or cur.isPtr()) and qual_handling == .standard) {
cur.qual = .{};
} else {
cur.qual = qual;
}
return cur;
}
pub fn get(ty: *const Type, specifier: Specifier) ?*const Type {
std.debug.assert(specifier != .typeof_type and specifier != .typeof_expr);
return switch (ty.specifier) {
.typeof_type => ty.data.sub_type.get(specifier),
.typeof_expr => ty.data.expr.ty.get(specifier),
.attributed => ty.data.attributed.base.get(specifier),
else => if (ty.specifier == specifier) ty else null,
};
}
pub fn eql(a_param: Type, b_param: Type, check_qualifiers: bool) bool {
const a = a_param.canonicalize(.standard);
const b = b_param.canonicalize(.standard);
if (a.alignment != b.alignment) return false;
if (a.isPtr()) {
if (!b.isPtr()) return false;
} else if (a.isFunc()) {
if (!b.isFunc()) return false;
} else if (a.isArray()) {
if (!b.isArray()) return false;
} else if (a.specifier != b.specifier) return false;
if (a.qual.atomic != b.qual.atomic) return false;
if (check_qualifiers) {
if (a.qual.@"const" != b.qual.@"const") return false;
if (a.qual.@"volatile" != b.qual.@"volatile") return false;
}
switch (a.specifier) {
.pointer,
.decayed_array,
.decayed_static_array,
.decayed_incomplete_array,
.decayed_variable_len_array,
.decayed_unspecified_variable_len_array,
=> if (!a_param.elemType().eql(b_param.elemType(), check_qualifiers)) return false,
.func,
.var_args_func,
.old_style_func,
=> {
// TODO validate this
if (a.data.func.params.len != b.data.func.params.len) return false;
if (!a.data.func.return_type.eql(b.data.func.return_type, check_qualifiers)) return false;
for (a.data.func.params) |param, i| {
if (!param.ty.eql(b.data.func.params[i].ty, check_qualifiers)) return false;
}
},
.array,
.static_array,
.incomplete_array,
=> {
if (!std.meta.eql(a.arrayLen(), b.arrayLen())) return false;
if (!a.elemType().eql(b.elemType(), check_qualifiers)) return false;
},
.variable_len_array => if (!a.elemType().eql(b.elemType(), check_qualifiers)) return false,
.@"struct", .@"union" => if (a.data.record != b.data.record) return false,
.@"enum" => if (a.data.@"enum" != b.data.@"enum") return false,
else => {},
}
return true;
}
/// Decays an array to a pointer
pub fn decayArray(ty: *Type) void {
// the decayed array type is the current specifier +1
ty.specifier = @intToEnum(Type.Specifier, @enumToInt(ty.specifier) + 1);
}
pub fn combine(inner: *Type, outer: Type, p: *Parser, source_tok: TokenIndex) Parser.Error!void {
switch (inner.specifier) {
.pointer => return inner.data.sub_type.combine(outer, p, source_tok),
.unspecified_variable_len_array => {
try inner.data.sub_type.combine(outer, p, source_tok);
const elem_ty = inner.data.sub_type.*;
if (elem_ty.hasIncompleteSize()) try p.errStr(.array_incomplete_elem, source_tok, try p.typeStr(elem_ty));
if (elem_ty.isFunc()) try p.errTok(.array_func_elem, source_tok);
if (elem_ty.anyQual() and elem_ty.isArray()) try p.errTok(.qualifier_non_outermost_array, source_tok);
},
.variable_len_array => {
try inner.data.expr.ty.combine(outer, p, source_tok);
const elem_ty = inner.data.expr.ty;
if (elem_ty.hasIncompleteSize()) try p.errStr(.array_incomplete_elem, source_tok, try p.typeStr(elem_ty));
if (elem_ty.isFunc()) try p.errTok(.array_func_elem, source_tok);
if (elem_ty.anyQual() and elem_ty.isArray()) try p.errTok(.qualifier_non_outermost_array, source_tok);
},
.array, .static_array, .incomplete_array => {
try inner.data.array.elem.combine(outer, p, source_tok);
const elem_ty = inner.data.array.elem;
if (elem_ty.hasIncompleteSize()) try p.errStr(.array_incomplete_elem, source_tok, try p.typeStr(elem_ty));
if (elem_ty.isFunc()) try p.errTok(.array_func_elem, source_tok);
if (elem_ty.specifier == .static_array and elem_ty.isArray()) try p.errTok(.static_non_outermost_array, source_tok);
if (elem_ty.anyQual() and elem_ty.isArray()) try p.errTok(.qualifier_non_outermost_array, source_tok);
},
.func, .var_args_func, .old_style_func => {
try inner.data.func.return_type.combine(outer, p, source_tok);
if (inner.data.func.return_type.isArray()) try p.errTok(.func_cannot_return_array, source_tok);
if (inner.data.func.return_type.isFunc()) try p.errTok(.func_cannot_return_func, source_tok);
},
.decayed_array,
.decayed_static_array,
.decayed_incomplete_array,
.decayed_variable_len_array,
.decayed_unspecified_variable_len_array,
.decayed_typeof_type,
.decayed_typeof_expr,
=> unreachable, // type should not be able to decay before being combined
else => inner.* = outer,
}
}
/// An unfinished Type
pub const Builder = struct {
typedef: ?struct {
tok: TokenIndex,
ty: Type,
} = null,
specifier: Builder.Specifier = .none,
qual: Qualifiers.Builder = .{},
alignment: u29 = 0,
align_tok: ?TokenIndex = null,
typeof: ?Type = null,
/// When true an error is returned instead of adding a diagnostic message.
/// Used for trying to combine typedef types.
error_on_invalid: bool = false,
pub const Specifier = union(enum) {
none,
void,
bool,
char,
schar,
uchar,
unsigned,
signed,
short,
sshort,
ushort,
short_int,
sshort_int,
ushort_int,
int,
sint,
uint,
long,
slong,
ulong,
long_int,
slong_int,
ulong_int,
long_long,
slong_long,
ulong_long,
long_long_int,
slong_long_int,
ulong_long_int,
float,
double,
long_double,
complex,
complex_long,
complex_float,
complex_double,
complex_long_double,
pointer: *Type,
unspecified_variable_len_array: *Type,
decayed_unspecified_variable_len_array: *Type,
func: *Func,
var_args_func: *Func,
old_style_func: *Func,
array: *Array,
decayed_array: *Array,
static_array: *Array,
decayed_static_array: *Array,
incomplete_array: *Array,
decayed_incomplete_array: *Array,
variable_len_array: *Expr,
decayed_variable_len_array: *Expr,
@"struct": *Record,
@"union": *Record,
@"enum": *Enum,
typeof_type: *Type,
decayed_typeof_type: *Type,
typeof_expr: *Expr,
decayed_typeof_expr: *Expr,
attributed: *Attributed,
pub fn str(spec: Builder.Specifier) ?[]const u8 {
return switch (spec) {
.none => unreachable,
.void => "void",
.bool => "_Bool",
.char => "char",
.schar => "signed char",
.uchar => "unsigned char",
.unsigned => "unsigned",
.signed => "signed",
.short => "short",
.ushort => "unsigned short",
.sshort => "signed short",
.short_int => "short int",
.sshort_int => "signed short int",
.ushort_int => "unsigned short int",
.int => "int",
.sint => "signed int",
.uint => "unsigned int",
.long => "long",
.slong => "signed long",
.ulong => "unsigned long",
.long_int => "long int",
.slong_int => "signed long int",
.ulong_int => "unsigned long int",
.long_long => "long long",
.slong_long => "signed long long",
.ulong_long => "unsigned long long",
.long_long_int => "long long int",
.slong_long_int => "signed long long int",
.ulong_long_int => "unsigned long long int",
.float => "float",
.double => "double",
.long_double => "long double",
.complex => "_Complex",
.complex_long => "_Complex long",
.complex_float => "_Complex float",
.complex_double => "_Complex double",
.complex_long_double => "_Complex long double",
.attributed => |attributed| Builder.fromType(attributed.base).str(),
else => null,
};
}
};
pub fn finish(b: Builder, p: *Parser) Parser.Error!Type {
var ty: Type = .{ .specifier = undefined };
switch (b.specifier) {
.none => {
if (b.typeof) |typeof| {
ty = typeof;
} else {
ty.specifier = .int;
try p.err(.missing_type_specifier);
}
},
.void => ty.specifier = .void,
.bool => ty.specifier = .bool,
.char => ty.specifier = .char,
.schar => ty.specifier = .schar,
.uchar => ty.specifier = .uchar,
.unsigned => ty.specifier = .uint,
.signed => ty.specifier = .int,
.short_int, .sshort_int, .short, .sshort => ty.specifier = .short,
.ushort, .ushort_int => ty.specifier = .ushort,
.int, .sint => ty.specifier = .int,
.uint => ty.specifier = .uint,
.long, .slong, .long_int, .slong_int => ty.specifier = .long,
.ulong, .ulong_int => ty.specifier = .ulong,
.long_long, .slong_long, .long_long_int, .slong_long_int => ty.specifier = .long_long,
.ulong_long, .ulong_long_int => ty.specifier = .ulong_long,
.float => ty.specifier = .float,
.double => ty.specifier = .double,
.long_double => ty.specifier = .long_double,
.complex_float => ty.specifier = .complex_float,
.complex_double => ty.specifier = .complex_double,
.complex_long_double => ty.specifier = .complex_long_double,
.complex, .complex_long => {
try p.errExtra(.type_is_invalid, p.tok_i, .{ .str = b.specifier.str().? });
return error.ParsingFailed;
},
.pointer => |data| {
ty.specifier = .pointer;
ty.data = .{ .sub_type = data };
},
.unspecified_variable_len_array => |data| {
ty.specifier = .unspecified_variable_len_array;
ty.data = .{ .sub_type = data };
},
.decayed_unspecified_variable_len_array => |data| {
ty.specifier = .decayed_unspecified_variable_len_array;
ty.data = .{ .sub_type = data };
},
.func => |data| {
ty.specifier = .func;
ty.data = .{ .func = data };
},
.var_args_func => |data| {
ty.specifier = .var_args_func;
ty.data = .{ .func = data };
},
.old_style_func => |data| {
ty.specifier = .old_style_func;
ty.data = .{ .func = data };
},
.array => |data| {
ty.specifier = .array;
ty.data = .{ .array = data };
},
.decayed_array => |data| {
ty.specifier = .decayed_array;
ty.data = .{ .array = data };
},
.static_array => |data| {
ty.specifier = .static_array;
ty.data = .{ .array = data };
},
.decayed_static_array => |data| {
ty.specifier = .decayed_static_array;
ty.data = .{ .array = data };
},
.incomplete_array => |data| {
ty.specifier = .incomplete_array;
ty.data = .{ .array = data };
},
.decayed_incomplete_array => |data| {
ty.specifier = .decayed_incomplete_array;
ty.data = .{ .array = data };
},
.variable_len_array => |data| {
ty.specifier = .variable_len_array;
ty.data = .{ .expr = data };
},
.decayed_variable_len_array => |data| {
ty.specifier = .decayed_variable_len_array;
ty.data = .{ .expr = data };
},
.@"struct" => |data| {
ty.specifier = .@"struct";
ty.data = .{ .record = data };
},
.@"union" => |data| {
ty.specifier = .@"union";
ty.data = .{ .record = data };
},
.@"enum" => |data| {
ty.specifier = .@"enum";
ty.data = .{ .@"enum" = data };
},
.typeof_type => |data| {
ty.specifier = .typeof_type;
ty.data = .{ .sub_type = data };
},
.decayed_typeof_type => |data| {
ty.specifier = .decayed_typeof_type;
ty.data = .{ .sub_type = data };
},
.typeof_expr => |data| {
ty.specifier = .typeof_expr;
ty.data = .{ .expr = data };
},
.decayed_typeof_expr => |data| {
ty.specifier = .decayed_typeof_expr;
ty.data = .{ .expr = data };
},
.attributed => |data| {
ty.specifier = .attributed;
ty.data = .{ .attributed = data };
},
}
try b.qual.finish(p, &ty);
if (b.align_tok) |align_tok| {
const default = ty.alignof(p.pp.comp);
if (ty.isFunc()) {
try p.errTok(.alignas_on_func, align_tok);
} else if (b.alignment != 0 and b.alignment < default) {
try p.errExtra(.minimum_alignment, align_tok, .{ .unsigned = default });
} else {
ty.alignment = b.alignment;
}
}
return ty;
}
fn cannotCombine(b: Builder, p: *Parser, source_tok: TokenIndex) !void {
if (b.error_on_invalid) return error.CannotCombine;
const prev_ty = b.finish(p) catch unreachable;
try p.errExtra(.cannot_combine_spec, source_tok, .{ .str = try p.typeStr(prev_ty) });
if (b.typedef) |some| try p.errStr(.spec_from_typedef, some.tok, try p.typeStr(some.ty));
}
fn duplicateSpec(b: *Builder, p: *Parser, spec: []const u8) !void {
if (b.error_on_invalid) return error.CannotCombine;
try p.errStr(.duplicate_decl_spec, p.tok_i, spec);
}
pub fn combineFromTypeof(b: *Builder, p: *Parser, new: Type, source_tok: TokenIndex) Compilation.Error!void {
if (b.typeof != null) return p.errStr(.cannot_combine_spec, source_tok, "typeof");
if (b.specifier != .none) return p.errStr(.invalid_typeof, source_tok, @tagName(b.specifier));
const inner = switch (new.specifier) {
.typeof_type => new.data.sub_type.*,
.typeof_expr => new.data.expr.ty,
else => unreachable,
};
b.typeof = switch (inner.specifier) {
.attributed => inner.data.attributed.base,
else => new,
};
}
/// Try to combine type from typedef, returns true if successful.
pub fn combineTypedef(b: *Builder, p: *Parser, typedef_ty: Type, name_tok: TokenIndex) Compilation.Error!bool {
b.error_on_invalid = true;
defer b.error_on_invalid = false;
const new_spec = fromType(typedef_ty);
b.combineExtra(p, new_spec, 0) catch |err| switch (err) {
error.FatalError => unreachable, // we do not add any diagnostics
error.OutOfMemory => unreachable, // we do not add any diagnostics
error.CannotCombine => return false,
};
b.typedef = .{ .tok = name_tok, .ty = typedef_ty };
return true;
}
pub fn combine(b: *Builder, p: *Parser, new: Builder.Specifier, source_tok: TokenIndex) Compilation.Error!void {
b.combineExtra(p, new, source_tok) catch |err| switch (err) {
error.CannotCombine => unreachable,
else => |e| return e,
};
}
fn combineExtra(b: *Builder, p: *Parser, new: Builder.Specifier, source_tok: TokenIndex) !void {
if (b.typeof != null) {
if (b.error_on_invalid) return error.CannotCombine;
try p.errStr(.invalid_typeof, source_tok, @tagName(new));
}
switch (new) {
else => switch (b.specifier) {
.none => b.specifier = new,
else => return b.cannotCombine(p, source_tok),
},
.signed => b.specifier = switch (b.specifier) {
.none => .signed,
.char => .schar,
.short => .sshort,
.short_int => .sshort_int,
.int => .sint,
.long => .slong,
.long_int => .slong_int,
.long_long => .slong_long,
.long_long_int => .slong_long_int,
.sshort,
.sshort_int,
.sint,
.slong,
.slong_int,
.slong_long,
.slong_long_int,
=> return b.duplicateSpec(p, "signed"),
else => return b.cannotCombine(p, source_tok),
},
.unsigned => b.specifier = switch (b.specifier) {
.none => .unsigned,
.char => .uchar,
.short => .ushort,
.short_int => .ushort_int,
.int => .uint,
.long => .ulong,
.long_int => .ulong_int,
.long_long => .ulong_long,
.long_long_int => .ulong_long_int,
.ushort,
.ushort_int,
.uint,
.ulong,
.ulong_int,
.ulong_long,
.ulong_long_int,
=> return b.duplicateSpec(p, "unsigned"),
else => return b.cannotCombine(p, source_tok),
},
.char => b.specifier = switch (b.specifier) {
.none => .char,
.unsigned => .uchar,
.signed => .schar,
.char, .schar, .uchar => return b.duplicateSpec(p, "char"),
else => return b.cannotCombine(p, source_tok),
},
.short => b.specifier = switch (b.specifier) {
.none => .short,
.unsigned => .ushort,
.signed => .sshort,
else => return b.cannotCombine(p, source_tok),
},
.int => b.specifier = switch (b.specifier) {
.none => .int,
.signed => .sint,
.unsigned => .uint,
.short => .short_int,
.sshort => .sshort_int,
.ushort => .ushort_int,
.long => .long_int,
.slong => .slong_int,
.ulong => .ulong_int,
.long_long => .long_long_int,
.slong_long => .slong_long_int,
.ulong_long => .ulong_long_int,
.int,
.sint,
.uint,
.short_int,
.sshort_int,
.ushort_int,
.long_int,
.slong_int,
.ulong_int,
.long_long_int,
.slong_long_int,
.ulong_long_int,
=> return b.duplicateSpec(p, "int"),
else => return b.cannotCombine(p, source_tok),
},
.long => b.specifier = switch (b.specifier) {
.none => .long,
.long => .long_long,
.unsigned => .ulong,
.signed => .long,
.int => .long_int,
.sint => .slong_int,
.ulong => .ulong_long,
.long_long, .ulong_long => return b.duplicateSpec(p, "long"),
else => return b.cannotCombine(p, source_tok),
},
.float => b.specifier = switch (b.specifier) {
.none => .float,
.complex => .complex_float,
.complex_float, .float => return b.duplicateSpec(p, "float"),
else => return b.cannotCombine(p, source_tok),
},
.double => b.specifier = switch (b.specifier) {
.none => .double,
.long => .long_double,
.complex_long => .complex_long_double,
.complex => .complex_double,
.long_double,
.complex_long_double,
.complex_double,
.double,
=> return b.duplicateSpec(p, "double"),
else => return b.cannotCombine(p, source_tok),
},
.complex => b.specifier = switch (b.specifier) {
.none => .complex,
.long => .complex_long,
.float => .complex_float,
.double => .complex_double,
.long_double => .complex_long_double,
.complex,
.complex_long,
.complex_float,
.complex_double,
.complex_long_double,
=> return b.duplicateSpec(p, "_Complex"),
else => return b.cannotCombine(p, source_tok),
},
}
}
pub fn fromType(ty: Type) Builder.Specifier {
return switch (ty.specifier) {
.void => .void,
.bool => .bool,
.char => .char,
.schar => .schar,
.uchar => .uchar,
.short => .short,
.ushort => .ushort,
.int => .int,
.uint => .uint,
.long => .long,
.ulong => .ulong,
.long_long => .long_long,
.ulong_long => .ulong_long,
.float => .float,
.double => .double,
.long_double => .long_double,
.complex_float => .complex_float,
.complex_double => .complex_double,
.complex_long_double => .complex_long_double,
.pointer => .{ .pointer = ty.data.sub_type },
.unspecified_variable_len_array => .{ .unspecified_variable_len_array = ty.data.sub_type },
.decayed_unspecified_variable_len_array => .{ .decayed_unspecified_variable_len_array = ty.data.sub_type },
.func => .{ .func = ty.data.func },
.var_args_func => .{ .var_args_func = ty.data.func },
.old_style_func => .{ .old_style_func = ty.data.func },
.array => .{ .array = ty.data.array },
.decayed_array => .{ .decayed_array = ty.data.array },
.static_array => .{ .static_array = ty.data.array },
.decayed_static_array => .{ .decayed_static_array = ty.data.array },
.incomplete_array => .{ .incomplete_array = ty.data.array },
.decayed_incomplete_array => .{ .decayed_incomplete_array = ty.data.array },
.variable_len_array => .{ .variable_len_array = ty.data.expr },
.decayed_variable_len_array => .{ .decayed_variable_len_array = ty.data.expr },
.@"struct" => .{ .@"struct" = ty.data.record },
.@"union" => .{ .@"union" = ty.data.record },
.@"enum" => .{ .@"enum" = ty.data.@"enum" },
.typeof_type => .{ .typeof_type = ty.data.sub_type },
.decayed_typeof_type => .{ .decayed_typeof_type = ty.data.sub_type },
.typeof_expr => .{ .typeof_expr = ty.data.expr },
.decayed_typeof_expr => .{ .decayed_typeof_expr = ty.data.expr },
.attributed => .{ .attributed = ty.data.attributed },
};
}
};
/// Print type in C style
pub fn print(ty: Type, w: anytype) @TypeOf(w).Error!void {
_ = try ty.printPrologue(w);
try ty.printEpilogue(w);
}
pub fn printNamed(ty: Type, name: []const u8, w: anytype) @TypeOf(w).Error!void {
const simple = try ty.printPrologue(w);
if (simple) try w.writeByte(' ');
try w.writeAll(name);
try ty.printEpilogue(w);
}
/// return true if `ty` is simple
fn printPrologue(ty: Type, w: anytype) @TypeOf(w).Error!bool {
if (ty.qual.atomic) {
var non_atomic_ty = ty;
non_atomic_ty.qual.atomic = false;
try w.writeAll("_Atomic(");
try non_atomic_ty.print(w);
try w.writeAll(")");
return true;
}
switch (ty.specifier) {
.pointer,
.decayed_array,
.decayed_static_array,
.decayed_incomplete_array,
.decayed_variable_len_array,
.decayed_unspecified_variable_len_array,
.decayed_typeof_type,
.decayed_typeof_expr,
=> {
const elem_ty = ty.elemType();
const simple = try elem_ty.printPrologue(w);
if (simple) try w.writeByte(' ');
if (elem_ty.isFunc() or elem_ty.isArray()) try w.writeByte('(');
try w.writeByte('*');
try ty.qual.dump(w);
if (ty.alignment != 0) try w.print(" _Alignas({d})", .{ty.alignment});
return false;
},
.func, .var_args_func, .old_style_func => {
const ret_ty = ty.data.func.return_type;
const simple = try ret_ty.printPrologue(w);
if (simple) try w.writeByte(' ');
return false;
},
.array, .static_array, .incomplete_array, .unspecified_variable_len_array, .variable_len_array => {
const elem_ty = ty.elemType();
const simple = try elem_ty.printPrologue(w);
if (simple) try w.writeByte(' ');
return false;
},
.typeof_type, .typeof_expr => {
const actual = ty.canonicalize(.standard);
return actual.printPrologue(w);
},
.attributed => {
const actual = ty.canonicalize(.standard);
return actual.printPrologue(w);
},
else => {},
}
try ty.qual.dump(w);
if (ty.alignment != 0) try w.print("_Alignas({d}) ", .{ty.alignment});
switch (ty.specifier) {
.@"enum" => try w.print("enum {s}", .{ty.data.@"enum".name}),
.@"struct" => try w.print("struct {s}", .{ty.data.record.name}),
.@"union" => try w.print("union {s}", .{ty.data.record.name}),
else => try w.writeAll(Builder.fromType(ty).str().?),
}
return true;
}
fn printEpilogue(ty: Type, w: anytype) @TypeOf(w).Error!void {
if (ty.qual.atomic) return;
switch (ty.specifier) {
.pointer,
.decayed_array,
.decayed_static_array,
.decayed_incomplete_array,
.decayed_variable_len_array,
.decayed_unspecified_variable_len_array,
.decayed_typeof_type,
.decayed_typeof_expr,
=> {
const elem_ty = ty.elemType();
if (elem_ty.isFunc() or elem_ty.isArray()) try w.writeByte(')');
try elem_ty.printEpilogue(w);
},
.func, .var_args_func, .old_style_func => {
try w.writeByte('(');
for (ty.data.func.params) |param, i| {
if (i != 0) try w.writeAll(", ");
_ = try param.ty.printPrologue(w);
try param.ty.printEpilogue(w);
}
if (ty.specifier != .func) {
if (ty.data.func.params.len != 0) try w.writeAll(", ");
try w.writeAll("...");
} else if (ty.data.func.params.len == 0) {
try w.writeAll("void");
}
try w.writeByte(')');
try ty.data.func.return_type.printEpilogue(w);
},
.array, .static_array => {
try w.writeByte('[');
if (ty.specifier == .static_array) try w.writeAll("static ");
try ty.qual.dump(w);
if (ty.alignment != 0) try w.print(" _Alignas({d})", .{ty.alignment});
try w.print("{d}]", .{ty.data.array.len});
try ty.data.array.elem.printEpilogue(w);
},
.incomplete_array => {
try w.writeByte('[');
try ty.qual.dump(w);
if (ty.alignment != 0) try w.print(" _Alignas({d})", .{ty.alignment});
try w.writeByte(']');
try ty.data.array.elem.printEpilogue(w);
},
.unspecified_variable_len_array => {
try w.writeByte('[');
try ty.qual.dump(w);
if (ty.alignment != 0) try w.print(" _Alignas({d})", .{ty.alignment});
try w.writeAll("*]");
try ty.data.sub_type.printEpilogue(w);
},
.variable_len_array => {
try w.writeByte('[');
try ty.qual.dump(w);
if (ty.alignment != 0) try w.print(" _Alignas({d})", .{ty.alignment});
try w.writeAll("<expr>]");
try ty.data.expr.ty.printEpilogue(w);
},
else => {},
}
}
/// Useful for debugging, too noisy to be enabled by default.
const dump_detailed_containers = false;
// Print as Zig types since those are actually readable
pub fn dump(ty: Type, w: anytype) @TypeOf(w).Error!void {
try ty.qual.dump(w);
if (ty.alignment != 0) try w.print("_Alignas({d}) ", .{ty.alignment});
switch (ty.specifier) {
.pointer => {
try w.writeAll("*");
try ty.data.sub_type.dump(w);
},
.func, .var_args_func, .old_style_func => {
try w.writeAll("fn (");
for (ty.data.func.params) |param, i| {
if (i != 0) try w.writeAll(", ");
if (param.name.len != 0) try w.print("{s}: ", .{param.name});
try param.ty.dump(w);
}
if (ty.specifier != .func) {
if (ty.data.func.params.len != 0) try w.writeAll(", ");
try w.writeAll("...");
}
try w.writeAll(") ");
try ty.data.func.return_type.dump(w);
},
.array, .static_array, .decayed_array, .decayed_static_array => {
if (ty.specifier == .decayed_array or ty.specifier == .decayed_static_array) try w.writeByte('d');
try w.writeByte('[');
if (ty.specifier == .static_array or ty.specifier == .decayed_static_array) try w.writeAll("static ");
try w.print("{d}]", .{ty.data.array.len});
try ty.data.array.elem.dump(w);
},
.incomplete_array, .decayed_incomplete_array => {
if (ty.specifier == .decayed_incomplete_array) try w.writeByte('d');
try w.writeAll("[]");
try ty.data.array.elem.dump(w);
},
.@"enum" => {
try w.print("enum {s}", .{ty.data.@"enum".name});
if (dump_detailed_containers) try dumpEnum(ty.data.@"enum", w);
},
.@"struct" => {
try w.print("struct {s}", .{ty.data.record.name});
if (dump_detailed_containers) try dumpRecord(ty.data.record, w);
},
.@"union" => {
try w.print("union {s}", .{ty.data.record.name});
if (dump_detailed_containers) try dumpRecord(ty.data.record, w);
},
.unspecified_variable_len_array, .decayed_unspecified_variable_len_array => {
if (ty.specifier == .decayed_unspecified_variable_len_array) try w.writeByte('d');
try w.writeAll("[*]");
try ty.data.sub_type.dump(w);
},
.variable_len_array, .decayed_variable_len_array => {
if (ty.specifier == .decayed_variable_len_array) try w.writeByte('d');
try w.writeAll("[<expr>]");
try ty.data.expr.ty.dump(w);
},
.typeof_type, .decayed_typeof_type => {
try w.writeAll("typeof(");
try ty.data.sub_type.dump(w);
try w.writeAll(")");
},
.typeof_expr, .decayed_typeof_expr => {
try w.writeAll("typeof(<expr>: ");
try ty.data.expr.ty.dump(w);
try w.writeAll(")");
},
.attributed => {
try w.writeAll("attributed(");
try ty.data.attributed.base.dump(w);
try w.writeAll(")");
},
else => try w.writeAll(Builder.fromType(ty).str().?),
}
}
fn dumpEnum(@"enum": *Enum, w: anytype) @TypeOf(w).Error!void {
try w.writeAll(" {");
for (@"enum".fields) |field| {
try w.print(" {s} = {d},", .{ field.name, field.value });
}
try w.writeAll(" }");
}
fn dumpRecord(record: *Record, w: anytype) @TypeOf(w).Error!void {
try w.writeAll(" {");
for (record.fields) |field| {
try w.writeByte(' ');
try field.ty.dump(w);
try w.print(" {s}: {d};", .{ field.name, field.bit_width });
}
try w.writeAll(" }");
} | src/Type.zig |
const std = @import("std.zig");
const builtin = @import("builtin");
const assert = debug.assert;
const autoHash = std.hash.autoHash;
const debug = std.debug;
const warn = debug.warn;
const math = std.math;
const mem = std.mem;
const meta = std.meta;
const trait = meta.trait;
const Allocator = mem.Allocator;
const Wyhash = std.hash.Wyhash;
pub fn getAutoHashFn(comptime K: type) (fn (K) u64) {
return struct {
fn hash(key: K) u64 {
if (comptime trait.hasUniqueRepresentation(K)) {
return Wyhash.hash(0, std.mem.asBytes(&key));
} else {
var hasher = Wyhash.init(0);
autoHash(&hasher, key);
return hasher.final();
}
}
}.hash;
}
pub fn getAutoEqlFn(comptime K: type) (fn (K, K) bool) {
return struct {
fn eql(a: K, b: K) bool {
return meta.eql(a, b);
}
}.eql;
}
pub fn AutoHashMap(comptime K: type, comptime V: type) type {
return HashMap(K, V, getAutoHashFn(K), getAutoEqlFn(K), DefaultMaxLoadPercentage);
}
pub fn AutoHashMapUnmanaged(comptime K: type, comptime V: type) type {
return HashMapUnmanaged(K, V, getAutoHashFn(K), getAutoEqlFn(K), DefaultMaxLoadPercentage);
}
/// Builtin hashmap for strings as keys.
pub fn StringHashMap(comptime V: type) type {
return HashMap([]const u8, V, hashString, eqlString, DefaultMaxLoadPercentage);
}
pub fn StringHashMapUnmanaged(comptime V: type) type {
return HashMapUnmanaged([]const u8, V, hashString, eqlString, DefaultMaxLoadPercentage);
}
pub fn eqlString(a: []const u8, b: []const u8) bool {
return mem.eql(u8, a, b);
}
pub fn hashString(s: []const u8) u64 {
return std.hash.Wyhash.hash(0, s);
}
pub const DefaultMaxLoadPercentage = 80;
/// General purpose hash table.
/// No order is guaranteed and any modification invalidates live iterators.
/// It provides fast operations (lookup, insertion, deletion) with quite high
/// load factors (up to 80% by default) for a low memory usage.
/// For a hash map that can be initialized directly that does not store an Allocator
/// field, see `HashMapUnmanaged`.
/// If iterating over the table entries is a strong usecase and needs to be fast,
/// prefer the alternative `std.ArrayHashMap`.
pub fn HashMap(
comptime K: type,
comptime V: type,
comptime hashFn: fn (key: K) u64,
comptime eqlFn: fn (a: K, b: K) bool,
comptime MaxLoadPercentage: u64,
) type {
return struct {
unmanaged: Unmanaged,
allocator: *Allocator,
pub const Unmanaged = HashMapUnmanaged(K, V, hashFn, eqlFn, MaxLoadPercentage);
pub const Entry = Unmanaged.Entry;
pub const Hash = Unmanaged.Hash;
pub const Iterator = Unmanaged.Iterator;
pub const Size = Unmanaged.Size;
pub const GetOrPutResult = Unmanaged.GetOrPutResult;
const Self = @This();
pub fn init(allocator: *Allocator) Self {
return .{
.unmanaged = .{},
.allocator = allocator,
};
}
pub fn deinit(self: *Self) void {
self.unmanaged.deinit(self.allocator);
self.* = undefined;
}
pub fn clearRetainingCapacity(self: *Self) void {
return self.unmanaged.clearRetainingCapacity();
}
pub fn clearAndFree(self: *Self) void {
return self.unmanaged.clearAndFree(self.allocator);
}
pub fn count(self: Self) Size {
return self.unmanaged.count();
}
pub fn iterator(self: *const Self) Iterator {
return self.unmanaged.iterator();
}
/// If key exists this function cannot fail.
/// If there is an existing item with `key`, then the result
/// `Entry` pointer points to it, and found_existing is true.
/// Otherwise, puts a new item with undefined value, and
/// the `Entry` pointer points to it. Caller should then initialize
/// the value (but not the key).
pub fn getOrPut(self: *Self, key: K) !GetOrPutResult {
return self.unmanaged.getOrPut(self.allocator, key);
}
/// If there is an existing item with `key`, then the result
/// `Entry` pointer points to it, and found_existing is true.
/// Otherwise, puts a new item with undefined value, and
/// the `Entry` pointer points to it. Caller should then initialize
/// the value (but not the key).
/// If a new entry needs to be stored, this function asserts there
/// is enough capacity to store it.
pub fn getOrPutAssumeCapacity(self: *Self, key: K) GetOrPutResult {
return self.unmanaged.getOrPutAssumeCapacity(key);
}
pub fn getOrPutValue(self: *Self, key: K, value: V) !*Entry {
return self.unmanaged.getOrPutValue(self.allocator, key, value);
}
/// Increases capacity, guaranteeing that insertions up until the
/// `expected_count` will not cause an allocation, and therefore cannot fail.
pub fn ensureCapacity(self: *Self, expected_count: Size) !void {
return self.unmanaged.ensureCapacity(self.allocator, expected_count);
}
/// Returns the number of total elements which may be present before it is
/// no longer guaranteed that no allocations will be performed.
pub fn capacity(self: *Self) Size {
return self.unmanaged.capacity();
}
/// Clobbers any existing data. To detect if a put would clobber
/// existing data, see `getOrPut`.
pub fn put(self: *Self, key: K, value: V) !void {
return self.unmanaged.put(self.allocator, key, value);
}
/// Inserts a key-value pair into the hash map, asserting that no previous
/// entry with the same key is already present
pub fn putNoClobber(self: *Self, key: K, value: V) !void {
return self.unmanaged.putNoClobber(self.allocator, key, value);
}
/// Asserts there is enough capacity to store the new key-value pair.
/// Clobbers any existing data. To detect if a put would clobber
/// existing data, see `getOrPutAssumeCapacity`.
pub fn putAssumeCapacity(self: *Self, key: K, value: V) void {
return self.unmanaged.putAssumeCapacity(key, value);
}
/// Asserts there is enough capacity to store the new key-value pair.
/// Asserts that it does not clobber any existing data.
/// To detect if a put would clobber existing data, see `getOrPutAssumeCapacity`.
pub fn putAssumeCapacityNoClobber(self: *Self, key: K, value: V) void {
return self.unmanaged.putAssumeCapacityNoClobber(key, value);
}
/// Inserts a new `Entry` into the hash map, returning the previous one, if any.
pub fn fetchPut(self: *Self, key: K, value: V) !?Entry {
return self.unmanaged.fetchPut(self.allocator, key, value);
}
/// Inserts a new `Entry` into the hash map, returning the previous one, if any.
/// If insertion happuns, asserts there is enough capacity without allocating.
pub fn fetchPutAssumeCapacity(self: *Self, key: K, value: V) ?Entry {
return self.unmanaged.fetchPutAssumeCapacity(key, value);
}
pub fn get(self: Self, key: K) ?V {
return self.unmanaged.get(key);
}
pub fn getEntry(self: Self, key: K) ?*Entry {
return self.unmanaged.getEntry(key);
}
pub fn contains(self: Self, key: K) bool {
return self.unmanaged.contains(key);
}
/// If there is an `Entry` with a matching key, it is deleted from
/// the hash map, and then returned from this function.
pub fn remove(self: *Self, key: K) ?Entry {
return self.unmanaged.remove(key);
}
/// Asserts there is an `Entry` with matching key, deletes it from the hash map,
/// and discards it.
pub fn removeAssertDiscard(self: *Self, key: K) void {
return self.unmanaged.removeAssertDiscard(key);
}
pub fn clone(self: Self) !Self {
var other = try self.unmanaged.clone(self.allocator);
return other.promote(self.allocator);
}
};
}
/// A HashMap based on open addressing and linear probing.
/// A lookup or modification typically occurs only 2 cache misses.
/// No order is guaranteed and any modification invalidates live iterators.
/// It achieves good performance with quite high load factors (by default,
/// grow is triggered at 80% full) and only one byte of overhead per element.
/// The struct itself is only 16 bytes for a small footprint. This comes at
/// the price of handling size with u32, which should be reasonnable enough
/// for almost all uses.
/// Deletions are achieved with tombstones.
pub fn HashMapUnmanaged(
comptime K: type,
comptime V: type,
hashFn: fn (key: K) u64,
eqlFn: fn (a: K, b: K) bool,
comptime MaxLoadPercentage: u64,
) type {
comptime assert(MaxLoadPercentage > 0 and MaxLoadPercentage < 100);
return struct {
const Self = @This();
// This is actually a midway pointer to the single buffer containing
// a `Header` field, the `Metadata`s and `Entry`s.
// At `-@sizeOf(Header)` is the Header field.
// At `sizeOf(Metadata) * capacity + offset`, which is pointed to by
// self.header().entries, is the array of entries.
// This means that the hashmap only holds one live allocation, to
// reduce memory fragmentation and struct size.
/// Pointer to the metadata.
metadata: ?[*]Metadata = null,
/// Current number of elements in the hashmap.
size: Size = 0,
// Having a countdown to grow reduces the number of instructions to
// execute when determining if the hashmap has enough capacity already.
/// Number of available slots before a grow is needed to satisfy the
/// `MaxLoadPercentage`.
available: Size = 0,
// This is purely empirical and not a /very smart magic constant™/.
/// Capacity of the first grow when bootstrapping the hashmap.
const MinimalCapacity = 8;
// This hashmap is specially designed for sizes that fit in a u32.
const Size = u32;
// u64 hashes guarantee us that the fingerprint bits will never be used
// to compute the index of a slot, maximizing the use of entropy.
const Hash = u64;
pub const Entry = struct {
key: K,
value: V,
};
const Header = packed struct {
entries: [*]Entry,
capacity: Size,
};
/// Metadata for a slot. It can be in three states: empty, used or
/// tombstone. Tombstones indicate that an entry was previously used,
/// they are a simple way to handle removal.
/// To this state, we add 6 bits from the slot's key hash. These are
/// used as a fast way to disambiguate between entries without
/// having to use the equality function. If two fingerprints are
/// different, we know that we don't have to compare the keys at all.
/// The 6 bits are the highest ones from a 64 bit hash. This way, not
/// only we use the `log2(capacity)` lowest bits from the hash to determine
/// a slot index, but we use 6 more bits to quickly resolve collisions
/// when multiple elements with different hashes end up wanting to be in / the same slot.
/// Not using the equality function means we don't have to read into
/// the entries array, avoiding a likely cache miss.
const Metadata = packed struct {
const FingerPrint = u6;
used: u1 = 0,
tombstone: u1 = 0,
fingerprint: FingerPrint = 0,
pub fn isUsed(self: Metadata) bool {
return self.used == 1;
}
pub fn isTombstone(self: Metadata) bool {
return self.tombstone == 1;
}
pub fn takeFingerprint(hash: Hash) FingerPrint {
const hash_bits = @typeInfo(Hash).Int.bits;
const fp_bits = @typeInfo(FingerPrint).Int.bits;
return @truncate(FingerPrint, hash >> (hash_bits - fp_bits));
}
pub fn fill(self: *Metadata, fp: FingerPrint) void {
self.used = 1;
self.tombstone = 0;
self.fingerprint = fp;
}
pub fn remove(self: *Metadata) void {
self.used = 0;
self.tombstone = 1;
self.fingerprint = 0;
}
};
comptime {
assert(@sizeOf(Metadata) == 1);
assert(@alignOf(Metadata) == 1);
}
const Iterator = struct {
hm: *const Self,
index: Size = 0,
pub fn next(it: *Iterator) ?*Entry {
assert(it.index <= it.hm.capacity());
if (it.hm.size == 0) return null;
const cap = it.hm.capacity();
const end = it.hm.metadata.? + cap;
var metadata = it.hm.metadata.? + it.index;
while (metadata != end) : ({
metadata += 1;
it.index += 1;
}) {
if (metadata[0].isUsed()) {
const entry = &it.hm.entries()[it.index];
it.index += 1;
return entry;
}
}
return null;
}
};
pub const GetOrPutResult = struct {
entry: *Entry,
found_existing: bool,
};
pub const Managed = HashMap(K, V, hashFn, eqlFn, MaxLoadPercentage);
pub fn promote(self: Self, allocator: *Allocator) Managed {
return .{
.unmanaged = self,
.allocator = allocator,
};
}
fn isUnderMaxLoadPercentage(size: Size, cap: Size) bool {
return size * 100 < MaxLoadPercentage * cap;
}
pub fn init(allocator: *Allocator) Self {
return .{};
}
pub fn deinit(self: *Self, allocator: *Allocator) void {
self.deallocate(allocator);
self.* = undefined;
}
fn deallocate(self: *Self, allocator: *Allocator) void {
if (self.metadata == null) return;
const cap = self.capacity();
const meta_size = @sizeOf(Header) + cap * @sizeOf(Metadata);
const alignment = @alignOf(Entry) - 1;
const entries_size = @as(usize, cap) * @sizeOf(Entry) + alignment;
const total_size = meta_size + entries_size;
var slice: []u8 = undefined;
slice.ptr = @intToPtr([*]u8, @ptrToInt(self.header()));
slice.len = total_size;
allocator.free(slice);
self.metadata = null;
self.available = 0;
}
fn capacityForSize(size: Size) Size {
var new_cap = @truncate(u32, (@as(u64, size) * 100) / MaxLoadPercentage + 1);
new_cap = math.ceilPowerOfTwo(u32, new_cap) catch unreachable;
return new_cap;
}
pub fn ensureCapacity(self: *Self, allocator: *Allocator, new_size: Size) !void {
if (new_size > self.size)
try self.growIfNeeded(allocator, new_size - self.size);
}
pub fn clearRetainingCapacity(self: *Self) void {
if (self.metadata) |_| {
self.initMetadatas();
self.size = 0;
self.available = @truncate(u32, (self.capacity() * MaxLoadPercentage) / 100);
}
}
pub fn clearAndFree(self: *Self, allocator: *Allocator) void {
self.deallocate(allocator);
self.size = 0;
self.available = 0;
}
pub fn count(self: *const Self) Size {
return self.size;
}
fn header(self: *const Self) *Header {
return @ptrCast(*Header, @ptrCast([*]Header, self.metadata.?) - 1);
}
fn entries(self: *const Self) [*]Entry {
return self.header().entries;
}
pub fn capacity(self: *const Self) Size {
if (self.metadata == null) return 0;
return self.header().capacity;
}
pub fn iterator(self: *const Self) Iterator {
return .{ .hm = self };
}
/// Insert an entry in the map. Assumes it is not already present.
pub fn putNoClobber(self: *Self, allocator: *Allocator, key: K, value: V) !void {
assert(!self.contains(key));
try self.growIfNeeded(allocator, 1);
self.putAssumeCapacityNoClobber(key, value);
}
/// Asserts there is enough capacity to store the new key-value pair.
/// Clobbers any existing data. To detect if a put would clobber
/// existing data, see `getOrPutAssumeCapacity`.
pub fn putAssumeCapacity(self: *Self, key: K, value: V) void {
const gop = self.getOrPutAssumeCapacity(key);
gop.entry.value = value;
}
/// Insert an entry in the map. Assumes it is not already present,
/// and that no allocation is needed.
pub fn putAssumeCapacityNoClobber(self: *Self, key: K, value: V) void {
assert(!self.contains(key));
const hash = hashFn(key);
const mask = self.capacity() - 1;
var idx = @truncate(usize, hash & mask);
var metadata = self.metadata.? + idx;
while (metadata[0].isUsed()) {
idx = (idx + 1) & mask;
metadata = self.metadata.? + idx;
}
if (!metadata[0].isTombstone()) {
assert(self.available > 0);
self.available -= 1;
}
const fingerprint = Metadata.takeFingerprint(hash);
metadata[0].fill(fingerprint);
self.entries()[idx] = Entry{ .key = key, .value = value };
self.size += 1;
}
/// Inserts a new `Entry` into the hash map, returning the previous one, if any.
pub fn fetchPut(self: *Self, allocator: *Allocator, key: K, value: V) !?Entry {
const gop = try self.getOrPut(allocator, key);
var result: ?Entry = null;
if (gop.found_existing) {
result = gop.entry.*;
}
gop.entry.value = value;
return result;
}
/// Inserts a new `Entry` into the hash map, returning the previous one, if any.
/// If insertion happens, asserts there is enough capacity without allocating.
pub fn fetchPutAssumeCapacity(self: *Self, key: K, value: V) ?Entry {
const gop = self.getOrPutAssumeCapacity(key);
var result: ?Entry = null;
if (gop.found_existing) {
result = gop.entry.*;
}
gop.entry.value = value;
return result;
}
pub fn getEntry(self: Self, key: K) ?*Entry {
if (self.size == 0) {
return null;
}
const hash = hashFn(key);
const mask = self.capacity() - 1;
const fingerprint = Metadata.takeFingerprint(hash);
var idx = @truncate(usize, hash & mask);
var metadata = self.metadata.? + idx;
while (metadata[0].isUsed() or metadata[0].isTombstone()) {
if (metadata[0].isUsed() and metadata[0].fingerprint == fingerprint) {
const entry = &self.entries()[idx];
if (eqlFn(entry.key, key)) {
return entry;
}
}
idx = (idx + 1) & mask;
metadata = self.metadata.? + idx;
}
return null;
}
/// Insert an entry if the associated key is not already present, otherwise update preexisting value.
/// Returns true if the key was already present.
pub fn put(self: *Self, allocator: *Allocator, key: K, value: V) !void {
const result = try self.getOrPut(allocator, key);
result.entry.value = value;
}
/// Get an optional pointer to the value associated with key, if present.
pub fn get(self: Self, key: K) ?V {
if (self.size == 0) {
return null;
}
const hash = hashFn(key);
const mask = self.capacity() - 1;
const fingerprint = Metadata.takeFingerprint(hash);
var idx = @truncate(usize, hash & mask);
var metadata = self.metadata.? + idx;
while (metadata[0].isUsed() or metadata[0].isTombstone()) {
if (metadata[0].isUsed() and metadata[0].fingerprint == fingerprint) {
const entry = &self.entries()[idx];
if (eqlFn(entry.key, key)) {
return entry.value;
}
}
idx = (idx + 1) & mask;
metadata = self.metadata.? + idx;
}
return null;
}
pub fn getOrPut(self: *Self, allocator: *Allocator, key: K) !GetOrPutResult {
try self.growIfNeeded(allocator, 1);
return self.getOrPutAssumeCapacity(key);
}
pub fn getOrPutAssumeCapacity(self: *Self, key: K) GetOrPutResult {
const hash = hashFn(key);
const mask = self.capacity() - 1;
const fingerprint = Metadata.takeFingerprint(hash);
var idx = @truncate(usize, hash & mask);
var first_tombstone_idx: usize = self.capacity(); // invalid index
var metadata = self.metadata.? + idx;
while (metadata[0].isUsed() or metadata[0].isTombstone()) {
if (metadata[0].isUsed() and metadata[0].fingerprint == fingerprint) {
const entry = &self.entries()[idx];
if (eqlFn(entry.key, key)) {
return GetOrPutResult{ .entry = entry, .found_existing = true };
}
} else if (first_tombstone_idx == self.capacity() and metadata[0].isTombstone()) {
first_tombstone_idx = idx;
}
idx = (idx + 1) & mask;
metadata = self.metadata.? + idx;
}
if (first_tombstone_idx < self.capacity()) {
// Cheap try to lower probing lengths after deletions. Recycle a tombstone.
idx = first_tombstone_idx;
metadata = self.metadata.? + idx;
} else {
// We're using a slot previously free.
self.available -= 1;
}
metadata[0].fill(fingerprint);
const entry = &self.entries()[idx];
entry.* = .{ .key = key, .value = undefined };
self.size += 1;
return GetOrPutResult{ .entry = entry, .found_existing = false };
}
pub fn getOrPutValue(self: *Self, allocator: *Allocator, key: K, value: V) !*Entry {
const res = try self.getOrPut(allocator, key);
if (!res.found_existing) res.entry.value = value;
return res.entry;
}
/// Return true if there is a value associated with key in the map.
pub fn contains(self: *const Self, key: K) bool {
return self.get(key) != null;
}
/// If there is an `Entry` with a matching key, it is deleted from
/// the hash map, and then returned from this function.
pub fn remove(self: *Self, key: K) ?Entry {
if (self.size == 0) return null;
const hash = hashFn(key);
const mask = self.capacity() - 1;
const fingerprint = Metadata.takeFingerprint(hash);
var idx = @truncate(usize, hash & mask);
var metadata = self.metadata.? + idx;
while (metadata[0].isUsed() or metadata[0].isTombstone()) {
if (metadata[0].isUsed() and metadata[0].fingerprint == fingerprint) {
const entry = &self.entries()[idx];
if (eqlFn(entry.key, key)) {
const removed_entry = entry.*;
metadata[0].remove();
entry.* = undefined;
self.size -= 1;
return removed_entry;
}
}
idx = (idx + 1) & mask;
metadata = self.metadata.? + idx;
}
return null;
}
/// Asserts there is an `Entry` with matching key, deletes it from the hash map,
/// and discards it.
pub fn removeAssertDiscard(self: *Self, key: K) void {
assert(self.contains(key));
const hash = hashFn(key);
const mask = self.capacity() - 1;
const fingerprint = Metadata.takeFingerprint(hash);
var idx = @truncate(usize, hash & mask);
var metadata = self.metadata.? + idx;
while (metadata[0].isUsed() or metadata[0].isTombstone()) {
if (metadata[0].isUsed() and metadata[0].fingerprint == fingerprint) {
const entry = &self.entries()[idx];
if (eqlFn(entry.key, key)) {
metadata[0].remove();
entry.* = undefined;
self.size -= 1;
return;
}
}
idx = (idx + 1) & mask;
metadata = self.metadata.? + idx;
}
unreachable;
}
fn initMetadatas(self: *Self) void {
@memset(@ptrCast([*]u8, self.metadata.?), 0, @sizeOf(Metadata) * self.capacity());
}
// This counts the number of occupied slots, used + tombstones, which is
// what has to stay under the MaxLoadPercentage of capacity.
fn load(self: *const Self) Size {
const max_load = (self.capacity() * MaxLoadPercentage) / 100;
assert(max_load >= self.available);
return @truncate(Size, max_load - self.available);
}
fn growIfNeeded(self: *Self, allocator: *Allocator, new_count: Size) !void {
if (new_count > self.available) {
try self.grow(allocator, capacityForSize(self.load() + new_count));
}
}
pub fn clone(self: Self, allocator: *Allocator) !Self {
var other = Self{};
if (self.size == 0)
return other;
const new_cap = capacityForSize(self.size);
try other.allocate(allocator, new_cap);
other.initMetadatas();
other.available = @truncate(u32, (new_cap * MaxLoadPercentage) / 100);
var i: Size = 0;
var metadata = self.metadata.?;
var entr = self.entries();
while (i < self.capacity()) : (i += 1) {
if (metadata[i].isUsed()) {
const entry = &entr[i];
other.putAssumeCapacityNoClobber(entry.key, entry.value);
if (other.size == self.size)
break;
}
}
return other;
}
fn grow(self: *Self, allocator: *Allocator, new_capacity: Size) !void {
const new_cap = std.math.max(new_capacity, MinimalCapacity);
assert(new_cap > self.capacity());
assert(std.math.isPowerOfTwo(new_cap));
var map = Self{};
defer map.deinit(allocator);
try map.allocate(allocator, new_cap);
map.initMetadatas();
map.available = @truncate(u32, (new_cap * MaxLoadPercentage) / 100);
if (self.size != 0) {
const old_capacity = self.capacity();
var i: Size = 0;
var metadata = self.metadata.?;
var entr = self.entries();
while (i < old_capacity) : (i += 1) {
if (metadata[i].isUsed()) {
const entry = &entr[i];
map.putAssumeCapacityNoClobber(entry.key, entry.value);
if (map.size == self.size)
break;
}
}
}
self.size = 0;
std.mem.swap(Self, self, &map);
}
fn allocate(self: *Self, allocator: *Allocator, new_capacity: Size) !void {
const meta_size = @sizeOf(Header) + new_capacity * @sizeOf(Metadata);
const alignment = @alignOf(Entry) - 1;
const entries_size = @as(usize, new_capacity) * @sizeOf(Entry) + alignment;
const total_size = meta_size + entries_size;
const slice = try allocator.alignedAlloc(u8, @alignOf(Header), total_size);
const ptr = @ptrToInt(slice.ptr);
const metadata = ptr + @sizeOf(Header);
var entry_ptr = ptr + meta_size;
entry_ptr = (entry_ptr + alignment) & ~@as(usize, alignment);
assert(entry_ptr + @as(usize, new_capacity) * @sizeOf(Entry) <= ptr + total_size);
const hdr = @intToPtr(*Header, ptr);
hdr.entries = @intToPtr([*]Entry, entry_ptr);
hdr.capacity = new_capacity;
self.metadata = @intToPtr([*]Metadata, metadata);
}
};
}
const testing = std.testing;
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
test "std.hash_map basic usage" {
var map = AutoHashMap(u32, u32).init(std.testing.allocator);
defer map.deinit();
const count = 5;
var i: u32 = 0;
var total: u32 = 0;
while (i < count) : (i += 1) {
try map.put(i, i);
total += i;
}
var sum: u32 = 0;
var it = map.iterator();
while (it.next()) |kv| {
sum += kv.key;
}
expect(sum == total);
i = 0;
sum = 0;
while (i < count) : (i += 1) {
expectEqual(map.get(i).?, i);
sum += map.get(i).?;
}
expectEqual(total, sum);
}
test "std.hash_map ensureCapacity" {
var map = AutoHashMap(i32, i32).init(std.testing.allocator);
defer map.deinit();
try map.ensureCapacity(20);
const initial_capacity = map.capacity();
testing.expect(initial_capacity >= 20);
var i: i32 = 0;
while (i < 20) : (i += 1) {
testing.expect(map.fetchPutAssumeCapacity(i, i + 10) == null);
}
// shouldn't resize from putAssumeCapacity
testing.expect(initial_capacity == map.capacity());
}
test "std.hash_map ensureCapacity with tombstones" {
var map = AutoHashMap(i32, i32).init(std.testing.allocator);
defer map.deinit();
var i: i32 = 0;
while (i < 100) : (i += 1) {
try map.ensureCapacity(@intCast(u32, map.count() + 1));
map.putAssumeCapacity(i, i);
// Remove to create tombstones that still count as load in the hashmap.
_ = map.remove(i);
}
}
test "std.hash_map clearRetainingCapacity" {
var map = AutoHashMap(u32, u32).init(std.testing.allocator);
defer map.deinit();
map.clearRetainingCapacity();
try map.put(1, 1);
expectEqual(map.get(1).?, 1);
expectEqual(map.count(), 1);
map.clearRetainingCapacity();
map.putAssumeCapacity(1, 1);
expectEqual(map.get(1).?, 1);
expectEqual(map.count(), 1);
const cap = map.capacity();
expect(cap > 0);
map.clearRetainingCapacity();
map.clearRetainingCapacity();
expectEqual(map.count(), 0);
expectEqual(map.capacity(), cap);
expect(!map.contains(1));
}
test "std.hash_map grow" {
var map = AutoHashMap(u32, u32).init(std.testing.allocator);
defer map.deinit();
const growTo = 12456;
var i: u32 = 0;
while (i < growTo) : (i += 1) {
try map.put(i, i);
}
expectEqual(map.count(), growTo);
i = 0;
var it = map.iterator();
while (it.next()) |kv| {
expectEqual(kv.key, kv.value);
i += 1;
}
expectEqual(i, growTo);
i = 0;
while (i < growTo) : (i += 1) {
expectEqual(map.get(i).?, i);
}
}
test "std.hash_map clone" {
var map = AutoHashMap(u32, u32).init(std.testing.allocator);
defer map.deinit();
var a = try map.clone();
defer a.deinit();
expectEqual(a.count(), 0);
try a.put(1, 1);
try a.put(2, 2);
try a.put(3, 3);
var b = try a.clone();
defer b.deinit();
expectEqual(b.count(), 3);
expectEqual(b.get(1), 1);
expectEqual(b.get(2), 2);
expectEqual(b.get(3), 3);
}
test "std.hash_map ensureCapacity with existing elements" {
var map = AutoHashMap(u32, u32).init(std.testing.allocator);
defer map.deinit();
try map.put(0, 0);
expectEqual(map.count(), 1);
expectEqual(map.capacity(), @TypeOf(map).Unmanaged.MinimalCapacity);
try map.ensureCapacity(65);
expectEqual(map.count(), 1);
expectEqual(map.capacity(), 128);
}
test "std.hash_map ensureCapacity satisfies max load factor" {
var map = AutoHashMap(u32, u32).init(std.testing.allocator);
defer map.deinit();
try map.ensureCapacity(127);
expectEqual(map.capacity(), 256);
}
test "std.hash_map remove" {
var map = AutoHashMap(u32, u32).init(std.testing.allocator);
defer map.deinit();
var i: u32 = 0;
while (i < 16) : (i += 1) {
try map.put(i, i);
}
i = 0;
while (i < 16) : (i += 1) {
if (i % 3 == 0) {
_ = map.remove(i);
}
}
expectEqual(map.count(), 10);
var it = map.iterator();
while (it.next()) |kv| {
expectEqual(kv.key, kv.value);
expect(kv.key % 3 != 0);
}
i = 0;
while (i < 16) : (i += 1) {
if (i % 3 == 0) {
expect(!map.contains(i));
} else {
expectEqual(map.get(i).?, i);
}
}
}
test "std.hash_map reverse removes" {
var map = AutoHashMap(u32, u32).init(std.testing.allocator);
defer map.deinit();
var i: u32 = 0;
while (i < 16) : (i += 1) {
try map.putNoClobber(i, i);
}
i = 16;
while (i > 0) : (i -= 1) {
_ = map.remove(i - 1);
expect(!map.contains(i - 1));
var j: u32 = 0;
while (j < i - 1) : (j += 1) {
expectEqual(map.get(j).?, j);
}
}
expectEqual(map.count(), 0);
}
test "std.hash_map multiple removes on same metadata" {
var map = AutoHashMap(u32, u32).init(std.testing.allocator);
defer map.deinit();
var i: u32 = 0;
while (i < 16) : (i += 1) {
try map.put(i, i);
}
_ = map.remove(7);
_ = map.remove(15);
_ = map.remove(14);
_ = map.remove(13);
expect(!map.contains(7));
expect(!map.contains(15));
expect(!map.contains(14));
expect(!map.contains(13));
i = 0;
while (i < 13) : (i += 1) {
if (i == 7) {
expect(!map.contains(i));
} else {
expectEqual(map.get(i).?, i);
}
}
try map.put(15, 15);
try map.put(13, 13);
try map.put(14, 14);
try map.put(7, 7);
i = 0;
while (i < 16) : (i += 1) {
expectEqual(map.get(i).?, i);
}
}
test "std.hash_map put and remove loop in random order" {
var map = AutoHashMap(u32, u32).init(std.testing.allocator);
defer map.deinit();
var keys = std.ArrayList(u32).init(std.testing.allocator);
defer keys.deinit();
const size = 32;
const iterations = 100;
var i: u32 = 0;
while (i < size) : (i += 1) {
try keys.append(i);
}
var rng = std.rand.DefaultPrng.init(0);
while (i < iterations) : (i += 1) {
std.rand.Random.shuffle(&rng.random, u32, keys.items);
for (keys.items) |key| {
try map.put(key, key);
}
expectEqual(map.count(), size);
for (keys.items) |key| {
_ = map.remove(key);
}
expectEqual(map.count(), 0);
}
}
test "std.hash_map remove one million elements in random order" {
const Map = AutoHashMap(u32, u32);
const n = 1000 * 1000;
var map = Map.init(std.heap.page_allocator);
defer map.deinit();
var keys = std.ArrayList(u32).init(std.heap.page_allocator);
defer keys.deinit();
var i: u32 = 0;
while (i < n) : (i += 1) {
keys.append(i) catch unreachable;
}
var rng = std.rand.DefaultPrng.init(0);
std.rand.Random.shuffle(&rng.random, u32, keys.items);
for (keys.items) |key| {
map.put(key, key) catch unreachable;
}
std.rand.Random.shuffle(&rng.random, u32, keys.items);
i = 0;
while (i < n) : (i += 1) {
const key = keys.items[i];
_ = map.remove(key);
}
}
test "std.hash_map put" {
var map = AutoHashMap(u32, u32).init(std.testing.allocator);
defer map.deinit();
var i: u32 = 0;
while (i < 16) : (i += 1) {
_ = try map.put(i, i);
}
i = 0;
while (i < 16) : (i += 1) {
expectEqual(map.get(i).?, i);
}
i = 0;
while (i < 16) : (i += 1) {
try map.put(i, i * 16 + 1);
}
i = 0;
while (i < 16) : (i += 1) {
expectEqual(map.get(i).?, i * 16 + 1);
}
}
test "std.hash_map putAssumeCapacity" {
var map = AutoHashMap(u32, u32).init(std.testing.allocator);
defer map.deinit();
try map.ensureCapacity(20);
var i: u32 = 0;
while (i < 20) : (i += 1) {
map.putAssumeCapacityNoClobber(i, i);
}
i = 0;
var sum = i;
while (i < 20) : (i += 1) {
sum += map.get(i).?;
}
expectEqual(sum, 190);
i = 0;
while (i < 20) : (i += 1) {
map.putAssumeCapacity(i, 1);
}
i = 0;
sum = i;
while (i < 20) : (i += 1) {
sum += map.get(i).?;
}
expectEqual(sum, 20);
}
test "std.hash_map getOrPut" {
var map = AutoHashMap(u32, u32).init(std.testing.allocator);
defer map.deinit();
var i: u32 = 0;
while (i < 10) : (i += 1) {
try map.put(i * 2, 2);
}
i = 0;
while (i < 20) : (i += 1) {
var n = try map.getOrPutValue(i, 1);
}
i = 0;
var sum = i;
while (i < 20) : (i += 1) {
sum += map.get(i).?;
}
expectEqual(sum, 30);
}
test "std.hash_map basic hash map usage" {
var map = AutoHashMap(i32, i32).init(std.testing.allocator);
defer map.deinit();
testing.expect((try map.fetchPut(1, 11)) == null);
testing.expect((try map.fetchPut(2, 22)) == null);
testing.expect((try map.fetchPut(3, 33)) == null);
testing.expect((try map.fetchPut(4, 44)) == null);
try map.putNoClobber(5, 55);
testing.expect((try map.fetchPut(5, 66)).?.value == 55);
testing.expect((try map.fetchPut(5, 55)).?.value == 66);
const gop1 = try map.getOrPut(5);
testing.expect(gop1.found_existing == true);
testing.expect(gop1.entry.value == 55);
gop1.entry.value = 77;
testing.expect(map.getEntry(5).?.value == 77);
const gop2 = try map.getOrPut(99);
testing.expect(gop2.found_existing == false);
gop2.entry.value = 42;
testing.expect(map.getEntry(99).?.value == 42);
const gop3 = try map.getOrPutValue(5, 5);
testing.expect(gop3.value == 77);
const gop4 = try map.getOrPutValue(100, 41);
testing.expect(gop4.value == 41);
testing.expect(map.contains(2));
testing.expect(map.getEntry(2).?.value == 22);
testing.expect(map.get(2).? == 22);
const rmv1 = map.remove(2);
testing.expect(rmv1.?.key == 2);
testing.expect(rmv1.?.value == 22);
testing.expect(map.remove(2) == null);
testing.expect(map.getEntry(2) == null);
testing.expect(map.get(2) == null);
map.removeAssertDiscard(3);
}
test "std.hash_map clone" {
var original = AutoHashMap(i32, i32).init(std.testing.allocator);
defer original.deinit();
var i: u8 = 0;
while (i < 10) : (i += 1) {
try original.putNoClobber(i, i * 10);
}
var copy = try original.clone();
defer copy.deinit();
i = 0;
while (i < 10) : (i += 1) {
testing.expect(copy.get(i).? == i * 10);
}
} | lib/std/hash_map.zig |
const std = @import("std");
const ascii = std.ascii;
const fmt = std.fmt;
const math = std.math;
const testing = std.testing;
const assert = std.debug.assert;
pub fn parseHexFloat(comptime T: type, s: []const u8) !T {
assert(@typeInfo(T) == .Float);
const TBits = std.meta.Int(.unsigned, @typeInfo(T).Float.bits);
const mantissa_bits = math.floatMantissaBits(T);
const exponent_bits = math.floatExponentBits(T);
const exponent_min = math.floatExponentMin(T);
const exponent_max = math.floatExponentMax(T);
const exponent_bias = exponent_max;
const sign_shift = mantissa_bits + exponent_bits;
if (s.len == 0)
return error.InvalidCharacter;
if (ascii.eqlIgnoreCase(s, "nan")) {
return math.nan(T);
} else if (ascii.eqlIgnoreCase(s, "inf") or ascii.eqlIgnoreCase(s, "+inf")) {
return math.inf(T);
} else if (ascii.eqlIgnoreCase(s, "-inf")) {
return -math.inf(T);
}
var negative: bool = false;
var exp_negative: bool = false;
var mantissa: u128 = 0;
var exponent: i16 = 0;
var frac_scale: i16 = 0;
const State = enum {
MaybeSign,
Prefix,
LeadingIntegerDigit,
IntegerDigit,
MaybeDot,
LeadingFractionDigit,
FractionDigit,
ExpPrefix,
MaybeExpSign,
ExpDigit,
};
var state = State.MaybeSign;
var i: usize = 0;
while (i < s.len) {
const c = s[i];
switch (state) {
.MaybeSign => {
state = .Prefix;
if (c == '+') {
i += 1;
} else if (c == '-') {
negative = true;
i += 1;
}
},
.Prefix => {
state = .LeadingIntegerDigit;
// Match both 0x and 0X.
if (i + 2 > s.len or s[i] != '0' or s[i + 1] | 32 != 'x')
return error.InvalidCharacter;
i += 2;
},
.LeadingIntegerDigit => {
if (c == '0') {
// Skip leading zeros.
i += 1;
} else if (c == '_') {
return error.InvalidCharacter;
} else {
state = .IntegerDigit;
}
},
.IntegerDigit => {
if (ascii.isXDigit(c)) {
if (mantissa >= math.maxInt(u128) / 16)
return error.Overflow;
mantissa *%= 16;
mantissa += try fmt.charToDigit(c, 16);
i += 1;
} else if (c == '_') {
i += 1;
} else {
state = .MaybeDot;
}
},
.MaybeDot => {
if (c == '.') {
state = .LeadingFractionDigit;
i += 1;
} else state = .ExpPrefix;
},
.LeadingFractionDigit => {
if (c == '_') {
return error.InvalidCharacter;
} else state = .FractionDigit;
},
.FractionDigit => {
if (ascii.isXDigit(c)) {
if (mantissa < math.maxInt(u128) / 16) {
mantissa *%= 16;
mantissa +%= try fmt.charToDigit(c, 16);
frac_scale += 1;
} else if (c != '0') {
return error.Overflow;
}
i += 1;
} else if (c == '_') {
i += 1;
} else {
state = .ExpPrefix;
}
},
.ExpPrefix => {
state = .MaybeExpSign;
// Match both p and P.
if (c | 32 != 'p')
return error.InvalidCharacter;
i += 1;
},
.MaybeExpSign => {
state = .ExpDigit;
if (c == '+') {
i += 1;
} else if (c == '-') {
exp_negative = true;
i += 1;
}
},
.ExpDigit => {
if (ascii.isXDigit(c)) {
if (exponent >= math.maxInt(i16) / 10)
return error.Overflow;
exponent *%= 10;
exponent +%= try fmt.charToDigit(c, 10);
i += 1;
} else if (c == '_') {
i += 1;
} else {
return error.InvalidCharacter;
}
},
}
}
if (exp_negative)
exponent *= -1;
// Bring the decimal part to the left side of the decimal dot.
exponent -= frac_scale * 4;
if (mantissa == 0) {
// Signed zero.
return if (negative) -0.0 else 0.0;
}
// Divide by 2^mantissa_bits to right-align the mantissa in the fractional
// part.
exponent += mantissa_bits;
// Keep around two extra bits to correctly round any value that doesn't fit
// the available mantissa bits. The result LSB serves as Guard bit, the
// following one is the Round bit and the last one is the Sticky bit,
// computed by OR-ing all the dropped bits.
// Normalize by aligning the implicit one bit.
while (mantissa >> (mantissa_bits + 2) == 0) {
mantissa <<= 1;
exponent -= 1;
}
// Normalize again by dropping the excess precision.
// Note that the discarded bits are folded into the Sticky bit.
while (mantissa >> (mantissa_bits + 2 + 1) != 0) {
mantissa = mantissa >> 1 | (mantissa & 1);
exponent += 1;
}
// Very small numbers can be possibly represented as denormals, reduce the
// exponent as much as possible.
while (mantissa != 0 and exponent < exponent_min - 2) {
mantissa = mantissa >> 1 | (mantissa & 1);
exponent += 1;
}
// Whenever the guard bit is one (G=1) and:
// - we've truncated more than 0.5ULP (R=S=1)
// - we've truncated exactly 0.5ULP (R=1 S=0)
// Were are going to increase the mantissa (round up)
const guard_bit_and_half_or_more = (mantissa & 0b110) == 0b110;
mantissa >>= 2;
exponent += 2;
if (guard_bit_and_half_or_more) {
mantissa += 1;
}
if (mantissa == (1 << (mantissa_bits + 1))) {
// Renormalize, if the exponent overflows we'll catch that below.
mantissa >>= 1;
exponent += 1;
}
if (mantissa >> mantissa_bits == 0) {
// This is a denormal number, the biased exponent is zero.
exponent = -exponent_bias;
}
if (exponent > exponent_max) {
// Overflow, return +inf.
return math.inf(T);
}
// Remove the implicit bit.
mantissa &= @as(u128, (1 << mantissa_bits) - 1);
const raw: TBits =
(if (negative) @as(TBits, 1) << sign_shift else 0) |
@as(TBits, @bitCast(u16, exponent + exponent_bias)) << mantissa_bits |
@truncate(TBits, mantissa);
return @bitCast(T, raw);
}
test "special" {
try testing.expect(math.isNan(try parseHexFloat(f32, "nAn")));
try testing.expect(math.isPositiveInf(try parseHexFloat(f32, "iNf")));
try testing.expect(math.isPositiveInf(try parseHexFloat(f32, "+Inf")));
try testing.expect(math.isNegativeInf(try parseHexFloat(f32, "-iNf")));
}
test "zero" {
try testing.expectEqual(@as(f32, 0.0), try parseHexFloat(f32, "0x0"));
try testing.expectEqual(@as(f32, 0.0), try parseHexFloat(f32, "-0x0"));
try testing.expectEqual(@as(f32, 0.0), try parseHexFloat(f32, "0x0p42"));
try testing.expectEqual(@as(f32, 0.0), try parseHexFloat(f32, "-0x0.00000p42"));
try testing.expectEqual(@as(f32, 0.0), try parseHexFloat(f32, "0x0.00000p666"));
}
test "f16" {
const Case = struct { s: []const u8, v: f16 };
const cases: []const Case = &[_]Case{
.{ .s = "0x1p0", .v = 1.0 },
.{ .s = "-0x1p-1", .v = -0.5 },
.{ .s = "0x10p+10", .v = 16384.0 },
.{ .s = "0x10p-10", .v = 0.015625 },
// Max normalized value.
.{ .s = "0x1.ffcp+15", .v = math.floatMax(f16) },
.{ .s = "-0x1.ffcp+15", .v = -math.floatMax(f16) },
// Min normalized value.
.{ .s = "0x1p-14", .v = math.floatMin(f16) },
.{ .s = "-0x1p-14", .v = -math.floatMin(f16) },
// Min denormal value.
.{ .s = "0x1p-24", .v = math.floatTrueMin(f16) },
.{ .s = "-0x1p-24", .v = -math.floatTrueMin(f16) },
};
for (cases) |case| {
try testing.expectEqual(case.v, try parseHexFloat(f16, case.s));
}
}
test "f32" {
const Case = struct { s: []const u8, v: f32 };
const cases: []const Case = &[_]Case{
.{ .s = "0x1p0", .v = 1.0 },
.{ .s = "-0x1p-1", .v = -0.5 },
.{ .s = "0x10p+10", .v = 16384.0 },
.{ .s = "0x10p-10", .v = 0.015625 },
.{ .s = "0x0.ffffffp128", .v = 0x0.ffffffp128 },
.{ .s = "0x0.1234570p-125", .v = 0x0.1234570p-125 },
// Max normalized value.
.{ .s = "0x1.fffffeP+127", .v = math.floatMax(f32) },
.{ .s = "-0x1.fffffeP+127", .v = -math.floatMax(f32) },
// Min normalized value.
.{ .s = "0x1p-126", .v = math.floatMin(f32) },
.{ .s = "-0x1p-126", .v = -math.floatMin(f32) },
// Min denormal value.
.{ .s = "0x1P-149", .v = math.floatTrueMin(f32) },
.{ .s = "-0x1P-149", .v = -math.floatTrueMin(f32) },
};
for (cases) |case| {
try testing.expectEqual(case.v, try parseHexFloat(f32, case.s));
}
}
test "f64" {
const Case = struct { s: []const u8, v: f64 };
const cases: []const Case = &[_]Case{
.{ .s = "0x1p0", .v = 1.0 },
.{ .s = "-0x1p-1", .v = -0.5 },
.{ .s = "0x10p+10", .v = 16384.0 },
.{ .s = "0x10p-10", .v = 0.015625 },
// Max normalized value.
.{ .s = "0x1.fffffffffffffp+1023", .v = math.floatMax(f64) },
.{ .s = "-0x1.fffffffffffffp1023", .v = -math.floatMax(f64) },
// Min normalized value.
.{ .s = "0x1p-1022", .v = math.floatMin(f64) },
.{ .s = "-0x1p-1022", .v = -math.floatMin(f64) },
// Min denormalized value.
.{ .s = "0x1p-1074", .v = math.floatTrueMin(f64) },
.{ .s = "-0x1p-1074", .v = -math.floatTrueMin(f64) },
};
for (cases) |case| {
try testing.expectEqual(case.v, try parseHexFloat(f64, case.s));
}
}
test "f128" {
const Case = struct { s: []const u8, v: f128 };
const cases: []const Case = &[_]Case{
.{ .s = "0x1p0", .v = 1.0 },
.{ .s = "-0x1p-1", .v = -0.5 },
.{ .s = "0x10p+10", .v = 16384.0 },
.{ .s = "0x10p-10", .v = 0.015625 },
// Max normalized value.
.{ .s = "0xf.fffffffffffffffffffffffffff8p+16380", .v = math.floatMax(f128) },
.{ .s = "-0xf.fffffffffffffffffffffffffff8p+16380", .v = -math.floatMax(f128) },
// Min normalized value.
.{ .s = "0x1p-16382", .v = math.floatMin(f128) },
.{ .s = "-0x1p-16382", .v = -math.floatMin(f128) },
// // Min denormalized value.
.{ .s = "0x1p-16494", .v = math.floatTrueMin(f128) },
.{ .s = "-0x1p-16494", .v = -math.floatTrueMin(f128) },
.{ .s = "0x1.edcb34a235253948765432134674fp-1", .v = 0x1.edcb34a235253948765432134674fp-1 },
};
for (cases) |case| {
try testing.expectEqual(@bitCast(u128, case.v), @bitCast(u128, try parseHexFloat(f128, case.s)));
}
} | lib/std/fmt/parse_hex_float.zig |
const std = @import("std.zig");
const assert = std.debug.assert;
const meta = std.meta;
const mem = std.mem;
const Allocator = mem.Allocator;
const testing = std.testing;
pub fn MultiArrayList(comptime S: type) type {
return struct {
bytes: [*]align(@alignOf(S)) u8 = undefined,
len: usize = 0,
capacity: usize = 0,
pub const Elem = S;
pub const Field = meta.FieldEnum(S);
pub const Slice = struct {
/// This array is indexed by the field index which can be obtained
/// by using @enumToInt() on the Field enum
ptrs: [fields.len][*]u8,
len: usize,
capacity: usize,
pub fn items(self: Slice, comptime field: Field) []FieldType(field) {
const byte_ptr = self.ptrs[@enumToInt(field)];
const F = FieldType(field);
const casted_ptr = @ptrCast([*]F, @alignCast(@alignOf(F), byte_ptr));
return casted_ptr[0..self.len];
}
pub fn toMultiArrayList(self: Slice) Self {
if (self.ptrs.len == 0) {
return .{};
}
const unaligned_ptr = self.ptrs[sizes.fields[0]];
const aligned_ptr = @alignCast(@alignOf(S), unaligned_ptr);
const casted_ptr = @ptrCast([*]align(@alignOf(S)) u8, aligned_ptr);
return .{
.bytes = casted_ptr,
.len = self.len,
.capacity = self.capacity,
};
}
pub fn deinit(self: *Slice, gpa: *Allocator) void {
var other = self.toMultiArrayList();
other.deinit(gpa);
self.* = undefined;
}
};
const Self = @This();
const fields = meta.fields(S);
/// `sizes.bytes` is an array of @sizeOf each S field. Sorted by alignment, descending.
/// `sizes.fields` is an array mapping from `sizes.bytes` array index to field index.
const sizes = blk: {
const Data = struct {
size: usize,
size_index: usize,
alignment: usize,
};
var data: [fields.len]Data = undefined;
for (fields) |field_info, i| {
data[i] = .{
.size = @sizeOf(field_info.field_type),
.size_index = i,
.alignment = field_info.alignment,
};
}
const Sort = struct {
fn lessThan(trash: *i32, lhs: Data, rhs: Data) bool {
return lhs.alignment >= rhs.alignment;
}
};
var trash: i32 = undefined; // workaround for stage1 compiler bug
std.sort.sort(Data, &data, &trash, Sort.lessThan);
var sizes_bytes: [fields.len]usize = undefined;
var field_indexes: [fields.len]usize = undefined;
for (data) |elem, i| {
sizes_bytes[i] = elem.size;
field_indexes[i] = elem.size_index;
}
break :blk .{
.bytes = sizes_bytes,
.fields = field_indexes,
};
};
/// Release all allocated memory.
pub fn deinit(self: *Self, gpa: *Allocator) void {
gpa.free(self.allocatedBytes());
self.* = undefined;
}
/// The caller owns the returned memory. Empties this MultiArrayList.
pub fn toOwnedSlice(self: *Self) Slice {
const result = self.slice();
self.* = .{};
return result;
}
pub fn slice(self: Self) Slice {
var result: Slice = .{
.ptrs = undefined,
.len = self.len,
.capacity = self.capacity,
};
var ptr: [*]u8 = self.bytes;
for (sizes.bytes) |field_size, i| {
result.ptrs[sizes.fields[i]] = ptr;
ptr += field_size * self.capacity;
}
return result;
}
pub fn items(self: Self, comptime field: Field) []FieldType(field) {
return self.slice().items(field);
}
/// Overwrite one array element with new data.
pub fn set(self: *Self, index: usize, elem: S) void {
const slices = self.slice();
inline for (fields) |field_info, i| {
slices.items(@intToEnum(Field, i))[index] = @field(elem, field_info.name);
}
}
/// Obtain all the data for one array element.
pub fn get(self: *Self, index: usize) S {
const slices = self.slice();
var result: S = undefined;
inline for (fields) |field_info, i| {
@field(result, field_info.name) = slices.items(@intToEnum(Field, i))[index];
}
return result;
}
/// Extend the list by 1 element. Allocates more memory as necessary.
pub fn append(self: *Self, gpa: *Allocator, elem: S) !void {
try self.ensureCapacity(gpa, self.len + 1);
self.appendAssumeCapacity(elem);
}
/// Extend the list by 1 element, but asserting `self.capacity`
/// is sufficient to hold an additional item.
pub fn appendAssumeCapacity(self: *Self, elem: S) void {
assert(self.len < self.capacity);
self.len += 1;
self.set(self.len - 1, elem);
}
/// Adjust the list's length to `new_len`.
/// Does not initialize added items, if any.
pub fn resize(self: *Self, gpa: *Allocator, new_len: usize) !void {
try self.ensureCapacity(gpa, new_len);
self.len = new_len;
}
/// Attempt to reduce allocated capacity to `new_len`.
/// If `new_len` is greater than zero, this may fail to reduce the capacity,
/// but the data remains intact and the length is updated to new_len.
pub fn shrinkAndFree(self: *Self, gpa: *Allocator, new_len: usize) void {
if (new_len == 0) {
gpa.free(self.allocatedBytes());
self.* = .{};
return;
}
assert(new_len <= self.capacity);
assert(new_len <= self.len);
const other_bytes = gpa.allocAdvanced(
u8,
@alignOf(S),
capacityInBytes(new_len),
.exact,
) catch {
const self_slice = self.slice();
inline for (fields) |field_info, i| {
const field = @intToEnum(Field, i);
const dest_slice = self_slice.items(field)[new_len..];
const byte_count = dest_slice.len * @sizeOf(field_info.field_type);
// We use memset here for more efficient codegen in safety-checked,
// valgrind-enabled builds. Otherwise the valgrind client request
// will be repeated for every element.
@memset(@ptrCast([*]u8, dest_slice.ptr), undefined, byte_count);
}
self.len = new_len;
return;
};
var other = Self{
.bytes = other_bytes.ptr,
.capacity = new_len,
.len = new_len,
};
self.len = new_len;
const self_slice = self.slice();
const other_slice = other.slice();
inline for (fields) |field_info, i| {
const field = @intToEnum(Field, i);
// TODO we should be able to use std.mem.copy here but it causes a
// test failure on aarch64 with -OReleaseFast
const src_slice = mem.sliceAsBytes(self_slice.items(field));
const dst_slice = mem.sliceAsBytes(other_slice.items(field));
@memcpy(dst_slice.ptr, src_slice.ptr, src_slice.len);
}
gpa.free(self.allocatedBytes());
self.* = other;
}
/// Reduce length to `new_len`.
/// Invalidates pointers to elements `items[new_len..]`.
/// Keeps capacity the same.
pub fn shrinkRetainingCapacity(self: *Self, new_len: usize) void {
self.len = new_len;
}
/// Modify the array so that it can hold at least `new_capacity` items.
/// Implements super-linear growth to achieve amortized O(1) append operations.
/// Invalidates pointers if additional memory is needed.
pub fn ensureCapacity(self: *Self, gpa: *Allocator, new_capacity: usize) !void {
var better_capacity = self.capacity;
if (better_capacity >= new_capacity) return;
while (true) {
better_capacity += better_capacity / 2 + 8;
if (better_capacity >= new_capacity) break;
}
return self.setCapacity(gpa, better_capacity);
}
/// Modify the array so that it can hold exactly `new_capacity` items.
/// Invalidates pointers if additional memory is needed.
/// `new_capacity` must be greater or equal to `len`.
pub fn setCapacity(self: *Self, gpa: *Allocator, new_capacity: usize) !void {
assert(new_capacity >= self.len);
const new_bytes = try gpa.allocAdvanced(
u8,
@alignOf(S),
capacityInBytes(new_capacity),
.exact,
);
if (self.len == 0) {
gpa.free(self.allocatedBytes());
self.bytes = new_bytes.ptr;
self.capacity = new_capacity;
return;
}
var other = Self{
.bytes = new_bytes.ptr,
.capacity = new_capacity,
.len = self.len,
};
const self_slice = self.slice();
const other_slice = other.slice();
inline for (fields) |field_info, i| {
const field = @intToEnum(Field, i);
// TODO we should be able to use std.mem.copy here but it causes a
// test failure on aarch64 with -OReleaseFast
const src_slice = mem.sliceAsBytes(self_slice.items(field));
const dst_slice = mem.sliceAsBytes(other_slice.items(field));
@memcpy(dst_slice.ptr, src_slice.ptr, src_slice.len);
}
gpa.free(self.allocatedBytes());
self.* = other;
}
fn capacityInBytes(capacity: usize) usize {
const sizes_vector: std.meta.Vector(sizes.bytes.len, usize) = sizes.bytes;
const capacity_vector = @splat(sizes.bytes.len, capacity);
return @reduce(.Add, capacity_vector * sizes_vector);
}
fn allocatedBytes(self: Self) []align(@alignOf(S)) u8 {
return self.bytes[0..capacityInBytes(self.capacity)];
}
fn FieldType(field: Field) type {
return meta.fieldInfo(S, field).field_type;
}
};
}
test "basic usage" {
const ally = testing.allocator;
const Foo = struct {
a: u32,
b: []const u8,
c: u8,
};
var list = MultiArrayList(Foo){};
defer list.deinit(ally);
try list.ensureCapacity(ally, 2);
list.appendAssumeCapacity(.{
.a = 1,
.b = "foobar",
.c = 'a',
});
list.appendAssumeCapacity(.{
.a = 2,
.b = "zigzag",
.c = 'b',
});
testing.expectEqualSlices(u32, list.items(.a), &[_]u32{ 1, 2 });
testing.expectEqualSlices(u8, list.items(.c), &[_]u8{ 'a', 'b' });
testing.expectEqual(@as(usize, 2), list.items(.b).len);
testing.expectEqualStrings("foobar", list.items(.b)[0]);
testing.expectEqualStrings("zigzag", list.items(.b)[1]);
try list.append(ally, .{
.a = 3,
.b = "fizzbuzz",
.c = 'c',
});
testing.expectEqualSlices(u32, list.items(.a), &[_]u32{ 1, 2, 3 });
testing.expectEqualSlices(u8, list.items(.c), &[_]u8{ 'a', 'b', 'c' });
testing.expectEqual(@as(usize, 3), list.items(.b).len);
testing.expectEqualStrings("foobar", list.items(.b)[0]);
testing.expectEqualStrings("zigzag", list.items(.b)[1]);
testing.expectEqualStrings("fizzbuzz", list.items(.b)[2]);
// Add 6 more things to force a capacity increase.
var i: usize = 0;
while (i < 6) : (i += 1) {
try list.append(ally, .{
.a = @intCast(u32, 4 + i),
.b = "whatever",
.c = @intCast(u8, 'd' + i),
});
}
testing.expectEqualSlices(
u32,
&[_]u32{ 1, 2, 3, 4, 5, 6, 7, 8, 9 },
list.items(.a),
);
testing.expectEqualSlices(
u8,
&[_]u8{ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' },
list.items(.c),
);
list.shrinkAndFree(ally, 3);
testing.expectEqualSlices(u32, list.items(.a), &[_]u32{ 1, 2, 3 });
testing.expectEqualSlices(u8, list.items(.c), &[_]u8{ 'a', 'b', 'c' });
testing.expectEqual(@as(usize, 3), list.items(.b).len);
testing.expectEqualStrings("foobar", list.items(.b)[0]);
testing.expectEqualStrings("zigzag", list.items(.b)[1]);
testing.expectEqualStrings("fizzbuzz", list.items(.b)[2]);
}
// This was observed to fail on aarch64 with LLVM 11, when the capacityInBytes
// function used the @reduce code path.
test "regression test for @reduce bug" {
const ally = testing.allocator;
var list = MultiArrayList(struct {
tag: std.zig.Token.Tag,
start: u32,
}){};
defer list.deinit(ally);
try list.ensureCapacity(ally, 20);
try list.append(ally, .{ .tag = .keyword_const, .start = 0 });
try list.append(ally, .{ .tag = .identifier, .start = 6 });
try list.append(ally, .{ .tag = .equal, .start = 10 });
try list.append(ally, .{ .tag = .builtin, .start = 12 });
try list.append(ally, .{ .tag = .l_paren, .start = 19 });
try list.append(ally, .{ .tag = .string_literal, .start = 20 });
try list.append(ally, .{ .tag = .r_paren, .start = 25 });
try list.append(ally, .{ .tag = .semicolon, .start = 26 });
try list.append(ally, .{ .tag = .keyword_pub, .start = 29 });
try list.append(ally, .{ .tag = .keyword_fn, .start = 33 });
try list.append(ally, .{ .tag = .identifier, .start = 36 });
try list.append(ally, .{ .tag = .l_paren, .start = 40 });
try list.append(ally, .{ .tag = .r_paren, .start = 41 });
try list.append(ally, .{ .tag = .identifier, .start = 43 });
try list.append(ally, .{ .tag = .bang, .start = 51 });
try list.append(ally, .{ .tag = .identifier, .start = 52 });
try list.append(ally, .{ .tag = .l_brace, .start = 57 });
try list.append(ally, .{ .tag = .identifier, .start = 63 });
try list.append(ally, .{ .tag = .period, .start = 66 });
try list.append(ally, .{ .tag = .identifier, .start = 67 });
try list.append(ally, .{ .tag = .period, .start = 70 });
try list.append(ally, .{ .tag = .identifier, .start = 71 });
try list.append(ally, .{ .tag = .l_paren, .start = 75 });
try list.append(ally, .{ .tag = .string_literal, .start = 76 });
try list.append(ally, .{ .tag = .comma, .start = 113 });
try list.append(ally, .{ .tag = .period, .start = 115 });
try list.append(ally, .{ .tag = .l_brace, .start = 116 });
try list.append(ally, .{ .tag = .r_brace, .start = 117 });
try list.append(ally, .{ .tag = .r_paren, .start = 118 });
try list.append(ally, .{ .tag = .semicolon, .start = 119 });
try list.append(ally, .{ .tag = .r_brace, .start = 121 });
try list.append(ally, .{ .tag = .eof, .start = 123 });
const tags = list.items(.tag);
testing.expectEqual(tags[1], .identifier);
testing.expectEqual(tags[2], .equal);
testing.expectEqual(tags[3], .builtin);
testing.expectEqual(tags[4], .l_paren);
testing.expectEqual(tags[5], .string_literal);
testing.expectEqual(tags[6], .r_paren);
testing.expectEqual(tags[7], .semicolon);
testing.expectEqual(tags[8], .keyword_pub);
testing.expectEqual(tags[9], .keyword_fn);
testing.expectEqual(tags[10], .identifier);
testing.expectEqual(tags[11], .l_paren);
testing.expectEqual(tags[12], .r_paren);
testing.expectEqual(tags[13], .identifier);
testing.expectEqual(tags[14], .bang);
testing.expectEqual(tags[15], .identifier);
testing.expectEqual(tags[16], .l_brace);
testing.expectEqual(tags[17], .identifier);
testing.expectEqual(tags[18], .period);
testing.expectEqual(tags[19], .identifier);
testing.expectEqual(tags[20], .period);
testing.expectEqual(tags[21], .identifier);
testing.expectEqual(tags[22], .l_paren);
testing.expectEqual(tags[23], .string_literal);
testing.expectEqual(tags[24], .comma);
testing.expectEqual(tags[25], .period);
testing.expectEqual(tags[26], .l_brace);
testing.expectEqual(tags[27], .r_brace);
testing.expectEqual(tags[28], .r_paren);
testing.expectEqual(tags[29], .semicolon);
testing.expectEqual(tags[30], .r_brace);
testing.expectEqual(tags[31], .eof);
}
test "ensure capacity on empty list" {
const ally = testing.allocator;
const Foo = struct {
a: u32,
b: u8,
};
var list = MultiArrayList(Foo){};
defer list.deinit(ally);
try list.ensureCapacity(ally, 2);
list.appendAssumeCapacity(.{ .a = 1, .b = 2 });
list.appendAssumeCapacity(.{ .a = 3, .b = 4 });
testing.expectEqualSlices(u32, &[_]u32{ 1, 3 }, list.items(.a));
testing.expectEqualSlices(u8, &[_]u8{ 2, 4 }, list.items(.b));
list.len = 0;
list.appendAssumeCapacity(.{ .a = 5, .b = 6 });
list.appendAssumeCapacity(.{ .a = 7, .b = 8 });
testing.expectEqualSlices(u32, &[_]u32{ 5, 7 }, list.items(.a));
testing.expectEqualSlices(u8, &[_]u8{ 6, 8 }, list.items(.b));
list.len = 0;
try list.ensureCapacity(ally, 16);
list.appendAssumeCapacity(.{ .a = 9, .b = 10 });
list.appendAssumeCapacity(.{ .a = 11, .b = 12 });
testing.expectEqualSlices(u32, &[_]u32{ 9, 11 }, list.items(.a));
testing.expectEqualSlices(u8, &[_]u8{ 10, 12 }, list.items(.b));
} | lib/std/multi_array_list.zig |
allocator: Allocator,
src: []const u8,
iter: std.unicode.Utf8Iterator,
span: SpanData = .{ .start = 0, .end = 0 },
whitespace_len: u16 = 0,
tokens: std.MultiArrayList(Token) = .{},
spans: std.ArrayListUnmanaged(SpanData) = .{},
// errors: std.ArrayListUnmanaged()
const std = @import("std");
const Allocator = std.mem.Allocator;
const ziglyph = @import("ziglyph");
const super = @import("!mod.zig");
const Token = super.Token;
const TokenKind = super.TokenKind;
const SpanData = super.SpanData;
const Self = @This();
const Rune = u21;
const LexResult = struct {
spans: []const SpanData,
tokens: std.MultiArrayList(Token).Slice,
pub fn deinit(self: *LexResult, allocator: Allocator) void {
allocator.free(self.spans);
self.tokens.deinit(allocator);
}
};
pub fn lex(allocator: Allocator, src: []const u8) LexResult {
var lexer = Self.init(allocator, src);
lexer.performLex();
return .{
.spans = lexer.spans.toOwnedSlice(allocator),
.tokens = lexer.tokens.toOwnedSlice(),
};
}
fn init(allocator: Allocator, src: []const u8) Self {
const iter = std.unicode.Utf8Iterator{ .bytes = src, .i = 0 };
return .{
.allocator = allocator,
.src = src,
.iter = iter,
};
}
fn performLex(self: *Self) void {
while (self.next()) {}
self.tok(.EOF);
}
fn next(self: *Self) bool {
const char = self.advance() orelse return false;
switch (char) {
' ', '\n', '\t', '\r' => {
self.whitespace_len += 1;
while (switch (self.peek()) {
' ', '\n', '\t', '\r' => true,
else => false,
}) {
self.advanceAssume();
self.whitespace_len += 1;
}
},
'(' => self.tok(.brkt_paren_open),
')' => self.tok(.brkt_paren_close),
'{' => self.tok(.brkt_brace_open),
'}' => self.tok(.brkt_brace_close),
'[' => self.tok(.brkt_square_open),
']' => self.tok(.brkt_square_close),
':' => self.tok(if (self.match(':')) .punct_dblColon else .punct_colon),
';' => self.tok(.punct_semiColon),
',' => self.tok(.punct_comma),
'=' => self.tok(.punct_eq),
'+' => self.tok(.punct_plus),
'-' => self.tok(.punct_minus),
'*' => self.tok(.punct_star),
'/' => if (self.match('/')) {
self.whitespace_len += 2; // '//'
while (switch (self.peek()) { // while not at end or newline
'\n', 0 => false,
else => true,
}) {
self.advanceAssume();
self.whitespace_len += 1;
}
} else {
self.tok(.punct_slash);
},
'"' => self.lexString(),
else => {
// number literals
if (char == '0') {
switch (self.peek()) {
'x' => { // 0x..
self.lexBasicNumberGeneric(.int_hex, isNumberHex);
return true;
},
'o' => { // 0o..
self.lexBasicNumberGeneric(.int_oct, isNumberOctal);
return true;
},
'b' => { // 0b..
self.lexBasicNumberGeneric(.int_bin, isNumberBinary);
return true;
},
else => {
// continue with other checks below
},
}
}
if (isNumberStart(char)) {
self.lexNumber();
} else if (isIdentStart(char)) {
self.lexIdent();
} else {
@panic("todo: unknown char");
}
},
}
return true;
}
fn tok(self: *Self, kind: TokenKind) void {
self.tokens.append(self.allocator, .{
.kind = kind,
.preceding_whitespace_len = self.whitespace_len,
}) catch unreachable;
const span = SpanData{ .start = self.span.start + self.whitespace_len, .end = self.span.end };
self.spans.append(self.allocator, span) catch unreachable;
self.whitespace_len = 0;
self.span.start = self.span.end;
}
fn advance(self: *Self) ?Rune {
const slice = self.iter.nextCodepointSlice() orelse return null;
self.span.end += @intCast(u32, slice.len);
return std.unicode.utf8Decode(slice) catch unreachable;
}
fn advanceAssume(self: *Self) void {
_ = self.advance() orelse unreachable;
}
fn peekRaw(self: *Self, n: usize) Rune {
// const slice = self.iter.peek(n);
self.iter.i += n - 1;
const slice = self.iter.nextCodepointSlice() orelse return 0;
self.iter.i -= n;
if (slice.len == 0)
return 0;
return std.unicode.utf8Decode(slice) catch unreachable;
}
fn peek(self: *Self) Rune {
return self.peekRaw(1);
}
fn peekNext(self: *Self) Rune {
return self.peekRaw(2);
}
fn at(self: *Self, ch: Rune) bool {
return self.peek() == ch;
}
fn match(self: *Self, expected: Rune) bool {
if (self.at(expected)) {
self.advanceAssume();
return true;
}
return false;
}
fn consume(self: *Self) Rune {
if (self.advance()) |ch| {
return ch;
} else {
// self.reportHere(.UnexpectedEof);
// return 0;
@panic("TODO: Report error");
}
}
// fn expect(self: *Self, expected: Rune) !void {
// if (self.match(expected)) {
// return;
// } else {
// // self.report(.{
// // .kind = .ExpectedChar,
// // .span = .{
// // .start = self.span.end,
// // .end = self.span.end,
// // },
// // .pl = .{ .what = expected },
// // });
// return error.failed;
// }
// }
fn lexNumber(self: *Self) void {
var kind = TokenKind.int_dec;
self.lexWhileCondition(isNumberMid);
if (self.peek() == '.' and isNumberMid(self.peekNext())) {
kind = .float;
self.advanceAssume();
self.lexWhileCondition(isNumberMid);
if (self.match('E')) {
switch (self.peek()) {
'+', '-' => self.advanceAssume(),
// else => self.reportAtCurrentChar(.ExpectedSignInFloatExponent),
else => @panic("TODO: report error in lex float exponent"),
}
self.lexWhileCondition(isNumberMid);
}
}
self.tok(kind);
// self.lexLiteralSuffix();
}
fn lexBasicNumberGeneric(self: *Self, kind: TokenKind, condition: fn (Rune) bool) void {
self.advanceAssume();
self.lexWhileCondition(condition);
self.tok(kind);
// self.lexLiteralSuffix();
}
fn lexString(self: *Self) void {
// const start = self.span.start;
self.tok(.string_open);
var p = self.peek();
while (p != '\"' and p != 0) : (p = self.peek()) {
if (p == '\\') {
if (self.span.start != self.span.end)
self.tok(.string_literal);
self.advanceAssume();
self.lexEscape();
} else {
self.advanceAssume();
}
}
if (self.span.start != self.span.end)
self.tok(.string_literal);
if (!self.match('\"'))
// self.report(.{ .kind = .UnterminatedString, .span = .{ .start = start, .end = self.span.end } });
@panic("todo: report error");
self.tok(.string_close);
}
fn lexEscape(self: *Self) void {
const kind: TokenKind = switch (self.consume()) {
'\'' => .esc_quote_single,
'\"' => .esc_quote_double,
'n' => .esc_ascii_newline,
'r' => .esc_ascii_carriageReturn,
't' => .esc_ascii_tab,
'\\' => .esc_ascii_backslash,
'0' => .esc_ascii_null,
'e' => .esc_ascii_escape,
// 'x' => blk: {
// // @TODO: dry
// const one = self.consume();
// if (!is.number.hex(one))
// self.reportAtLastChar(.ExpectedHexDigit);
// const two = self.consume();
// if (!is.number.hex(two))
// self.reportAtLastChar(.ExpectedHexDigit);
// break :blk .Esc_Ascii_CharacterCode;
// },
// 'u' => blk: {
// self.lexEscapeUnicode() catch {};
// break :blk .Esc_Unicode;
// },
else => {
// self.reportAtLastChar(.UnexpectedEscape);
// return;
@panic("todo: report error");
},
};
self.tok(kind);
}
fn lexWhileCondition(self: *Self, condition: fn (Rune) bool) void {
while (condition(self.peek()))
self.advanceAssume();
}
fn lexIdent(self: *Self) void {
self.lexWhileCondition(isIdentMid);
const slice = self.src;
const start = self.whitespace_len + self.span.start;
const kind: TokenKind = switch (slice[start]) {
// // and
// 'a' => self.checkKw(1, "nd", .Kw_and),
// fn
'f' => switch (slice[start + 1]) {
'n' => self.checkKw(2, "", .kw_fn), // @SPEED
else => .ident,
},
// let
'l' => self.checkKw(1, "et", .kw_let),
// // mut
// 'm' => self.checkKw(1, "ut", .Kw_mut),
// // not
// 'n' => self.checkKw(1, "ot", .Kw_not),
// // or
// 'o' => self.checkKw(1, "r", .Kw_or),
// use
'u' => self.checkKw(1, "se", .kw_use),
else => .ident,
};
self.tok(kind);
}
fn checkKw(self: *Self, start: usize, rest: []const u8, kind: TokenKind) TokenKind {
const lex_start = self.whitespace_len + self.span.start;
const len = rest.len;
const str = self.src[lex_start + start .. lex_start + start + len];
return if (self.span.end - lex_start == start + len and std.mem.eql(u8, rest, str))
kind
else
.ident;
}
fn isIdentStart(ch: Rune) bool {
return ziglyph.isAlphabetic(ch) or ch == '_';
}
fn isIdentMid(ch: Rune) bool {
return ziglyph.isAlphaNum(ch) or ch == '_';
}
fn isNumberStart(ch: Rune) bool {
return ziglyph.isAsciiDigit(ch);
}
fn isNumberMid(ch: Rune) bool {
return isNumberStart(ch) or ch == '_';
}
fn isNumberHex(ch: Rune) bool {
return ziglyph.isAsciiHexDigit(ch) or ch == '_';
}
fn isNumberBinary(ch: Rune) bool {
return switch (ch) {
'0', '1', '_' => true,
else => false,
};
}
fn isNumberOctal(ch: Rune) bool {
return switch (ch) {
'0'...'7', '_' => true,
else => false,
};
} | fexc/src/parse/Lexer.zig |
const std = @import("std");
const fmt = std.fmt;
inline fn gen_semaphore_var_name(comptime provider:[]const u8, comptime name: []const u8)
*const [provider.len + name.len + 15:0]u8{
return "sdt_semaphore_" ++ provider ++ "_" ++ name;
}
pub inline fn SDT_DEFINE_SEMAPHORE(comptime provider:[]const u8, comptime name: []const u8) void {
comptime const sema_name = gen_semaphore_var_name(provider, name);
const SEMAPHORE = struct {
var x:u16 = 0;
};
@export(SEMAPHORE.x, .{ .name = sema_name, .linkage = .Strong , .section=".probes"});
}
pub inline fn SDT_ENABLED(comptime provider:[]const u8, comptime name: []const u8) bool {
comptime const sema_name = gen_semaphore_var_name(provider, name);
var ret: u32 = 0;
asm volatile(
"movzwl " ++ sema_name ++ "(%%rip), %[ret]"
: [ret] "=r" (ret)
:
);
return ret != 0;
}
pub inline fn SDT(comptime provider:[]const u8, comptime name: []const u8, args:anytype) void {
_SDT(provider, name, "0", args);
}
pub inline fn SDT_WITH_SEMAPHORE(comptime provider:[]const u8, comptime name: []const u8, args:anytype) void {
comptime const sema_name = gen_semaphore_var_name(provider, name);
_SDT(provider, name, sema_name , args);
}
inline fn _SDT(comptime provider:[]const u8, comptime name: []const u8, comptime sema: []const u8, args:anytype) void {
comptime const width = blk: {
const ptr_width = std.builtin.cpu.arch.ptrBitWidth();
if(ptr_width == 64){
break :blk " .8byte ";
} else if(ptr_width == 32){
break :blk " .4byte ";
} else {
unreachable;
}
};
comptime const part1 =
\\ 990: nop
\\ .pushsection .note.stapsdt,"","note"
\\ .balign 4
\\ .4byte 992f-991f,994f-993f,3
\\ 991: .asciz "stapsdt"
\\ 992: .balign 4
\\
++ " 993:" ++ width ++ "990b" ++ "\n"
++ width ++ "0" ++ "\n"
++ width ++ sema ++ "\n"
++ " .asciz \"" ++ provider ++ "\"\n"
++ " .asciz \"" ++ name ++ "\"\n"
++ " .asciz \"";
comptime const part3 = "\"\n" ++
\\ 994: .balign 4
\\ .popsection
\\
;
comptime var buffer: [200]u8 = undefined;
comptime var var_name = 'a';
comptime var arg_index = 0;
comptime const arg_len = args.len;
comptime var end = 0;
inline while(arg_index<arg_len) :(arg_index += 1){
comptime var h = fmt.bufPrint(buffer[end..], "-{}@%[{c}] ", .{ @sizeOf(@TypeOf(args[arg_index])), var_name}) catch unreachable;
var_name += 1;
end += h.len;
}
if(end > 0)
end -= 1;
comptime const result = part1 ++ buffer[0..end] ++ part3;
if(arg_len == 0){
asm volatile(
result
:
:
);
} else if(arg_len == 1){
const a = args[0];
asm volatile(
result
:
:
[a] "nor" (a),
);
} else if(arg_len == 2){
const a = args[0];
const b = args[1];
asm volatile(
result
:
:
[a] "nor" (a),
[b] "nor" (b),
);
} else if(arg_len == 3) {
const a = args[0];
const b = args[1];
const c = args[2];
asm volatile(
result
:
:
[a] "nor" (a),
[b] "nor" (b),
[c] "nor" (c),
);
} else if(arg_len == 4) {
const a = args[0];
const b = args[1];
const c = args[2];
const d = args[3];
asm volatile(
result
:
:
[a] "nor" (a),
[b] "nor" (b),
[c] "nor" (c),
[d] "nor" (d),
);
} else if(arg_len == 5) {
const a = args[0];
const b = args[1];
const c = args[2];
const d = args[3];
const e = args[4];
asm volatile(
result
:
:
[a] "nor" (a),
[b] "nor" (b),
[c] "nor" (c),
[d] "nor" (d),
[e] "nor" (e),
);
} else if(arg_len == 6) {
const a = args[0];
const b = args[1];
const c = args[2];
const d = args[3];
const e = args[4];
const f = args[5];
asm volatile(
result
:
:
[a] "nor" (a),
[b] "nor" (b),
[c] "nor" (c),
[d] "nor" (d),
[e] "nor" (e),
[f] "nor" (f),
);
} else if(arg_len == 7) {
const a = args[0];
const b = args[1];
const c = args[2];
const d = args[3];
const e = args[4];
const f = args[5];
const g = args[6];
asm volatile(
result
:
:
[a] "nor" (a),
[b] "nor" (b),
[c] "nor" (c),
[d] "nor" (d),
[e] "nor" (e),
[f] "nor" (f),
[g] "nor" (g),
);
} else if(arg_len == 8) {
const a = args[0];
const b = args[1];
const c = args[2];
const d = args[3];
const e = args[4];
const f = args[5];
const g = args[6];
const h = args[7];
asm volatile(
result
:
:
[a] "nor" (a),
[b] "nor" (b),
[c] "nor" (c),
[d] "nor" (d),
[e] "nor" (e),
[f] "nor" (f),
[g] "nor" (g),
[h] "nor" (h),
);
} else {
@compileLog("too many arguments");
}
} | tracing.zig |
const std = @import("std");
const Url = @import("url.zig").Url;
const pike = @import("pike");
/// Represents a request made by a client
pub const Request = struct {
/// HTTP methods as specified in RFC 7231
pub const Method = enum {
get,
head,
post,
put,
delete,
connect,
options,
trace,
patch,
any,
fn fromString(method: []const u8) Method {
return switch (method[0]) {
'G' => Method.get,
'H' => Method.head,
'P' => switch (method[1]) {
'O' => Method.post,
'U' => Method.put,
else => Method.patch,
},
'D' => Method.delete,
'C' => Method.connect,
'O' => Method.options,
'T' => Method.trace,
else => Method.any,
};
}
};
/// HTTP Protocol version
pub const Protocol = enum {
http1_0,
http1_1,
http2_0,
/// Checks the given string and gives its protocol version
/// Defaults to HTTP/1.1
fn fromString(protocol: []const u8) Protocol {
const eql = std.mem.eql;
if (eql(u8, protocol, "HTTP/1.1")) return .http1_1;
if (eql(u8, protocol, "HTTP/2.0")) return .http2_0;
if (eql(u8, protocol, "HTTP/1.0")) return .http1_0;
return .http1_1;
}
};
/// Represents an HTTP Header
pub const Header = struct {
key: []const u8,
value: []const u8,
};
/// Alias to StringHashMapUnmanaged([]const u8)
pub const Headers = std.StringHashMapUnmanaged([]const u8);
/// GET, POST, PUT, DELETE or PATCH
method: Method,
/// Url object, get be used to retrieve path or query parameters
url: Url,
/// HTTP Request headers data.
raw_header_data: []const u8,
/// Body, which can be empty
body: []const u8,
/// Protocol used by the requester, http1.1, http2.0, etc.
protocol: Protocol,
/// Length of requests body
content_length: usize,
/// True if http protocol version 1.0 or invalid request
should_close: bool,
/// Hostname the request was sent to. Includes its port. Required for HTTP/1.1
/// Cannot be null for user when `protocol` is `http1_1`.
host: ?[]const u8,
/// Iterator to iterate through headers
const Iterator = struct {
slice: []const u8,
index: usize,
/// Searches for the next header.
/// Parsing cannot be failed as that would have been caught by `parse()`
pub fn next(self: *Iterator) ?Header {
if (self.index >= self.slice.len) return null;
var state: enum { key, value } = .key;
var header: Header = undefined;
var start = self.index;
while (self.index < self.slice.len) : (self.index += 1) {
const c = self.slice[self.index];
if (state == .key and c == ':') {
header.key = self.slice[start..self.index];
start = self.index + 2;
state = .value;
}
if (state == .value and c == '\r') {
header.value = self.slice[start..self.index];
self.index += 2;
return header;
}
}
return null;
}
};
/// Creates an iterator to retrieve all headers
/// As the data is known, this does not require any allocations
/// If all headers needs to be known at once, use `headers()`.
pub fn iterator(self: Request) Iterator {
return Iterator{
.slice = self.raw_header_data[0..],
.index = 0,
};
}
/// Creates an unmanaged Hashmap from the request headers, memory is owned by caller
/// Every header key and value will be allocated for the map and must therefore be freed
/// manually as well.
pub fn headers(self: Request, allocator: *std.mem.Allocator) !Headers {
var map = Headers{};
var it = self.iterator();
while (it.next()) |header| {
try map.put(allocator, try allocator.dupe(u8, header.key), try allocator.dupe(u8, header.value));
}
return map;
}
};
/// Errors which can occur during the parsing of
/// a HTTP request.
pub const ParseError = error{
OutOfMemory,
/// Method is missing or invalid
InvalidMethod,
/// URL is missing in status line or invalid
InvalidUrl,
/// Protocol in status line is missing or invalid
InvalidProtocol,
/// Headers are missing
MissingHeaders,
/// Invalid header was found
IncorrectHeader,
/// Buffer overflow when parsing an integer
Overflow,
/// Invalid character when parsing an integer
InvalidCharacter,
/// When the connection has been closed or no more data is available
EndOfStream,
};
/// Parse accepts an `io.Reader`, it will read all data it contains
/// and tries to parse it into a `Request`. Can return `ParseError` if data is corrupt
/// The memory of the `Request` is owned by the caller and can be freed by using deinit()
/// `buffer_size` is the size that is allocated to parse the request line and headers, any headers
/// bigger than this size will be skipped.
pub fn parse(
allocator: *std.mem.Allocator,
reader: anytype,
comptime buffer_size: usize,
) !Request {
const State = enum {
method,
url,
protocol,
header,
body,
};
var state: State = .method;
var request: Request = .{
.body = "",
.method = .get,
.url = Url{
.path = "/",
.raw_path = "/",
.raw_query = "",
},
.raw_header_data = undefined,
.protocol = .http1_1,
.content_length = 0,
.should_close = false,
.host = null,
};
// we allocate memory for body if neccesary seperately.
const buffer = try allocator.alloc(u8, buffer_size);
const read = try reader.read(buffer);
if (read == 0) return ParseError.EndOfStream;
// index for where header data starts to save
var header_Start: usize = 0;
var i: usize = 0;
while (i < read) {
switch (state) {
.method => {
const index = std.mem.indexOf(u8, buffer[i..], " ") orelse
return ParseError.InvalidMethod;
request.method = Request.Method.fromString(buffer[i .. i + index]);
i += index + 1;
state = .url;
},
.url => {
const index = std.mem.indexOf(u8, buffer[i..], " ") orelse
return ParseError.InvalidUrl;
request.url = Url.init(buffer[i .. i + index]);
i += request.url.raw_path.len + 1;
state = .protocol;
},
.protocol => {
const index = std.mem.indexOf(u8, buffer[i..], "\r\n") orelse
return ParseError.InvalidProtocol;
if (index > 8) return ParseError.InvalidProtocol;
request.protocol = Request.Protocol.fromString(buffer[i .. i + index]);
i += index + 2; // skip \r\n
state = .header;
header_Start = i;
},
.header => {
if (buffer[i] == '\r') {
if (request.content_length == 0) break;
state = .body;
i += 2; //Skip the \r\n
request.raw_header_data = buffer[header_Start..i]; // remove the \r\n
continue;
}
const index = std.mem.indexOf(u8, buffer[i..], ": ") orelse
return ParseError.MissingHeaders;
const key = buffer[i .. i + index];
i += key.len + 2; // skip ": "
const end = std.mem.indexOf(u8, buffer[i..], "\r\n") orelse
return ParseError.IncorrectHeader;
const value = buffer[i .. i + end];
i += value.len + 2; //skip \r\n
if (request.content_length == 0 and std.ascii.eqlIgnoreCase(key, "content-length")) {
request.content_length = try std.fmt.parseInt(usize, value, 10);
continue;
}
if (request.protocol == .http1_1 and std.ascii.eqlIgnoreCase(key, "connection")) {
if (std.ascii.eqlIgnoreCase(value, "close")) request.should_close = true;
continue;
}
if (request.host == null and std.ascii.eqlIgnoreCase(key, "host"))
request.host = value;
},
.body => {
const length = request.content_length;
// if body fit inside the 4kb buffer, we use that,
// else allocate more memory
if (length <= read - i) {
request.body = buffer[i .. i + length];
} else {
var body = try allocator.alloc(u8, length);
std.mem.copy(u8, body, buffer[i..]);
var index: usize = read - i;
while (index < body.len) {
index += try reader.read(body[index..]);
}
request.body = body;
}
break;
},
}
}
return request;
}
test "Basic request parse" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const contents = "GET /test?test HTTP/1.1\r\n" ++
"Host: localhost:8080\r\n" ++
"User-Agent: insomnia/7.1.1\r\n" ++
"Accept: */*\r\n" ++
"Content-Length: 9\r\n" ++
"\r\n" ++
"some body";
const stream = std.io.fixedBufferStream(contents).reader();
var request = try parse(&arena.allocator, stream, 4096);
std.testing.expectEqualStrings("/test", request.url.path);
std.testing.expectEqual(Request.Protocol.http1_1, request.protocol);
std.testing.expectEqual(Request.Method.get, request.method);
std.testing.expectEqualStrings("some body", request.body);
var headers = try request.headers(std.testing.allocator);
defer {
var it = headers.iterator();
while (it.next()) |header| {
std.testing.allocator.free(header.key);
std.testing.allocator.free(header.value);
}
headers.deinit(std.testing.allocator);
}
std.testing.expect(headers.contains("Host"));
std.testing.expect(headers.contains("Accept"));
}
test "Request iterator" {
const headers = "User-Agent: ApplePieClient/1\r\n" ++
"Accept: application/json\r\n" ++
"content-Length: 0\r\n";
var it = Request.Iterator{
.slice = headers,
.index = 0,
};
const header1 = it.next().?;
const header2 = it.next().?;
const header3 = it.next().?;
const header4 = it.next();
std.testing.expectEqualStrings("User-Agent", header1.key);
std.testing.expectEqualStrings("ApplePieClient/1", header1.value);
std.testing.expectEqualStrings("Accept", header2.key);
std.testing.expectEqualStrings("content-Length", header3.key);
std.testing.expectEqual(@as(?Request.Header, null), header4);
} | src/request.zig |
const std = @import("std");
const assert = std.debug.assert;
const math = std.math;
const mem = std.mem;
const config = @import("../config.zig");
const vsr = @import("../vsr.zig");
const log = std.log.scoped(.storage);
// TODOs:
// less than a majority of replicas may have corruption
// have an option to enable/disable the following corruption types:
// bitrot
// misdirected read/write
// corrupt sector
// latent sector error
// - emulate by zeroing sector, as this is how we handle this in the real Storage implementation
// - likely that surrounding sectors also corrupt
// - likely that stuff written at the same time is also corrupt even if written to a far away sector
pub const Storage = struct {
/// Options for fault injection during fuzz testing
pub const Options = struct {
/// Seed for the storage PRNG
seed: u64,
/// Minimum number of ticks it may take to read data.
read_latency_min: u64,
/// Average number of ticks it may take to read data. Must be >= read_latency_min.
read_latency_mean: u64,
/// Minimum number of ticks it may take to write data.
write_latency_min: u64,
/// Average number of ticks it may take to write data. Must be >= write_latency_min.
write_latency_mean: u64,
/// Chance out of 100 that a read will return incorrect data, if the target memory is within
/// the faulty area of this replica.
read_fault_probability: u8,
/// Chance out of 100 that a read will return incorrect data, if the target memory is within
/// the faulty area of this replica.
write_fault_probability: u8,
};
/// See usage in Journal.write_sectors() for details.
/// TODO: allow testing in both modes.
pub const synchronicity: enum {
always_synchronous,
always_asynchronous,
} = .always_asynchronous;
pub const Read = struct {
callback: fn (read: *Storage.Read) void,
buffer: []u8,
offset: u64,
/// Tick at which this read is considered "completed" and the callback should be called.
done_at_tick: u64,
fn less_than(storage: *Read, other: *Read) math.Order {
return math.order(storage.done_at_tick, other.done_at_tick);
}
};
pub const Write = struct {
callback: fn (write: *Storage.Write) void,
buffer: []const u8,
offset: u64,
/// Tick at which this write is considered "completed" and the callback should be called.
done_at_tick: u64,
fn less_than(storage: *Write, other: *Write) math.Order {
return math.order(storage.done_at_tick, other.done_at_tick);
}
};
/// Faulty areas are always sized to message_size_max
/// If the faulty areas of all replicas are superimposed, the padding between them is always message_size_max.
/// For a single replica, the padding between faulty areas depends on the number of other replicas.
pub const FaultyAreas = struct {
first_offset: u64,
period: u64,
};
memory: []align(config.sector_size) u8,
size: u64,
options: Options,
replica_index: u8,
prng: std.rand.DefaultPrng,
// We can't allow storage faults for the same message in a majority of
// the replicas as that would make recovery impossible. Instead, we only
// allow faults in certian areas which differ between replicas.
faulty_areas: FaultyAreas,
reads: std.PriorityQueue(*Storage.Read),
writes: std.PriorityQueue(*Storage.Write),
ticks: u64 = 0,
pub fn init(
allocator: *mem.Allocator,
size: u64,
options: Storage.Options,
replica_index: u8,
faulty_areas: FaultyAreas,
) !Storage {
assert(options.write_latency_mean >= options.write_latency_min);
assert(options.read_latency_mean >= options.read_latency_min);
const memory = try allocator.allocAdvanced(u8, config.sector_size, size, .exact);
errdefer allocator.free(memory);
// TODO: random data
mem.set(u8, memory, 0);
var reads = std.PriorityQueue(*Storage.Read).init(allocator, Storage.Read.less_than);
errdefer reads.deinit();
try reads.ensureCapacity(config.io_depth_read);
var writes = std.PriorityQueue(*Storage.Write).init(allocator, Storage.Write.less_than);
errdefer writes.deinit();
try writes.ensureCapacity(config.io_depth_write);
return Storage{
.memory = memory,
.size = size,
.options = options,
.replica_index = replica_index,
.prng = std.rand.DefaultPrng.init(options.seed),
.faulty_areas = faulty_areas,
.reads = reads,
.writes = writes,
};
}
/// Cancel any currently in progress reads/writes but leave the stored data untouched.
pub fn reset(storage: *Storage) void {
storage.reads.len = 0;
storage.writes.len = 0;
}
pub fn deinit(storage: *Storage, allocator: *mem.Allocator) void {
allocator.free(storage.memory);
storage.reads.deinit();
storage.writes.deinit();
}
pub fn tick(storage: *Storage) void {
storage.ticks += 1;
while (storage.reads.peek()) |read| {
if (read.done_at_tick > storage.ticks) break;
_ = storage.reads.remove();
storage.read_sectors_finish(read);
}
while (storage.writes.peek()) |write| {
if (write.done_at_tick > storage.ticks) break;
_ = storage.writes.remove();
storage.write_sectors_finish(write);
}
}
pub fn read_sectors(
storage: *Storage,
callback: fn (read: *Storage.Read) void,
read: *Storage.Read,
buffer: []u8,
offset: u64,
) void {
storage.assert_bounds_and_alignment(buffer, offset);
read.* = .{
.callback = callback,
.buffer = buffer,
.offset = offset,
.done_at_tick = storage.ticks + storage.read_latency(),
};
// We ensure the capacity is sufficient for config.io_depth_read in init()
storage.reads.add(read) catch unreachable;
}
fn read_sectors_finish(storage: *Storage, read: *Storage.Read) void {
const faulty = storage.faulty_sectors(read.offset, read.buffer.len);
if (faulty.len > 0 and storage.x_in_100(storage.options.read_fault_probability)) {
// Randomly corrupt one of the faulty sectors the read targeted
// TODO: inject more realistic and varied storage faults as described above.
const sector_count = @divExact(faulty.len, config.sector_size);
const faulty_sector = storage.prng.random.uintLessThan(u64, sector_count);
const faulty_sector_offset = faulty_sector * config.sector_size;
const faulty_sector_bytes = faulty[faulty_sector_offset..][0..config.sector_size];
log.info("corrupting sector at offset {} during read by replica {}", .{
faulty_sector_offset,
storage.replica_index,
});
storage.prng.random.bytes(faulty_sector_bytes);
}
mem.copy(u8, read.buffer, storage.memory[read.offset..][0..read.buffer.len]);
read.callback(read);
}
pub fn write_sectors(
storage: *Storage,
callback: fn (write: *Storage.Write) void,
write: *Storage.Write,
buffer: []const u8,
offset: u64,
) void {
storage.assert_bounds_and_alignment(buffer, offset);
write.* = .{
.callback = callback,
.buffer = buffer,
.offset = offset,
.done_at_tick = storage.ticks + storage.write_latency(),
};
// We ensure the capacity is sufficient for config.io_depth_write in init()
storage.writes.add(write) catch unreachable;
}
fn write_sectors_finish(storage: *Storage, write: *Storage.Write) void {
mem.copy(u8, storage.memory[write.offset..][0..write.buffer.len], write.buffer);
const faulty = storage.faulty_sectors(write.offset, write.buffer.len);
if (faulty.len > 0 and storage.x_in_100(storage.options.write_fault_probability)) {
// Randomly corrupt one of the faulty sectors the write targeted
// TODO: inject more realistic and varied storage faults as described above.
const sector_count = @divExact(faulty.len, config.sector_size);
const faulty_sector = storage.prng.random.uintLessThan(u64, sector_count);
const faulty_sector_offset = faulty_sector * config.sector_size;
const faulty_sector_bytes = faulty[faulty_sector_offset..][0..config.sector_size];
log.info("corrupting sector at offset {} during write by replica {}", .{
faulty_sector_offset,
storage.replica_index,
});
storage.prng.random.bytes(faulty_sector_bytes);
}
write.callback(write);
}
fn assert_bounds_and_alignment(storage: *Storage, buffer: []const u8, offset: u64) void {
assert(buffer.len > 0);
assert(offset + buffer.len <= storage.size);
// Ensure that the read or write is aligned correctly for Direct I/O:
// If this is not the case, the underlying syscall will return EINVAL.
assert(@mod(@ptrToInt(buffer.ptr), config.sector_size) == 0);
assert(@mod(buffer.len, config.sector_size) == 0);
assert(@mod(offset, config.sector_size) == 0);
}
fn read_latency(storage: *Storage) u64 {
return storage.latency(storage.options.read_latency_min, storage.options.read_latency_mean);
}
fn write_latency(storage: *Storage) u64 {
return storage.latency(storage.options.write_latency_min, storage.options.write_latency_mean);
}
fn latency(storage: *Storage, min: u64, mean: u64) u64 {
return min + @floatToInt(u64, @intToFloat(f64, mean - min) * storage.prng.random.floatExp(f64));
}
/// Return true with probability x/100.
fn x_in_100(storage: *Storage, x: u8) bool {
assert(x <= 100);
return x > storage.prng.random.uintLessThan(u8, 100);
}
/// The return value is a slice into the provided out array.
pub fn generate_faulty_areas(
prng: *std.rand.Random,
size: u64,
replica_count: u8,
out: *[config.replicas_max]FaultyAreas,
) []FaultyAreas {
comptime assert(config.message_size_max % config.sector_size == 0);
const message_size_max = config.message_size_max;
// We need to ensure there is message_size_max fault-free padding
// between faulty areas of memory so that a single message
// cannot straddle the corruptable areas of a majority of replicas.
switch (replica_count) {
1 => {
// If there is only one replica in the cluster, storage faults are not recoverable.
out[0] = .{ .first_offset = size, .period = 1 };
},
2 => {
// 0123456789
// 0X X X
// 1 X X X
out[0] = .{ .first_offset = 0 * message_size_max, .period = 4 * message_size_max };
out[1] = .{ .first_offset = 2 * message_size_max, .period = 4 * message_size_max };
},
3 => {
// 0123456789
// 0X X
// 1 X X
// 2 X X
out[0] = .{ .first_offset = 0 * message_size_max, .period = 6 * message_size_max };
out[1] = .{ .first_offset = 2 * message_size_max, .period = 6 * message_size_max };
out[2] = .{ .first_offset = 4 * message_size_max, .period = 6 * message_size_max };
},
4 => {
// 0123456789
// 0X X X
// 1X X X
// 2 X X X
// 3 X X X
out[0] = .{ .first_offset = 0 * message_size_max, .period = 4 * message_size_max };
out[1] = .{ .first_offset = 0 * message_size_max, .period = 4 * message_size_max };
out[2] = .{ .first_offset = 2 * message_size_max, .period = 4 * message_size_max };
out[3] = .{ .first_offset = 2 * message_size_max, .period = 4 * message_size_max };
},
5 => {
// 0123456789
// 0X X
// 1X X
// 2 X X
// 3 X X
// 4 X X
out[0] = .{ .first_offset = 0 * message_size_max, .period = 6 * message_size_max };
out[1] = .{ .first_offset = 0 * message_size_max, .period = 6 * message_size_max };
out[2] = .{ .first_offset = 2 * message_size_max, .period = 6 * message_size_max };
out[3] = .{ .first_offset = 2 * message_size_max, .period = 6 * message_size_max };
out[4] = .{ .first_offset = 4 * message_size_max, .period = 6 * message_size_max };
},
else => unreachable,
}
prng.shuffle(FaultyAreas, out[0..replica_count]);
return out[0..replica_count];
}
/// Given an offest and size of a read/write, returns a slice into storage.memory of any
/// faulty sectors touched by the read/write
fn faulty_sectors(storage: *Storage, offset: u64, size: u64) []align(config.sector_size) u8 {
assert(size <= config.message_size_max);
const message_size_max = config.message_size_max;
const period = storage.faulty_areas.period;
const faulty_offset = storage.faulty_areas.first_offset + (offset / period) * period;
const start = std.math.max(offset, faulty_offset);
const end = std.math.min(offset + size, faulty_offset + message_size_max);
// The read/write does not touch any faulty sectors
if (start >= end) return &[0]u8{};
return storage.memory[start..end];
}
}; | src/test/storage.zig |
const std = @import("std");
const c = @import("c.zig");
const android = @import("android-bind.zig");
const build_options = @import("build_options");
pub const egl = @import("egl.zig");
pub const JNI = @import("jni.zig").JNI;
const app_log = std.log.scoped(.app_glue);
// Export the flat functions for now
// pub const native = android;
pub usingnamespace android;
const AndroidApp = @import("root").AndroidApp;
pub var sdk_version: c_int = 0;
/// Actual application entry point
export fn ANativeActivity_onCreate(activity: *android.ANativeActivity, savedState: ?[*]u8, savedStateSize: usize) callconv(.C) void {
{
var sdk_ver_str: [92]u8 = undefined;
const len = android.__system_property_get("ro.build.version.sdk", &sdk_ver_str);
if (len <= 0) {
sdk_version = 0;
} else {
const str = sdk_ver_str[0..@intCast(usize, len)];
sdk_version = std.fmt.parseInt(c_int, str, 10) catch 0;
}
}
app_log.debug("Starting on Android Version {}\n", .{
sdk_version,
});
const app = std.heap.c_allocator.create(AndroidApp) catch {
app_log.emerg("Could not create new AndroidApp: OutOfMemory!\n", .{});
return;
};
activity.callbacks.* = ANativeActivityGlue(AndroidApp).init();
if (savedState) |state| {
app.* = AndroidApp.initRestore(std.heap.c_allocator, activity, state[0..savedStateSize]) catch |err| {
std.emerg("Failed to restore app state: {}\n", .{err});
std.heap.c_allocator.destroy(app);
return;
};
} else {
app.* = AndroidApp.initFresh(std.heap.c_allocator, activity) catch |err| {
std.emerg("Failed to restore app state: {}\n", .{err});
std.heap.c_allocator.destroy(app);
return;
};
}
app.start() catch |err| {
std.log.emerg("Failed to start app state: {}\n", .{err});
app.deinit();
std.heap.c_allocator.destroy(app);
return;
};
activity.instance = app;
app_log.debug("Successfully started the app.\n", .{});
}
// // Required by C code for now…
threadlocal var errno: c_int = 0;
export fn __errno_location() *c_int {
return &errno;
}
// Android Panic implementation
pub fn panic(message: []const u8, stack_trace: ?*std.builtin.StackTrace) noreturn {
std.log.emerg("PANIC: {s}\n", .{message});
std.os.exit(1);
}
// Android Logging implementation
pub fn log(
comptime message_level: std.log.Level,
comptime scope: @Type(.EnumLiteral),
comptime format: []const u8,
args: anytype,
) void {
var buffer: [8192]u8 = undefined;
const msg = std.fmt.bufPrint(&buffer, format ++ "\x00", args) catch {
// TODO: Handle missing format here…
return;
};
// Make slice 0-terminated with added nul terminator
const msg0 = msg[0..(msg.len - 1) :0];
// Using the function from liblog to write to the actual debug output
_ = android.__android_log_write(switch (message_level) {
// => .ANDROID_LOG_VERBOSE,
.debug => android.ANDROID_LOG_DEBUG,
.info, .notice => android.ANDROID_LOG_INFO,
.warn => android.ANDROID_LOG_WARN,
.err => android.ANDROID_LOG_ERROR,
.crit, .alert, .emerg => android.ANDROID_LOG_FATAL,
}, @import("root").android_app_name, msg0.ptr);
}
/// Returns a wrapper implementation for the given App type which implements all
/// ANativeActivity callbacks.
fn ANativeActivityGlue(comptime App: type) type {
return struct {
pub fn init() android.ANativeActivityCallbacks {
return android.ANativeActivityCallbacks{
.onStart = onStart,
.onResume = onResume,
.onSaveInstanceState = onSaveInstanceState,
.onPause = onPause,
.onStop = onStop,
.onDestroy = onDestroy,
.onWindowFocusChanged = onWindowFocusChanged,
.onNativeWindowCreated = onNativeWindowCreated,
.onNativeWindowResized = onNativeWindowResized,
.onNativeWindowRedrawNeeded = onNativeWindowRedrawNeeded,
.onNativeWindowDestroyed = onNativeWindowDestroyed,
.onInputQueueCreated = onInputQueueCreated,
.onInputQueueDestroyed = onInputQueueDestroyed,
.onContentRectChanged = onContentRectChanged,
.onConfigurationChanged = onConfigurationChanged,
.onLowMemory = onLowMemory,
};
}
fn invoke(activity: *android.ANativeActivity, comptime func: []const u8, args: anytype) void {
if (@hasDecl(App, func)) {
if (activity.instance) |instance| {
@call(.{}, @field(App, func), .{@ptrCast(*App, @alignCast(@alignOf(App), instance))} ++ args);
}
} else {
app_log.debug("ANativeActivity callback {s} not available on {s}", .{ func, @typeName(App) });
}
}
// return value must be created with malloc(), so we pass the c_allocator to App.onSaveInstanceState
fn onSaveInstanceState(activity: *android.ANativeActivity, outSize: *usize) callconv(.C) ?[*]u8 {
outSize.* = 0;
if (@hasDecl(App, "onSaveInstanceState")) {
if (activity.instance) |instance| {
const optional_slice = @ptrCast(*App, @alignCast(@alignOf(App), instance)).onSaveInstanceState(std.heap.c_allocator);
if (optional_slice) |slice| {
outSize.* = slice.len;
return slice.ptr;
}
}
} else {
app_log.debug("ANativeActivity callback onSaveInstanceState not available on {s}", .{@typeName(App)});
}
return null;
}
fn onDestroy(activity: *android.ANativeActivity) callconv(.C) void {
if (activity.instance) |instance| {
const app = @ptrCast(*App, @alignCast(@alignOf(App), instance));
app.deinit();
std.heap.c_allocator.destroy(app);
}
}
fn onStart(activity: *android.ANativeActivity) callconv(.C) void {
invoke(activity, "onStart", .{});
}
fn onResume(activity: *android.ANativeActivity) callconv(.C) void {
invoke(activity, "onResume", .{});
}
fn onPause(activity: *android.ANativeActivity) callconv(.C) void {
invoke(activity, "onPause", .{});
}
fn onStop(activity: *android.ANativeActivity) callconv(.C) void {
invoke(activity, "onStop", .{});
}
fn onConfigurationChanged(activity: *android.ANativeActivity) callconv(.C) void {
invoke(activity, "onConfigurationChanged", .{});
}
fn onLowMemory(activity: *android.ANativeActivity) callconv(.C) void {
invoke(activity, "onLowMemory", .{});
}
fn onWindowFocusChanged(activity: *android.ANativeActivity, hasFocus: c_int) callconv(.C) void {
invoke(activity, "onWindowFocusChanged", .{(hasFocus != 0)});
}
fn onNativeWindowCreated(activity: *android.ANativeActivity, window: *android.ANativeWindow) callconv(.C) void {
invoke(activity, "onNativeWindowCreated", .{window});
}
fn onNativeWindowResized(activity: *android.ANativeActivity, window: *android.ANativeWindow) callconv(.C) void {
invoke(activity, "onNativeWindowResized", .{window});
}
fn onNativeWindowRedrawNeeded(activity: *android.ANativeActivity, window: *android.ANativeWindow) callconv(.C) void {
invoke(activity, "onNativeWindowRedrawNeeded", .{window});
}
fn onNativeWindowDestroyed(activity: *android.ANativeActivity, window: *android.ANativeWindow) callconv(.C) void {
invoke(activity, "onNativeWindowDestroyed", .{window});
}
fn onInputQueueCreated(activity: *android.ANativeActivity, input_queue: *android.AInputQueue) callconv(.C) void {
invoke(activity, "onInputQueueCreated", .{input_queue});
}
fn onInputQueueDestroyed(activity: *android.ANativeActivity, input_queue: *android.AInputQueue) callconv(.C) void {
invoke(activity, "onInputQueueDestroyed", .{input_queue});
}
fn onContentRectChanged(activity: *android.ANativeActivity, rect: *const android.ARect) callconv(.C) void {
invoke(activity, "onContentRectChanged", .{rect});
}
};
} | src/android-support.zig |
const std = @import("std");
const math = std.math;
const assert = std.debug.assert;
const expect = std.testing.expect;
/// Returns x * 2^n.
pub fn ldexp(x: anytype, n: i32) @TypeOf(x) {
var base = x;
var shift = n;
const T = @TypeOf(base);
const TBits = std.meta.Int(.unsigned, @typeInfo(T).Float.bits);
const mantissa_bits = math.floatMantissaBits(T);
const exponent_min = math.floatExponentMin(T);
const exponent_max = math.floatExponentMax(T);
const exponent_bias = exponent_max;
// fix double rounding errors in subnormal ranges
// https://git.musl-libc.org/cgit/musl/commit/src/math/ldexp.c?id=8c44a060243f04283ca68dad199aab90336141db
const scale_min_expo = exponent_min + mantissa_bits + 1;
const scale_min = @bitCast(T, @as(TBits, scale_min_expo + exponent_bias) << mantissa_bits);
const scale_max = @bitCast(T, @intCast(TBits, exponent_max + exponent_bias) << mantissa_bits);
// scale `shift` within floating point limits, if possible
// second pass is possible due to subnormal range
// third pass always results in +/-0.0 or +/-inf
if (shift > exponent_max) {
base *= scale_max;
shift -= exponent_max;
if (shift > exponent_max) {
base *= scale_max;
shift -= exponent_max;
if (shift > exponent_max) shift = exponent_max;
}
} else if (shift < exponent_min) {
base *= scale_min;
shift -= scale_min_expo;
if (shift < exponent_min) {
base *= scale_min;
shift -= scale_min_expo;
if (shift < exponent_min) shift = exponent_min;
}
}
return base * @bitCast(T, @intCast(TBits, shift + exponent_bias) << mantissa_bits);
}
test "math.ldexp" {
// TODO derive the various constants here with new maths API
// basic usage
try expect(ldexp(@as(f16, 1.5), 4) == 24.0);
try expect(ldexp(@as(f32, 1.5), 4) == 24.0);
try expect(ldexp(@as(f64, 1.5), 4) == 24.0);
try expect(ldexp(@as(f128, 1.5), 4) == 24.0);
// subnormals
try expect(math.isNormal(ldexp(@as(f16, 1.0), -14)));
try expect(!math.isNormal(ldexp(@as(f16, 1.0), -15)));
try expect(math.isNormal(ldexp(@as(f32, 1.0), -126)));
try expect(!math.isNormal(ldexp(@as(f32, 1.0), -127)));
try expect(math.isNormal(ldexp(@as(f64, 1.0), -1022)));
try expect(!math.isNormal(ldexp(@as(f64, 1.0), -1023)));
try expect(math.isNormal(ldexp(@as(f128, 1.0), -16382)));
try expect(!math.isNormal(ldexp(@as(f128, 1.0), -16383)));
// unreliable due to lack of native f16 support, see talk on PR #8733
// try expect(ldexp(@as(f16, 0x1.1FFp-1), -14 - 9) == math.floatTrueMin(f16));
try expect(ldexp(@as(f32, 0x1.3FFFFFp-1), -126 - 22) == math.floatTrueMin(f32));
try expect(ldexp(@as(f64, 0x1.7FFFFFFFFFFFFp-1), -1022 - 51) == math.floatTrueMin(f64));
try expect(ldexp(@as(f128, 0x1.7FFFFFFFFFFFFFFFFFFFFFFFFFFFp-1), -16382 - 111) == math.floatTrueMin(f128));
// float limits
try expect(ldexp(math.floatMax(f32), -128 - 149) > 0.0);
try expect(ldexp(math.floatMax(f32), -128 - 149 - 1) == 0.0);
try expect(!math.isPositiveInf(ldexp(math.floatTrueMin(f16), 15 + 24)));
try expect(math.isPositiveInf(ldexp(math.floatTrueMin(f16), 15 + 24 + 1)));
try expect(!math.isPositiveInf(ldexp(math.floatTrueMin(f32), 127 + 149)));
try expect(math.isPositiveInf(ldexp(math.floatTrueMin(f32), 127 + 149 + 1)));
try expect(!math.isPositiveInf(ldexp(math.floatTrueMin(f64), 1023 + 1074)));
try expect(math.isPositiveInf(ldexp(math.floatTrueMin(f64), 1023 + 1074 + 1)));
try expect(!math.isPositiveInf(ldexp(math.floatTrueMin(f128), 16383 + 16494)));
try expect(math.isPositiveInf(ldexp(math.floatTrueMin(f128), 16383 + 16494 + 1)));
} | lib/std/math/ldexp.zig |
const std = @import("../index.zig");
const math = std.math;
const assert = std.debug.assert;
const maxInt = std.math.maxInt;
pub fn trunc(x: var) @typeOf(x) {
const T = @typeOf(x);
return switch (T) {
f32 => trunc32(x),
f64 => trunc64(x),
else => @compileError("trunc not implemented for " ++ @typeName(T)),
};
}
fn trunc32(x: f32) f32 {
const u = @bitCast(u32, x);
var e = @intCast(i32, ((u >> 23) & 0xFF)) - 0x7F + 9;
var m: u32 = undefined;
if (e >= 23 + 9) {
return x;
}
if (e < 9) {
e = 1;
}
m = u32(maxInt(u32)) >> @intCast(u5, e);
if (u & m == 0) {
return x;
} else {
math.forceEval(x + 0x1p120);
return @bitCast(f32, u & ~m);
}
}
fn trunc64(x: f64) f64 {
const u = @bitCast(u64, x);
var e = @intCast(i32, ((u >> 52) & 0x7FF)) - 0x3FF + 12;
var m: u64 = undefined;
if (e >= 52 + 12) {
return x;
}
if (e < 12) {
e = 1;
}
m = u64(maxInt(u64)) >> @intCast(u6, e);
if (u & m == 0) {
return x;
} else {
math.forceEval(x + 0x1p120);
return @bitCast(f64, u & ~m);
}
}
test "math.trunc" {
assert(trunc(f32(1.3)) == trunc32(1.3));
assert(trunc(f64(1.3)) == trunc64(1.3));
}
test "math.trunc32" {
assert(trunc32(1.3) == 1.0);
assert(trunc32(-1.3) == -1.0);
assert(trunc32(0.2) == 0.0);
}
test "math.trunc64" {
assert(trunc64(1.3) == 1.0);
assert(trunc64(-1.3) == -1.0);
assert(trunc64(0.2) == 0.0);
}
test "math.trunc32.special" {
assert(trunc32(0.0) == 0.0); // 0x3F800000
assert(trunc32(-0.0) == -0.0);
assert(math.isPositiveInf(trunc32(math.inf(f32))));
assert(math.isNegativeInf(trunc32(-math.inf(f32))));
assert(math.isNan(trunc32(math.nan(f32))));
}
test "math.trunc64.special" {
assert(trunc64(0.0) == 0.0);
assert(trunc64(-0.0) == -0.0);
assert(math.isPositiveInf(trunc64(math.inf(f64))));
assert(math.isNegativeInf(trunc64(-math.inf(f64))));
assert(math.isNan(trunc64(math.nan(f64))));
} | std/math/trunc.zig |
const builtin = @import("builtin");
const std = @import("std");
const fmt = std.fmt;
const mem = std.mem;
const testing = std.testing;
/// Parses RedisSimpleString values
pub const SimpleStringParser = struct {
pub fn isSupported(comptime T: type) bool {
return switch (@typeInfo(T)) {
.Int, .Float, .Array => true,
else => false,
};
}
pub fn parse(comptime T: type, comptime _: type, msg: anytype) !T {
switch (@typeInfo(T)) {
else => unreachable,
.Int => {
var buf: [100]u8 = undefined;
var end: usize = 0;
for (buf) |*elem, i| {
const ch = try msg.readByte();
elem.* = ch;
if (ch == '\r') {
end = i;
break;
}
}
try msg.skipBytes(1, .{});
return fmt.parseInt(T, buf[0..end], 10);
},
.Float => {
var buf: [100]u8 = undefined;
var end: usize = 0;
for (buf) |*elem, i| {
const ch = try msg.readByte();
elem.* = ch;
if (ch == '\r') {
end = i;
break;
}
}
try msg.skipBytes(1, .{});
return fmt.parseFloat(T, buf[0..end]);
},
.Array => |arr| {
var res: [arr.len]arr.child = undefined;
var bytesSlice = mem.sliceAsBytes(res[0..]);
var ch = try msg.readByte();
for (bytesSlice) |*elem| {
if (ch == '\r') {
return error.LengthMismatch;
}
elem.* = ch;
ch = try msg.readByte();
}
if (ch != '\r') return error.LengthMismatch;
try msg.skipBytes(1, .{});
return res;
},
}
}
pub fn isSupportedAlloc(comptime T: type) bool {
return switch (@typeInfo(T)) {
.Pointer => |ptr| switch (ptr.size) {
.Slice, .C => ptr.child == u8, // TODO: relax constraint
.One, .Many => false,
},
else => isSupported(T),
};
}
pub fn parseAlloc(comptime T: type, comptime _: type, allocator: std.mem.Allocator, msg: anytype) !T {
switch (@typeInfo(T)) {
.Pointer => |ptr| {
switch (ptr.size) {
.One, .Many => @compileError("Only Slices and C pointers should reach sub-parsers"),
.Slice => {
const bytes = try msg.readUntilDelimiterAlloc(allocator, '\r', 4096);
_ = std.math.divExact(usize, bytes.len, @sizeOf(ptr.child)) catch return error.LengthMismatch;
try msg.skipBytes(1, .{});
return bytes;
},
.C => {
// var bytes = try msg.readUntilDelimiterAlloc(allocator, '\n', 4096);
// res[res.len - 1] = 0;
// return res;
// TODO implement this
return error.Unimplemented;
},
}
},
else => return parse(T, struct {}, msg),
}
}
}; | src/parser/t_string_simple.zig |
const std = @import("std");
fn root() []const u8 {
return std.fs.path.dirname(@src().file) orelse unreachable;
}
const root_path = root() ++ "/";
const srcs = &.{
root_path ++ "libssh2/src/channel.c",
root_path ++ "libssh2/src/comp.c",
root_path ++ "libssh2/src/crypt.c",
root_path ++ "libssh2/src/hostkey.c",
root_path ++ "libssh2/src/kex.c",
root_path ++ "libssh2/src/mac.c",
root_path ++ "libssh2/src/misc.c",
root_path ++ "libssh2/src/packet.c",
root_path ++ "libssh2/src/publickey.c",
root_path ++ "libssh2/src/scp.c",
root_path ++ "libssh2/src/session.c",
root_path ++ "libssh2/src/sftp.c",
root_path ++ "libssh2/src/userauth.c",
root_path ++ "libssh2/src/transport.c",
root_path ++ "libssh2/src/version.c",
root_path ++ "libssh2/src/knownhost.c",
root_path ++ "libssh2/src/agent.c",
root_path ++ "libssh2/src/mbedtls.c",
root_path ++ "libssh2/src/pem.c",
root_path ++ "libssh2/src/keepalive.c",
root_path ++ "libssh2/src/global.c",
root_path ++ "libssh2/src/blowfish.c",
root_path ++ "libssh2/src/bcrypt_pbkdf.c",
root_path ++ "libssh2/src/agent_win.c",
};
pub const include_dir = root_path ++ "libssh2/include";
const config_dir = root_path ++ "config";
pub const Library = struct {
step: *std.build.LibExeObjStep,
pub fn link(self: Library, other: *std.build.LibExeObjStep) void {
other.addIncludeDir(include_dir);
other.linkLibrary(self.step);
}
};
pub fn create(
b: *std.build.Builder,
target: std.zig.CrossTarget,
mode: std.builtin.Mode,
) Library {
var ret = b.addStaticLibrary("ssh2", null);
ret.setTarget(target);
ret.setBuildMode(mode);
ret.addIncludeDir(include_dir);
ret.addIncludeDir(config_dir);
ret.addCSourceFiles(srcs, &.{});
ret.linkLibC();
ret.defineCMacro("LIBSSH2_MBEDTLS", null);
if (target.isWindows()) {
ret.defineCMacro("_CRT_SECURE_NO_DEPRECATE", "1");
ret.defineCMacro("HAVE_LIBCRYPT32", null);
ret.defineCMacro("HAVE_WINSOCK2_H", null);
ret.defineCMacro("HAVE_IOCTLSOCKET", null);
ret.defineCMacro("HAVE_SELECT", null);
ret.defineCMacro("LIBSSH2_DH_GEX_NEW", "1");
if (target.getAbi().isGnu()) {
ret.defineCMacro("HAVE_UNISTD_H", null);
ret.defineCMacro("HAVE_INTTYPES_H", null);
ret.defineCMacro("HAVE_SYS_TIME_H", null);
ret.defineCMacro("HAVE_GETTIMEOFDAY", null);
}
} else {
ret.defineCMacro("HAVE_UNISTD_H", null);
ret.defineCMacro("HAVE_INTTYPES_H", null);
ret.defineCMacro("HAVE_STDLIB_H", null);
ret.defineCMacro("HAVE_SYS_SELECT_H", null);
ret.defineCMacro("HAVE_SYS_UIO_H", null);
ret.defineCMacro("HAVE_SYS_SOCKET_H", null);
ret.defineCMacro("HAVE_SYS_IOCTL_H", null);
ret.defineCMacro("HAVE_SYS_TIME_H", null);
ret.defineCMacro("HAVE_SYS_UN_H", null);
ret.defineCMacro("HAVE_LONGLONG", null);
ret.defineCMacro("HAVE_GETTIMEOFDAY", null);
ret.defineCMacro("HAVE_INET_ADDR", null);
ret.defineCMacro("HAVE_POLL", null);
ret.defineCMacro("HAVE_SELECT", null);
ret.defineCMacro("HAVE_SOCKET", null);
ret.defineCMacro("HAVE_STRTOLL", null);
ret.defineCMacro("HAVE_SNPRINTF", null);
ret.defineCMacro("HAVE_O_NONBLOCK", null);
}
return Library{ .step = ret };
} | .gyro/zig-libssh2-mattnite-github.com-b5472a81/pkg/libssh2.zig |
const std = @import("../std.zig");
const InStream = std.io.InStream;
pub fn SeekableStream(comptime SeekErrorType: type, comptime GetSeekPosErrorType: type) type {
return struct {
const Self = @This();
pub const SeekError = SeekErrorType;
pub const GetSeekPosError = GetSeekPosErrorType;
seekToFn: fn (self: *Self, pos: u64) SeekError!void,
seekByFn: fn (self: *Self, pos: i64) SeekError!void,
getPosFn: fn (self: *Self) GetSeekPosError!u64,
getEndPosFn: fn (self: *Self) GetSeekPosError!u64,
pub fn seekTo(self: *Self, pos: u64) SeekError!void {
return self.seekToFn(self, pos);
}
pub fn seekBy(self: *Self, amt: i64) SeekError!void {
return self.seekByFn(self, amt);
}
pub fn getEndPos(self: *Self) GetSeekPosError!u64 {
return self.getEndPosFn(self);
}
pub fn getPos(self: *Self) GetSeekPosError!u64 {
return self.getPosFn(self);
}
};
}
pub const SliceSeekableInStream = struct {
const Self = @This();
pub const Error = error{};
pub const SeekError = error{EndOfStream};
pub const GetSeekPosError = error{};
pub const Stream = InStream(Error);
pub const SeekableInStream = SeekableStream(SeekError, GetSeekPosError);
stream: Stream,
seekable_stream: SeekableInStream,
pos: usize,
slice: []const u8,
pub fn init(slice: []const u8) Self {
return Self{
.slice = slice,
.pos = 0,
.stream = Stream{ .readFn = readFn },
.seekable_stream = SeekableInStream{
.seekToFn = seekToFn,
.seekByFn = seekByFn,
.getEndPosFn = getEndPosFn,
.getPosFn = getPosFn,
},
};
}
fn readFn(in_stream: *Stream, dest: []u8) Error!usize {
const self = @fieldParentPtr(Self, "stream", in_stream);
const size = std.math.min(dest.len, self.slice.len - self.pos);
const end = self.pos + size;
std.mem.copy(u8, dest[0..size], self.slice[self.pos..end]);
self.pos = end;
return size;
}
fn seekToFn(in_stream: *SeekableInStream, pos: u64) SeekError!void {
const self = @fieldParentPtr(Self, "seekable_stream", in_stream);
const usize_pos = @intCast(usize, pos);
if (usize_pos >= self.slice.len) return error.EndOfStream;
self.pos = usize_pos;
}
fn seekByFn(in_stream: *SeekableInStream, amt: i64) SeekError!void {
const self = @fieldParentPtr(Self, "seekable_stream", in_stream);
if (amt < 0) {
const abs_amt = @intCast(usize, -amt);
if (abs_amt > self.pos) return error.EndOfStream;
self.pos -= abs_amt;
} else {
const usize_amt = @intCast(usize, amt);
if (self.pos + usize_amt >= self.slice.len) return error.EndOfStream;
self.pos += usize_amt;
}
}
fn getEndPosFn(in_stream: *SeekableInStream) GetSeekPosError!u64 {
const self = @fieldParentPtr(Self, "seekable_stream", in_stream);
return @intCast(u64, self.slice.len);
}
fn getPosFn(in_stream: *SeekableInStream) GetSeekPosError!u64 {
const self = @fieldParentPtr(Self, "seekable_stream", in_stream);
return @intCast(u64, self.pos);
}
}; | lib/std/io/seekable_stream.zig |
const std = @import("std");
const unicode = @import("../unicode.zig");
const utf8 = @import("index.zig");
const t = std.testing;
test "init" {
t.expectEqual(utf8.max_rune, unicode.tables.max_rune);
t.expectEqual(utf8.rune_error, unicode.tables.replacement_char);
}
const Utf8Map = struct {
r: i32,
str: []const u8,
fn init(r: i32, str: []const u8) Utf8Map {
return Utf8Map{ .r = r, .str = str };
}
};
const utf8_map = [_]Utf8Map{
Utf8Map.init(0x0000, "\x00"),
Utf8Map.init(0x0001, "\x01"),
Utf8Map.init(0x007e, "\x7e"),
Utf8Map.init(0x007f, "\x7f"),
Utf8Map.init(0x0080, "\xc2\x80"),
Utf8Map.init(0x0081, "\xc2\x81"),
Utf8Map.init(0x00bf, "\xc2\xbf"),
Utf8Map.init(0x00c0, "\xc3\x80"),
Utf8Map.init(0x00c1, "\xc3\x81"),
Utf8Map.init(0x00c8, "\xc3\x88"),
Utf8Map.init(0x00d0, "\xc3\x90"),
Utf8Map.init(0x00e0, "\xc3\xa0"),
Utf8Map.init(0x00f0, "\xc3\xb0"),
Utf8Map.init(0x00f8, "\xc3\xb8"),
Utf8Map.init(0x00ff, "\xc3\xbf"),
Utf8Map.init(0x0100, "\xc4\x80"),
Utf8Map.init(0x07ff, "\xdf\xbf"),
Utf8Map.init(0x0400, "\xd0\x80"),
Utf8Map.init(0x0800, "\xe0\xa0\x80"),
Utf8Map.init(0x0801, "\xe0\xa0\x81"),
Utf8Map.init(0x1000, "\xe1\x80\x80"),
Utf8Map.init(0xd000, "\xed\x80\x80"),
Utf8Map.init(0xd7ff, "\xed\x9f\xbf"), // last code point before surrogate half.
Utf8Map.init(0xe000, "\xee\x80\x80"), // first code point after surrogate half.
Utf8Map.init(0xfffe, "\xef\xbf\xbe"),
Utf8Map.init(0xffff, "\xef\xbf\xbf"),
Utf8Map.init(0x10000, "\xf0\x90\x80\x80"),
Utf8Map.init(0x10001, "\xf0\x90\x80\x81"),
Utf8Map.init(0x40000, "\xf1\x80\x80\x80"),
Utf8Map.init(0x10fffe, "\xf4\x8f\xbf\xbe"),
Utf8Map.init(0x10ffff, "\xf4\x8f\xbf\xbf"),
Utf8Map.init(0xFFFD, "\xef\xbf\xbd"),
};
const surrogete_map = [_]Utf8Map{
Utf8Map.init(0xd800, "\xed\xa0\x80"),
Utf8Map.init(0xdfff, "\xed\xbf\xbf"),
};
const test_strings = [][]const u8{
"",
"abcd",
"☺☻☹",
"日a本b語ç日ð本Ê語þ日¥本¼語i日©",
"日a本b語ç日ð本Ê語þ日¥本¼語i日©日a本b語ç日ð本Ê語þ日¥本¼語i日©日a本b語ç日ð本Ê語þ日¥本¼語i日©",
"\x80\x80\x80\x80",
};
test "fullRune" {
for (utf8_map) |m| {
t.expectEqual(true, utf8.fullRune(m.str));
}
const sample = [_][]const u8{ "\xc0", "\xc1" };
for (sample) |m| {
t.expectEqual(true, utf8.fullRune(m));
}
}
test "encodeRune" {
for (utf8_map) |m, idx| {
var buf = [_]u8{0} ** 10;
const n = try utf8.encodeRune(buf[0..], m.r);
const ok = std.mem.eql(u8, buf[0..n], m.str);
t.expectEqualSlices(u8, m.str, buf[0..n]);
}
}
test "decodeRune" {
for (utf8_map) |m| {
const r = try utf8.decodeRune(m.str);
t.expectEqual(m.r, r.value);
t.expectEqual(m.str.len, r.size);
}
}
test "surrogateRune" {
for (surrogete_map) |m| {
t.expectError(error.RuneError, utf8.decodeRune(m.str));
}
}
test "Iterator" {
const source = "a,b,c";
var iter = utf8.Iterator.init(source);
var a = try iter.next();
t.expect(a != null);
t.expect('a' == a.?.value);
_ = try iter.next();
a = try iter.next();
t.expect(a != null);
t.expect(a != null);
t.expect('b' == a.?.value);
_ = try iter.next();
_ = try iter.next();
a = try iter.next();
t.expect(a == null);
iter.reset(0);
a = try iter.peek();
t.expect(a != null);
const b = try iter.next();
t.expect(b != null);
t.expectEqual(a.?.value, b.?.value);
} | src/unicode/utf8/index_test.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const json = std.json;
const gl = @import("webgl.zig");
/// A gltf buffer
pub const BufferView = struct {
vbo: usize,
stride: usize,
/// Creates a buffer view given a gltf json buffer view, also uploads the data as a vbo.
pub fn fromJson(view: json.ObjectMap, buffers: []const []const u8) BufferView {
const buffer = if (view.get("buffer")) |d| @intCast(usize, d.Integer) else 0;
const offset = if (view.get("byteOffset")) |d| @intCast(usize, d.Integer) else 0;
const length = if (view.get("byteLength")) |d| @intCast(usize, d.Integer) else 0;
const stride = if (view.get("byteStride")) |d| @intCast(usize, d.Integer) else 0;
const target = if (view.get("target")) |d| @intCast(usize, d.Integer) else gl.ARRAY_BUFFER;
const vbo = gl.createBuffer();
gl.bindBuffer(target, vbo);
gl.bufferData(target, length, @ptrCast([*]const u8, &buffers[buffer][offset]), gl.STATIC_DRAW);
return .{ .vbo = vbo, .stride = stride };
}
};
/// A gltf accessor
pub const Accessor = struct {
view: usize,
offset: usize,
count: usize,
glType: usize,
/// Creates an accessor given a gltf json accessor.
pub fn fromJson(accessor: json.ObjectMap) Accessor {
return .{
.view = if (accessor.get("bufferView")) |d| @intCast(usize, d.Integer) else 0,
.offset = if (accessor.get("byteOffset")) |d| @intCast(usize, d.Integer) else 0,
.count = if (accessor.get("count")) |d| @intCast(usize, d.Integer) else 0,
.glType = if (accessor.get("componentType")) |d| @intCast(usize, d.Integer) else 0,
};
}
};
/// A gltf primitive
pub const Primitive = struct {
position: ?usize,
normal: ?usize,
tangent: ?usize,
texcoord_0: ?usize,
texcoord_1: ?usize,
color_0: ?usize,
joints_0: ?usize,
weights_0: ?usize,
indices: ?usize,
material: ?usize,
mode: usize,
/// Creates a primitive given a gltf json accessor.
pub fn fromJson(primitive: json.ObjectMap) !Primitive {
const attributes = if (primitive.get("attributes")) |d| d.Object else return error.BadGltf;
return Primitive{
.position = if (attributes.get("POSITION")) |d| @intCast(usize, d.Integer) else null,
.normal = if (attributes.get("NORMAL")) |d| @intCast(usize, d.Integer) else null,
.tangent = if (attributes.get("TANGENT")) |d| @intCast(usize, d.Integer) else null,
.texcoord_0 = if (attributes.get("TEXCOORD_0")) |d| @intCast(usize, d.Integer) else null,
.texcoord_1 = if (attributes.get("TEXCOORD_1")) |d| @intCast(usize, d.Integer) else null,
.color_0 = if (attributes.get("COLOR_0")) |d| @intCast(usize, d.Integer) else null,
.joints_0 = if (attributes.get("JOINTS_0")) |d| @intCast(usize, d.Integer) else null,
.weights_0 = if (attributes.get("WEIGHTS_0")) |d| @intCast(usize, d.Integer) else null,
.indices = if (primitive.get("indices")) |d| @intCast(usize, d.Integer) else null,
.material = if (primitive.get("material")) |d| @intCast(usize, d.Integer) else null,
.mode = if (primitive.get("mode")) |d| @intCast(usize, d.Integer) else 0,
};
}
};
/// A gltf Mesh
pub const Mesh = struct {
primitives: []Primitive,
weights: ?[]f32,
pub fn fromJson(allocator: *Allocator, mesh: json.ObjectMap) !Mesh {
const gltf_primitives = if (mesh.get("primitives")) |d| d.Array.items else return error.BadGltf;
var primitives = try allocator.alloc(Primitive, gltf_primitives.len);
{
var i: usize = 0;
while (i < primitives.len) : (i += 1) {
primitives[i] = try Primitive.fromJson(gltf_primitives[i].Object);
}
}
var weights: ?[]f32 = null;
if (mesh.get("weights")) |d| {
const gltf_weights = d.Array.items;
weights = try allocator.alloc(f32, gltf_weights.len);
var i: usize = 0;
while (i < weights.?.len) : (i += 1) {
weights.?[i] = @floatCast(f32, gltf_weights[i].Float);
}
}
return Mesh{ .primitives = primitives, .weights = weights };
}
pub fn deinit(self: *Mesh, allocator: *Allocator) void {
allocator.free(self.primitives);
if (self.weights) |weights| {
allocator.free(weights);
}
}
};
pub const PerspectiveCamera = struct {
aspect_ratio: f32,
yfov: f32,
znear: f32,
zfar: f32,
pub fn fromJson(cam: json.ObjectMap) !PerspectiveCamera {
const aspect_ratio = if (cam.get("aspectRatio")) |d| @floatCast(f32, d.Float) else return error.BadGltf;
const yfov = if (cam.get("yfov")) |d| @floatCast(f32, d.Float) else return error.BadGltf;
const znear = if (cam.get("znear")) |d| @floatCast(f32, d.Float) else return error.BadGltf;
const zfar = if (cam.get("zfar")) |d| @floatCast(f32, d.Float) else 1000.0;
return PerspectiveCamera{
.aspect_ratio = aspect_ratio,
.yfov = yfov,
.znear = znear,
.zfar = zfar,
};
}
};
pub const OrthoCamera = struct {
xmag: f32,
ymag: f32,
zfar: f32,
znear: f32,
pub fn fromJson(cam: json.ObjectMap) !OrthoCamera {
const xmag = if (cam.get("xmag")) |d| @floatCast(f32, d.Float) else return error.BadGltf;
const ymag = if (cam.get("ymag")) |d| @floatCast(f32, d.Float) else return error.BadGltf;
const znear = if (cam.get("znear")) |d| @floatCast(f32, d.Float) else return error.BadGltf;
const zfar = if (cam.get("zfar")) |d| @floatCast(f32, d.Float) else return error.BadGltf;
return OrthoCamera{
.xmag = xmag,
.ymag = ymag,
.znear = znear,
.zfar = zfar,
};
}
};
pub const Camera = union(enum) {
perspective: PerspectiveCamera,
orthographic: OrthoCamera,
pub fn fromJson(cam: json.ObjectMap) !Camera {
if (cam.get("perspective")) |c| {
return Camera{ .perspective = try PerspectiveCamera.fromJson(c.Object) };
}
if (cam.get("orthographic")) |c| {
return Camera { .orthographic = try OrthoCamera.fromJson(c.Object) };
}
return error.BadGltf;
}
};
pub const Scene = struct {};
pub const Node = struct {};
pub const Material = struct {};
pub const Texture = struct {};
pub const Image = struct {};
pub const Sampler = struct {};
pub const Skin = struct {};
pub const Animation = struct {};
// A fully loaded gltf file
pub const Gltf = struct {
allocator: *Allocator,
accessors: []Accessor,
buffer_views: []BufferView,
cameras: []Camera,
meshes: []Mesh,
pub fn fromJson(allocator: *Allocator, gltf: json.ObjectMap, buffers: []const []const u8) !Gltf {
const gltf_accessors = if (gltf.get("accessors")) |d| d.Array.items else return error.BadGltf;
var accessors = try allocator.alloc(Accessor, gltf_accessors.len);
{
var i: usize = 0;
while (i < accessors.len) : (i += 1) {
accessors[i] = Accessor.fromJson(gltf_accessors[i].Object);
}
}
const gltf_buffer_views = if (gltf.get("bufferViews")) |d| d.Array.items else return error.BadGltf;
var buffer_views = try allocator.alloc(BufferView, gltf_buffer_views.len);
{
var i: usize = 0;
while (i < buffer_views.len) : (i += 1) {
buffer_views[i] = BufferView.fromJson(gltf_buffer_views[i].Object, buffers);
}
}
const gltf_cameras = if (gltf.get("cameras")) |d| d.Array.items else return error.BadGltf;
var cameras = try allocator.alloc(Camera, gltf_cameras.len);
{
var i: usize = 0;
while (i < cameras.len) : (i += 1) {
cameras[i] = try Camera.fromJson(gltf_cameras[i].Object);
}
}
const gltf_meshes = if (gltf.get("meshes")) |d| d.Array.items else return error.BadGltf;
var meshes = try allocator.alloc(Mesh, gltf_meshes.len);
{
var i: usize = 0;
while (i < meshes.len) : (i += 1) {
meshes[i] = try Mesh.fromJson(allocator, gltf_meshes[i].Object);
}
}
return Gltf{
.allocator = allocator,
.accessors = accessors,
.buffer_views = buffer_views,
.cameras = cameras,
.meshes = meshes,
};
}
pub fn fromBytes(allocator: *Allocator, bytes: []const u8, buffers: []const []const u8) !Gltf {
var parser = json.Parser.init(allocator, false);
defer parser.deinit();
const value_tree = try parser.parse(bytes);
const root = value_tree.root.Object;
return fromJson(allocator, root, buffers);
}
pub fn deinit(self: *Gltf) void {
for (self.meshes) |mesh| {
mesh.deinit();
}
self.allocator.free(self.buffer_views);
self.allocator.free(self.accessors);
self.allocator.free(self.meshes);
}
}; | src/gltf.zig |
const std = @import("../std.zig");
const Allocator = std.mem.Allocator;
/// This allocator is used in front of another allocator and logs to `std.log`
/// on every call to the allocator.
/// For logging to a `std.io.Writer` see `std.heap.LogToWriterAllocator`
pub fn LoggingAllocator(
comptime success_log_level: std.log.Level,
comptime failure_log_level: std.log.Level,
) type {
return ScopedLoggingAllocator(.default, success_log_level, failure_log_level);
}
/// This allocator is used in front of another allocator and logs to `std.log`
/// with the given scope on every call to the allocator.
/// For logging to a `std.io.Writer` see `std.heap.LogToWriterAllocator`
pub fn ScopedLoggingAllocator(
comptime scope: @Type(.EnumLiteral),
comptime success_log_level: std.log.Level,
comptime failure_log_level: std.log.Level,
) type {
const log = std.log.scoped(scope);
return struct {
allocator: Allocator,
parent_allocator: *Allocator,
const Self = @This();
pub fn init(parent_allocator: *Allocator) Self {
return .{
.allocator = Allocator{
.allocFn = alloc,
.resizeFn = resize,
},
.parent_allocator = parent_allocator,
};
}
// This function is required as the `std.log.log` function is not public
inline fn logHelper(comptime log_level: std.log.Level, comptime format: []const u8, args: anytype) void {
switch (log_level) {
.emerg => log.emerg(format, args),
.alert => log.alert(format, args),
.crit => log.crit(format, args),
.err => log.err(format, args),
.warn => log.warn(format, args),
.notice => log.notice(format, args),
.info => log.info(format, args),
.debug => log.debug(format, args),
}
}
fn alloc(
allocator: *Allocator,
len: usize,
ptr_align: u29,
len_align: u29,
ra: usize,
) error{OutOfMemory}![]u8 {
const self = @fieldParentPtr(Self, "allocator", allocator);
const result = self.parent_allocator.allocFn(self.parent_allocator, len, ptr_align, len_align, ra);
if (result) |_| {
logHelper(
success_log_level,
"alloc - success - len: {}, ptr_align: {}, len_align: {}",
.{ len, ptr_align, len_align },
);
} else |err| {
logHelper(
failure_log_level,
"alloc - failure: {s} - len: {}, ptr_align: {}, len_align: {}",
.{ @errorName(err), len, ptr_align, len_align },
);
}
return result;
}
fn resize(
allocator: *Allocator,
buf: []u8,
buf_align: u29,
new_len: usize,
len_align: u29,
ra: usize,
) error{OutOfMemory}!usize {
const self = @fieldParentPtr(Self, "allocator", allocator);
if (self.parent_allocator.resizeFn(self.parent_allocator, buf, buf_align, new_len, len_align, ra)) |resized_len| {
if (new_len == 0) {
logHelper(success_log_level, "free - success - len: {}", .{buf.len});
} else if (new_len <= buf.len) {
logHelper(
success_log_level,
"shrink - success - {} to {}, len_align: {}, buf_align: {}",
.{ buf.len, new_len, len_align, buf_align },
);
} else {
logHelper(
success_log_level,
"expand - success - {} to {}, len_align: {}, buf_align: {}",
.{ buf.len, new_len, len_align, buf_align },
);
}
return resized_len;
} else |err| {
std.debug.assert(new_len > buf.len);
logHelper(
failure_log_level,
"expand - failure: {s} - {} to {}, len_align: {}, buf_align: {}",
.{ @errorName(err), buf.len, new_len, len_align, buf_align },
);
return err;
}
}
};
}
/// This allocator is used in front of another allocator and logs to `std.log`
/// on every call to the allocator.
/// For logging to a `std.io.Writer` see `std.heap.LogToWriterAllocator`
pub fn loggingAllocator(parent_allocator: *Allocator) LoggingAllocator(.debug, .crit) {
return LoggingAllocator(.debug, .crit).init(parent_allocator);
} | lib/std/heap/logging_allocator.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const print = std.debug.print;
const data = @embedFile("data/day18.txt");
pub fn main() !void {
var lines = std.mem.tokenize(data, "\r\n");
var result1: usize = 0;
var result2: usize = 0;
while (lines.next()) |line| {
if (line.len == 0) continue;
var pos: usize = 0;
result1 += eval1(line, &pos);
pos = 0;
result2 += eval2(line, &pos);
}
print("Day 1: {}, Day 2: {}\n", .{ result1, result2 });
}
fn eval1(expr: []const u8, pos: *usize) u64 {
var op: u8 = '?';
var value: u64 = 0;
while (pos.* < expr.len) {
var idx = pos.*;
pos.* += 1;
const c = expr[idx];
switch (c) {
'*', '+' => op = c,
' ' => {},
'(' => {
const curr = eval1(expr, pos);
switch (op) {
'?' => value = curr,
'*' => value *= curr,
'+' => value += curr,
else => unreachable,
}
op = '!';
},
')' => break,
'0'...'9' => {
const curr = c - '0';
switch (op) {
'?' => value = curr,
'*' => value *= curr,
'+' => value += curr,
else => unreachable,
}
op = '!';
},
else => unreachable,
}
}
return value;
}
fn eval2(expr: []const u8, pos: *usize) u64 {
var result: u64 = 1;
var curr: u64 = 0;
while (pos.* < expr.len) {
switch (expr[pos.*]) {
'*' => {
pos.* += 1;
result *= curr;
curr = 0;
},
' ', '+' => {
pos.* += 1;
},
'(' => {
pos.* += 1;
curr += eval2(expr, pos);
pos.* += 1;
},
')' => break,
'0'...'9' => |c| {
pos.* += 1;
curr += (c - '0');
},
else => unreachable,
}
}
if (curr != 0) result *= curr;
return result;
} | src/day18.zig |
const std = @import("std");
const warn = std.debug.warn;
const stack_trace_enabled = false;
fn stack_trace_none(fmt: []const u8, va_args: ...) void {}
const stack_trace = comptime if (stack_trace_enabled) std.debug.warn else stack_trace_none;
const idToString = @import("zig_grammar.debug.zig").idToString;
const Lexer = @import("zig_lexer.zig").Lexer;
const Types = @import("zig_grammar.types.zig");
const Errors = @import("zig_grammar.errors.zig");
const Tokens = @import("zig_grammar.tokens.zig");
const Actions = @import("zig_grammar.actions.zig");
const Transitions = @import("zig_grammar.tables.zig");
const DirectArena = @import("direct_arena.zig").DirectArena;
pub usingnamespace Types;
usingnamespace Errors;
usingnamespace Tokens;
usingnamespace Actions;
usingnamespace Transitions;
const Engine = struct {
state: i16 = 0,
stack: Stack,
allocator: *std.mem.Allocator,
errors: ErrorList,
pub fn init(allocator: *std.mem.Allocator, arena_allocator: *std.mem.Allocator) Self {
return Self{ .stack = Stack.init(allocator), .errors = ErrorList.init(allocator), .allocator = arena_allocator };
}
pub fn deinit(self: *Self) void {
self.errors.deinit();
self.stack.deinit();
}
fn printStack(self: *const Self) void {
if (stack_trace_enabled) {
var it = self.stack.iterator();
while (it.next()) |item| {
switch (item.value) {
.Token => |id| {
stack_trace("{} ", idToString(id));
},
.Terminal => |id| {
if (item.item != 0) {
stack_trace("{} ", terminalIdToString(id));
}
},
}
}
}
}
const ActionResult = enum {
Ok,
Fail,
IncompleteLine,
};
pub const Self = @This();
pub const Stack = std.ArrayList(StackItem);
pub const ErrorInfo = struct {
info: ParseError,
line: usize,
start: usize,
end: usize,
};
pub const ErrorList = std.SegmentedList(ErrorInfo, 4);
pub fn createNode(self: *Self, comptime T: type) !*T {
const node = try self.allocator.create(T);
// Allocator memsets to 0xaa but we rely on structs being zero-initialized
@memset(@ptrCast([*]align(@alignOf(T)) u8, node), 0, @sizeOf(T));
node.base.id = Node.typeToId(T);
return node;
}
pub fn createRecoveryNode(self: *Self, token: *Token) !*Node {
const node = try self.allocator.create(Node.Recovery);
// Allocator memsets to 0xaa but we rely on structs being zero-initialized
@memset(@ptrCast([*]align(@alignOf(Node.Recovery)) u8, node), 0, @sizeOf(Node.Recovery));
node.base.id = Node.typeToId(Node.Recovery);
node.token = token;
return &node.base;
}
pub fn createRecoveryToken(self: *Self, token: *Token) !*Token {
const recovery_token = try self.allocator.create(Token);
recovery_token.* = token.*;
recovery_token.id = .Recovery;
return recovery_token;
}
pub fn createTemporary(self: *Self, comptime T: type) !*T {
const node = try self.allocator.create(T);
// Allocator memsets to 0xaa but we rely on structs being zero-initialized
@memset(@ptrCast([*]align(@alignOf(T)) u8, node), 0, @sizeOf(T));
return node;
}
pub fn createListWithNode(self: *Self, comptime T: type, node: *Node) !*T {
const list = try self.allocator.create(T);
list.* = T.init(self.allocator);
try list.append(node);
return list;
}
pub fn createListWithToken(self: *Self, comptime T: type, token: *Token) !*T {
const list = try self.allocator.create(T);
list.* = T.init(self.allocator);
try list.append(token);
return list;
}
fn earlyDetectUnmatched(self: *Self, open_token_id: Id, close_token_id: Id, token: *Token) bool {
var ptr = @ptrCast([*]Token, token) + 1;
var cnt: usize = 1;
// Check if it gets matched on same line
while (ptr[0].id != .Eof and ptr[0].id != .Newline and cnt > 0) : (ptr += 1) {
if (ptr[0].id == open_token_id) cnt += 1;
if (ptr[0].id == close_token_id) cnt -= 1;
}
// Still unmatched
if (cnt > 0) {
// Check that more tokens are available
if (ptr[0].id == .Newline) {
// Tokens on next line
if (ptr[1].id != .Newline and ptr[1].id != .Eof) {
// If not a closing } assume the line is valid
if (ptr[1].id != .RBrace)
return false;
// Check if under-indented
const next_line_offset = ptr[1].start - ptr[0].end;
const own_line = @ptrCast([*]Token, token.line);
const own_line_offset = own_line[1].start - own_line[0].end;
return own_line_offset > next_line_offset;
}
// Continue on to line with tokens
ptr += 1;
while (ptr[0].id != .Eof and ptr[0].id != .Newline) : (ptr += 1) {}
// If we reached the end it must be unmatched
if (ptr[0].id == .Eof)
return true;
// Look at indentation and make a guess
const next_line_offset = ptr[1].start - ptr[0].end;
const own_line = @ptrCast([*]Token, token.line);
const own_line_offset = own_line[1].start - own_line[0].end;
if (own_line_offset > next_line_offset) {
// Indentation must be larger
return true;
}
if (own_line_offset == next_line_offset) {
// Only allow } on same indentation
return ptr[1].id != .RBrace;
}
}
return true;
}
return false;
}
pub fn reportError(self: *Self, parse_error: ParseError, token: *Token) !void {
const line = token.line.?.start;
const start_offset = token.start - token.line.?.end + 1;
const end_offset = token.end - token.line.?.end;
try self.errors.push(ErrorInfo{ .info = parse_error, .line = line, .start = start_offset, .end = end_offset });
}
pub fn reportErrorBackupToken(self: *Self, parse_error: ParseError, token: *Token) !void {
var ptr = @ptrCast([*]Token, token) - 1;
while (ptr[0].id == .Newline or ptr[0].id == .LineComment or ptr[0].id == .DocComment) : (ptr -= 1) {}
try self.reportError(parse_error, &ptr[0]);
}
pub fn action(self: *Self, token_id: Id, token: *Token) !ActionResult {
const id = @intCast(i16, @enumToInt(token_id));
action_loop: while (true) {
var state: usize = @bitCast(u16, self.state);
// Shifts
if (shift_table[state].len > 0) {
var shift: i16 = 0;
// Full table
if (shift_table[state][0] == -1) {
shift = shift_table[state][@bitCast(u16, id)];
}
// Key-Value pairs
else {
var i: usize = 0;
while (i < shift_table[state].len) : (i += 2) {
if (shift_table[state][i] == id) {
shift = shift_table[state][i + 1];
break;
}
}
}
if (shift > 0) {
// Unmatched {, [, ( must be detected early
switch (token.id) {
.LCurly, .LBrace => {
if (self.earlyDetectUnmatched(Id.LBrace, Id.RBrace, token)) {
try self.reportError(ParseError.UnmatchedBrace, token);
return ActionResult.IncompleteLine;
}
},
.LParen => {
if (self.earlyDetectUnmatched(Id.LParen, Id.RParen, token)) {
try self.reportError(ParseError.UnmatchedParen, token);
return ActionResult.IncompleteLine;
}
},
.LBracket => {
if (self.earlyDetectUnmatched(Id.LBracket, Id.RBracket, token)) {
try self.reportError(ParseError.UnmatchedBracket, token);
return ActionResult.IncompleteLine;
}
},
else => {},
}
stack_trace("{} ", idToString(token.id));
try self.stack.append(StackItem{ .item = @ptrToInt(token), .state = self.state, .value = StackValue{ .Token = token_id } });
self.state = shift;
return ActionResult.Ok;
}
}
// Reduces
// if (reduce_table[state].len > 0)
{
var reduce: i16 = 0;
// Key-Value pairs and default reduce
{
var i: usize = 0;
while (i < reduce_table[state].len) : (i += 2) {
if (reduce_table[state][i] == id or reduce_table[state][i] == -1) {
reduce = reduce_table[state][i + 1];
break;
}
}
}
if (reduce > 0) {
const consumes = consumes_table[@bitCast(u16, reduce)];
const produces = @enumToInt(try reduce_actions(Self, self, reduce, self.state));
state = @bitCast(u16, self.state);
// Gotos
const goto: i16 = goto_table[goto_index[state]][produces];
if (goto > 0) {
if (consumes > 0) {
stack_trace("\n");
self.printStack();
}
self.state = goto;
continue :action_loop;
}
}
}
break :action_loop;
}
if (self.stack.len == 1 and token_id == .Eof) {
switch (self.stack.at(0).value) {
.Terminal => |terminal_id| {
if (terminal_id == .Root)
return ActionResult.Ok;
},
else => {},
}
}
return ActionResult.Fail;
}
fn recovery(self: *Self, token_id: Id, token: *Token, index: *usize) !ActionResult {
const top = self.stack.len - 1;
const items = self.stack.items;
switch (items[top].value) {
.Terminal => |id| {
// Missing function return type (body block is in return type)
if (id == .FnProto) {
if (@intToPtr(*Node, items[top].item).cast(Node.FnProto)) |proto| {
switch (proto.return_type) {
.Explicit => |return_type| {
if (return_type.id == .Block) {
const lbrace = return_type.unsafe_cast(Node.Block).lbrace;
try self.reportError(ParseError.MissingReturnType, lbrace);
proto.body_node = return_type;
proto.return_type.Explicit = try self.createRecoveryNode(lbrace);
index.* -= 1;
return try self.action(Id.Semicolon, token);
}
},
else => {},
}
}
}
// Missing function return type (no body block)
else if (id == .MaybeLinkSection and token_id == .Semicolon) {
try self.reportError(ParseError.MissingReturnType, token);
const recovery_token = try self.createRecoveryToken(token);
index.* -= 1;
return try self.action(Id.Recovery, recovery_token);
}
// Missing semicolon after var decl or a comma
else if (id == .MaybeEqualExpr) {
if (token_id != .Comma) {
index.* -= 1;
}
try self.reportErrorBackupToken(ParseError.MissingSemicolon, token);
return try self.action(Id.Semicolon, token);
}
// Semicolon after statement
else if (id == .Statements and token_id == .Semicolon) {
try self.reportError(ParseError.SemicolonAfterStatement, token);
return ActionResult.Ok;
}
// Missing semicolon after AssignExpr
else if (id == .AssignExpr and token_id != .Semicolon) {
if (token_id == .Comma) {
try self.reportError(ParseError.CommaExpectedSemicolon, token);
} else {
try self.reportErrorBackupToken(ParseError.MissingSemicolon, token);
index.* -= 1;
}
return try self.action(Id.Semicolon, token);
}
// Missing comma after ContainerField
else if (id == .ContainerField and token_id == .RBrace) {
// try self.reportError(ParseError.MissingComma, token);
index.* -= 1;
return try self.action(Id.Comma, token);
}
// Curly vs Brace confusion
else if ((id == .IfPrefix or id == .WhilePrefix or id == .ForPrefix) and token_id == .LCurly) {
try self.reportError(ParseError.LCurlyExpectedLBrace, token);
return try self.action(Id.LBrace, token);
}
},
.Token => |id| {
if (id == .RParen and self.stack.len >= 4) {
switch (items[top - 3].value) {
.Terminal => |terminal_id| {},
.Token => |loop_id| {
// Missing PtrIndexPayload in for loop
if (loop_id == .Keyword_for) {
try self.reportError(ParseError.MissingPayload, token);
const recovery_node = try self.createRecoveryNode(token);
try self.stack.append(StackItem{ .item = @ptrToInt(recovery_node), .state = self.state, .value = StackValue{ .Terminal = .PtrIndexPayload } });
self.state = goto_table[goto_index[@bitCast(u16, self.state)]][@enumToInt(TerminalId.PtrIndexPayload)];
index.* -= 1;
return ActionResult.Ok;
}
},
}
}
},
}
if (token_id == .Semicolon) {
switch (items[top].value) {
.Terminal => |id| {
// Recovers a{expr; ...} and error{expr; ...}
if (id == .MaybeComma) {
try self.reportError(ParseError.SemicolonExpectedComma, token);
const state = @bitCast(u16, items[top - 1].state);
const produces = @enumToInt(items[top - 1].value.Terminal);
self.state = goto_table[goto_index[state]][produces];
self.stack.len -= 1;
return try self.action(Id.Comma, token);
}
// Recovers after ContainerField;
else if (id == .ContainerField) {
try self.reportError(ParseError.SemicolonExpectedComma, token);
return try self.action(Id.Comma, token);
}
},
else => {},
}
}
// else if(token_id == .Comma) {
// try self.reportError(ParseError.CommaExpectedSemicolon, token);
// return try self.action(Id.Semicolon, token);
// }
return ActionResult.Fail;
}
pub fn resync(self: *Self, token: *Token) bool {
while (self.stack.popOrNull()) |top| {
switch (top.value) {
.Token => |id| {
if (id == .LBrace) {
// Protect against parse stack corruption
if (@intToPtr(*Token, top.item).line.? == token.line.?)
return false;
self.stack.items[self.stack.len] = top;
self.stack.len += 1;
return true;
}
},
.Terminal => |id| {
if (id == .Statements or id == .ContainerMembers) {
self.stack.items[self.stack.len] = top;
self.stack.len += 1;
return true;
}
},
}
self.state = top.state;
}
return false;
}
};
pub const Parser = struct {
allocator: *std.mem.Allocator,
arena: *DirectArena,
engine: Engine = undefined,
tokens: std.ArrayList(Token) = undefined,
root: ?*Node.Root = null,
pub fn init(allocator: *std.mem.Allocator) !Parser {
var arena = try DirectArena.init();
errdefer arena.deinit();
return Parser{ .allocator = allocator, .arena = arena };
}
pub fn deinit(self: *Parser) void {
self.engine.deinit();
self.arena.deinit();
self.tokens.deinit();
}
pub fn run(self: *Parser, buffer: []const u8) !bool {
self.engine = Engine.init(self.allocator, &self.arena.allocator);
self.tokens = std.ArrayList(Token).init(self.allocator);
errdefer self.tokens.deinit();
try self.tokens.ensureCapacity((buffer.len * 10) / 8);
var lexer = Lexer.init(buffer);
try self.tokens.append(Token{ .start = 1, .end = 0, .id = .Newline });
while (true) {
var token = lexer.next();
try self.tokens.append(token);
if (token.id == .Eof)
break;
}
const shebang = if (self.tokens.items[1].id == .ShebangLine) @as(usize, 1) else @as(usize, 0);
var i: usize = shebang + 1;
// If file starts with a DocComment this is considered a RootComment
while (i < self.tokens.len) : (i += 1) {
self.tokens.items[i].id = if (self.tokens.items[i].id == .DocComment) .RootDocComment else break;
}
i = shebang + 1;
var line: usize = 1;
var last_newline = &self.tokens.items[0];
var resync_progress: usize = 0;
parser_loop: while (i < self.tokens.len) : (i += 1) {
const token = &self.tokens.items[i];
token.line = last_newline;
if (token.id == .Newline) {
line += 1;
token.start = line;
last_newline = token;
continue;
}
if (token.id == .LineComment) continue;
if (token.id == .Invalid) {
try self.engine.reportError(ParseError.InvalidCharacter, token);
continue;
}
var result = try self.engine.action(token.id, token);
if (result == .Ok)
continue;
if (result == .Fail) {
result = try self.engine.recovery(token.id, token, &i);
if (result == .Ok)
continue;
}
// Incomplete line
stack_trace("\n");
if (self.engine.resync(token)) {
// Unmatched already produced a more descriptive error
if (result == .Fail)
try self.engine.reportError(ParseError.DiscardedLine, &self.tokens.items[i]);
self.engine.printStack();
while (i < self.tokens.len and self.tokens.items[i].id != .Newline) : (i += 1) {
self.tokens.items[i].line = last_newline;
}
if (resync_progress < i - 1) {
i -= 1;
}
resync_progress = i;
continue :parser_loop;
}
// Abort parse
try self.engine.reportError(ParseError.AbortedParse, token);
break :parser_loop;
}
// Aborted parse may overrun counter
if (i >= self.tokens.len) i = self.tokens.len - 1;
stack_trace("\n");
if (self.engine.stack.len > 0) {
const Root = @intToPtr(?*Node.Root, self.engine.stack.at(0).item) orelse {
if (self.engine.errors.len > 0 and self.engine.errors.at(self.engine.errors.len - 1).info == .AbortedParse)
return false;
try self.engine.reportError(ParseError.AbortedParse, &self.tokens.items[i]);
return false;
};
if (shebang != 0)
Root.shebang_token = &self.tokens.items[1];
Root.eof_token = &self.tokens.items[self.tokens.len - 1];
self.root = Root;
return true;
}
if (self.engine.errors.len > 0 and self.engine.errors.at(self.engine.errors.len - 1).info == .AbortedParse)
return false;
try self.engine.reportError(ParseError.AbortedParse, &self.tokens.items[i]);
return false;
}
}; | zig/zig_parser.zig |
const std = @import("std");
const opt = @import("opt.zig");
const File = std.fs.File;
const stdout = &std.io.getStdOut().outStream();
const warn = std.debug.warn;
const BUFSIZ: u16 = 4096;
pub fn tail(n: u32, file: std.fs.File, is_bytes: bool) !void {
// check if user inputs illegal line number
if (n <= 0) {
try stdout.print("Error: illegal count: {}\n", .{n});
return;
}
var printPos = find_adjusted_start(n, file, is_bytes) catch |err| {
try stdout.print("Error: {}\n", .{err});
return;
};
// seek to start pos
var seekable = std.fs.File.seekableStream(file);
seekable.seekTo(printPos) catch |err| {
try stdout.print("Error: cannot seek file: {}\n", .{err});
return;
};
// print file from start pos
var in_stream = std.fs.File.inStream(file);
print_stream(&in_stream) catch |err| {
try stdout.print("Error: cannot print file: {}\n", .{err});
return;
};
}
// for stdin reading
pub fn alt_tail(n: u32, file: std.fs.File, is_bytes: bool) !void {
// check if user inputs illegal line number
if (n <= 0) {
try stdout.print("Error: illegal count: {}\n", .{n});
return;
}
const allocator = std.heap.page_allocator;
const lines = try allocator.alloc([]u8, n);
// make sure stuff is actually there in array in comparison later
var lineBuf: [BUFSIZ]u8 = undefined;
var i: u32 = 0;
var top: u32 = 0; // oldest row
var first_time: bool = true;
// add lines to buffer
while (file.inStream().readUntilDelimiterOrEof(lineBuf[0..], '\n')) |segment| {
if (segment == null) break;
// dealloc if already exist
if (!first_time) allocator.free(lines[i]);
lines[i] = try allocator.alloc(u8, segment.?.len);
std.mem.copy(u8, lines[i], segment.?);
i += 1;
top = i; // i love top
if (i >= n) {
i = 0;
first_time = false;
}
} else |err| return err;
var new_n: u32 = if (first_time) i else n;
var x: u32 = top;
if (!is_bytes) {
i = 0;
while ((i == 0 or x != top) and i <= new_n) : (x += 1) {
// loop buffer location around
if (x >= new_n) x = 0;
try stdout.print("{}\n", .{lines[x]});
i += 1;
}
} else {
x -= 1; // go to bottom and work up
// find starting point
var bytes_ate: usize = 0;
var start_pos: usize = 0;
while (x != top + 1 or bytes_ate == 0) : (x -= 1) {
bytes_ate += lines[x].len + 1;
if (bytes_ate >= n) {
start_pos = bytes_ate - n;
break;
}
if (x <= 0) x = new_n;
}
// print till end
while (x != top) : (x += 1) {
if (x >= new_n) x = 0;
if (!first_time and x > top) break;
try stdout.print("{}\n", .{lines[x][start_pos..]});
start_pos = 0;
}
}
}
// Prints stream from current pointer to end of file in BUFSIZ
// chunks.
pub fn print_stream(stream: *std.fs.File.InStream) anyerror!void {
var buffer: [BUFSIZ]u8 = undefined;
var size = try stream.readAll(&buffer);
// loop until EOF hit
while (size > 0) : (size = (try stream.readAll(&buffer))) {
try stdout.print("{}", .{buffer[0..size]});
}
}
pub fn find_adjusted_start(n: u32, file: std.fs.File, is_bytes: bool) anyerror!u64 {
// Create streams for file access
var seekable = std.fs.File.seekableStream(file);
var in_stream = std.fs.File.inStream(file);
// Find ending position of file
var endPos: u64 = seekable.getEndPos() catch |err| {
try stdout.print("Error: cannot find endpos of file: {}\n", .{err});
return err;
};
// set to EOF to step backwards from
seekable.seekTo(endPos) catch |err| {
try stdout.print("Error: cannot seek file: {}\n", .{err});
return err;
};
// step backwards until front of file or n new lines found
var offset: u64 = 0;
var amt_read: u32 = 0;
var char: u8 = undefined;
while (amt_read < (n + 1) and offset < endPos) {
offset += 1;
seekable.seekTo(endPos - offset) catch |err| {
try stdout.print("Error: cannot seek: {}\n", .{err});
return err;
};
char = in_stream.readByte() catch |err| {
try stdout.print("Error: cannot read byte: {}\n", .{err});
return err;
};
if (char == '\n' and !is_bytes) {
amt_read += 1;
} else if (is_bytes) {
amt_read += 1;
}
}
// adjust offset if consumed \n
if (offset < endPos) offset -= 1;
return endPos - offset;
}
pub fn str_to_n(str: []u8) anyerror!u32 {
return std.fmt.parseInt(u32, str, 10) catch |err| {
return 0;
};
}
const TailFlags = enum {
Lines,
Bytes,
Help,
Version,
};
var flags = [_]opt.Flag(TailFlags){
.{
.name = TailFlags.Help,
.long = "help",
},
.{
.name = TailFlags.Version,
.long = "version",
},
.{
.name = TailFlags.Bytes,
.short = 'c',
.kind = opt.ArgTypeTag.String,
.mandatory = true,
},
.{
.name = TailFlags.Lines,
.short = 'n',
.kind = opt.ArgTypeTag.String,
.mandatory = true,
},
};
const PrintOptions = enum {
Full,
Lines,
Bytes,
};
pub fn main(args: [][]u8) anyerror!u8 {
var opts: PrintOptions = PrintOptions.Full;
var length: []u8 = undefined;
var it = opt.FlagIterator(TailFlags).init(flags[0..], args);
while (it.next_flag() catch {
return 1;
}) |flag| {
switch (flag.name) {
TailFlags.Help => {
warn("(help screen here)\n", .{});
return 1;
},
TailFlags.Version => {
warn("(version info here)\n", .{});
return 1;
},
TailFlags.Bytes => {
opts = PrintOptions.Bytes;
length = flag.value.String.?;
},
TailFlags.Lines => {
opts = PrintOptions.Lines;
length = flag.value.String.?;
},
}
}
var n: u32 = 10;
if (opts != PrintOptions.Full) n = try str_to_n(length[0..]);
var files = std.ArrayList([]u8).init(std.heap.page_allocator);
while (it.next_arg()) |file_name| {
try files.append(file_name);
}
if (files.items.len > 0) {
for (files.items) |file_name| {
const file = std.fs.cwd().openFile(file_name[0..], File.OpenFlags{ .read = true, .write = false }) catch |err| {
try stdout.print("Error: cannot open file {}\n", .{file_name});
return 1;
};
if (files.items.len >= 2) try stdout.print("==> {} <==\n", .{file_name});
try tail(n, file, opts == PrintOptions.Bytes);
file.close();
}
} else {
const file = std.io.getStdIn();
try alt_tail(n, file, opts == PrintOptions.Bytes);
}
return 0;
} | src/tail.zig |
const std = @import("std");
/// Zig version. When writing code that supports multiple versions of Zig, prefer
/// feature detection (i.e. with `@hasDecl` or `@hasField`) over version checks.
pub const zig_version = std.SemanticVersion.parse("0.9.0") catch unreachable;
/// Temporary until self-hosted is feature complete.
pub const zig_is_stage2 = false;
/// Temporary until self-hosted supports the `cpu.arch` value.
pub const stage2_arch: std.Target.Cpu.Arch = .x86_64;
/// Temporary until self-hosted can call `std.Target.x86.featureSetHas` at comptime.
pub const stage2_x86_cx16 = true;
pub const output_mode = std.builtin.OutputMode.Exe;
pub const link_mode = std.builtin.LinkMode.Static;
pub const is_test = false;
pub const single_threaded = false;
pub const abi = std.Target.Abi.gnu;
pub const cpu: std.Target.Cpu = .{
.arch = .x86_64,
.model = &std.Target.x86.cpu.sandybridge,
.features = std.Target.x86.featureSet(&[_]std.Target.x86.Feature{
.@"64bit",
.avx,
.cmov,
.cx16,
.cx8,
.false_deps_popcnt,
.fast_15bytenop,
.fast_scalar_fsqrt,
.fast_shld_rotate,
.fxsr,
.idivq_to_divl,
.macrofusion,
.mmx,
.nopl,
.pclmul,
.popcnt,
.sahf,
.slow_3ops_lea,
.slow_unaligned_mem_32,
.sse,
.sse2,
.sse3,
.sse4_1,
.sse4_2,
.ssse3,
.vzeroupper,
.x87,
.xsave,
.xsaveopt,
}),
};
pub const os = std.Target.Os{
.tag = .linux,
.version_range = .{ .linux = .{
.range = .{
.min = .{
.major = 5,
.minor = 15,
.patch = 23,
},
.max = .{
.major = 5,
.minor = 15,
.patch = 23,
},
},
.glibc = .{
.major = 2,
.minor = 19,
.patch = 0,
},
}},
};
pub const target = std.Target{
.cpu = cpu,
.os = os,
.abi = abi,
};
pub const object_format = std.Target.ObjectFormat.elf;
pub const mode = std.builtin.Mode.Debug;
pub const link_libc = false;
pub const link_libcpp = false;
pub const have_error_return_tracing = true;
pub const valgrind_support = true;
pub const position_independent_code = false;
pub const position_independent_executable = false;
pub const strip_debug_info = false;
pub const code_model = std.builtin.CodeModel.default; | zig-cache/o/ee67e79fdc1324c042df3d56fd7921a7/builtin.zig |
const std = @import("std");
const pkgs = struct {
// TinyVG package
const tvg = std.build.Pkg{
.name = "tvg",
.path = .{ .path = "src/lib/tinyvg.zig" },
.dependencies = &.{ptk},
};
const ptk = std.build.Pkg{
.name = "ptk",
.path = .{ .path = "vendor/parser-toolkit/src/main.zig" },
};
const args = std.build.Pkg{
.name = "args",
.path = .{ .path = "vendor/zig-args/args.zig" },
};
};
fn initNativeLibrary(lib: *std.build.LibExeObjStep, mode: std.builtin.Mode, target: std.zig.CrossTarget) void {
lib.addPackage(pkgs.tvg);
lib.addIncludeDir("src/binding/include");
lib.setBuildMode(mode);
lib.setTarget(target);
lib.bundle_compiler_rt = true;
}
pub fn build(b: *std.build.Builder) !void {
const www_folder = std.build.InstallDir{ .custom = "www" };
const install_include = b.option(bool, "install-include", "Installs the include directory") orelse true;
const install_www = b.option(bool, "install-www", "Installs the www directory (polyfill)") orelse true;
const install_lib = b.option(bool, "install-lib", "Installs the lib directory") orelse true;
const install_bin = b.option(bool, "install-bin", "Installs the bin directory") orelse true;
const target = b.standardTargetOptions(.{});
const mode = b.standardReleaseOptions();
const static_native_lib = b.addStaticLibrary("tinyvg", "src/binding/binding.zig");
initNativeLibrary(static_native_lib, mode, target);
if (install_lib) {
static_native_lib.install();
}
const dynamic_lib_name = if (target.isWindows())
"tinyvg.dll"
else
"tinyvg";
const dynamic_native_lib = b.addSharedLibrary(dynamic_lib_name, "src/binding/binding.zig", .unversioned);
initNativeLibrary(dynamic_native_lib, mode, target);
if (install_lib) {
dynamic_native_lib.install();
}
if (install_include) {
const install_header = b.addInstallFileWithDir(.{ .path = "src/binding/include/tinyvg.h" }, .header, "tinyvg.h");
b.getInstallStep().dependOn(&install_header.step);
}
const render = b.addExecutable("tvg-render", "src/tools/render.zig");
render.setBuildMode(mode);
render.setTarget(target);
render.addPackage(pkgs.tvg);
render.addPackage(pkgs.args);
if (install_bin) {
render.install();
}
const text = b.addExecutable("tvg-text", "src/tools/text.zig");
text.setBuildMode(mode);
text.setTarget(target);
text.addPackage(pkgs.tvg);
text.addPackage(pkgs.args);
text.addPackage(pkgs.ptk);
if (install_bin) {
text.install();
}
const ground_truth_generator = b.addExecutable("ground-truth-generator", "src/data/ground-truth.zig");
ground_truth_generator.setBuildMode(mode);
ground_truth_generator.addPackage(pkgs.tvg);
const generate_ground_truth = ground_truth_generator.run();
generate_ground_truth.cwd = "zig-cache";
const gen_gt_step = b.step("generate", "Regenerates the ground truth data.");
const files = [_][]const u8{
"shield-16.tvg", "shield-8.tvg", "shield-32.tvg",
"everything.tvg", "everything-32.tvg",
};
inline for (files) |file| {
const tvg_conversion = render.run();
tvg_conversion.addArg(file);
tvg_conversion.addArg("--super-sampling");
tvg_conversion.addArg("2");
tvg_conversion.addArg("--output");
tvg_conversion.addArg(file[0 .. file.len - 3] ++ "tga");
tvg_conversion.cwd = "zig-cache";
tvg_conversion.step.dependOn(&generate_ground_truth.step);
const tvgt_conversion = text.run();
tvgt_conversion.addArg(file);
tvgt_conversion.addArg("--output");
tvgt_conversion.addArg(file[0 .. file.len - 3] ++ "tvgt");
tvgt_conversion.cwd = "zig-cache";
tvgt_conversion.step.dependOn(&generate_ground_truth.step);
gen_gt_step.dependOn(&tvgt_conversion.step);
gen_gt_step.dependOn(&tvg_conversion.step);
}
{
const tvg_tests = b.addTestSource(pkgs.tvg.path);
for (pkgs.tvg.dependencies.?) |dep| {
tvg_tests.addPackage(dep);
}
tvg_tests.addPackage(std.build.Pkg{
.name = "ground-truth",
.path = .{ .path = "src/data/ground-truth.zig" },
.dependencies = &[_]std.build.Pkg{
pkgs.tvg,
},
});
const static_binding_test = b.addExecutable("static-native-binding", null);
static_binding_test.setBuildMode(mode);
static_binding_test.linkLibC();
static_binding_test.addIncludeDir("src/binding/include");
static_binding_test.addCSourceFile("examples/usage.c", &[_][]const u8{ "-Wall", "-Wextra", "-pedantic", "-std=c99" });
static_binding_test.linkLibrary(static_native_lib);
const dynamic_binding_test = b.addExecutable("static-native-binding", null);
dynamic_binding_test.setBuildMode(mode);
dynamic_binding_test.linkLibC();
dynamic_binding_test.addIncludeDir("src/binding/include");
dynamic_binding_test.addCSourceFile("examples/usage.c", &[_][]const u8{ "-Wall", "-Wextra", "-pedantic", "-std=c99" });
dynamic_binding_test.linkLibrary(dynamic_native_lib);
const static_binding_test_run = static_binding_test.run();
static_binding_test_run.cwd = "zig-cache";
const dynamic_binding_test_run = dynamic_binding_test.run();
dynamic_binding_test_run.cwd = "zig-cache";
const test_step = b.step("test", "Runs all tests");
test_step.dependOn(&tvg_tests.step);
test_step.dependOn(&static_binding_test_run.step);
test_step.dependOn(&dynamic_binding_test_run.step);
}
const polyfill = b.addSharedLibrary("tinyvg", "src/polyfill/tinyvg.zig", .unversioned);
polyfill.strip = (mode != .Debug);
polyfill.setBuildMode(mode);
polyfill.setTarget(.{
.cpu_arch = .wasm32,
.cpu_model = .baseline,
.os_tag = .freestanding,
});
polyfill.addPackage(pkgs.tvg);
if (install_www) {
polyfill.install();
polyfill.install_step.?.dest_dir = www_folder;
}
const copy_stuff = b.addInstallFileWithDir(.{ .path = "src/polyfill/tinyvg.js" }, www_folder, "tinyvg.js");
if (install_www) {
b.getInstallStep().dependOn(©_stuff.step);
}
} | build.zig |
const std = @import("std");
const testing = std.testing;
const mem = std.mem;
const c = @import("c.zig").c;
const glfw = @import("main.zig");
const Error = @import("errors.zig").Error;
const getError = @import("errors.zig").getError;
const Image = @import("Image.zig");
const Monitor = @import("Monitor.zig");
const Cursor = @import("Cursor.zig");
const Key = @import("key.zig").Key;
const Action = @import("action.zig").Action;
const Mods = @import("mod.zig").Mods;
const MouseButton = @import("mouse_button.zig").MouseButton;
const internal_debug = @import("internal_debug.zig");
const Window = @This();
handle: *c.GLFWwindow,
/// Returns a Zig GLFW window from an underlying C GLFW window handle.
pub inline fn from(handle: *c.GLFWwindow) Window {
return Window{ .handle = handle };
}
/// Resets all window hints to their default values.
///
/// This function resets all window hints to their default values.
///
/// Possible errors include glfw.Error.NotInitialized.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_hints, glfw.Window.hint, glfw.Window.hintString
inline fn defaultHints() void {
internal_debug.assertInitialized();
c.glfwDefaultWindowHints();
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
}
/// Window hints
const Hint = enum(c_int) {
resizable = c.GLFW_RESIZABLE,
visible = c.GLFW_VISIBLE,
decorated = c.GLFW_DECORATED,
focused = c.GLFW_FOCUSED,
auto_iconify = c.GLFW_AUTO_ICONIFY,
floating = c.GLFW_FLOATING,
maximized = c.GLFW_MAXIMIZED,
center_cursor = c.GLFW_CENTER_CURSOR,
transparent_framebuffer = c.GLFW_TRANSPARENT_FRAMEBUFFER,
focus_on_show = c.GLFW_FOCUS_ON_SHOW,
mouse_passthrough = c.GLFW_MOUSE_PASSTHROUGH,
scale_to_monitor = c.GLFW_SCALE_TO_MONITOR,
/// Framebuffer hints
red_bits = c.GLFW_RED_BITS,
green_bits = c.GLFW_GREEN_BITS,
blue_bits = c.GLFW_BLUE_BITS,
alpha_bits = c.GLFW_ALPHA_BITS,
depth_bits = c.GLFW_DEPTH_BITS,
stencil_bits = c.GLFW_STENCIL_BITS,
accum_red_bits = c.GLFW_ACCUM_RED_BITS,
accum_green_bits = c.GLFW_ACCUM_GREEN_BITS,
accum_blue_bits = c.GLFW_ACCUM_BLUE_BITS,
accum_alpha_bits = c.GLFW_ACCUM_ALPHA_BITS,
aux_buffers = c.GLFW_AUX_BUFFERS,
/// Framebuffer MSAA samples
samples = c.GLFW_SAMPLES,
/// Monitor refresh rate
refresh_rate = c.GLFW_REFRESH_RATE,
/// OpenGL stereoscopic rendering
stereo = c.GLFW_STEREO,
/// Framebuffer sRGB
srgb_capable = c.GLFW_SRGB_CAPABLE,
/// Framebuffer double buffering
doublebuffer = c.GLFW_DOUBLEBUFFER,
client_api = c.GLFW_CLIENT_API,
context_creation_api = c.GLFW_CONTEXT_CREATION_API,
context_version_major = c.GLFW_CONTEXT_VERSION_MAJOR,
context_version_minor = c.GLFW_CONTEXT_VERSION_MINOR,
context_robustness = c.GLFW_CONTEXT_ROBUSTNESS,
context_release_behavior = c.GLFW_CONTEXT_RELEASE_BEHAVIOR,
context_no_error = c.GLFW_CONTEXT_NO_ERROR,
// NOTE: This supersedes opengl_debug_context / GLFW_OPENGL_DEBUG_CONTEXT
context_debug = c.GLFW_CONTEXT_DEBUG,
opengl_forward_compat = c.GLFW_OPENGL_FORWARD_COMPAT,
opengl_profile = c.GLFW_OPENGL_PROFILE,
/// macOS specific
cocoa_retina_framebuffer = c.GLFW_COCOA_RETINA_FRAMEBUFFER,
/// macOS specific
cocoa_frame_name = c.GLFW_COCOA_FRAME_NAME,
/// macOS specific
cocoa_graphics_switching = c.GLFW_COCOA_GRAPHICS_SWITCHING,
/// X11 specific
x11_class_name = c.GLFW_X11_CLASS_NAME,
/// X11 specific
x11_instance_name = c.GLFW_X11_INSTANCE_NAME,
/// Windows specific
win32_keyboard_menu = c.GLFW_WIN32_KEYBOARD_MENU,
};
/// Window hints
pub const Hints = struct {
// Note: The defaults here are directly from the GLFW source of the glfwDefaultWindowHints function
resizable: bool = true,
visible: bool = true,
decorated: bool = true,
focused: bool = true,
auto_iconify: bool = true,
floating: bool = false,
maximized: bool = false,
center_cursor: bool = true,
transparent_framebuffer: bool = false,
focus_on_show: bool = true,
mouse_passthrough: bool = false,
scale_to_monitor: bool = false,
/// Framebuffer hints
red_bits: ?PositiveCInt = 8,
green_bits: ?PositiveCInt = 8,
blue_bits: ?PositiveCInt = 8,
alpha_bits: ?PositiveCInt = 8,
depth_bits: ?PositiveCInt = 24,
stencil_bits: ?PositiveCInt = 8,
accum_red_bits: ?PositiveCInt = 0,
accum_green_bits: ?PositiveCInt = 0,
accum_blue_bits: ?PositiveCInt = 0,
accum_alpha_bits: ?PositiveCInt = 0,
aux_buffers: ?PositiveCInt = 0,
/// Framebuffer MSAA samples
samples: ?PositiveCInt = 0,
/// Monitor refresh rate
refresh_rate: ?PositiveCInt = null,
/// OpenGL stereoscopic rendering
stereo: bool = false,
/// Framebuffer sRGB
srgb_capable: bool = false,
/// Framebuffer double buffering
doublebuffer: bool = true,
client_api: ClientAPI = .opengl_api,
context_creation_api: ContextCreationAPI = .native_context_api,
context_version_major: c_int = 1,
context_version_minor: c_int = 0,
context_robustness: ContextRobustness = .no_robustness,
context_release_behavior: ContextReleaseBehavior = .any_release_behavior,
/// Note: disables the context creating errors,
/// instead turning them into undefined behavior.
context_no_error: bool = false,
context_debug: bool = false,
opengl_forward_compat: bool = false,
opengl_profile: OpenGLProfile = .opengl_any_profile,
/// macOS specific
cocoa_retina_framebuffer: bool = true,
/// macOS specific
cocoa_frame_name: [:0]const u8 = "",
/// macOS specific
cocoa_graphics_switching: bool = false,
/// X11 specific
x11_class_name: [:0]const u8 = "",
/// X11 specific
x11_instance_name: [:0]const u8 = "",
/// Windows specific
win32_keyboard_menu: bool = false,
pub const PositiveCInt = std.math.IntFittingRange(0, std.math.maxInt(c_int));
pub const ClientAPI = enum(c_int) {
opengl_api = c.GLFW_OPENGL_API,
opengl_es_api = c.GLFW_OPENGL_ES_API,
no_api = c.GLFW_NO_API,
};
pub const ContextCreationAPI = enum(c_int) {
native_context_api = c.GLFW_NATIVE_CONTEXT_API,
egl_context_api = c.GLFW_EGL_CONTEXT_API,
osmesa_context_api = c.GLFW_OSMESA_CONTEXT_API,
};
pub const ContextRobustness = enum(c_int) {
no_robustness = c.GLFW_NO_ROBUSTNESS,
no_reset_notification = c.GLFW_NO_RESET_NOTIFICATION,
lose_context_on_reset = c.GLFW_LOSE_CONTEXT_ON_RESET,
};
pub const ContextReleaseBehavior = enum(c_int) {
any_release_behavior = c.GLFW_ANY_RELEASE_BEHAVIOR,
release_behavior_flush = c.GLFW_RELEASE_BEHAVIOR_FLUSH,
release_behavior_none = c.GLFW_RELEASE_BEHAVIOR_NONE,
};
pub const OpenGLProfile = enum(c_int) {
opengl_any_profile = c.GLFW_OPENGL_ANY_PROFILE,
opengl_compat_profile = c.GLFW_OPENGL_COMPAT_PROFILE,
opengl_core_profile = c.GLFW_OPENGL_CORE_PROFILE,
};
fn set(hints: Hints) void {
internal_debug.assertInitialized();
inline for (comptime std.meta.fieldNames(Hint)) |field_name| {
const hint_tag = @enumToInt(@field(Hint, field_name));
const hint_value = @field(hints, field_name);
switch (@TypeOf(hint_value)) {
bool => c.glfwWindowHint(hint_tag, @boolToInt(hint_value)),
?PositiveCInt => c.glfwWindowHint(hint_tag, if (hint_value) |unwrapped| unwrapped else glfw.dont_care),
c_int => c.glfwWindowHint(hint_tag, hint_value),
ClientAPI,
ContextCreationAPI,
ContextRobustness,
ContextReleaseBehavior,
OpenGLProfile,
=> c.glfwWindowHint(hint_tag, @enumToInt(hint_value)),
[:0]const u8 => c.glfwWindowHintString(hint_tag, hint_value.ptr),
else => unreachable,
}
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.InvalidEnum => unreachable,
else => unreachable,
};
}
}
};
/// Creates a window and its associated context.
///
/// This function creates a window and its associated OpenGL or OpenGL ES context. Most of the
/// options controlling how the window and its context should be created are specified with window
/// hints using `glfw.Window.hint`.
///
/// Successful creation does not change which context is current. Before you can use the newly
/// created context, you need to make it current using `glfw.Window.makeContextCurrent`. For
/// information about the `share` parameter, see context_sharing.
///
/// The created window, framebuffer and context may differ from what you requested, as not all
/// parameters and hints are hard constraints. This includes the size of the window, especially for
/// full screen windows. To query the actual attributes of the created window, framebuffer and
/// context, see glfw.Window.getAttrib, glfw.Window.getSize and glfw.window.getFramebufferSize.
///
/// To create a full screen window, you need to specify the monitor the window will cover. If no
/// monitor is specified, the window will be windowed mode. Unless you have a way for the user to
/// choose a specific monitor, it is recommended that you pick the primary monitor. For more
/// information on how to query connected monitors, see @ref monitor_monitors.
///
/// For full screen windows, the specified size becomes the resolution of the window's _desired
/// video mode_. As long as a full screen window is not iconified, the supported video mode most
/// closely matching the desired video mode is set for the specified monitor. For more information
/// about full screen windows, including the creation of so called _windowed full screen_ or
/// _borderless full screen_ windows, see window_windowed_full_screen.
///
/// Once you have created the window, you can switch it between windowed and full screen mode with
/// glfw.Window.setMonitor. This will not affect its OpenGL or OpenGL ES context.
///
/// By default, newly created windows use the placement recommended by the window system. To create
/// the window at a specific position, make it initially invisible using the glfw.version window
/// hint, set its position and then show it.
///
/// As long as at least one full screen window is not iconified, the screensaver is prohibited from
/// starting.
///
/// Window systems put limits on window sizes. Very large or very small window dimensions may be
/// overridden by the window system on creation. Check the actual size after creation.
///
/// The swap interval is not set during window creation and the initial value may vary depending on
/// driver settings and defaults.
///
/// Possible errors include glfw.Error.NotInitialized, glfw.Error.InvalidEnum, glfw.Error.InvalidValue,
/// glfw.Error.APIUnavailable, glfw.Error.VersionUnavailable, glfw.Error.FormatUnavailable and
/// glfw.Error.PlatformError.
///
/// Parameters are as follows:
///
/// * `width` The desired width, in screen coordinates, of the window.
/// * `height` The desired height, in screen coordinates, of the window.
/// * `title` The initial, UTF-8 encoded window title.
/// * `monitor` The monitor to use for full screen mode, or `null` for windowed mode.
/// * `share` The window whose context to share resources with, or `null` to not share resources.
///
/// win32: Window creation will fail if the Microsoft GDI software OpenGL implementation is the
/// only one available.
///
/// win32: If the executable has an icon resource named `GLFW_ICON`, it will be set as the initial
/// icon for the window. If no such icon is present, the `IDI_APPLICATION` icon will be used
/// instead. To set a different icon, see glfw.Window.setIcon.
///
/// win32: The context to share resources with must not be current on any other thread.
///
/// macos: The OS only supports forward-compatible core profile contexts for OpenGL versions 3.2
/// and later. Before creating an OpenGL context of version 3.2 or later you must set the
/// `glfw.opengl_forward_compat` and `glfw.opengl_profile` hints accordingly. OpenGL 3.0 and 3.1
/// contexts are not supported at all on macOS.
///
/// macos: The OS only supports core profile contexts for OpenGL versions 3.2 and later. Before
/// creating an OpenGL context of version 3.2 or later you must set the `glfw.opengl_profile` hint
/// accordingly. OpenGL 3.0 and 3.1 contexts are not supported at all on macOS.
///
/// macos: The GLFW window has no icon, as it is not a document window, but the dock icon will be
/// the same as the application bundle's icon. For more information on bundles, see the
/// [Bundle Programming Guide](https://developer.apple.com/library/mac/documentation/CoreFoundation/Conceptual/CFBundles/)
/// in the Mac Developer Library.
///
/// macos: On OS X 10.10 and later the window frame will not be rendered at full resolution on
/// Retina displays unless the glfw.cocoa_retina_framebuffer hint is true (1) and the `NSHighResolutionCapable`
/// key is enabled in the application bundle's `Info.plist`. For more information, see
/// [High Resolution Guidelines for OS X](https://developer.apple.com/library/mac/documentation/GraphicsAnimation/Conceptual/HighResolutionOSX/Explained/Explained.html)
/// in the Mac Developer Library. The GLFW test and example programs use a custom `Info.plist`
/// template for this, which can be found as `CMake/Info.plist.in` in the source tree.
///
/// macos: When activating frame autosaving with glfw.cocoa_frame_name, the specified window size
/// and position may be overridden by previously saved values.
///
/// x11: Some window managers will not respect the placement of initially hidden windows.
///
/// x11: Due to the asynchronous nature of X11, it may take a moment for a window to reach its
/// requested state. This means you may not be able to query the final size, position or other
/// attributes directly after window creation.
///
/// x11: The class part of the `WM_CLASS` window property will by default be set to the window title
/// passed to this function. The instance part will use the contents of the `RESOURCE_NAME`
/// environment variable, if present and not empty, or fall back to the window title. Set the glfw.x11_class_name
/// and glfw.x11_instance_name window hints to override this.
///
/// wayland: Compositors should implement the xdg-decoration protocol for GLFW to decorate the
/// window properly. If this protocol isn't supported, or if the compositor prefers client-side
/// decorations, a very simple fallback frame will be drawn using the wp_viewporter protocol. A
/// compositor can still emit close, maximize or fullscreen events, using for instance a keybind
/// mechanism. If neither of these protocols is supported, the window won't be decorated.
///
/// wayland: A full screen window will not attempt to change the mode, no matter what the
/// requested size or refresh rate.
///
/// wayland: Screensaver inhibition requires the idle-inhibit protocol to be implemented in the
/// user's compositor.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_creation, glfw.Window.destroy
pub inline fn create(
width: u32,
height: u32,
title: [*:0]const u8,
monitor: ?Monitor,
share: ?Window,
hints: Hints,
) error{ APIUnavailable, VersionUnavailable, FormatUnavailable, PlatformError }!Window {
internal_debug.assertInitialized();
const ignore_hints_struct = if (comptime @import("builtin").is_test) testing_ignore_window_hints_struct else false;
if (!ignore_hints_struct) hints.set();
defer if (!ignore_hints_struct) defaultHints();
if (c.glfwCreateWindow(
@intCast(c_int, width),
@intCast(c_int, height),
&title[0],
if (monitor) |m| m.handle else null,
if (share) |w| w.handle else null,
)) |handle| return from(handle);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.InvalidEnum => unreachable,
Error.InvalidValue => unreachable,
Error.APIUnavailable,
Error.PlatformError,
Error.VersionUnavailable,
Error.FormatUnavailable,
=> |e| e,
else => unreachable,
};
// `glfwCreateWindow` returns `null` only for errors
unreachable;
}
var testing_ignore_window_hints_struct = if (@import("builtin").is_test) false else @as(void, {});
/// Destroys the specified window and its context.
///
/// This function destroys the specified window and its context. On calling this function, no
/// further callbacks will be called for that window.
///
/// If the context of the specified window is current on the main thread, it is detached before
/// being destroyed.
///
/// note: The context of the specified window must not be current on any other thread when this
/// function is called.
///
/// @reentrancy This function must not be called from a callback.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_creation, glfw.Window.create
pub inline fn destroy(self: Window) void {
internal_debug.assertInitialized();
c.glfwDestroyWindow(self.handle);
// Technically, glfwDestroyWindow could produce errors including glfw.Error.NotInitialized and
// glfw.Error.PlatformError. But how would anybody handle them? By creating a new window to
// warn the user? That seems user-hostile. Also, `defer try window.destroy()` isn't possible in
// Zig, so by returning an error we'd make it harder to destroy the window properly. So we differ
// from GLFW here: we discard any potential error from this operation.
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.PlatformError => std.log.debug("{}: was unable to destroy Window.\n", .{err}),
else => unreachable,
};
}
/// Checks the close flag of the specified window.
///
/// This function returns the value of the close flag of the specified window.
///
/// @thread_safety This function may be called from any thread. Access is not synchronized.
///
/// see also: window_close
pub inline fn shouldClose(self: Window) bool {
internal_debug.assertInitialized();
const flag = c.glfwWindowShouldClose(self.handle);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
return flag == c.GLFW_TRUE;
}
/// Sets the close flag of the specified window.
///
/// This function sets the value of the close flag of the specified window. This can be used to
/// override the user's attempt to close the window, or to signal that it should be closed.
///
/// Possible errors include glfw.Error.NotInitialized.
///
/// @thread_safety This function may be called from any thread. Access is not
/// synchronized.
///
/// see also: window_close
pub inline fn setShouldClose(self: Window, value: bool) void {
internal_debug.assertInitialized();
const boolean = if (value) c.GLFW_TRUE else c.GLFW_FALSE;
c.glfwSetWindowShouldClose(self.handle, boolean);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
}
/// Sets the UTF-8 encoded title of the specified window.
///
/// This function sets the window title, encoded as UTF-8, of the specified window.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// macos: The window title will not be updated until the next time you process events.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_title
pub inline fn setTitle(self: Window, title: [*:0]const u8) error{PlatformError}!void {
internal_debug.assertInitialized();
c.glfwSetWindowTitle(self.handle, title);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
}
/// Sets the icon for the specified window.
///
/// This function sets the icon of the specified window. If passed an array of candidate images,
/// those of or closest to the sizes desired by the system are selected. If no images are
/// specified, the window reverts to its default icon.
///
/// The pixels are 32-bit, little-endian, non-premultiplied RGBA, i.e. eight bits per channel with
/// the red channel first. They are arranged canonically as packed sequential rows, starting from
/// the top-left corner.
///
/// The desired image sizes varies depending on platform and system settings. The selected images
/// will be rescaled as needed. Good sizes include 16x16, 32x32 and 48x48.
///
/// @pointer_lifetime The specified image data is copied before this function returns.
///
/// macos: Regular windows do not have icons on macOS. This function will emit FeatureUnavailable.
/// The dock icon will be the same as the application bundle's icon. For more information on
/// bundles, see the [Bundle Programming Guide](https://developer.apple.com/library/mac/documentation/CoreFoundation/Conceptual/CFBundles/)
/// in the Mac Developer Library.
///
/// wayland: There is no existing protocol to change an icon, the window will thus inherit the one
/// defined in the application's desktop file. This function will emit glfw.Error.FeatureUnavailable.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_icon
pub inline fn setIcon(self: Window, allocator: mem.Allocator, images: ?[]Image) (mem.Allocator.Error || error{ InvalidValue, FeatureUnavailable })!void {
internal_debug.assertInitialized();
if (images) |im| {
const tmp = try allocator.alloc(c.GLFWimage, im.len);
defer allocator.free(tmp);
for (im) |img, index| tmp[index] = img.toC();
c.glfwSetWindowIcon(self.handle, @intCast(c_int, im.len), &tmp[0]);
} else c.glfwSetWindowIcon(self.handle, 0, null);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.InvalidValue => |e| e,
Error.FeatureUnavailable => |e| e,
else => unreachable,
};
}
pub const Pos = struct {
x: u32,
y: u32,
};
/// Retrieves the position of the content area of the specified window.
///
/// This function retrieves the position, in screen coordinates, of the upper-left corner of the
/// content area of the specified window.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.FeatureUnavailable.
///
/// wayland: There is no way for an application to retrieve the global position of its windows,
/// this function will always emit glfw.Error.FeatureUnavailable.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_pos glfw.Window.setPos
pub inline fn getPos(self: Window) error{FeatureUnavailable}!Pos {
internal_debug.assertInitialized();
var x: c_int = 0;
var y: c_int = 0;
c.glfwGetWindowPos(self.handle, &x, &y);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.FeatureUnavailable => |e| e,
else => unreachable,
};
return Pos{ .x = @intCast(u32, x), .y = @intCast(u32, y) };
}
/// Sets the position of the content area of the specified window.
///
/// This function sets the position, in screen coordinates, of the upper-left corner of the content
/// area of the specified windowed mode window. If the window is a full screen window, this
/// function does nothing.
///
/// __Do not use this function__ to move an already visible window unless you have very good
/// reasons for doing so, as it will confuse and annoy the user.
///
/// The window manager may put limits on what positions are allowed. GLFW cannot and should not
/// override these limits.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.FeatureUnavailable.
///
/// wayland: There is no way for an application to set the global position of its windows, this
/// function will always emit glfw.Error.FeatureUnavailable.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_pos, glfw.Window.getPos
pub inline fn setPos(self: Window, pos: Pos) error{FeatureUnavailable}!void {
internal_debug.assertInitialized();
c.glfwSetWindowPos(self.handle, @intCast(c_int, pos.x), @intCast(c_int, pos.y));
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.FeatureUnavailable => |e| e,
else => unreachable,
};
}
pub const Size = struct {
width: u32,
height: u32,
};
/// Retrieves the size of the content area of the specified window.
///
/// This function retrieves the size, in screen coordinates, of the content area of the specified
/// window. If you wish to retrieve the size of the framebuffer of the window in pixels, see
/// glfw.Window.getFramebufferSize.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_size, glfw.Window.setSize
pub inline fn getSize(self: Window) error{PlatformError}!Size {
internal_debug.assertInitialized();
var width: c_int = 0;
var height: c_int = 0;
c.glfwGetWindowSize(self.handle, &width, &height);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
return Size{ .width = @intCast(u32, width), .height = @intCast(u32, height) };
}
/// Sets the size of the content area of the specified window.
///
/// This function sets the size, in screen coordinates, of the content area of the specified window.
///
/// For full screen windows, this function updates the resolution of its desired video mode and
/// switches to the video mode closest to it, without affecting the window's context. As the
/// context is unaffected, the bit depths of the framebuffer remain unchanged.
///
/// If you wish to update the refresh rate of the desired video mode in addition to its resolution,
/// see glfw.Window.setMonitor.
///
/// The window manager may put limits on what sizes are allowed. GLFW cannot and should not
/// override these limits.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// wayland: A full screen window will not attempt to change the mode, no matter what the requested
/// size.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_size, glfw.Window.getSize, glfw.Window.SetMonitor
pub inline fn setSize(self: Window, size: Size) error{PlatformError}!void {
internal_debug.assertInitialized();
c.glfwSetWindowSize(self.handle, @intCast(c_int, size.width), @intCast(c_int, size.height));
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
}
/// A size with option width/height, used to represent e.g. constraints on a windows size while
/// allowing specific axis to be unconstrained (null) if desired.
pub const SizeOptional = struct {
width: ?u32,
height: ?u32,
};
/// Sets the size limits of the specified window's content area.
///
/// This function sets the size limits of the content area of the specified window. If the window
/// is full screen, the size limits only take effect/ once it is made windowed. If the window is not
/// resizable, this function does nothing.
///
/// The size limits are applied immediately to a windowed mode window and may cause it to be resized.
///
/// The maximum dimensions must be greater than or equal to the minimum dimensions. glfw.dont_care
/// may be used for any width/height parameter.
///
/// Possible errors include glfw.Error.NotInitialized, glfw.Error.InvalidValue and glfw.Error.PlatformError.
///
/// If you set size limits and an aspect ratio that conflict, the results are undefined.
///
/// wayland: The size limits will not be applied until the window is actually resized, either by
/// the user or by the compositor.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_sizelimits, glfw.Window.setAspectRatio
pub inline fn setSizeLimits(self: Window, min: SizeOptional, max: SizeOptional) error{PlatformError}!void {
internal_debug.assertInitialized();
if (min.width != null and max.width != null) {
std.debug.assert(min.width.? <= max.width.?);
}
if (min.height != null and max.height != null) {
std.debug.assert(min.height.? <= max.height.?);
}
c.glfwSetWindowSizeLimits(
self.handle,
if (min.width) |min_width| @intCast(c_int, min_width) else glfw.dont_care,
if (min.height) |min_height| @intCast(c_int, min_height) else glfw.dont_care,
if (max.width) |max_width| @intCast(c_int, max_width) else glfw.dont_care,
if (max.height) |max_height| @intCast(c_int, max_height) else glfw.dont_care,
);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.InvalidValue => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
}
/// Sets the aspect ratio of the specified window.
///
/// This function sets the required aspect ratio of the content area of the specified window. If
/// the window is full screen, the aspect ratio only takes effect once it is made windowed. If the
/// window is not resizable, this function does nothing.
///
/// The aspect ratio is specified as a numerator and a denominator and both values must be greater
/// than zero. For example, the common 16:9 aspect ratio is specified as 16 and 9, respectively.
///
/// If the numerator AND denominator is set to `glfw.dont_care` then the aspect ratio limit is
/// disabled.
///
/// The aspect ratio is applied immediately to a windowed mode window and may cause it to be
/// resized.
///
/// Possible errors include glfw.Error.NotInitialized, glfw.Error.InvalidValue and
/// glfw.Error.PlatformError.
///
/// If you set size limits and an aspect ratio that conflict, the results are undefined.
///
/// wayland: The aspect ratio will not be applied until the window is actually resized, either by
/// the user or by the compositor.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_sizelimits, glfw.Window.setSizeLimits
pub inline fn setAspectRatio(self: Window, numerator: ?u32, denominator: ?u32) error{PlatformError}!void {
internal_debug.assertInitialized();
if (numerator != null and denominator != null) {
std.debug.assert(numerator.? > 0);
std.debug.assert(denominator.? > 0);
}
c.glfwSetWindowAspectRatio(
self.handle,
if (numerator) |numerator_unwrapped| @intCast(c_int, numerator_unwrapped) else glfw.dont_care,
if (denominator) |denominator_unwrapped| @intCast(c_int, denominator_unwrapped) else glfw.dont_care,
);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.InvalidValue => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
}
/// Retrieves the size of the framebuffer of the specified window.
///
/// This function retrieves the size, in pixels, of the framebuffer of the specified window. If you
/// wish to retrieve the size of the window in screen coordinates, see @ref glfwGetWindowSize.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_fbsize, glfwWindow.setFramebufferSizeCallback
pub inline fn getFramebufferSize(self: Window) error{PlatformError}!Size {
internal_debug.assertInitialized();
var width: c_int = 0;
var height: c_int = 0;
c.glfwGetFramebufferSize(self.handle, &width, &height);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
return Size{ .width = @intCast(u32, width), .height = @intCast(u32, height) };
}
pub const FrameSize = struct {
left: u32,
top: u32,
right: u32,
bottom: u32,
};
/// Retrieves the size of the frame of the window.
///
/// This function retrieves the size, in screen coordinates, of each edge of the frame of the
/// specified window. This size includes the title bar, if the window has one. The size of the
/// frame may vary depending on the window-related hints used to create it.
///
/// Because this function retrieves the size of each window frame edge and not the offset along a
/// particular coordinate axis, the retrieved values will always be zero or positive.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_size
pub inline fn getFrameSize(self: Window) error{PlatformError}!FrameSize {
internal_debug.assertInitialized();
var left: c_int = 0;
var top: c_int = 0;
var right: c_int = 0;
var bottom: c_int = 0;
c.glfwGetWindowFrameSize(self.handle, &left, &top, &right, &bottom);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
return FrameSize{
.left = @intCast(u32, left),
.top = @intCast(u32, top),
.right = @intCast(u32, right),
.bottom = @intCast(u32, bottom),
};
}
pub const ContentScale = struct {
x_scale: f32,
y_scale: f32,
};
/// Retrieves the content scale for the specified window.
///
/// This function retrieves the content scale for the specified window. The content scale is the
/// ratio between the current DPI and the platform's default DPI. This is especially important for
/// text and any UI elements. If the pixel dimensions of your UI scaled by this look appropriate on
/// your machine then it should appear at a reasonable size on other machines regardless of their
/// DPI and scaling settings. This relies on the system DPI and scaling settings being somewhat
/// correct.
///
/// On platforms where each monitors can have its own content scale, the window content scale will
/// depend on which monitor the system considers the window to be on.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_scale, glfwSetWindowContentScaleCallback, glfwGetMonitorContentScale
pub inline fn getContentScale(self: Window) error{PlatformError}!ContentScale {
internal_debug.assertInitialized();
var x_scale: f32 = 0;
var y_scale: f32 = 0;
c.glfwGetWindowContentScale(self.handle, &x_scale, &y_scale);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
return ContentScale{ .x_scale = x_scale, .y_scale = y_scale };
}
/// Returns the opacity of the whole window.
///
/// This function returns the opacity of the window, including any decorations.
///
/// The opacity (or alpha) value is a positive finite number between zero and one, where zero is
/// fully transparent and one is fully opaque. If the system does not support whole window
/// transparency, this function always returns one.
///
/// The initial opacity value for newly created windows is one.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_transparency, glfw.Window.setOpacity
pub inline fn getOpacity(self: Window) error{PlatformError}!f32 {
internal_debug.assertInitialized();
const opacity = c.glfwGetWindowOpacity(self.handle);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
return opacity;
}
/// Sets the opacity of the whole window.
///
/// This function sets the opacity of the window, including any decorations.
///
/// The opacity (or alpha) value is a positive finite number between zero and one, where zero is
/// fully transparent and one is fully opaque.
///
/// The initial opacity value for newly created windows is one.
///
/// A window created with framebuffer transparency may not use whole window transparency. The
/// results of doing this are undefined.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_transparency, glfw.Window.getOpacity
pub inline fn setOpacity(self: Window, opacity: f32) error{ PlatformError, FeatureUnavailable }!void {
internal_debug.assertInitialized();
c.glfwSetWindowOpacity(self.handle, opacity);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.PlatformError => |e| e,
Error.FeatureUnavailable => |e| e,
else => unreachable,
};
}
/// Iconifies the specified window.
///
/// This function iconifies (minimizes) the specified window if it was previously restored. If the
/// window is already iconified, this function does nothing.
///
/// If the specified window is a full screen window, the original monitor resolution is restored
/// until the window is restored.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// wayland: Once a window is iconified, glfw.Window.restorebe able to restore it. This is a design
/// decision of the xdg-shell protocol.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_iconify, glfw.Window.restore, glfw.Window.maximize
pub inline fn iconify(self: Window) error{PlatformError}!void {
internal_debug.assertInitialized();
c.glfwIconifyWindow(self.handle);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
}
/// Restores the specified window.
///
/// This function restores the specified window if it was previously iconified (minimized) or
/// maximized. If the window is already restored, this function does nothing.
///
/// If the specified window is a full screen window, the resolution chosen for the window is
/// restored on the selected monitor.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_iconify, glfw.Window.iconify, glfw.Window.maximize
pub inline fn restore(self: Window) error{PlatformError}!void {
internal_debug.assertInitialized();
c.glfwRestoreWindow(self.handle);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
}
/// Maximizes the specified window.
///
/// This function maximizes the specified window if it was previously not maximized. If the window
/// is already maximized, this function does nothing.
///
/// If the specified window is a full screen window, this function does nothing.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_iconify, glfw.Window.iconify, glfw.Window.restore
pub inline fn maximize(self: Window) error{PlatformError}!void {
internal_debug.assertInitialized();
c.glfwMaximizeWindow(self.handle);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
}
/// Makes the specified window visible.
///
/// This function makes the specified window visible if it was previously hidden. If the window is
/// already visible or is in full screen mode, this function does nothing.
///
/// By default, windowed mode windows are focused when shown Set the glfw.focus_on_show window hint
/// to change this behavior for all newly created windows, or change the
/// behavior for an existing window with glfw.Window.setAttrib.
///
/// wayland: Because Wayland wants every frame of the desktop to be complete, this function does
/// not immediately make the window visible. Instead it will become visible the next time the window
/// framebuffer is updated after this call.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_hide, glfw.Window.hide
pub inline fn show(self: Window) error{PlatformError}!void {
internal_debug.assertInitialized();
c.glfwShowWindow(self.handle);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
}
/// Hides the specified window.
///
/// This function hides the specified window if it was previously visible. If the window is already
/// hidden or is in full screen mode, this function does nothing.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_hide, glfw.Window.show
pub inline fn hide(self: Window) error{PlatformError}!void {
internal_debug.assertInitialized();
c.glfwHideWindow(self.handle);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
}
/// Brings the specified window to front and sets input focus.
///
/// This function brings the specified window to front and sets input focus. The window should
/// already be visible and not iconified.
///
/// By default, both windowed and full screen mode windows are focused when initially created. Set
/// the glfw.focused to disable this behavior.
///
/// Also by default, windowed mode windows are focused when shown with glfw.Window.show. Set the
/// glfw.focus_on_show to disable this behavior.
///
/// __Do not use this function__ to steal focus from other applications unless you are certain that
/// is what the user wants. Focus stealing can be extremely disruptive.
///
/// For a less disruptive way of getting the user's attention, see [attention requests (window_attention).
///
/// wayland It is not possible for an application to set the input focus. This function will emit glfw.Error.FeatureUnavailable.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_focus, window_attention
pub inline fn focus(self: Window) error{ PlatformError, FeatureUnavailable }!void {
internal_debug.assertInitialized();
c.glfwFocusWindow(self.handle);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.PlatformError => |e| e,
Error.FeatureUnavailable => |e| e,
else => unreachable,
};
}
/// Requests user attention to the specified window.
///
/// This function requests user attention to the specified window. On platforms where this is not
/// supported, attention is requested to the application as a whole.
///
/// Once the user has given attention, usually by focusing the window or application, the system will end the request automatically.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// macos: Attention is requested to the application as a whole, not the
/// specific window.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_attention
pub inline fn requestAttention(self: Window) error{PlatformError}!void {
internal_debug.assertInitialized();
c.glfwRequestWindowAttention(self.handle);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
}
/// Swaps the front and back buffers of the specified window.
///
/// This function swaps the front and back buffers of the specified window when rendering with
/// OpenGL or OpenGL ES. If the swap interval is greater than zero, the GPU driver waits the
/// specified number of screen updates before swapping the buffers.
///
/// The specified window must have an OpenGL or OpenGL ES context. Specifying a window without a
/// context will generate Error.NoWindowContext.
///
/// This function does not apply to Vulkan. If you are rendering with Vulkan, see `vkQueuePresentKHR`
/// instead.
///
/// @param[in] window The window whose buffers to swap.
///
/// Possible errors include glfw.Error.NotInitialized, glfw.Error.NoWindowContext and glfw.Error.PlatformError.
///
/// __EGL:__ The context of the specified window must be current on the calling thread.
///
/// @thread_safety This function may be called from any thread.
///
/// see also: buffer_swap, glfwSwapInterval
pub inline fn swapBuffers(self: Window) error{ NoWindowContext, PlatformError }!void {
internal_debug.assertInitialized();
c.glfwSwapBuffers(self.handle);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.NoWindowContext, Error.PlatformError => |e| e,
else => unreachable,
};
}
/// Returns the monitor that the window uses for full screen mode.
///
/// This function returns the handle of the monitor that the specified window is in full screen on.
///
/// @return The monitor, or null if the window is in windowed mode.
///
/// Possible errors include glfw.Error.NotInitialized.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_monitor, glfw.Window.setMonitor
pub inline fn getMonitor(self: Window) ?Monitor {
internal_debug.assertInitialized();
if (c.glfwGetWindowMonitor(self.handle)) |monitor| return Monitor{ .handle = monitor };
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
return null;
}
/// Sets the mode, monitor, video mode and placement of a window.
///
/// This function sets the monitor that the window uses for full screen mode or, if the monitor is
/// null, makes it windowed mode.
///
/// When setting a monitor, this function updates the width, height and refresh rate of the desired
/// video mode and switches to the video mode closest to it. The window position is ignored when
/// setting a monitor.
///
/// When the monitor is null, the position, width and height are used to place the window content
/// area. The refresh rate is ignored when no monitor is specified.
///
/// If you only wish to update the resolution of a full screen window or the size of a windowed
/// mode window, see @ref glfwSetWindowSize.
///
/// When a window transitions from full screen to windowed mode, this function restores any
/// previous window settings such as whether it is decorated, floating, resizable, has size or
/// aspect ratio limits, etc.
///
/// @param[in] window The window whose monitor, size or video mode to set.
/// @param[in] monitor The desired monitor, or null to set windowed mode.
/// @param[in] xpos The desired x-coordinate of the upper-left corner of the content area.
/// @param[in] ypos The desired y-coordinate of the upper-left corner of the content area.
/// @param[in] width The desired with, in screen coordinates, of the content area or video mode.
/// @param[in] height The desired height, in screen coordinates, of the content area or video mode.
/// @param[in] refreshRate The desired refresh rate, in Hz, of the video mode, or `glfw.dont_care`.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// The OpenGL or OpenGL ES context will not be destroyed or otherwise affected by any resizing or
/// mode switching, although you may need to update your viewport if the framebuffer size has
/// changed.
///
/// wayland: The desired window position is ignored, as there is no way for an application to set
/// this property.
///
/// wayland: Setting the window to full screen will not attempt to change the mode, no matter what
/// the requested size or refresh rate.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_monitor, window_full_screen, glfw.Window.getMonitor, glfw.Window.setSize
pub inline fn setMonitor(self: Window, monitor: ?Monitor, xpos: u32, ypos: u32, width: u32, height: u32, refresh_rate: ?u32) error{PlatformError}!void {
internal_debug.assertInitialized();
c.glfwSetWindowMonitor(
self.handle,
if (monitor) |m| m.handle else null,
@intCast(c_int, xpos),
@intCast(c_int, ypos),
@intCast(c_int, width),
@intCast(c_int, height),
if (refresh_rate) |refresh_rate_unwrapped| @intCast(c_int, refresh_rate_unwrapped) else glfw.dont_care,
);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
}
/// Window attributes
pub const Attrib = enum(c_int) {
iconified = c.GLFW_ICONIFIED,
resizable = c.GLFW_RESIZABLE,
visible = c.GLFW_VISIBLE,
decorated = c.GLFW_DECORATED,
focused = c.GLFW_FOCUSED,
auto_iconify = c.GLFW_AUTO_ICONIFY,
floating = c.GLFW_FLOATING,
maximized = c.GLFW_MAXIMIZED,
transparent_framebuffer = c.GLFW_TRANSPARENT_FRAMEBUFFER,
hovered = c.GLFW_HOVERED,
focus_on_show = c.GLFW_FOCUS_ON_SHOW,
mouse_passthrough = c.GLFW_MOUSE_PASSTHROUGH,
doublebuffer = c.GLFW_DOUBLEBUFFER,
client_api = c.GLFW_CLIENT_API,
context_creation_api = c.GLFW_CONTEXT_CREATION_API,
context_version_major = c.GLFW_CONTEXT_VERSION_MAJOR,
context_version_minor = c.GLFW_CONTEXT_VERSION_MINOR,
context_revision = c.GLFW_CONTEXT_REVISION,
context_robustness = c.GLFW_CONTEXT_ROBUSTNESS,
context_release_behavior = c.GLFW_CONTEXT_RELEASE_BEHAVIOR,
context_no_error = c.GLFW_CONTEXT_NO_ERROR,
context_debug = c.GLFW_CONTEXT_DEBUG,
opengl_forward_compat = c.GLFW_OPENGL_FORWARD_COMPAT,
opengl_profile = c.GLFW_OPENGL_PROFILE,
};
/// Returns an attribute of the specified window.
///
/// This function returns the value of an attribute of the specified window or its OpenGL or OpenGL
/// ES context.
///
/// @param[in] attrib The window attribute (see window_attribs) whose value to return.
/// @return The value of the attribute, or zero if an error occurred.
///
/// Possible errors include glfw.Error.NotInitialized, glfw.Error.InvalidEnum and glfw.Error.PlatformError.
///
/// Framebuffer related hints are not window attributes. See window_attribs_fb for more information.
///
/// Zero is a valid value for many window and context related attributes so you cannot use a return
/// value of zero as an indication of errors. However, this function should not fail as long as it
/// is passed valid arguments and the library has been initialized.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_attribs, glfw.Window.setAttrib
pub inline fn getAttrib(self: Window, attrib: Attrib) error{PlatformError}!i32 {
internal_debug.assertInitialized();
const v = c.glfwGetWindowAttrib(self.handle, @enumToInt(attrib));
if (v != 0) return v;
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.InvalidEnum => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
// this is not unreachable as `0` is a valid value
return v;
}
/// Sets an attribute of the specified window.
///
/// This function sets the value of an attribute of the specified window.
///
/// The supported attributes are glfw.decorated, glfw.resizable, glfw.floating, glfw.auto_iconify,
/// glfw.focus_on_show.
///
/// Some of these attributes are ignored for full screen windows. The new value will take effect
/// if the window is later made windowed.
///
/// Some of these attributes are ignored for windowed mode windows. The new value will take effect
/// if the window is later made full screen.
///
/// @param[in] attrib A supported window attribute.
///
/// Possible errors include glfw.Error.NotInitialized, glfw.Error.InvalidEnum, glfw.Error.InvalidValue and glfw.Error.PlatformError.
///
/// Calling glfw.Window.getAttrib will always return the latest
/// value, even if that value is ignored by the current mode of the window.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_attribs, glfw.Window.getAttrib
///
pub inline fn setAttrib(self: Window, attrib: Attrib, value: bool) error{PlatformError}!void {
internal_debug.assertInitialized();
std.debug.assert(switch (attrib) {
.decorated,
.resizable,
.floating,
.auto_iconify,
.focus_on_show,
.mouse_passthrough,
.doublebuffer,
=> true,
else => false,
});
c.glfwSetWindowAttrib(self.handle, @enumToInt(attrib), if (value) c.GLFW_TRUE else c.GLFW_FALSE);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.InvalidEnum => unreachable,
Error.InvalidValue => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
}
/// Sets the user pointer of the specified window.
///
/// This function sets the user-defined pointer of the specified window. The current value is
/// retained until the window is destroyed. The initial value is null.
///
/// @thread_safety This function may be called from any thread. Access is not synchronized.
///
/// see also: window_userptr, glfw.Window.getUserPointer
pub inline fn setUserPointer(self: Window, pointer: ?*anyopaque) void {
internal_debug.assertInitialized();
c.glfwSetWindowUserPointer(self.handle, pointer);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
}
/// Returns the user pointer of the specified window.
///
/// This function returns the current value of the user-defined pointer of the specified window.
/// The initial value is null.
///
/// @thread_safety This function may be called from any thread. Access is not synchronized.
///
/// see also: window_userptr, glfw.Window.setUserPointer
pub inline fn getUserPointer(self: Window, comptime T: type) ?*T {
internal_debug.assertInitialized();
if (c.glfwGetWindowUserPointer(self.handle)) |user_pointer| return @ptrCast(?*T, @alignCast(@alignOf(T), user_pointer));
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
return null;
}
/// Sets the position callback for the specified window.
///
/// This function sets the position callback of the specified window, which is called when the
/// window is moved. The callback is provided with the position, in screen coordinates, of the
/// upper-left corner of the content area of the window.
///
/// @param[in] callback The new callback, or null to remove the currently set callback.
///
/// @callback_param `window` the window that moved.
/// @callback_param `xpos` the new x-coordinate, in screen coordinates, of the upper-left corner of
/// the content area of the window.
/// @callback_param `ypos` the new y-coordinate, in screen coordinates, of the upper-left corner of
/// the content area of the window.
///
/// wayland: This callback will never be called, as there is no way for an application to know its
/// global position.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_pos
pub inline fn setPosCallback(self: Window, comptime callback: ?fn (window: Window, xpos: i32, ypos: i32) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn posCallbackWrapper(handle: ?*c.GLFWwindow, xpos: c_int, ypos: c_int) callconv(.C) void {
@call(.{ .modifier = .always_inline }, user_callback, .{
from(handle.?),
@intCast(i32, xpos),
@intCast(i32, ypos),
});
}
};
if (c.glfwSetWindowPosCallback(self.handle, CWrapper.posCallbackWrapper) != null) return;
} else {
if (c.glfwSetWindowPosCallback(self.handle, null) != null) return;
}
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
}
/// Sets the size callback for the specified window.
///
/// This function sets the size callback of the specified window, which is called when the window
/// is resized. The callback is provided with the size, in screen coordinates, of the content area
/// of the window.
///
/// @callback_param `window` the window that was resized.
/// @callback_param `width` the new width, in screen coordinates, of the window.
/// @callback_param `height` the new height, in screen coordinates, of the window.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_size
pub inline fn setSizeCallback(self: Window, comptime callback: ?fn (window: Window, width: i32, height: i32) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn sizeCallbackWrapper(handle: ?*c.GLFWwindow, width: c_int, height: c_int) callconv(.C) void {
@call(.{ .modifier = .always_inline }, user_callback, .{
from(handle.?),
@intCast(i32, width),
@intCast(i32, height),
});
}
};
if (c.glfwSetWindowSizeCallback(self.handle, CWrapper.sizeCallbackWrapper) != null) return;
} else {
if (c.glfwSetWindowSizeCallback(self.handle, null) != null) return;
}
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
}
/// Sets the close callback for the specified window.
///
/// This function sets the close callback of the specified window, which is called when the user
/// attempts to close the window, for example by clicking the close widget in the title bar.
///
/// The close flag is set before this callback is called, but you can modify it at any time with
/// glfw.Window.setShouldClose.
///
/// The close callback is not triggered by glfw.Window.destroy.
///
/// @param[in] window The window whose callback to set.
/// @param[in] callback The new callback, or null to remove the currently set callback.
///
/// @callback_param `window` the window that the user attempted to close.
///
/// macos: Selecting Quit from the application menu will trigger the close callback for all
/// windows.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_close
pub inline fn setCloseCallback(self: Window, comptime callback: ?fn (window: Window) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn closeCallbackWrapper(handle: ?*c.GLFWwindow) callconv(.C) void {
@call(.{ .modifier = .always_inline }, user_callback, .{
from(handle.?),
});
}
};
if (c.glfwSetWindowCloseCallback(self.handle, CWrapper.closeCallbackWrapper) != null) return;
} else {
if (c.glfwSetWindowCloseCallback(self.handle, null) != null) return;
}
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
}
/// Sets the refresh callback for the specified window.
///
/// This function sets the refresh callback of the specified window, which is
/// called when the content area of the window needs to be redrawn, for example
/// if the window has been exposed after having been covered by another window.
///
/// On compositing window systems such as Aero, Compiz, Aqua or Wayland, where
/// the window contents are saved off-screen, this callback may be called only
/// very infrequently or never at all.
///
/// @param[in] window The window whose callback to set.
/// @param[in] callback The new callback, or null to remove the currently set
/// callback.
///
/// @callback_param `window` the window whose content needs to be refreshed.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_refresh
pub inline fn setRefreshCallback(self: Window, comptime callback: ?fn (window: Window) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn refreshCallbackWrapper(handle: ?*c.GLFWwindow) callconv(.C) void {
@call(.{ .modifier = .always_inline }, user_callback, .{
from(handle.?),
});
}
};
if (c.glfwSetWindowRefreshCallback(self.handle, CWrapper.refreshCallbackWrapper) != null) return;
} else {
if (c.glfwSetWindowRefreshCallback(self.handle, null) != null) return;
}
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
}
/// Sets the focus callback for the specified window.
///
/// This function sets the focus callback of the specified window, which is
/// called when the window gains or loses input focus.
///
/// After the focus callback is called for a window that lost input focus,
/// synthetic key and mouse button release events will be generated for all such
/// that had been pressed. For more information, see @ref glfwSetKeyCallback
/// and @ref glfwSetMouseButtonCallback.
///
/// @param[in] window The window whose callback to set.
/// @param[in] callback The new callback, or null to remove the currently set
/// callback.
///
/// @callback_param `window` the window whose input focus has changed.
/// @callback_param `focused` `true` if the window was given input focus, or `false` if it lost it.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_focus
pub inline fn setFocusCallback(self: Window, comptime callback: ?fn (window: Window, focused: bool) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn focusCallbackWrapper(handle: ?*c.GLFWwindow, focused: c_int) callconv(.C) void {
@call(.{ .modifier = .always_inline }, user_callback, .{
from(handle.?),
focused == c.GLFW_TRUE,
});
}
};
if (c.glfwSetWindowFocusCallback(self.handle, CWrapper.focusCallbackWrapper) != null) return;
} else {
if (c.glfwSetWindowFocusCallback(self.handle, null) != null) return;
}
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
}
/// Sets the iconify callback for the specified window.
///
/// This function sets the iconification callback of the specified window, which
/// is called when the window is iconified or restored.
///
/// @param[in] window The window whose callback to set.
/// @param[in] callback The new callback, or null to remove the currently set
/// callback.
///
/// @callback_param `window` the window which was iconified or restored.
/// @callback_param `iconified` `true` if the window was iconified, or `false` if it was restored.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_iconify
pub inline fn setIconifyCallback(self: Window, comptime callback: ?fn (window: Window, iconified: bool) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn iconifyCallbackWrapper(handle: ?*c.GLFWwindow, iconified: c_int) callconv(.C) void {
@call(.{ .modifier = .always_inline }, user_callback, .{
from(handle.?),
iconified == c.GLFW_TRUE,
});
}
};
if (c.glfwSetWindowIconifyCallback(self.handle, CWrapper.iconifyCallbackWrapper) != null) return;
} else {
if (c.glfwSetWindowIconifyCallback(self.handle, null) != null) return;
}
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
}
/// Sets the maximize callback for the specified window.
///
/// This function sets the maximization callback of the specified window, which
/// is called when the window is maximized or restored.
///
/// @param[in] window The window whose callback to set.
/// @param[in] callback The new callback, or null to remove the currently set
/// callback.
///
/// @callback_param `window` the window which was maximized or restored.
/// @callback_param `maximized` `true` if the window was maximized, or `false` if it was restored.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_maximize
// GLFWAPI GLFWwindowmaximizefun glfwSetWindowMaximizeCallback(GLFWwindow* window, GLFWwindowmaximizefun callback);
pub inline fn setMaximizeCallback(self: Window, comptime callback: ?fn (window: Window, maximized: bool) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn maximizeCallbackWrapper(handle: ?*c.GLFWwindow, maximized: c_int) callconv(.C) void {
@call(.{ .modifier = .always_inline }, user_callback, .{
from(handle.?),
maximized == c.GLFW_TRUE,
});
}
};
if (c.glfwSetWindowMaximizeCallback(self.handle, CWrapper.maximizeCallbackWrapper) != null) return;
} else {
if (c.glfwSetWindowMaximizeCallback(self.handle, null) != null) return;
}
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
}
/// Sets the framebuffer resize callback for the specified window.
///
/// This function sets the framebuffer resize callback of the specified window,
/// which is called when the framebuffer of the specified window is resized.
///
/// @param[in] window The window whose callback to set.
/// @param[in] callback The new callback, or null to remove the currently set
/// callback.
///
/// @callback_param `window` the window whose framebuffer was resized.
/// @callback_param `width` the new width, in pixels, of the framebuffer.
/// @callback_param `height` the new height, in pixels, of the framebuffer.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_fbsize
pub inline fn setFramebufferSizeCallback(self: Window, comptime callback: ?fn (window: Window, width: u32, height: u32) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn framebufferSizeCallbackWrapper(handle: ?*c.GLFWwindow, width: c_int, height: c_int) callconv(.C) void {
@call(.{ .modifier = .always_inline }, user_callback, .{
from(handle.?),
@intCast(u32, width),
@intCast(u32, height),
});
}
};
if (c.glfwSetFramebufferSizeCallback(self.handle, CWrapper.framebufferSizeCallbackWrapper) != null) return;
} else {
if (c.glfwSetFramebufferSizeCallback(self.handle, null) != null) return;
}
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
}
/// Sets the window content scale callback for the specified window.
///
/// This function sets the window content scale callback of the specified window,
/// which is called when the content scale of the specified window changes.
///
/// @param[in] window The window whose callback to set.
/// @param[in] callback The new callback, or null to remove the currently set
/// callback.
///
/// @callback_param `window` the window whose content scale changed.
/// @callback_param `xscale` the new x-axis content scale of the window.
/// @callback_param `yscale` the new y-axis content scale of the window.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_scale, glfw.Window.getContentScale
pub inline fn setContentScaleCallback(self: Window, comptime callback: ?fn (window: Window, xscale: f32, yscale: f32) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn windowScaleCallbackWrapper(handle: ?*c.GLFWwindow, xscale: f32, yscale: f32) callconv(.C) void {
@call(.{ .modifier = .always_inline }, user_callback, .{
from(handle.?),
xscale,
yscale,
});
}
};
if (c.glfwSetWindowContentScaleCallback(self.handle, CWrapper.windowScaleCallbackWrapper) != null) return;
} else {
if (c.glfwSetWindowContentScaleCallback(self.handle, null) != null) return;
}
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
}
pub const InputMode = enum(c_int) {
cursor = c.GLFW_CURSOR,
sticky_keys = c.GLFW_STICKY_KEYS,
sticky_mouse_buttons = c.GLFW_STICKY_MOUSE_BUTTONS,
lock_key_mods = c.GLFW_LOCK_KEY_MODS,
raw_mouse_motion = c.GLFW_RAW_MOUSE_MOTION,
};
/// A cursor input mode to be supplied to `glfw.Window.setInputModeCursor`
pub const InputModeCursor = enum(c_int) {
/// Makes the cursor visible and behaving normally.
normal = c.GLFW_CURSOR_NORMAL,
/// Makes the cursor invisible when it is over the content area of the window but does not
/// restrict it from leaving.
hidden = c.GLFW_CURSOR_HIDDEN,
/// Hides and grabs the cursor, providing virtual and unlimited cursor movement. This is useful
/// for implementing for example 3D camera controls.
disabled = c.GLFW_CURSOR_DISABLED,
};
/// Sets the input mode of the cursor, whether it should behave normally, be hidden, or grabbed.
pub inline fn setInputModeCursor(self: Window, value: InputModeCursor) error{ PlatformError, FeatureUnavailable }!void {
return self.setInputMode(InputMode.cursor, value);
}
/// Gets the current input mode of the cursor.
pub inline fn getInputModeCursor(self: Window) InputModeCursor {
return @intToEnum(InputModeCursor, self.getInputMode(InputMode.cursor));
}
/// Sets the input mode of sticky keys, if enabled a key press will ensure that `glfw.Window.getKey`
/// return `.press` the next time it is called even if the key had been released before the call.
///
/// This is useful when you are only interested in whether keys have been pressed but not when or
/// in which order.
pub inline fn setInputModeStickyKeys(self: Window, enabled: bool) error{ PlatformError, FeatureUnavailable }!void {
return self.setInputMode(InputMode.sticky_keys, enabled);
}
/// Tells if the sticky keys input mode is enabled.
pub inline fn getInputModeStickyKeys(self: Window) bool {
return self.getInputMode(InputMode.sticky_keys) == 1;
}
/// Sets the input mode of sticky mouse buttons, if enabled a mouse button press will ensure that
/// `glfw.Window.getMouseButton` return `.press` the next time it is called even if the button had
/// been released before the call.
///
/// This is useful when you are only interested in whether buttons have been pressed but not when
/// or in which order.
pub inline fn setInputModeStickyMouseButtons(self: Window, enabled: bool) error{ PlatformError, FeatureUnavailable }!void {
return self.setInputMode(InputMode.sticky_mouse_buttons, enabled);
}
/// Tells if the sticky mouse buttons input mode is enabled.
pub inline fn getInputModeStickyMouseButtons(self: Window) bool {
return self.getInputMode(InputMode.sticky_mouse_buttons) == 1;
}
/// Sets the input mode of locking key modifiers, if enabled callbacks that receive modifier bits
/// will also have the glfw.mod.caps_lock bit set when the event was generated with Caps Lock on,
/// and the glfw.mod.num_lock bit when Num Lock was on.
pub inline fn setInputModeLockKeyMods(self: Window, enabled: bool) error{ PlatformError, FeatureUnavailable }!void {
return self.setInputMode(InputMode.lock_key_mods, enabled);
}
/// Tells if the locking key modifiers input mode is enabled.
pub inline fn getInputModeLockKeyMods(self: Window) bool {
return self.getInputMode(InputMode.lock_key_mods) == 1;
}
/// Sets whether the raw mouse motion input mode is enabled, if enabled unscaled and unaccelerated
/// mouse motion events will be sent, otherwise standard mouse motion events respecting the user's
/// OS settings will be sent.
///
/// If raw motion is not supported, attempting to set this will emit glfw.Error.FeatureUnavailable. Call
/// glfw.rawMouseMotionSupported to check for support.
pub inline fn setInputModeRawMouseMotion(self: Window, enabled: bool) error{ PlatformError, FeatureUnavailable }!void {
return self.setInputMode(InputMode.raw_mouse_motion, enabled);
}
/// Tells if the raw mouse motion input mode is enabled.
pub inline fn getInputModeRawMouseMotion(self: Window) bool {
return self.getInputMode(InputMode.raw_mouse_motion) == 1;
}
/// Returns the value of an input option for the specified window.
///
/// Consider using one of the following variants instead, if applicable, as they'll give you a
/// typed return value:
///
/// * `glfw.Window.getInputModeCursor`
/// * `glfw.Window.getInputModeStickyKeys`
/// * `glfw.Window.getInputModeStickyMouseButtons`
/// * `glfw.Window.getInputModeLockKeyMods`
/// * `glfw.Window.getInputModeRawMouseMotion`
///
/// This function returns the value of an input option for the specified window. The mode must be
/// one of the `glfw.Window.InputMode` enumerations.
///
/// Boolean values, such as for `glfw.Window.InputMode.raw_mouse_motion`, are returned as integers.
/// You may convert to a boolean using `== 1`.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: glfw.Window.setInputMode
pub inline fn getInputMode(self: Window, mode: InputMode) i32 {
internal_debug.assertInitialized();
const value = c.glfwGetInputMode(self.handle, @enumToInt(mode));
getError() catch |err| return switch (err) {
Error.InvalidEnum => unreachable,
Error.NotInitialized => unreachable,
else => unreachable,
};
return @intCast(i32, value);
}
/// Sets an input option for the specified window.
///
/// Consider using one of the following variants instead, if applicable, as they'll guide you to
/// the right input value via enumerations:
///
/// * `glfw.Window.setInputModeCursor`
/// * `glfw.Window.setInputModeStickyKeys`
/// * `glfw.Window.setInputModeStickyMouseButtons`
/// * `glfw.Window.setInputModeLockKeyMods`
/// * `glfw.Window.setInputModeRawMouseMotion`
///
/// @param[in] mode One of the `glfw.Window.InputMode` enumerations.
/// @param[in] value The new value of the specified input mode.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: glfw.Window.getInputMode
pub inline fn setInputMode(self: Window, mode: InputMode, value: anytype) error{ PlatformError, FeatureUnavailable }!void {
internal_debug.assertInitialized();
const T = @TypeOf(value);
std.debug.assert(switch (mode) {
.cursor => switch (@typeInfo(T)) {
.Enum => T == InputModeCursor,
.EnumLiteral => @hasField(InputModeCursor, @tagName(value)),
else => false,
},
.sticky_keys => T == bool,
.sticky_mouse_buttons => T == bool,
.lock_key_mods => T == bool,
.raw_mouse_motion => T == bool,
});
const int_value: c_int = switch (@typeInfo(T)) {
.Enum,
.EnumLiteral,
=> @enumToInt(@as(InputModeCursor, value)),
else => @boolToInt(value),
};
c.glfwSetInputMode(self.handle, @enumToInt(mode), int_value);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.InvalidEnum => unreachable,
Error.PlatformError => |e| e,
Error.FeatureUnavailable => |e| e,
else => unreachable,
};
}
/// Returns the last reported press state of a keyboard key for the specified window.
///
/// This function returns the last press state reported for the specified key to the specified
/// window. The returned state is one of `true` (pressed) or `false` (released). The higher-level
/// action `glfw.Action.repeat` is only reported to the key callback.
///
/// If the `glfw.sticky_keys` input mode is enabled, this function returns `glfw.Action.press` the
/// first time you call it for a key that was pressed, even if that key has already been released.
///
/// The key functions deal with physical keys, with key tokens (see keys) named after their use on
/// the standard US keyboard layout. If you want to input text, use the Unicode character callback
/// instead.
///
/// The modifier key bit masks (see mods) are not key tokens and cannot be used with this function.
///
/// __Do not use this function__ to implement text input, use glfw.Window.setCharCallback instead.
///
/// @param[in] window The desired window.
/// @param[in] key The desired keyboard key (see keys). `glfw.key.unknown` is not a valid key for
/// this function.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.InvalidEnum.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: input_key
pub inline fn getKey(self: Window, key: Key) Action {
internal_debug.assertInitialized();
const state = c.glfwGetKey(self.handle, @enumToInt(key));
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.InvalidEnum => unreachable,
else => unreachable,
};
return @intToEnum(Action, state);
}
/// Returns the last reported state of a mouse button for the specified window.
///
/// This function returns whether the specified mouse button is pressed or not.
///
/// If the glfw.sticky_mouse_buttons input mode is enabled, this function returns `true` the first
/// time you call it for a mouse button that was pressed, even if that mouse button has already been
/// released.
///
/// @param[in] button The desired mouse button.
/// @return One of `true` (if pressed) or `false` (if released)
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.InvalidEnum.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: input_mouse_button
pub inline fn getMouseButton(self: Window, button: MouseButton) Action {
internal_debug.assertInitialized();
const state = c.glfwGetMouseButton(self.handle, @enumToInt(button));
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.InvalidEnum => unreachable,
else => unreachable,
};
return @intToEnum(Action, state);
}
pub const CursorPos = struct {
xpos: f64,
ypos: f64,
};
/// Retrieves the position of the cursor relative to the content area of the window.
///
/// This function returns the position of the cursor, in screen coordinates, relative to the
/// upper-left corner of the content area of the specified window.
///
/// If the cursor is disabled (with `glfw.cursor_disabled`) then the cursor position is unbounded
/// and limited only by the minimum and maximum values of a `f64`.
///
/// The coordinate can be converted to their integer equivalents with the `floor` function. Casting
/// directly to an integer type works for positive coordinates, but fails for negative ones.
///
/// Any or all of the position arguments may be null. If an error occurs, all non-null position
/// arguments will be set to zero.
///
/// @param[in] window The desired window.
/// @param[out] xpos Where to store the cursor x-coordinate, relative to the left edge of the
/// content area, or null.
/// @param[out] ypos Where to store the cursor y-coordinate, relative to the to top edge of the
/// content area, or null.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: cursor_pos, glfw.Window.setCursorPos
pub inline fn getCursorPos(self: Window) error{PlatformError}!CursorPos {
internal_debug.assertInitialized();
var pos: CursorPos = undefined;
c.glfwGetCursorPos(self.handle, &pos.xpos, &pos.ypos);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
return pos;
}
/// Sets the position of the cursor, relative to the content area of the window.
///
/// This function sets the position, in screen coordinates, of the cursor relative to the upper-left
/// corner of the content area of the specified window. The window must have input focus. If the
/// window does not have input focus when this function is called, it fails silently.
///
/// __Do not use this function__ to implement things like camera controls. GLFW already provides the
/// `glfw.cursor_disabled` cursor mode that hides the cursor, transparently re-centers it and
/// provides unconstrained cursor motion. See glfw.Window.setInputMode for more information.
///
/// If the cursor mode is `glfw.cursor_disabled` then the cursor position is unconstrained and
/// limited only by the minimum and maximum values of a `double`.
///
/// @param[in] window The desired window.
/// @param[in] xpos The desired x-coordinate, relative to the left edge of the content area.
/// @param[in] ypos The desired y-coordinate, relative to the top edge of the content area.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// wayland: This function will only work when the cursor mode is `glfw.cursor_disabled`, otherwise
/// it will do nothing.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: cursor_pos, glfw.Window.getCursorPos
pub inline fn setCursorPos(self: Window, xpos: f64, ypos: f64) error{PlatformError}!void {
internal_debug.assertInitialized();
c.glfwSetCursorPos(self.handle, xpos, ypos);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
}
/// Sets the cursor for the window.
///
/// This function sets the cursor image to be used when the cursor is over the content area of the
/// specified window. The set cursor will only be visible when the cursor mode (see cursor_mode) of
/// the window is `glfw.Cursor.normal`.
///
/// On some platforms, the set cursor may not be visible unless the window also has input focus.
///
/// @param[in] cursor The cursor to set, or null to switch back to the default arrow cursor.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: cursor_object
pub inline fn setCursor(self: Window, cursor: Cursor) error{PlatformError}!void {
internal_debug.assertInitialized();
c.glfwSetCursor(self.handle, cursor.ptr);
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.PlatformError => |e| e,
else => unreachable,
};
}
/// Sets the key callback.
///
/// This function sets the key callback of the specified window, which is called when a key is
/// pressed, repeated or released.
///
/// The key functions deal with physical keys, with layout independent key tokens (see keys) named
/// after their values in the standard US keyboard layout. If you want to input text, use the
/// character callback (see glfw.Window.setCharCallback) instead.
///
/// When a window loses input focus, it will generate synthetic key release events for all pressed
/// keys. You can tell these events from user-generated events by the fact that the synthetic ones
/// are generated after the focus loss event has been processed, i.e. after the window focus
/// callback (see glfw.Window.setFocusCallback) has been called.
///
/// The scancode of a key is specific to that platform or sometimes even to that machine. Scancodes
/// are intended to allow users to bind keys that don't have a GLFW key token. Such keys have `key`
/// set to `glfw.key.unknown`, their state is not saved and so it cannot be queried with
/// glfw.Window.getKey.
///
/// Sometimes GLFW needs to generate synthetic key events, in which case the scancode may be zero.
///
/// @param[in] window The window whose callback to set.
/// @param[in] callback The new key callback, or null to remove the currently set callback.
///
/// @callback_param[in] window The window that received the event.
/// @callback_param[in] key The keyboard key (see keys) that was pressed or released.
/// @callback_param[in] scancode The platform-specific scancode of the key.
/// @callback_param[in] action `glfw.Action.press`, `glfw.Action.release` or `glfw.Action.repeat`.
/// Future releases may add more actions.
/// @callback_param[in] mods Bit field describing which modifier keys (see mods) were held down.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: input_key
pub inline fn setKeyCallback(self: Window, comptime callback: ?fn (window: Window, key: Key, scancode: i32, action: Action, mods: Mods) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn keyCallbackWrapper(handle: ?*c.GLFWwindow, key: c_int, scancode: c_int, action: c_int, mods: c_int) callconv(.C) void {
@call(.{ .modifier = .always_inline }, user_callback, .{
from(handle.?),
@intToEnum(Key, key),
@intCast(i32, scancode),
@intToEnum(Action, action),
Mods.fromInt(mods),
});
}
};
if (c.glfwSetKeyCallback(self.handle, CWrapper.keyCallbackWrapper) != null) return;
} else {
if (c.glfwSetKeyCallback(self.handle, null) != null) return;
}
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
}
/// Sets the Unicode character callback.
///
/// This function sets the character callback of the specified window, which is called when a
/// Unicode character is input.
///
/// The character callback is intended for Unicode text input. As it deals with characters, it is
/// keyboard layout dependent, whereas the key callback (see glfw.Window.setKeyCallback) is not.
/// Characters do not map 1:1 to physical keys, as a key may produce zero, one or more characters.
/// If you want to know whether a specific physical key was pressed or released, see the key
/// callback instead.
///
/// The character callback behaves as system text input normally does and will not be called if
/// modifier keys are held down that would prevent normal text input on that platform, for example a
/// Super (Command) key on macOS or Alt key on Windows.
///
/// @param[in] window The window whose callback to set.
/// @param[in] callback The new callback, or null to remove the currently set callback.
///
/// @callback_param[in] window The window that received the event.
/// @callback_param[in] codepoint The Unicode code point of the character.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: input_char
pub inline fn setCharCallback(self: Window, comptime callback: ?fn (window: Window, codepoint: u21) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn charCallbackWrapper(handle: ?*c.GLFWwindow, codepoint: c_uint) callconv(.C) void {
@call(.{ .modifier = .always_inline }, user_callback, .{
from(handle.?),
@intCast(u21, codepoint),
});
}
};
if (c.glfwSetCharCallback(self.handle, CWrapper.charCallbackWrapper) != null) return;
} else {
if (c.glfwSetCharCallback(self.handle, null) != null) return;
}
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
}
/// Sets the mouse button callback.
///
/// This function sets the mouse button callback of the specified window, which is called when a
/// mouse button is pressed or released.
///
/// When a window loses input focus, it will generate synthetic mouse button release events for all
/// pressed mouse buttons. You can tell these events from user-generated events by the fact that the
/// synthetic ones are generated after the focus loss event has been processed, i.e. after the
/// window focus callback (see glfw.Window.setFocusCallback) has been called.
///
/// @param[in] window The window whose callback to set.
/// @param[in] callback The new callback, or null to remove the currently set callback.
///
/// @callback_param[in] window The window that received the event.
/// @callback_param[in] button The mouse button that was pressed or released.
/// @callback_param[in] action One of `glfw.Action.press` or `glfw.Action.release`. Future releases
/// may add more actions.
/// @callback_param[in] mods Bit field describing which modifier keys (see mods) were held down.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: input_mouse_button
pub inline fn setMouseButtonCallback(self: Window, comptime callback: ?fn (window: Window, button: MouseButton, action: Action, mods: Mods) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn mouseButtonCallbackWrapper(handle: ?*c.GLFWwindow, button: c_int, action: c_int, mods: c_int) callconv(.C) void {
@call(.{ .modifier = .always_inline }, user_callback, .{
from(handle.?),
@intToEnum(MouseButton, button),
@intToEnum(Action, action),
Mods.fromInt(mods),
});
}
};
if (c.glfwSetMouseButtonCallback(self.handle, CWrapper.mouseButtonCallbackWrapper) != null) return;
} else {
if (c.glfwSetMouseButtonCallback(self.handle, null) != null) return;
}
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
}
/// Sets the cursor position callback.
///
/// This function sets the cursor position callback of the specified window, which is called when
/// the cursor is moved. The callback is provided with the position, in screen coordinates, relative
/// to the upper-left corner of the content area of the window.
///
/// @param[in] callback The new callback, or null to remove the currently set callback.
///
/// @callback_param[in] window The window that received the event.
/// @callback_param[in] xpos The new cursor x-coordinate, relative to the left edge of the content
/// area.
/// callback_@param[in] ypos The new cursor y-coordinate, relative to the top edge of the content
/// area.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: cursor_pos
pub inline fn setCursorPosCallback(self: Window, comptime callback: ?fn (window: Window, xpos: f64, ypos: f64) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn cursorPosCallbackWrapper(handle: ?*c.GLFWwindow, xpos: f64, ypos: f64) callconv(.C) void {
@call(.{ .modifier = .always_inline }, user_callback, .{
from(handle.?),
xpos,
ypos,
});
}
};
if (c.glfwSetCursorPosCallback(self.handle, CWrapper.cursorPosCallbackWrapper) != null) return;
} else {
if (c.glfwSetCursorPosCallback(self.handle, null) != null) return;
}
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
}
/// Sets the cursor enter/leave callback.
///
/// This function sets the cursor boundary crossing callback of the specified window, which is
/// called when the cursor enters or leaves the content area of the window.
///
/// @param[in] callback The new callback, or null to remove the currently set callback.
///
/// @callback_param[in] window The window that received the event.
/// @callback_param[in] entered `true` if the cursor entered the window's content area, or `false`
/// if it left it.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: cursor_enter
pub inline fn setCursorEnterCallback(self: Window, comptime callback: ?fn (window: Window, entered: bool) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn cursorEnterCallbackWrapper(handle: ?*c.GLFWwindow, entered: c_int) callconv(.C) void {
@call(.{ .modifier = .always_inline }, user_callback, .{
from(handle.?),
entered == c.GLFW_TRUE,
});
}
};
if (c.glfwSetCursorEnterCallback(self.handle, CWrapper.cursorEnterCallbackWrapper) != null) return;
} else {
if (c.glfwSetCursorEnterCallback(self.handle, null) != null) return;
}
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
}
/// Sets the scroll callback.
///
/// This function sets the scroll callback of the specified window, which is called when a scrolling
/// device is used, such as a mouse wheel or scrolling area of a touchpad.
///
/// The scroll callback receives all scrolling input, like that from a mouse wheel or a touchpad
/// scrolling area.
///
/// @param[in] window The window whose callback to set.
/// @param[in] callback The new scroll callback, or null to remove the currently set callback.
///
/// @callback_param[in] window The window that received the event.
/// @callback_param[in] xoffset The scroll offset along the x-axis.
/// @callback_param[in] yoffset The scroll offset along the y-axis.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: scrolling
pub inline fn setScrollCallback(self: Window, comptime callback: ?fn (window: Window, xoffset: f64, yoffset: f64) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn scrollCallbackWrapper(handle: ?*c.GLFWwindow, xoffset: f64, yoffset: f64) callconv(.C) void {
@call(.{ .modifier = .always_inline }, user_callback, .{
from(handle.?),
xoffset,
yoffset,
});
}
};
if (c.glfwSetScrollCallback(self.handle, CWrapper.scrollCallbackWrapper) != null) return;
} else {
if (c.glfwSetScrollCallback(self.handle, null) != null) return;
}
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
}
/// Sets the path drop callback.
///
/// This function sets the path drop callback of the specified window, which is called when one or
/// more dragged paths are dropped on the window.
///
/// Because the path array and its strings may have been generated specifically for that event, they
/// are not guaranteed to be valid after the callback has returned. If you wish to use them after
/// the callback returns, you need to make a deep copy.
///
/// @param[in] callback The new file drop callback, or null to remove the currently set callback.
///
/// @callback_param[in] window The window that received the event.
/// @callback_param[in] path_count The number of dropped paths.
/// @callback_param[in] paths The UTF-8 encoded file and/or directory path names.
///
/// @callback_pointer_lifetime The path array and its strings are valid until the callback function
/// returns.
///
/// Possible errors include glfw.Error.NotInitialized.
///
/// wayland: File drop is currently unimplemented.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: path_drop
pub inline fn setDropCallback(self: Window, comptime callback: ?fn (window: Window, paths: [][*:0]const u8) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn dropCallbackWrapper(handle: ?*c.GLFWwindow, path_count: c_int, paths: [*c][*c]const u8) callconv(.C) void {
@call(.{ .modifier = .always_inline }, user_callback, .{
from(handle.?),
@ptrCast([*][*:0]const u8, paths)[0..@intCast(u32, path_count)],
});
}
};
if (c.glfwSetDropCallback(self.handle, CWrapper.dropCallbackWrapper) != null) return;
} else {
if (c.glfwSetDropCallback(self.handle, null) != null) return;
}
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
else => unreachable,
};
}
/// For testing purposes only; see glfw.Window.Hints and glfw.Window.create for the public API.
/// Sets the specified window hint to the desired value.
///
/// This function sets hints for the next call to glfw.Window.create. The hints, once set, retain
/// their values until changed by a call to this function or glfw.window.defaultHints, or until the
/// library is terminated.
///
/// This function does not check whether the specified hint values are valid. If you set hints to
/// invalid values this will instead be reported by the next call to glfw.createWindow.
///
/// Some hints are platform specific. These may be set on any platform but they will only affect
/// their specific platform. Other platforms will ignore them.
///
/// Possible errors include glfw.Error.NotInitialized and glfw.Error.InvalidEnum.
///
/// @pointer_lifetime in the event that value is of a str type, the specified string is copied before this function returns.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: window_hints, glfw.Window.defaultHints
inline fn hint(h: Hint, value: anytype) void {
internal_debug.assertInitialized();
const value_type = @TypeOf(value);
const value_type_info: std.builtin.TypeInfo = @typeInfo(value_type);
switch (value_type_info) {
.Int, .ComptimeInt => {
c.glfwWindowHint(@enumToInt(h), @intCast(c_int, value));
},
.Bool => {
const int_value = @boolToInt(value);
c.glfwWindowHint(@enumToInt(h), @intCast(c_int, int_value));
},
.Enum => {
const int_value = @enumToInt(value);
c.glfwWindowHint(@enumToInt(h), @intCast(c_int, int_value));
},
.Array => |arr_type| {
if (arr_type.child != u8) {
@compileError("expected array of u8, got " ++ @typeName(arr_type));
}
c.glfwWindowHintString(@enumToInt(h), &value[0]);
},
.Pointer => |pointer_info| {
const pointed_type = @typeInfo(pointer_info.child);
switch (pointed_type) {
.Array => |arr_type| {
if (arr_type.child != u8) {
@compileError("expected pointer to array of u8, got " ++ @typeName(arr_type));
}
},
else => @compileError("expected pointer to array, got " ++ @typeName(pointed_type)),
}
c.glfwWindowHintString(@enumToInt(h), &value[0]);
},
else => {
@compileError("expected a int, bool, enum, array, or pointer, got " ++ @typeName(value_type));
},
}
getError() catch |err| return switch (err) {
Error.NotInitialized => unreachable,
Error.InvalidEnum => unreachable,
else => unreachable,
};
}
test "defaultHints" {
try glfw.init(.{});
defer glfw.terminate();
defaultHints();
}
test "hint comptime int" {
try glfw.init(.{});
defer glfw.terminate();
hint(.focused, 1);
defaultHints();
}
test "hint int" {
try glfw.init(.{});
defer glfw.terminate();
var focused: i32 = 1;
hint(.focused, focused);
defaultHints();
}
test "hint bool" {
try glfw.init(.{});
defer glfw.terminate();
hint(.focused, true);
defaultHints();
}
test "hint enum(u1)" {
try glfw.init(.{});
defer glfw.terminate();
const MyEnum = enum(u1) {
@"true" = 1,
@"false" = 0,
};
hint(.focused, MyEnum.@"true");
defaultHints();
}
test "hint enum(i32)" {
try glfw.init(.{});
defer glfw.terminate();
const MyEnum = enum(i32) {
@"true" = 1,
@"false" = 0,
};
hint(.focused, MyEnum.@"true");
defaultHints();
}
test "hint array str" {
try glfw.init(.{});
defer glfw.terminate();
const str_arr = [_]u8{ 'm', 'y', 'c', 'l', 'a', 's', 's' };
hint(.x11_class_name, str_arr);
defaultHints();
}
test "hint pointer str" {
try glfw.init(.{});
defer glfw.terminate();
hint(.x11_class_name, "myclass");
}
test "createWindow" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
}
test "setShouldClose" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
window.setShouldClose(true);
defer window.destroy();
}
test "setTitle" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
try window.setTitle("Updated title!");
}
test "setIcon" {
const allocator = testing.allocator;
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
// Create an all-red icon image.
var width: u32 = 48;
var height: u32 = 48;
const icon = try Image.init(allocator, width, height, width * height * 4);
var x: u32 = 0;
var y: u32 = 0;
while (y <= height) : (y += 1) {
while (x <= width) : (x += 1) {
icon.pixels[(x * y * 4) + 0] = 255; // red
icon.pixels[(x * y * 4) + 1] = 0; // green
icon.pixels[(x * y * 4) + 2] = 0; // blue
icon.pixels[(x * y * 4) + 3] = 255; // alpha
}
}
window.setIcon(allocator, &[_]Image{icon}) catch |err| std.debug.print("can't set window icon, wayland maybe? error={}\n", .{err});
icon.deinit(allocator); // glfw copies it.
}
test "getPos" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = window.getPos() catch |err| std.debug.print("can't get window position, wayland maybe? error={}\n", .{err});
}
test "setPos" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = window.setPos(.{ .x = 0, .y = 0 }) catch |err| std.debug.print("can't set window position, wayland maybe? error={}\n", .{err});
}
test "getSize" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "<NAME>!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = try window.getSize();
}
test "setSize" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "<NAME>!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = try window.setSize(.{ .width = 640, .height = 480 });
}
test "setSizeLimits" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "<NAME>!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
try window.setSizeLimits(
.{ .width = 720, .height = 480 },
.{ .width = 1080, .height = 1920 },
);
}
test "setAspectRatio" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "<NAME>!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
try window.setAspectRatio(4, 3);
}
test "getFramebufferSize" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = try window.getFramebufferSize();
}
test "getFrameSize" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = try window.getFrameSize();
}
test "getContentScale" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = try window.getContentScale();
}
test "getOpacity" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = try window.getOpacity();
}
test "iconify" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = window.iconify() catch |err| std.debug.print("can't iconify window, wayland maybe? error={}\n", .{err});
}
test "restore" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = window.restore() catch |err| std.debug.print("can't restore window, not supported by OS maybe? error={}\n", .{err});
}
test "maximize" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "<NAME>!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = window.maximize() catch |err| std.debug.print("can't maximize window, not supported by OS maybe? error={}\n", .{err});
}
test "show" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = window.show() catch |err| std.debug.print("can't show window, not supported by OS maybe? error={}\n", .{err});
}
test "hide" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = window.hide() catch |err| std.debug.print("can't hide window, not supported by OS maybe? error={}\n", .{err});
}
test "focus" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = window.focus() catch |err| std.debug.print("can't focus window, wayland maybe? error={}\n", .{err});
}
test "requestAttention" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "<NAME>!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = window.requestAttention() catch |err| std.debug.print("can't request attention for window, not supported by OS maybe? error={}\n", .{err});
}
test "swapBuffers" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "<NAME>!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = try window.swapBuffers();
}
test "getMonitor" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "<NAME>!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = window.getMonitor();
}
test "setMonitor" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "<NAME>!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
window.setMonitor(null, 10, 10, 640, 480, 60) catch |err| std.debug.print("can't set monitor, not supported by OS maybe? error={}\n", .{err});
}
test "getAttrib" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "<NAME>!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = window.getAttrib(.focused) catch |err| std.debug.print("can't check if window is focused, not supported by OS maybe? error={}\n", .{err});
}
test "setAttrib" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "<NAME>!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
window.setAttrib(.decorated, false) catch |err| std.debug.print("can't remove window decorations, not supported by OS maybe? error={}\n", .{err});
}
test "setUserPointer" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "<NAME>!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
const T = struct { name: []const u8 };
var my_value = T{ .name = "my window!" };
window.setUserPointer(&my_value);
}
test "getUserPointer" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "<NAME>!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
const T = struct { name: []const u8 };
var my_value = T{ .name = "my window!" };
window.setUserPointer(&my_value);
const got = window.getUserPointer(T);
std.debug.assert(&my_value == got);
}
test "setPosCallback" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
window.setPosCallback((struct {
fn callback(_window: Window, xpos: i32, ypos: i32) void {
_ = _window;
_ = xpos;
_ = ypos;
}
}).callback);
}
test "setSizeCallback" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
window.setSizeCallback((struct {
fn callback(_window: Window, width: i32, height: i32) void {
_ = _window;
_ = width;
_ = height;
}
}).callback);
}
test "setCloseCallback" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
window.setCloseCallback((struct {
fn callback(_window: Window) void {
_ = _window;
}
}).callback);
}
test "setRefreshCallback" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
window.setRefreshCallback((struct {
fn callback(_window: Window) void {
_ = _window;
}
}).callback);
}
test "setFocusCallback" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
window.setFocusCallback((struct {
fn callback(_window: Window, focused: bool) void {
_ = _window;
_ = focused;
}
}).callback);
}
test "setIconifyCallback" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
window.setIconifyCallback((struct {
fn callback(_window: Window, iconified: bool) void {
_ = _window;
_ = iconified;
}
}).callback);
}
test "setMaximizeCallback" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "<NAME>!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
window.setMaximizeCallback((struct {
fn callback(_window: Window, maximized: bool) void {
_ = _window;
_ = maximized;
}
}).callback);
}
test "setFramebufferSizeCallback" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
window.setFramebufferSizeCallback((struct {
fn callback(_window: Window, width: u32, height: u32) void {
_ = _window;
_ = width;
_ = height;
}
}).callback);
}
test "setContentScaleCallback" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
window.setContentScaleCallback((struct {
fn callback(_window: Window, xscale: f32, yscale: f32) void {
_ = _window;
_ = xscale;
_ = yscale;
}
}).callback);
}
test "setDropCallback" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
window.setDropCallback((struct {
fn callback(_window: Window, paths: [][*:0]const u8) void {
_ = _window;
_ = paths;
}
}).callback);
}
test "getInputModeCursor" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = window.getInputModeCursor();
}
test "setInputModeCursor" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
window.setInputModeCursor(.hidden) catch |err| std.debug.print("failed to set input mode, not supported? error={}\n", .{err});
}
test "getInputModeStickyKeys" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "<NAME>!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = window.getInputModeStickyKeys();
}
test "setInputModeStickyKeys" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "<NAME>!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
window.setInputModeStickyKeys(false) catch |err| std.debug.print("failed to set input mode, not supported? error={}\n", .{err});
}
test "getInputModeStickyMouseButtons" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "<NAME>!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = window.getInputModeStickyMouseButtons();
}
test "setInputModeStickyMouseButtons" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "<NAME>!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
window.setInputModeStickyMouseButtons(false) catch |err| std.debug.print("failed to set input mode, not supported? error={}\n", .{err});
}
test "getInputModeLockKeyMods" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = window.getInputModeLockKeyMods();
}
test "setInputModeLockKeyMods" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
window.setInputModeLockKeyMods(false) catch |err| std.debug.print("failed to set input mode, not supported? error={}\n", .{err});
}
test "getInputModeRawMouseMotion" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "<NAME>!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = window.getInputModeRawMouseMotion();
}
test "setInputModeRawMouseMotion" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
window.setInputModeRawMouseMotion(false) catch |err| std.debug.print("failed to set input mode, not supported? error={}\n", .{err});
}
test "getInputMode" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "<NAME>!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = window.getInputMode(glfw.Window.InputMode.raw_mouse_motion) == 1;
}
test "setInputMode" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
// Boolean values.
window.setInputMode(glfw.Window.InputMode.sticky_mouse_buttons, true) catch |err| std.debug.print("failed to set input mode, not supported? error={}\n", .{err});
// Integer values.
window.setInputMode(glfw.Window.InputMode.cursor, glfw.Window.InputModeCursor.hidden) catch |err| std.debug.print("failed to set input mode, not supported? error={}\n", .{err});
}
test "getKey" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = window.getKey(glfw.Key.escape);
}
test "getMouseButton" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = window.getMouseButton(.left);
}
test "getCursorPos" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
_ = window.getCursorPos() catch |err| std.debug.print("failed to get cursor pos, not supported? error={}\n", .{err});
}
test "setCursorPos" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
window.setCursorPos(0, 0) catch |err| std.debug.print("failed to set cursor pos, not supported? error={}\n", .{err});
}
test "setCursor" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
const cursor = glfw.Cursor.createStandard(.ibeam) catch |err| {
std.debug.print("failed to create cursor, custom cursors not supported? error={}\n", .{err});
return;
};
defer cursor.destroy();
window.setCursor(cursor) catch |err| std.debug.print("failed to set cursor, custom cursors not supported? error={}\n", .{err});
}
test "setKeyCallback" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
window.setKeyCallback((struct {
fn callback(_window: Window, key: Key, scancode: i32, action: Action, mods: Mods) void {
_ = _window;
_ = key;
_ = scancode;
_ = action;
_ = mods;
}
}).callback);
}
test "setCharCallback" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
window.setCharCallback((struct {
fn callback(_window: Window, codepoint: u21) void {
_ = _window;
_ = codepoint;
}
}).callback);
}
test "setMouseButtonCallback" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
window.setMouseButtonCallback((struct {
fn callback(_window: Window, button: MouseButton, action: Action, mods: Mods) void {
_ = _window;
_ = button;
_ = action;
_ = mods;
}
}).callback);
}
test "setCursorPosCallback" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
window.setCursorPosCallback((struct {
fn callback(_window: Window, xpos: f64, ypos: f64) void {
_ = _window;
_ = xpos;
_ = ypos;
}
}).callback);
}
test "setCursorEnterCallback" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
window.setCursorEnterCallback((struct {
fn callback(_window: Window, entered: bool) void {
_ = _window;
_ = entered;
}
}).callback);
}
test "setScrollCallback" {
try glfw.init(.{});
defer glfw.terminate();
const window = glfw.Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window: {}\n", .{err});
return;
};
defer window.destroy();
window.setScrollCallback((struct {
fn callback(_window: Window, xoffset: f64, yoffset: f64) void {
_ = _window;
_ = xoffset;
_ = yoffset;
}
}).callback);
}
test "hint-attribute default value parity" {
try glfw.init(.{});
defer glfw.terminate();
testing_ignore_window_hints_struct = true;
const window_a = Window.create(640, 480, "Hello, Zig!", null, null, undefined) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window_a: {}\n", .{err});
return;
};
defer window_a.destroy();
testing_ignore_window_hints_struct = false;
const window_b = Window.create(640, 480, "Hello, Zig!", null, null, .{}) catch |err| {
// return without fail, because most of our CI environments are headless / we cannot open
// windows on them.
std.debug.print("note: failed to create window_b: {}\n", .{err});
return;
};
defer window_b.destroy();
inline for (comptime std.enums.values(Window.Hint)) |hint_tag| {
if (@hasField(Window.Attrib, @tagName(hint_tag))) {
const attrib_tag = @field(Window.Attrib, @tagName(hint_tag));
switch (attrib_tag) {
.resizable,
.visible,
.decorated,
.auto_iconify,
.floating,
.maximized,
.transparent_framebuffer,
.focus_on_show,
.mouse_passthrough,
.doublebuffer,
.client_api,
.context_creation_api,
.context_version_major,
.context_version_minor,
.context_robustness,
.context_release_behavior,
.context_no_error, // Note: at the time of writing this, GLFW does not list the default value for this hint in the documentation
.context_debug,
.opengl_forward_compat,
.opengl_profile,
=> {
const expected = window_a.getAttrib(attrib_tag) catch |err| {
std.debug.print("Failed to get attribute '{}' value from window_a with error '{}'.\n", .{ attrib_tag, err });
return;
};
const actual = window_b.getAttrib(attrib_tag) catch |err| {
std.debug.print("Failed to get attribute '{}' value from window_b with error '{}'.\n", .{ attrib_tag, err });
return;
};
testing.expectEqual(expected, actual) catch |err| {
std.debug.print("On attribute '{}'.\n", .{hint_tag});
return err;
};
},
// This attribute is based on a check for which window is currently in focus,
// and the default value, as of writing this comment, is 'true', which means
// that first window_a takes focus, and then window_b takes focus, meaning
// that we can't actually test for the default value.
.focused => continue,
.iconified,
.hovered,
.context_revision,
=> unreachable,
}
}
// Future: we could consider hint values that can't be retrieved via attributes:
// center_cursor
// mouse_passthrough
// scale_to_monitor
// red_bits
// green_bits
// blue_bits
// alpha_bits
// depth_bits
// stencil_bits
// accum_red_bits
// accum_green_bits
// accum_blue_bits
// accum_alpha_bits
// aux_buffers
// samples
// refresh_rate
// stereo
// srgb_capable
// doublebuffer
// platform specific, and thus not considered:
// cocoa_retina_framebuffer
// cocoa_frame_name
// cocoa_graphics_switching
}
} | glfw/src/Window.zig |
const std = @import("std");
const lola = @import("../main.zig");
usingnamespace @import("value.zig");
usingnamespace @import("../common/ir.zig");
usingnamespace @import("../common/compile-unit.zig");
usingnamespace @import("../common/decoder.zig");
usingnamespace @import("environment.zig");
usingnamespace @import("objects.zig");
pub const ExecutionResult = enum {
/// The vm instruction quota was exhausted and the execution was terminated.
exhausted,
/// The vm has encountered an asynchronous function call and waits for the completion.
paused,
/// The vm has completed execution of the program and has no more instructions to
/// process.
completed,
};
/// Executor of a compile unit. This virtual machine will
/// execute LoLa instructions.
pub const VM = struct {
const Self = @This();
const Context = struct {
/// Stores the local variables for this call.
locals: []Value,
/// Provides instruction fetches for the right compile unit
decoder: Decoder,
/// Stores the stack balance at start of the function call.
/// This is used to reset the stack to the right balance at the
/// end of a function call. It is also used to check for stack underflows.
stackBalance: usize,
/// The script function which this context is currently executing
environment: *Environment,
};
/// Describes a set of statistics for the virtual machine. Can be useful for benchmarking.
pub const Statistics = struct {
/// Number of instructions executed in total.
instructions: usize = 0,
/// Number of executions which were stalled by a asynchronous function
stalls: usize = 0,
};
allocator: *std.mem.Allocator,
stack: std.ArrayList(Value),
calls: std.ArrayList(Context),
currentAsynCall: ?AsyncFunctionCall,
objectPool: ObjectPoolInterface,
stats: Statistics = Statistics{},
/// Initialize a new virtual machine that will run the given environment.
pub fn init(allocator: *std.mem.Allocator, environment: *Environment) !Self {
var vm = Self{
.allocator = allocator,
.stack = std.ArrayList(Value).init(allocator),
.calls = std.ArrayList(Context).init(allocator),
.currentAsynCall = null,
.objectPool = environment.objectPool,
};
errdefer vm.stack.deinit();
errdefer vm.calls.deinit();
try vm.stack.ensureCapacity(128);
try vm.calls.ensureCapacity(32);
// Initialize with special "init context" that runs the script itself
// and hosts the global variables.
var initFun = try vm.createContext(ScriptFunction{
.environment = environment,
.entryPoint = 0, // start at the very first byte
.localCount = environment.compileUnit.temporaryCount,
});
errdefer vm.deinitContext(&initFun);
try vm.calls.append(initFun);
return vm;
}
pub fn deinit(self: *Self) void {
if (self.currentAsynCall) |*asyncCall| {
asyncCall.deinit();
}
for (self.stack.items) |*v| {
v.deinit();
}
for (self.calls.items) |*c| {
self.deinitContext(c);
}
self.stack.deinit();
self.calls.deinit();
self.* = undefined;
}
pub fn deinitContext(self: Self, ctx: *Context) void {
for (ctx.locals) |*v| {
v.deinit();
}
self.allocator.free(ctx.locals);
ctx.* = undefined;
}
/// Creates a new execution context.
/// The script function must have a resolved environment which
/// uses the same object pool as the main environment.
/// It is not possible to mix several object pools.
fn createContext(self: *Self, fun: ScriptFunction) !Context {
std.debug.assert(fun.environment != null);
std.debug.assert(fun.environment.?.objectPool.self == self.objectPool.self);
var ctx = Context{
.decoder = Decoder.init(fun.environment.?.compileUnit.code),
.stackBalance = self.stack.items.len,
.locals = undefined,
.environment = fun.environment.?,
};
ctx.decoder.offset = fun.entryPoint;
ctx.locals = try self.allocator.alloc(Value, fun.localCount);
for (ctx.locals) |*local| {
local.* = .void;
}
return ctx;
}
/// Pushes the value. Will take ownership of the pushed value.
fn push(self: *Self, value: Value) !void {
try self.stack.append(value);
}
/// Peeks at the top of the stack. The returned value is still owned
/// by the stack.
fn peek(self: Self) !*Value {
const slice = self.stack.items;
if (slice.len == 0)
return error.StackImbalance;
return &slice[slice.len - 1];
}
/// Pops a value from the stack. The ownership will be transferred to the caller.
fn pop(self: *Self) !Value {
if (self.calls.items.len > 0) {
const ctx = &self.calls.items[self.calls.items.len - 1];
// Assert we did not accidently have a stack underflow
std.debug.assert(self.stack.items.len >= ctx.stackBalance);
// this pop would produce a stack underrun for the current function call.
if (self.stack.items.len == ctx.stackBalance)
return error.StackImbalance;
}
return if (self.stack.popOrNull()) |v| v else return error.StackImbalance;
}
/// Runs the virtual machine for `quota` instructions.
pub fn execute(self: *Self, _quota: ?u32) !ExecutionResult {
std.debug.assert(self.calls.items.len > 0);
var quota = _quota;
while (true) {
if (quota) |*q| { // if we have a quota, reduce it til zero.
if (q.* == 0)
return ExecutionResult.exhausted;
q.* -= 1;
}
if (try self.executeSingle()) |result| {
switch (result) {
.completed => {
// A execution may only be completed if no calls
// are active anymore.
std.debug.assert(self.calls.items.len == 0);
std.debug.assert(self.stack.items.len == 0);
return ExecutionResult.completed;
},
.yield => return ExecutionResult.paused,
}
}
}
}
/// Executes a single instruction and returns the state of the machine.
fn executeSingle(self: *Self) !?SingleResult {
if (self.currentAsynCall) |*asyncCall| {
if (asyncCall.object) |obj| {
if (!self.objectPool.isObjectValid(obj))
return error.AsyncCallWithInvalidObject;
}
var res = try asyncCall.execute(asyncCall.context);
if (res) |*result| {
asyncCall.deinit();
self.currentAsynCall = null;
errdefer result.deinit();
try self.push(result.*);
} else {
// We are not finished, continue later...
self.stats.stalls += 1;
return .yield;
}
}
const ctx = &self.calls.items[self.calls.items.len - 1];
const environment = ctx.environment;
// std.debug.warn("execute 0x{X}…\n", .{ctx.decoder.offset});
const instruction = ctx.decoder.read(Instruction) catch |err| return switch (err) {
error.EndOfStream => error.InvalidJump,
else => error.InvalidBytecode,
};
self.stats.instructions += 1;
switch (instruction) {
// Auxiliary Section:
.nop => {},
.pop => {
var value = try self.pop();
value.deinit();
},
// Immediate Section:
.push_num => |i| try self.push(Value.initNumber(i.value)),
.push_str => |i| {
var val = try Value.initString(self.allocator, i.value);
errdefer val.deinit();
try self.push(val);
},
.push_true => try self.push(Value.initBoolean(true)),
.push_false => try self.push(Value.initBoolean(false)),
.push_void => try self.push(.void),
// Memory Access Section:
.store_global_idx => |i| {
if (i.value >= environment.scriptGlobals.len)
return error.InvalidGlobalVariable;
const value = try self.pop();
environment.scriptGlobals[i.value].replaceWith(value);
},
.load_global_idx => |i| {
if (i.value >= environment.scriptGlobals.len)
return error.InvalidGlobalVariable;
var value = try environment.scriptGlobals[i.value].clone();
errdefer value.deinit();
try self.push(value);
},
.store_local => |i| {
if (i.value >= ctx.locals.len)
return error.InvalidLocalVariable;
const value = try self.pop();
ctx.locals[i.value].replaceWith(value);
},
.load_local => |i| {
if (i.value >= ctx.locals.len)
return error.InvalidLocalVariable;
var value = try ctx.locals[i.value].clone();
errdefer value.deinit();
try self.push(value);
},
// Array Operations:
.array_pack => |i| {
var array = try Array.init(self.allocator, i.value);
errdefer array.deinit();
for (array.contents) |*item| {
var value = try self.pop();
errdefer value.deinit();
item.replaceWith(value);
}
try self.push(Value.fromArray(array));
},
.array_load => {
var indexed_val = try self.pop();
defer indexed_val.deinit();
var index_val = try self.pop();
defer index_val.deinit();
const index = try index_val.toInteger(usize);
var dupe: Value = switch (indexed_val) {
.array => |arr| blk: {
if (index >= arr.contents.len)
return error.IndexOutOfRange;
break :blk try arr.contents[index].clone();
},
.string => |str| blk: {
if (index >= str.contents.len)
return error.IndexOutOfRange;
break :blk Value.initInteger(u8, str.contents[index]);
},
else => return error.TypeMismatch,
};
errdefer dupe.deinit();
try self.push(dupe);
},
.array_store => {
var indexed_val = try self.pop();
errdefer indexed_val.deinit();
var index_val = try self.pop();
defer index_val.deinit();
if (indexed_val == .array) {
var value = try self.pop();
// only destroy value when we fail to get the array item,
// otherwise the value is stored in the array and must not
// be deinitialized after that
errdefer value.deinit();
const index = try index_val.toInteger(usize);
if (index >= indexed_val.array.contents.len)
return error.IndexOutOfRange;
indexed_val.array.contents[index].replaceWith(value);
} else if (indexed_val == .string) {
var value = try self.pop();
defer value.deinit();
const string = &indexed_val.string;
const byte = try value.toInteger(u8);
const index = try index_val.toInteger(usize);
if (index >= string.contents.len)
return error.IndexOutOfRange;
if (string.refcount != null and string.refcount.?.* > 1) {
var new_string = try String.init(self.allocator, string.contents);
string.deinit();
string.* = new_string;
}
std.debug.assert(string.refcount == null or string.refcount.?.* == 1);
const contents = try string.obtainMutableStorage();
contents[index] = byte;
} else {
return error.TypeMismatch;
}
try self.push(indexed_val);
},
// Iterator Section:
.iter_make => {
var array_val = try self.pop();
errdefer array_val.deinit();
// is still owned by array_val and will be destroyed in case of array.
var array = try array_val.toArray();
try self.push(Value.fromEnumerator(Enumerator.initFromOwned(array)));
},
.iter_next => {
const enumerator_val = try self.peek();
const enumerator = try enumerator_val.getEnumerator();
if (enumerator.next()) |value| {
self.push(value) catch |err| {
var clone = value;
clone.deinit();
return err;
};
try self.push(Value.initBoolean(true));
} else {
try self.push(Value.initBoolean(false));
}
},
// Control Flow Section:
.ret => {
var call = self.calls.pop();
defer self.deinitContext(&call);
// Restore stack balance
while (self.stack.items.len > call.stackBalance) {
var item = self.stack.pop();
item.deinit();
}
// No more context to execute: we have completed execution
if (self.calls.items.len == 0)
return .completed;
try self.push(.void);
},
.retval => {
var value = try self.pop();
errdefer value.deinit();
var call = self.calls.pop();
defer self.deinitContext(&call);
// Restore stack balance
while (self.stack.items.len > call.stackBalance) {
var item = self.stack.pop();
item.deinit();
}
// No more context to execute: we have completed execution
if (self.calls.items.len == 0) {
// TODO: How to handle returns from the main scrip?
value.deinit();
return .completed;
} else {
try self.push(value);
}
},
.jmp => |target| {
ctx.decoder.offset = target.value;
},
.jif, .jnf => |target| {
var value = try self.pop();
defer value.deinit();
const boolean = try value.toBoolean();
if (boolean == (instruction == .jnf)) {
ctx.decoder.offset = target.value;
}
},
.call_fn => |call| {
const method = environment.getMethod(call.function);
if (method == null)
return error.FunctionNotFound;
if (try self.executeFunctionCall(environment, call, method.?, null))
return .yield;
},
.call_obj => |call| {
var obj_val = try self.pop();
errdefer obj_val.deinit();
if (obj_val != .object)
return error.TypeMismatch;
const obj = obj_val.object;
if (!self.objectPool.isObjectValid(obj))
return error.InvalidObject;
const function_or_null = try self.objectPool.getMethod(obj, call.function);
if (function_or_null) |function| {
if (try self.executeFunctionCall(environment, call, function, obj))
return .yield;
} else {
return error.FunctionNotFound;
}
},
// Logic Section:
.bool_and => {
var lhs = try self.pop();
defer lhs.deinit();
var rhs = try self.pop();
defer rhs.deinit();
const a = try lhs.toBoolean();
const b = try rhs.toBoolean();
try self.push(Value.initBoolean(a and b));
},
.bool_or => {
var lhs = try self.pop();
defer lhs.deinit();
var rhs = try self.pop();
defer rhs.deinit();
const a = try lhs.toBoolean();
const b = try rhs.toBoolean();
try self.push(Value.initBoolean(a or b));
},
.bool_not => {
var val = try self.pop();
defer val.deinit();
const a = try val.toBoolean();
try self.push(Value.initBoolean(!a));
},
// Arithmetic Section:
.negate => {
var value = try self.pop();
defer value.deinit();
const num = try value.toNumber();
try self.push(Value.initNumber(-num));
},
.add => {
var rhs = try self.pop();
defer rhs.deinit();
var lhs = try self.pop();
defer lhs.deinit();
if (@as(TypeId, lhs) != @as(TypeId, rhs))
return error.TypeMismatch;
switch (lhs) {
.number => {
try self.push(Value.initNumber(lhs.number + rhs.number));
},
.string => {
const lstr = lhs.string.contents;
const rstr = rhs.string.contents;
var string = try String.initUninitialized(self.allocator, lstr.len + rstr.len);
errdefer string.deinit();
const buffer = try string.obtainMutableStorage();
std.mem.copy(u8, buffer[0..lstr.len], lstr);
std.mem.copy(u8, buffer[lstr.len..buffer.len], rstr);
try self.push(Value.fromString(string));
},
.array => {
const larr = lhs.array.contents;
const rarr = rhs.array.contents;
var result = try Array.init(self.allocator, larr.len + rarr.len);
errdefer result.deinit();
for (larr) |*item, i| {
result.contents[i].exchangeWith(item);
}
for (rarr) |*item, i| {
result.contents[larr.len + i].exchangeWith(item);
}
try self.push(Value.fromArray(result));
},
else => return error.TypeMismatch,
}
},
.sub => {
try self.executeNumberArithmetic(struct {
fn operator(lhs: f64, rhs: f64) error{DivideByZero}!f64 {
return lhs - rhs;
}
}.operator);
},
.mul => {
try self.executeNumberArithmetic(struct {
fn operator(lhs: f64, rhs: f64) error{DivideByZero}!f64 {
return lhs * rhs;
}
}.operator);
},
.div => {
try self.executeNumberArithmetic(struct {
fn operator(lhs: f64, rhs: f64) error{DivideByZero}!f64 {
if (rhs == 0)
return error.DivideByZero;
return lhs / rhs;
}
}.operator);
},
.mod => {
try self.executeNumberArithmetic(struct {
fn operator(lhs: f64, rhs: f64) error{DivideByZero}!f64 {
if (rhs == 0)
return error.DivideByZero;
return @mod(lhs, rhs);
}
}.operator);
},
// Comparisons:
.eq => {
var lhs = try self.pop();
defer lhs.deinit();
var rhs = try self.pop();
defer rhs.deinit();
try self.push(Value.initBoolean(lhs.eql(rhs)));
},
.neq => {
var lhs = try self.pop();
defer lhs.deinit();
var rhs = try self.pop();
defer rhs.deinit();
try self.push(Value.initBoolean(!lhs.eql(rhs)));
},
.less => try self.executeCompareValues(.lt, false),
.less_eq => try self.executeCompareValues(.lt, true),
.greater => try self.executeCompareValues(.gt, false),
.greater_eq => try self.executeCompareValues(.gt, true),
// Deperecated Section:
.scope_push,
.scope_pop,
.declare,
.store_global_name,
.load_global_name,
=> return error.DeprectedInstruction,
}
return null;
}
/// Initiates or executes a function call.
/// Returns `true` when the VM execution should suspend after the call, else `false`.
fn executeFunctionCall(self: *Self, environment: *Environment, call: anytype, function: Function, object: ?ObjectHandle) !bool {
return switch (function) {
.script => |fun| blk: {
var context = try self.createContext(fun);
errdefer self.deinitContext(&context);
try self.readLocals(call, context.locals);
// Fixup stack balance after popping all locals
context.stackBalance = self.stack.items.len;
try self.calls.append(context);
break :blk false;
},
.syncUser => |fun| blk: {
var locals = try self.allocator.alloc(Value, call.argc);
for (locals) |*l| {
l.* = .void;
}
defer {
for (locals) |*l| {
l.deinit();
}
self.allocator.free(locals);
}
try self.readLocals(call, locals);
var result = try fun.call(environment, fun.context, locals);
errdefer result.deinit();
try self.push(result);
break :blk false;
},
.asyncUser => |fun| blk: {
var locals = try self.allocator.alloc(Value, call.argc);
for (locals) |*l| {
l.* = .void;
}
defer {
for (locals) |*l| {
l.deinit();
}
self.allocator.free(locals);
}
try self.readLocals(call, locals);
self.currentAsynCall = try fun.call(environment, fun.context, locals);
self.currentAsynCall.?.object = object;
break :blk true;
},
};
}
/// Reads a number of call arguments into a slice.
/// If an error happens, all items in `locals` are valid and must be deinitialized.
fn readLocals(self: *Self, call: Instruction.CallArg, locals: []Value) !void {
var i: usize = 0;
while (i < call.argc) : (i += 1) {
var value = try self.pop();
if (i < locals.len) {
locals[i].replaceWith(value);
} else {
value.deinit(); // Discard the value
}
}
}
fn executeCompareValues(self: *Self, wantedOrder: std.math.Order, allowEql: bool) !void {
var rhs = try self.pop();
defer rhs.deinit();
var lhs = try self.pop();
defer lhs.deinit();
if (@as(TypeId, lhs) != @as(TypeId, rhs))
return error.TypeMismatch;
const order = switch (lhs) {
.number => |num| std.math.order(num, rhs.number),
.string => |str| std.mem.order(u8, str.contents, rhs.string.contents),
else => return error.InvalidOperator,
};
try self.push(Value.initBoolean(
if (order == .eq and allowEql) true else order == wantedOrder,
));
}
const SingleResult = enum {
/// The program has encountered an asynchronous function
completed,
/// execution and waits for completion.
yield,
};
fn executeNumberArithmetic(self: *Self, operator: fn (f64, f64) error{DivideByZero}!f64) !void {
var rhs = try self.pop();
defer rhs.deinit();
var lhs = try self.pop();
defer lhs.deinit();
const n_lhs = try lhs.toNumber();
const n_rhs = try rhs.toNumber();
const result = try operator(n_lhs, n_rhs);
try self.push(Value.initNumber(result));
}
/// Prints a stack trace for the current code position into `stream`.
pub fn printStackTrace(self: Self, stream: anytype) !void {
var i: usize = self.calls.items.len;
while (i > 0) {
i -= 1;
const call = self.calls.items[i];
const stack_compile_unit = call.environment.compileUnit;
const location = stack_compile_unit.lookUp(call.decoder.offset);
var current_fun: []const u8 = "<main>";
for (stack_compile_unit.functions) |fun| {
if (call.decoder.offset < fun.entryPoint)
break;
current_fun = fun.name;
}
try stream.print("[{}] at offset {} ({}:{}:{}) in function {}\n", .{
i,
call.decoder.offset,
stack_compile_unit.comment,
if (location) |l| l.sourceLine else 0,
if (location) |l| l.sourceColumn else 0,
current_fun,
});
}
}
pub fn serialize(self: Self, envmap: *lola.runtime.EnvironmentMap, stream: anytype) !void {
if (self.currentAsynCall != null)
return error.NotSupportedYet; // we cannot serialize async function that are in-flight atm
try stream.writeIntLittle(u64, self.stack.items.len);
try stream.writeIntLittle(u64, self.calls.items.len);
for (self.stack.items) |item| {
try item.serialize(stream);
}
for (self.calls.items) |item| {
try stream.writeIntLittle(u16, @intCast(u16, item.locals.len));
try stream.writeIntLittle(u32, item.decoder.offset); // we don't need to store the CompileUnit of the decoder, as it is implicitly referenced by the environment
try stream.writeIntLittle(u32, @intCast(u32, item.stackBalance));
if (envmap.queryByPtr(item.environment)) |env_id| {
try stream.writeIntLittle(u32, env_id);
} else {
return error.UnregisteredEnvironmentPointer;
}
for (item.locals) |loc| {
try loc.serialize(stream);
}
}
}
pub fn deserialize(allocator: *std.mem.Allocator, envmap: *lola.runtime.EnvironmentMap, stream: anytype) !Self {
const stack_size = try stream.readIntLittle(u64);
const call_size = try stream.readIntLittle(u64);
var vm = Self{
.allocator = allocator,
.stack = std.ArrayList(Value).init(allocator),
.calls = std.ArrayList(Context).init(allocator),
.currentAsynCall = null,
.objectPool = undefined,
};
errdefer vm.stack.deinit();
errdefer vm.calls.deinit();
try vm.stack.ensureCapacity(std.math.min(stack_size, 128));
try vm.calls.ensureCapacity(std.math.min(call_size, 32));
try vm.stack.resize(stack_size);
for (vm.stack.items) |*item| {
item.* = .void;
}
errdefer for (vm.stack.items) |*item| {
item.deinit();
};
for (vm.stack.items) |*item| {
item.* = try Value.deserialize(stream, allocator);
}
{
var i: usize = 0;
while (i < call_size) : (i += 1) {
const local_count = try stream.readIntLittle(u16);
const offset = try stream.readIntLittle(u32);
const stack_balance = try stream.readIntLittle(u32);
const env_id = try stream.readIntLittle(u32);
const env = envmap.queryById(env_id) orelse return error.UnregisteredEnvironmentPointer;
if (i == 0) {
// first call defines which environment we use for our
// object pool reference:
vm.objectPool = env.objectPool;
}
var ctx = try vm.createContext(ScriptFunction{
.environment = env,
.entryPoint = offset,
.localCount = local_count,
});
ctx.stackBalance = stack_balance;
errdefer vm.deinitContext(&ctx);
for (ctx.locals) |*local| {
local.* = try Value.deserialize(stream, allocator);
}
try vm.calls.append(ctx);
}
}
return vm;
}
};
const TestPool = ObjectPool(.{});
fn runTest(comptime TestRunner: type) !void {
var code = TestRunner.code;
const cu = CompileUnit{
.arena = undefined,
.comment = "",
.globalCount = 0,
.temporaryCount = 0,
.functions = &[_]CompileUnit.Function{},
.debugSymbols = &[0]CompileUnit.DebugSymbol{},
.code = &code,
};
var pool = TestPool.init(std.testing.allocator);
defer pool.deinit();
var env = try Environment.init(std.testing.allocator, &cu, pool.interface());
defer env.deinit();
var vm = try VM.init(std.testing.allocator, &env);
defer vm.deinit();
try TestRunner.verify(&vm);
}
test "VM basic execution" {
try runTest(struct {
var code = [_]u8{
@enumToInt(InstructionName.ret),
};
fn verify(vm: *VM) !void {
const result = try vm.execute(1);
std.testing.expectEqual(ExecutionResult.completed, result);
}
});
}
test "VM endless loop exhaustion" {
try runTest(struct {
var code = [_]u8{
@enumToInt(InstructionName.jmp),
0x00,
0x00,
0x00,
0x00,
};
fn verify(vm: *VM) !void {
const result = try vm.execute(1000);
std.testing.expectEqual(ExecutionResult.exhausted, result);
}
});
}
test "VM invalid code panic" {
try runTest(struct {
var code = [_]u8{
@enumToInt(InstructionName.jmp),
0x00,
0x00,
0x00,
};
fn verify(vm: *VM) !void {
std.testing.expectError(error.InvalidBytecode, vm.execute(1000));
}
});
}
test "VM invalid jump panic" {
try runTest(struct {
var code = [_]u8{
@enumToInt(InstructionName.jmp),
0x00,
0x00,
0x00,
0xFF,
};
fn verify(vm: *VM) !void {
std.testing.expectError(error.InvalidJump, vm.execute(1000));
}
});
} | src/library/runtime/vm.zig |
const std = @import("std");
const curl = @import("curl.zig");
const pacman = @import("pacman.zig");
const Host = "https://aur.archlinux.org/rpc/?v=5";
pub const Snapshot = "https://aur.archlinux.org/cgit/aur.git/snapshot";
pub const RPCRespV5 = struct {
version: usize,
type: []const u8,
resultcount: usize,
results: []Info,
};
pub const Info = struct {
ID: usize,
Name: []const u8,
PackageBaseID: usize,
PackageBase: []const u8,
Version: []const u8,
Description: ?[]const u8 = null,
URL: ?[]const u8 = null,
NumVotes: usize,
Popularity: f64,
OutOfDate: ?i32 = null, // TODO: parse this unixtime
Maintainer: ?[]const u8 = null,
FirstSubmitted: i32, // TODO: parse this unixtime
LastModified: i32, // TODO: parse this unixtime
URLPath: []const u8,
Depends: ?[][]const u8 = null,
MakeDepends: ?[][]const u8 = null,
OptDepends: ?[][]const u8 = null,
CheckDepends: ?[][]const u8 = null,
Conflicts: ?[][]const u8 = null,
Provides: ?[][]const u8 = null,
Replaces: ?[][]const u8 = null,
Groups: ?[][]const u8 = null,
License: ?[][]const u8 = null,
Keywords: ?[][]const u8 = null,
};
pub fn queryAll(allocator: std.mem.Allocator, pkgs: std.StringHashMap(*pacman.Package)) !RPCRespV5 {
const uri = try buildInfoQuery(allocator, pkgs);
var resp = try curl.get(allocator, uri);
@setEvalBranchQuota(100000);
var json_resp = std.json.TokenStream.init(resp.items);
var result = try std.json.parse(RPCRespV5, &json_resp, std.json.ParseOptions{ .allocator = allocator });
return result;
}
pub fn search(allocator: std.mem.Allocator, search_name: []const u8) !RPCRespV5 {
var uri = std.ArrayList(u8).init(allocator);
var parser = std.json.Parser.init(allocator, false);
defer parser.deinit();
try uri.appendSlice(Host);
try uri.appendSlice("&type=search&by=name&arg="); // TODO: maybe consider opening this up
try uri.appendSlice(search_name);
var uri_for_curl = try uri.toOwnedSliceSentinel(0);
var resp = try curl.get(allocator, uri_for_curl);
@setEvalBranchQuota(100000);
var tree = try parser.parse(resp.items);
defer tree.deinit();
var Error = tree.root.Object.get("error");
if (Error == null) {
var json_resp = std.json.TokenStream.init(resp.items);
var result = try std.json.parse(RPCRespV5, &json_resp, std.json.ParseOptions{ .allocator = allocator });
return result;
} else if (std.mem.eql(u8, Error.?.String, "Query arg too small.") ) {
try uri.appendSlice(Host);
try uri.appendSlice("&type=info&by=name&arg="); // TODO: maybe consider opening this up
try uri.appendSlice(search_name);
uri_for_curl = try uri.toOwnedSliceSentinel(0);
resp = try curl.get(allocator, uri_for_curl);
var json_resp = std.json.TokenStream.init(resp.items);
var result = try std.json.parse(RPCRespV5, &json_resp, std.json.ParseOptions{ .allocator = allocator });
return result;
} else {
std.debug.print("{s}\n", .{Error.?.String});
return error.aurerror;
}
}
fn buildInfoQuery(allocator: std.mem.Allocator, pkgs: std.StringHashMap(*pacman.Package)) ![*:0]const u8 {
var uri = std.ArrayList(u8).init(allocator);
try uri.appendSlice(Host);
try uri.appendSlice("&type=info");
var pkgs_iter = pkgs.iterator();
while (pkgs_iter.next()) |pkg| {
try uri.appendSlice("&arg[]=");
var copyKey = try allocator.alloc(u8, pkg.key_ptr.*.len);
std.mem.copy(u8, copyKey, pkg.key_ptr.*);
try uri.appendSlice(copyKey);
defer allocator.free(copyKey);
}
return try uri.toOwnedSliceSentinel(0);
} | src/aur.zig |
const utils = @import("utils");
const kernel = @import("root").kernel;
const print = kernel.print;
const io = kernel.io;
const memory = kernel.memory;
const MemoryError = memory.MemoryError;
const Allocator = memory.Allocator;
const devices = kernel.devices;
const pci = @import("pci.zig");
const putil = @import("util.zig");
const timing = @import("timing.zig");
pub const Error = error {
FailedToSelectDrive,
Timeout,
UnexpectedValues,
OperationError,
} || MemoryError;
const log_indent = " ";
const Sector = struct {
pub const size: u64 = 512;
address: u64,
data: [size]u8 align(8) = undefined,
};
const CommandStatus = packed struct {
in_error: bool,
unused_index: bool,
unused_corrected: bool,
data_ready: bool,
unused_seek_complete: bool,
fault: bool,
drive_ready: bool,
busy: bool,
pub fn assert_selectable(self: *CommandStatus) Error!void {
if (self.busy or self.data_ready) {
return Error.FailedToSelectDrive;
}
}
// TODO: Make these checks simpler?
pub fn drive_is_ready(self: *CommandStatus) Error!bool {
if (self.busy) {
return false;
}
if (self.in_error or self.fault) {
return Error.OperationError;
}
return self.drive_ready;
}
pub fn data_is_ready(self: *CommandStatus) Error!bool {
if (self.busy) {
return false;
}
if (self.in_error or self.fault) {
return Error.OperationError;
}
return self.data_ready;
}
};
const Control = packed struct {
unused_bit_0: bool = false,
interrupts_disabled: bool,
reset: bool,
unused_bits_3_7: u5 = 0,
};
const DriveHeadSelect = packed struct {
lba28_bits_24_27: u4 = 0,
select_slave: bool,
always_1_bit_5: bool = true,
lba: bool = false,
always_1_bit_7: bool = true,
};
const IndentifyResults = struct {
const Raw = packed struct {
// Word 0
unused_word_0_bits_0_14: u15,
is_atapi: bool,
// Words 1 - 9
unused_words_1_9: [9]u16,
// Words 10 - 19
serial_number: [10]u16,
// Words 20 - 22
used_words_20_22: [3]u16,
// Words 23 - 26
firmware_revision: [4]u16,
// Words 27 - 46
model: [20]u16,
// Words 47 - 48
used_words_47_48: [2]u16,
// Word 49
unused_word_49_bits_0_8: u9,
lba: bool,
unused_word_49_bits_10_15: u6,
// Words 50 - 59
unused_words_50_59: [10]u16,
// Words 60 - 61
lba28_sector_count: u32,
// Words 62 - 85
unused_words_62_85: [24]u16,
// Word 86
unused_word_86_bits_0_9: u10,
lba48: bool,
unused_word_86_bits_11_15: u5,
// Words 87 - 99
unused_words_87_99: [13]u16,
// Words 100 - 103
lba48_sector_count: u64,
// Words 104 - 255
unused_words_104_255: [152]u16,
};
comptime {
const raw_bit_size = utils.packed_bit_size(Raw);
const sector_bit_size = Sector.size * 8;
if (raw_bit_size != sector_bit_size) {
@compileLog("IndentifyResults.Raw is ", raw_bit_size, " bits");
@compileLog("Sector is ", sector_bit_size, " bits");
@compileError("IndentifyResults.Raw must match the size of a sector");
}
}
const AddressType = enum(u8) {
Lba28,
Lba48,
pub fn to_string(self: AddressType) []const u8 {
return switch (self) {
.Lba28 => "LBA 28",
.Lba48 => "LBA 48",
};
}
};
model: []u8,
sector_count: u64,
address_type: AddressType,
pub fn from_sector(sector: *Sector) Error!IndentifyResults {
var results: IndentifyResults = undefined;
const raw = @ptrCast(*Raw, §or.data[0]);
results.model.ptr = @ptrCast([*]u8, &raw.model[0]);
results.model.len = raw.model.len * 2;
for (raw.model) |*i| {
i.* = @byteSwap(u16, i.*);
}
results.model.len = utils.stripped_string_size(results.model);
// TODO: Other Strings
if (raw.lba) {
if (raw.lba48) {
results.address_type = .Lba48;
results.sector_count = raw.lba48_sector_count;
} else {
results.address_type = .Lba28;
results.sector_count = raw.lba28_sector_count;
}
} else {
print.string("Error: Drive does not support LBA\n");
return Error.UnexpectedValues;
}
return results;
}
};
const Controller = struct {
const default_primary_io_base_port: u16 = 0x01F0;
const default_primary_control_base_port: u16 = 0x03F4;
const default_primary_irq: u8 = 14;
const default_secondary_io_base_port: u16 = 0x0170;
const default_secondary_control_base_port: u16 = 0x0374;
const default_secondary_irq: u8 = 16;
pub const Device = struct {
pub const Id = enum(u1) {
Master,
Slave,
};
id: Id,
present: bool = false,
selected: bool = false,
alloc: *memory.Allocator = undefined,
block_store_interface: io.BlockStore = undefined,
fn get_channel(self: *Device) *Channel {
return if (self.id == .Master) @fieldParentPtr(Channel, "master", self)
else @fieldParentPtr(Channel, "slave", self);
}
pub fn select(self: *Device) Error!void {
// TODO
// if (self.selected) return;
const channel = self.get_channel();
try channel.read_command_status().assert_selectable();
channel.write_select(self.id);
timing.wait_microseconds(1);
_ = channel.read_command_status();
try channel.read_command_status().assert_selectable();
// self.selected = true;
// channel.selected(self.id);
}
const wait_timeout_ms = 5000;
// TODO: Merge these wait functions?
pub fn wait_while_busy(self: *Device) Error!void {
const channel = self.get_channel();
var milliseconds_left: u64 = wait_timeout_ms;
while (channel.read_command_status().busy) {
milliseconds_left -= 1;
if (milliseconds_left == 0) {
print.string("wait_while_busy Timeout\n");
return Error.Timeout;
}
timing.wait_milliseconds(1);
}
}
pub fn wait_for_drive(self: *Device) Error!void {
const channel = self.get_channel();
var milliseconds_left: u64 = wait_timeout_ms;
_ = channel.read_control_status();
while (!try channel.read_control_status().drive_is_ready()) {
milliseconds_left -= 1;
if (milliseconds_left == 0) {
print.format("wait_for_drive Timeout {}\n", .{
channel.read_control_status()});
return Error.Timeout;
}
timing.wait_milliseconds(1);
}
}
pub fn wait_for_data(self: *Device) Error!void {
const channel = self.get_channel();
var milliseconds_left: u64 = wait_timeout_ms;
_ = channel.read_control_status();
while (!try channel.read_control_status().data_is_ready()) {
milliseconds_left -= 1;
if (milliseconds_left == 0) {
print.string("wait_for_data Timeout\n");
return Error.Timeout;
}
timing.wait_milliseconds(1);
}
}
pub fn reset(self: *Device) Error!void {
try self.select();
const channel = self.get_channel();
// Enable Reset
channel.write_control(Control{.interrupts_disabled = true, .reset = true});
// Wait 5+ us
timing.wait_microseconds(5);
// Disable Reset
channel.write_control(Control{.interrupts_disabled = true, .reset = false});
// Wait 2+ ms
timing.wait_milliseconds(2);
// Wait for controller to stop being busy
try self.wait_while_busy();
// Wait 5+ ms
timing.wait_milliseconds(5);
_ = channel.read_error();
// Read Expected Values
const sector_count = channel.read_sector_count();
const sector_number = channel.read_sector_number();
if (sector_count != 1 and sector_number != 1) {
print.format(log_indent ++ " - reset: expected 1, 1 for sector count "
++ "and number, but got {}, {}\n", .{sector_count, sector_number});
return Error.UnexpectedValues;
}
print.format(log_indent ++ " - type: {:x}\n", .{channel.read_cylinder()});
}
pub fn init(self: *Device, temp_sector: *Sector, alloc: *memory.Allocator) Error!void {
print.format(log_indent ++ " - {}\n", .{
if (self.id == .Master)
@as([]const u8, "Master") else @as([]const u8, "Slave")});
const channel = self.get_channel();
self.alloc = alloc;
try self.reset();
try self.wait_for_drive();
channel.identify_command();
_ = channel.read_command_status();
try self.wait_for_data();
channel.read_sector(temp_sector);
const identity = try IndentifyResults.from_sector(temp_sector);
print.format(
log_indent ++ " - Drive Model: \"{}\"\n", .{identity.model});
print.format(
log_indent ++ " - Address Type: {}\n", .{
identity.address_type.to_string()});
print.format(
log_indent ++ " - Sector Count: {}\n", .{
@intCast(usize, identity.sector_count)});
self.present = true;
self.block_store_interface.block_size = Sector.size;
self.block_store_interface.read_block_impl = Device.read_block;
self.block_store_interface.free_block_impl = Device.free_block;
}
pub fn read_impl(self: *Device, address: u64, data: []u8) Error!void {
try self.select();
const channel = self.get_channel();
try self.wait_for_drive();
channel.write_lba48(self.id, address, 1);
timing.wait_microseconds(5);
channel.read_sectors_command();
_ = channel.read_command_status();
const error_reg = channel.read_error();
const status_reg = channel.read_command_status();
if (((error_reg & 0x80) != 0) or status_reg.in_error or status_reg.fault) {
print.string("ATA Read Error\n");
return Error.OperationError;
}
try self.wait_for_data();
channel.read_sector_impl(data);
}
pub fn read_sector(self: *Device, sector: *Sector) Error!void {
try self.read_impl(sector.address, sector.data[0..]);
}
pub fn read_block(block_store: *io.BlockStore, block: *io.Block) io.BlockError!void {
const self = @fieldParentPtr(Device, "block_store_interface", block_store);
if (block.data == null) {
block.data = try self.alloc.alloc_array(u8, Sector.size);
}
self.read_impl(block.address, block.data.?[0..])
catch return io.BlockError.Internal;
}
pub fn free_block(block_store: *io.BlockStore, block: *io.Block) io.BlockError!void {
const self = @fieldParentPtr(Device, "block_store_interface", block_store);
if (block.data) |data| {
try self.alloc.free_array(data);
}
}
};
const Channel = struct {
pub const Id = enum(u1) {
Primary,
Secondary,
};
id: Id,
io_base_port: u16,
control_base_port: u16,
irq: u8,
master: Device = Device{
.id = Device.Id.Master,
},
slave: Device = Device{
.id = Device.Id.Slave,
},
pub fn selected(self: *Channel, id: Device.Id) void {
if (id == Device.Id.Master) {
self.slave.selected = false;
} else {
self.master.selected = false;
}
}
pub fn read_command_status(self: *Channel) CommandStatus {
return @bitCast(CommandStatus, putil.in8(self.io_base_port + 7));
}
pub fn read_control_status(self: *Channel) CommandStatus {
return @bitCast(CommandStatus, putil.in8(self.control_base_port + 2));
}
pub fn read_error(self: *Channel) u8 { // TODO: Create Struct?
return putil.in8(self.io_base_port + 1);
}
pub fn read_sector_count(self: *Channel) u8 {
return putil.in8(self.io_base_port + 2);
}
pub fn read_sector_number(self: *Channel) u8 {
return putil.in8(self.io_base_port + 3);
}
pub fn read_cylinder(self: *Channel) u16 {
const low = @intCast(u16, putil.in8(self.io_base_port + 4));
const high = @intCast(u16, putil.in8(self.io_base_port + 5));
return (high << 8) | low;
}
pub fn write_drive_head_select(self: *Channel, value: DriveHeadSelect) void {
putil.out8(self.io_base_port + 6, @bitCast(u8, value));
}
pub fn write_select(self: *Channel, value: Device.Id) void {
self.write_drive_head_select(
DriveHeadSelect{.select_slave = value == Device.Id.Slave});
}
const sector_count_register = 2;
const lba_low_register = 3;
const lba_mid_register = 4;
const lba_high_register = 5;
const drive_head_register = 6;
pub fn write_lba48(self: *Channel,
device: Device.Id, lba: u64, sector_count: u16) void {
putil.out8(self.io_base_port + sector_count_register,
@truncate(u8, sector_count >> 8));
putil.out8(self.io_base_port + lba_low_register,
@truncate(u8, lba >> 24));
putil.out8(self.io_base_port + lba_mid_register,
@truncate(u8, lba >> 32));
putil.out8(self.io_base_port + lba_high_register,
@truncate(u8, lba >> 40));
putil.out8(self.io_base_port + sector_count_register,
@truncate(u8, sector_count));
putil.out8(self.io_base_port + lba_low_register,
@truncate(u8, lba));
putil.out8(self.io_base_port + lba_mid_register,
@truncate(u8, lba >> 8));
putil.out8(self.io_base_port + lba_high_register,
@truncate(u8, lba >> 16));
self.write_drive_head_select(DriveHeadSelect{
.lba = true,
.select_slave = device == Device.Id.Slave,
});
}
pub fn read_sectors_command(self: *Channel) void {
putil.out8(self.io_base_port + 7, 0x24);
}
pub fn identify_command(self: *Channel) void {
putil.out8(self.io_base_port + 7, 0xEC);
}
pub fn write_control(self: *Channel, value: Control) void {
putil.out8(self.control_base_port + 2, @bitCast(u8, value));
}
pub fn read_sector(self: *Channel, sector: *Sector) void {
self.read_sector_impl(sector.data[0..]);
}
pub fn read_sector_impl(self: *Channel, data: []u8) void {
putil.in_bytes(self.io_base_port + 0, data);
}
pub fn init(self: *Channel) void {
print.format(log_indent ++ "- {}\n", .{
if (self.id == .Primary) "Primary" else "Secondary"});
self.master.init() catch {
print.string(log_indent ++ " - Master Failed\n");
};
self.slave.init() catch {
print.string(log_indent ++ " - Slave Failed\n");
};
}
};
primary: Channel = Channel{
.id = Channel.Id.Primary,
.io_base_port = default_primary_io_base_port,
.control_base_port = default_primary_control_base_port,
.irq = default_primary_irq,
},
secondary: Channel = Channel{
.id = Channel.Id.Secondary,
.io_base_port = default_secondary_io_base_port,
.control_base_port = default_secondary_control_base_port,
.irq = default_secondary_irq,
},
device_interface: devices.Device = undefined,
alloc: *Allocator = undefined,
pub fn init(self: *Controller, alloc: *Allocator) void {
self.alloc = alloc;
self.device_interface.deinit_impl = Controller.deinit;
// Make sure this is Triton II controller emulated by QEMU
// if (header.vendor_id != 0x8086 or header.device_id != 0x7010 or
// header.prog_if != 0x80) {
// print.string(log_indent ++ "- Unknown IDE Controller\n");
// return;
// }
// TODO Better error handling
const temp_sector = alloc.alloc(Sector) catch @panic("ATA init alloc error");
defer alloc.free(temp_sector) catch @panic("ATA init free error");
// self.primary.init();
// self.secondary.init();
self.primary.master.init(temp_sector, alloc) catch {
print.string("Drive Initialize Failed\n");
return;
};
}
pub fn deinit(device: *devices.Device) anyerror!void {
const self = @fieldParentPtr(Controller, "device_interface", device);
try self.alloc.free(self);
}
};
pub fn init(dev: *const pci.Dev) void {
_ = dev;
var controller = kernel.alloc.alloc(Controller) catch {
@panic("Failure");
};
controller.* = Controller{};
controller.init(kernel.alloc);
kernel.device_mgr.add_device(&controller.device_interface) catch {
@panic("Failure");
};
if (controller.primary.master.present) {
kernel.raw_block_store = &controller.primary.master.block_store_interface;
}
} | kernel/platform/ata.zig |
const pi = @import("std").math.pi;
/// An angle.
///
/// See: https://dogma.dev/Angle
pub const Angle = extern struct {
/// The angle in radians.
_radians: f64,
const Self = @This();
/// Constructs an angle from radians.
pub fn init(radians: f64) Self {
return Self{ ._radians = radians };
}
/// Constructs an angle from radians.
pub fn fromRadians(radians_: f64) Self {
return Self{ ._radians = radians_ };
}
/// Constructs an angle from degrees.
pub fn fromDegrees(degrees_: f64) Self {
return Self{ ._radians = degrees_ / 180.0 * pi };
}
/// Constructs an angle from turns.
pub fn fromTurns(turns_: f64) Self {
return Self{ ._radians = turns_ * 2 * pi };
}
/// The angle in radians.
pub fn radians(self: Self) f64 {
return self._radians;
}
/// The angle in degrees.
pub fn degrees(self: Self) f64 {
return self._radians / pi * 180.0;
}
/// The angle in turns.
pub fn turns(self: Self) f64 {
return self._radians / (2 * pi);
}
};
test "Angle" { // zig test --main-pkg-path . src/angle.zig
const meta = @import("std").meta;
meta.refAllDecls(@This());
}
test "Angle.fromRadians() constructs the angle from radians" {
const expect = @import("std").testing.expect;
expect(Angle.fromRadians(0).radians() == 0);
expect(Angle.fromRadians(0.5 * pi).radians() == 0.5 * pi);
expect(Angle.fromRadians(pi).radians() == pi);
expect(Angle.fromRadians(2 * pi).radians() == 2 * pi);
}
test "Angle.fromDegrees() constructs the angle from degrees" {
const expect = @import("std").testing.expect;
expect(Angle.fromDegrees(0).degrees() == 0);
expect(Angle.fromDegrees(90).degrees() == 90);
expect(Angle.fromDegrees(180).degrees() == 180);
expect(Angle.fromDegrees(360).degrees() == 360);
}
test "Angle.fromTurns() constructs the angle from turns" {
const expect = @import("std").testing.expect;
expect(Angle.fromTurns(0).turns() == 0);
expect(Angle.fromTurns(0.25).turns() == 0.25);
expect(Angle.fromTurns(0.5).turns() == 0.5);
expect(Angle.fromTurns(1).turns() == 1);
} | src/angle.zig |
const std = @import("std");
const testing = std.testing;
const stringtime = @import("stringtime");
const StringTime = stringtime.StringTime;
test "Parse basic template" {
const Template = "Hi {{name}}!";
var template = try StringTime.init(testing.allocator, Template);
defer template.deinit();
testing.expectEqual(@as(usize, 3), template.commands.items.len);
testing.expect(template.commands.items[0] == .literal);
testing.expect(template.commands.items[1] == .substitution);
testing.expect(template.commands.items[2] == .literal);
testing.expectEqualStrings(template.commands.items[0].literal, "Hi ");
testing.expectEqualStrings(template.commands.items[1].substitution.variable_name, "name");
testing.expectEqualStrings(template.commands.items[2].literal, "!");
}
test "Basic substitution" {
const Template = "Hi {{name}}!";
const Context = struct {
name: []const u8,
};
var context: Context = .{
.name = "Zig stringtime",
};
var parsed_template = try StringTime.init(testing.allocator, Template);
defer parsed_template.deinit();
const result = try parsed_template.render(testing.allocator, context);
defer result.deinit();
testing.expectEqualStrings("Hi Zig stringtime!", result.str);
}
test "Malformated template delimiter" {
var context = .{
.name = "Zig stringtime",
};
const Inputs = [_][]const u8{
"Hi {{user_name}!",
"Hi {user_name}}!",
"Hi {{user_name",
"Hi user_name}}!",
};
for (Inputs) |input| {
var parsed_template = StringTime.init(testing.allocator, input);
testing.expectError(error.MismatchedTemplateDelimiter, parsed_template);
}
}
test "Variable name not found" {
const Template = "Hi {{user_name}}!";
var context = .{
.name = "Zig stringtime",
};
var template = try StringTime.init(testing.allocator, Template);
defer template.deinit();
const result = template.render(testing.allocator, context);
testing.expectError(error.VariableNameNotFound, result);
}
test "Multiple variable substitution" {
const Template = "Hi {{first_name}} {{last_name}}, welcome to Zig.";
var context = .{
.first_name = "Michael",
.last_name = "Larouche",
};
var template = try StringTime.init(testing.allocator, Template);
defer template.deinit();
const result = try template.render(testing.allocator, context);
defer result.deinit();
testing.expectEqualStrings("Hi <NAME>, welcome to Zig.", result.str);
}
test "Multiple renders with different context" {
const Template = "Hi {{name}}!";
var first_context = .{
.name = "Zig stringtime",
};
var second_context = .{
.name = "second context",
.dummy = "dummy",
.jump = "true",
};
const parsed_template = try StringTime.init(testing.allocator, Template);
defer parsed_template.deinit();
const first_result = try parsed_template.render(testing.allocator, first_context);
defer first_result.deinit();
testing.expectEqualStrings("Hi Zig stringtime!", first_result.str);
const second_result = try parsed_template.render(testing.allocator, second_context);
defer second_result.deinit();
testing.expectEqualStrings("Hi second context!", second_result.str);
}
test "Render C-style code properly" {
const Template = "fn {{fn_name}}() { std.log.info(\"Hello World!\"); }";
var context = .{
.fn_name = "testFunction",
};
const parsed_template = try StringTime.init(testing.allocator, Template);
defer parsed_template.deinit();
const result = try parsed_template.render(testing.allocator, context);
defer result.deinit();
testing.expectEqualStrings("fn testFunction() { std.log.info(\"Hello World!\"); }", result.str);
}
test "Render unicode aware" {
const Template = "こんにちは,{{first_name}}!Allô!";
var context = .{
.first_name = "Étoilé星ホシ",
};
const parsed_template = try StringTime.init(testing.allocator, Template);
defer parsed_template.deinit();
const result = try parsed_template.render(testing.allocator, context);
defer result.deinit();
testing.expectEqualStrings("こんにちは,Étoilé星ホシ!Allô!", result.str);
}
test "Start with template" {
const Template = "{{playable_character}}, you must choose wisely.";
var context = .{
.playable_character = "Crono",
};
const parsed_template = try StringTime.init(testing.allocator, Template);
defer parsed_template.deinit();
const result = try parsed_template.render(testing.allocator, context);
defer result.deinit();
testing.expectEqualStrings("Crono, you must choose wisely.", result.str);
}
test "for range loop action" {
const Template =
\\{{ for(0..4) }}Hello World!
\\{{ end }}
;
const Expected =
\\Hello World!
\\Hello World!
\\Hello World!
\\Hello World!
\\
;
const parsed_template = try StringTime.init(testing.allocator, Template);
defer parsed_template.deinit();
const result = try parsed_template.render(testing.allocator, .{});
defer result.deinit();
testing.expectEqualStrings(Expected, result.str);
}
test "Output integer in template" {
const Template = "i32={{signed_int}},u64={{unsigned_long}},unicode_codepoint={{codepoint}}";
const Expected = "i32=-123456,u64=987654321,unicode_codepoint=33609";
const Context = struct {
signed_int: i32,
unsigned_long: u64,
codepoint: u21,
};
var context = Context{
.signed_int = -123456,
.unsigned_long = 987654321,
.codepoint = '草',
};
const parsed_template = try StringTime.init(testing.allocator, Template);
defer parsed_template.deinit();
const result = try parsed_template.render(testing.allocator, context);
defer result.deinit();
testing.expectEqualStrings(Expected, result.str);
}
test "Output bool in template" {
const Template = "first={{first}},second={{second}}";
const Expected = "first=true,second=false";
var context = .{
.first = true,
.second = false,
};
const parsed_template = try StringTime.init(testing.allocator, Template);
defer parsed_template.deinit();
const result = try parsed_template.render(testing.allocator, context);
defer result.deinit();
testing.expectEqualStrings(Expected, result.str);
}
test "Output float in template" {
const Template = "pi={{pi}},tau={{tau}}";
const Expected = "pi=3.141592653589793e+00,tau=6.283185307179586e+00";
var context = .{
.pi = std.math.pi,
.tau = std.math.tau,
};
const parsed_template = try StringTime.init(testing.allocator, Template);
defer parsed_template.deinit();
const result = try parsed_template.render(testing.allocator, context);
defer result.deinit();
testing.expectEqualStrings(Expected, result.str);
}
test "Output enum in template" {
const Template = "Crono={{crono}}, Marle={{marle}}, Lucca={{lucca}}, Magus={{magus}}";
const Expected = "Crono=Lightning, Marle=Water, Lucca=Fire, Magus=Shadow";
const Magic = enum {
Lightning,
Water,
Fire,
Shadow,
};
var context = .{
.crono = Magic.Lightning,
.marle = Magic.Water,
.lucca = Magic.Fire,
.magus = Magic.Shadow,
};
const parsed_template = try StringTime.init(testing.allocator, Template);
defer parsed_template.deinit();
const result = try parsed_template.render(testing.allocator, context);
defer result.deinit();
testing.expectEqualStrings(Expected, result.str);
}
test "for range loop with index variable" {
const Template =
\\{{ for(0..4) |i| }}Index #{{i}}
\\{{ end }}
;
const Expected =
\\Index #0
\\Index #1
\\Index #2
\\Index #3
\\
;
const parsed_template = try StringTime.init(testing.allocator, Template);
defer parsed_template.deinit();
const result = try parsed_template.render(testing.allocator, .{});
defer result.deinit();
testing.expectEqualStrings(Expected, result.str);
}
test "foreach loop with static array of strings " {
const Template =
\\{{ for(list) |item| }}<li>{{item}}</li>
\\{{ end }}
;
const Expected =
\\<li>First</li>
\\<li>Second</li>
\\<li>Third</li>
\\
;
var context = .{
.list = [_][]const u8{
"First",
"Second",
"Third",
},
};
const parsed_template = try StringTime.init(testing.allocator, Template);
defer parsed_template.deinit();
const result = try parsed_template.render(testing.allocator, context);
defer result.deinit();
testing.expectEqualStrings(Expected, result.str);
}
test "foreach loop with index" {
const Template =
\\{{ for(list) |item, i| }}<li>{{item}} at index {{i}}</li>
\\{{ end }}
;
const Expected =
\\<li>First at index 0</li>
\\<li>Second at index 1</li>
\\<li>Third at index 2</li>
\\
;
var context = .{
.list = [_][]const u8{
"First",
"Second",
"Third",
},
};
const parsed_template = try StringTime.init(testing.allocator, Template);
defer parsed_template.deinit();
const result = try parsed_template.render(testing.allocator, context);
defer result.deinit();
testing.expectEqualStrings(Expected, result.str);
} | tests/template_tests.zig |
const std = @import("std");
usingnamespace (@import("../machine.zig"));
usingnamespace (@import("../util.zig"));
const reg = Operand.register;
const memRm = Operand.memoryRmDef;
test "80286" {
const m32 = Machine.init(.x86_32);
const m64 = Machine.init(.x64);
debugPrint(false);
{
testOp0(m32, .CLTS, "0F 06");
}
{
testOp1(m32, .LLDT, memRm(.WORD, .EAX, 0), "0F 00 10");
testOp1(m32, .LMSW, memRm(.WORD, .EAX, 0), "0F 01 30");
testOp1(m32, .LTR, memRm(.WORD, .EAX, 0), "0F 00 18");
testOp1(m32, .SLDT, memRm(.WORD, .EAX, 0), "0F 00 00");
testOp1(m32, .SMSW, memRm(.WORD, .EAX, 0), "0F 01 20");
testOp1(m32, .STR, memRm(.WORD, .EAX, 0), "0F 00 08");
testOp1(m32, .VERR, memRm(.WORD, .EAX, 0), "0F 00 20");
testOp1(m32, .VERW, memRm(.WORD, .EAX, 0), "0F 00 28");
}
{
testOp1(m32, .LLDT, reg(.AX), "0F 00 D0");
testOp1(m32, .LMSW, reg(.AX), "0F 01 F0");
testOp1(m32, .LTR, reg(.AX), "0F 00 D8");
testOp1(m32, .SLDT, reg(.AX), "66 0F 00 C0");
testOp1(m32, .SMSW, reg(.AX), "66 0F 01 E0");
testOp1(m32, .STR, reg(.AX), "66 0F 00 C8");
testOp1(m32, .VERR, reg(.AX), "0F 00 E0");
testOp1(m32, .VERW, reg(.AX), "0F 00 E8");
}
{
testOp1(m32, .LLDT, reg(.EAX), AsmError.InvalidOperand);
testOp1(m32, .LMSW, reg(.EAX), AsmError.InvalidOperand);
testOp1(m32, .LTR, reg(.EAX), AsmError.InvalidOperand);
testOp1(m32, .SLDT, reg(.EAX), "0F 00 C0");
testOp1(m32, .SMSW, reg(.EAX), "0F 01 E0");
testOp1(m32, .STR, reg(.EAX), "0F 00 C8");
testOp1(m32, .VERR, reg(.EAX), AsmError.InvalidOperand);
testOp1(m32, .VERW, reg(.EAX), AsmError.InvalidOperand);
}
{
testOp1(m64, .LLDT, reg(.RAX), AsmError.InvalidOperand);
testOp1(m64, .LMSW, reg(.RAX), AsmError.InvalidOperand);
testOp1(m64, .LTR, reg(.RAX), AsmError.InvalidOperand);
testOp1(m64, .SLDT, reg(.RAX), "48 0F 00 C0");
testOp1(m64, .SMSW, reg(.RAX), "48 0F 01 E0");
testOp1(m64, .STR, reg(.RAX), "48 0F 00 C8");
testOp1(m64, .VERR, reg(.RAX), AsmError.InvalidOperand);
testOp1(m64, .VERW, reg(.RAX), AsmError.InvalidOperand);
}
{
testOp1(m32, .LGDT, memRm(.Void, .EAX, 0), "0F 01 10");
testOp1(m32, .LIDT, memRm(.Void, .EAX, 0), "0F 01 18");
testOp1(m32, .SGDT, memRm(.Void, .EAX, 0), "0F 01 00");
testOp1(m32, .SIDT, memRm(.Void, .EAX, 0), "0F 01 08");
testOp1(m64, .LGDT, memRm(.Void, .EAX, 0), "67 0F 01 10");
testOp1(m64, .LIDT, memRm(.Void, .EAX, 0), "67 0F 01 18");
testOp1(m64, .SGDT, memRm(.Void, .EAX, 0), "67 0F 01 00");
testOp1(m64, .SIDT, memRm(.Void, .EAX, 0), "67 0F 01 08");
}
{
testOp2(m32, .ARPL, memRm(.WORD, .EAX, 0), reg(.AX), "63 00");
testOp2(m64, .ARPL, memRm(.WORD, .EAX, 0), reg(.AX), AsmError.InvalidOperand);
}
{
testOp2(m32, .LAR, reg(.AX), memRm(.WORD, .EAX, 0), "66 0F 02 00");
testOp2(m32, .LSL, reg(.AX), memRm(.WORD, .EAX, 0), "66 0F 03 00");
testOp2(m64, .LAR, reg(.AX), memRm(.WORD, .EAX, 0), "66 67 0F 02 00");
testOp2(m64, .LSL, reg(.AX), memRm(.WORD, .EAX, 0), "66 67 0F 03 00");
}
{
testOp2(m32, .LAR, reg(.EAX), memRm(.DWORD, .EAX, 0), "0F 02 00");
testOp2(m32, .LSL, reg(.EAX), memRm(.DWORD, .EAX, 0), "0F 03 00");
testOp2(m64, .LAR, reg(.EAX), memRm(.DWORD, .EAX, 0), "67 0F 02 00");
testOp2(m64, .LSL, reg(.EAX), memRm(.DWORD, .EAX, 0), "67 0F 03 00");
}
} | src/x86/tests/80286.zig |
const std = @import("std");
fn ishex(c: u8) bool {
if ('0' <= c and c <= '9') {
return true;
}
if ('a' <= c and c <= 'f') {
return true;
}
if ('A' <= c and c <= 'F') {
return true;
}
return false;
}
fn unhex(c: u8) u8 {
if ('0' <= c and c <= '9') {
return c - '0';
}
if ('a' <= c and c <= 'f') {
return c - 'a' + 10;
}
if ('A' <= c and c <= 'F') {
return c - 'A' + 10;
}
return 0;
}
fn tolower(str: []u8) void {
for (str) |*ch| {
ch.* = if (ch.* > 0x40 and ch.* < 0x5b) ch.* | 0x60 else ch.*;
}
}
pub const URLCategory = enum {
path,
builtin,
unknown,
};
pub const PartialURL = struct {
// always lowercase
scheme: [:0]const u8,
data: union(enum) {
entity: [:0]const u8,
normal: struct {
authority: ?[:0]const u8 = null,
path: ?[:0]const u8 = null,
},
},
const State = union(enum) {
scheme,
sep,
prehost,
authority: usize,
path: std.ArrayListUnmanaged(u8),
entity: usize,
};
const HexState = union(enum) {
initial: void,
start: void,
ready: u8,
};
pub fn parse(allocator: *std.mem.Allocator, input: []const u8) !@This() {
var ret: @This() = undefined;
var state: State = .scheme;
errdefer {
switch (state) {
.entity, .authority, .prehost, .sep => {
allocator.free(ret.scheme);
},
.path => |*list| {
list.deinit(allocator);
if (ret.data.normal.authority) |authority| allocator.free(authority);
allocator.free(ret.scheme);
},
.scheme => {},
}
}
var hex: HexState = .initial;
var last: usize = input.len;
for (input) |ch, i| out: {
switch (hex) {
.initial => {},
.start => {
if (ishex(ch)) {
hex = .{ .ready = unhex(ch) * 16 };
continue;
} else {
return error.InvalidHexEncoding;
}
},
.ready => |d| {
if (ishex(ch)) {
hex = .{ .ready = d + unhex(ch) };
} else {
return error.InvalidHexEncoding;
}
},
}
switch (state) {
.scheme => {
if (ch == ':') {
var scheme = try allocator.dupeZ(u8, input[0..i]);
tolower(scheme);
ret.scheme = scheme;
state = .sep;
}
},
.sep => {
if (ch == '/') {
state = .prehost;
} else {
state = .{ .entity = i };
}
},
.prehost => {
if (ch == '/') {
state = .{ .authority = i + 1 };
} else {
return error.UnsupportedURL;
}
},
.authority => |start| {
if (ch == '/') {
if (start == i) {
ret.data = .{ .normal = .{ .authority = null } };
} else {
ret.data = .{ .normal = .{ .authority = try allocator.dupeZ(u8, input[start..i]) } };
}
state = .{ .path = try std.ArrayListUnmanaged(u8).initCapacity(allocator, input.len - i + 1) };
}
},
.path => |*list| {
switch (hex) {
.ready => |d| {
hex = .initial;
list.appendAssumeCapacity(d);
continue;
},
else => {},
}
switch (ch) {
else => {
list.appendAssumeCapacity(ch);
},
'+' => {
list.appendAssumeCapacity(' ');
},
'?', '#' => {
last = i;
break :out;
},
'%' => {
hex = .start;
},
}
},
.entity => |start| {
switch (ch) {
'?' => {
last = i;
break :out;
},
else => {},
}
},
}
}
switch (hex) {
else => return error.IncompleteHexEncoding,
.initial => {},
}
switch (state) {
else => return error.IncompleteURL,
.entity => |start| {
ret.data = .{ .entity = try allocator.dupeZ(u8, input[start..last]) };
},
.path => |*list| {
list.appendAssumeCapacity(0);
const x = list.toOwnedSlice(allocator);
ret.data.normal.path = x[0 .. x.len - 1 :0];
},
}
return ret;
}
pub fn deinit(self: @This(), allocator: *std.mem.Allocator) void {
allocator.free(self.scheme);
switch (self.data) {
.normal => |data| {
if (data.authority) |authority| allocator.free(authority);
if (data.path) |path| allocator.free(path);
},
.entity => |data| {
allocator.free(data);
},
}
}
pub fn category(self: @This()) URLCategory {
if (std.mem.eql(u8, self.scheme, "file")) {
if (self.data != .normal or self.data.normal.path == null or self.data.normal.authority != null) return .unknown;
return .path;
} else if (std.mem.eql(u8, self.scheme, "builtin")) {
if (self.data != .entity) return .unknown;
return .builtin;
}
return .unknown;
}
fn resolvePath(allocator: *std.mem.Allocator, paths: []const []const u8) ![:0]const u8 {
const ret = try std.fs.path.resolve(allocator, paths);
defer allocator.free(ret);
return std.cstr.addNullByte(allocator, ret);
}
pub fn resolveModule(self: @This(), allocator: *std.mem.Allocator, side: []const u8) ?[:0]const u8 {
if (parse(allocator, side)) |rurl| {
defer rurl.deinit(allocator);
switch (rurl.category()) {
.path => {
return resolvePath(allocator, &[_][]const u8{rurl.data.normal.path.?}) catch null;
},
.builtin => {
return allocator.dupeZ(u8, side) catch null;
},
.unknown => return null,
}
} else |err| {
switch (self.category()) {
.path => {
return resolvePath(allocator, &[_][]const u8{
self.data.normal.path.?, "..", side,
}) catch null;
},
else => return null,
}
}
}
};
fn testUrl(input: []const u8) !void {
const url = try PartialURL.parse(std.testing.allocator, input);
try std.io.getStdOut().writer().print("{} => {}\n", .{ input, url });
defer url.deinit(std.testing.allocator);
}
test "parse url" {
try testUrl("file:///D:/Project/tinysh/test.js");
try testUrl("builtin:c");
try testUrl("https://wiki.tld/%E4%B8%AD%E6%96%87");
std.testing.expectError(error.IncompleteURL, testUrl("boom"));
std.testing.expectError(error.IncompleteHexEncoding, testUrl("https://wiki.tld/%E4%B8%AD%E6%96%8"));
}
test "resolve module" {
const url = try PartialURL.parse(std.testing.allocator, "file:///D:/Project/tinysh/test.js");
defer url.deinit(std.testing.allocator);
const t2 = url.resolveModule(std.testing.allocator, "builtin:c") orelse unreachable;
defer std.testing.allocator.free(t2);
try std.io.getStdOut().writer().print("{}\n", .{t2});
} | src/url.zig |
const c = @import("c.zig");
const std = @import("std");
const panic = std.debug.panic;
const debug_gl = @import("debug_gl.zig");
const glfw_impl = @import("glfw_impl.zig");
const gl3_impl = @import("gl3_impl.zig");
export fn errorCallback(err: c_int, description: [*c]const u8) void {
panic("Error: {}\n", .{description});
}
var rand: std.rand.DefaultPrng = undefined;
fn initRandom() !void {
var buf: [8]u8 = undefined;
try std.crypto.randomBytes(buf[0..]);
const seed = std.mem.readIntLittle(u64, buf[0..8]);
rand = std.rand.DefaultPrng.init(seed);
}
fn rgbColor(col: u32) u32 {
return rgbaColor(col << 8 | 0xFF);
}
fn rgbaColor(col: u32) u32 {
// ImGui format: a b g r
// our HTML-like format: r g b a
const a = (col & 0xFF) << 24;
const b = (col & 0xFF00) << 8;
const g = (col & 0xFF0000) >> 8;
const r = (col & 0xFF000000) >> 24;
return r | g | b | a;
}
const Dice = struct {
sides: u32,
color: u32,
color_hovered: u32,
};
const Roll = struct {
roll: u32,
dice: usize,
};
const dice = [_]Dice{
makeDice(2, 0xC9D127),
makeDice(4, 0x24A146),
makeDice(6, 0x27BCD1),
makeDice(8, 0x9334E6),
makeDice(10, 0xE13294),
makeDice(12, 0xD93025),
makeDice(20, 0xF36D00),
makeDice(100, 0x878787),
};
fn makeDice(sides: u32, color: u32) Dice {
return .{
.sides = sides,
.color = rgbaColor(color << 8 | 0xCC),
.color_hovered = rgbColor(color),
};
}
const max_rolls: usize = 20;
var rolls: [max_rolls]Roll = undefined;
var rolls_len: usize = 0;
fn doRoll() void {
var i: usize = 0;
while (i < rolls_len) : (i += 1) {
var roll = &rolls[i];
const d = dice[roll.dice];
roll.roll = rand.random.uintLessThan(u32, d.sides) + 1;
}
}
fn render() !void {
c.igSetNextWindowSizeXY(500, 300, c.ImGuiCond_Once);
// c.igSetNextWindowPos(10, 10, c.ImGuiCond_Once)
var p_open = false;
_ = c.igBegin("Dice Roller", &p_open, c.ImGuiWindowFlags_None);
c.igText("Rolls");
c.igPushIDStr("Rolls buttons");
{
var i: usize = 0;
while (i < rolls_len) : (i += 1) {
const roll = rolls[i];
const d = dice[roll.dice];
c.igPushIDInt(@intCast(c_int, i));
c.igPushStyleColorU32(c.ImGuiCol_Button, d.color);
c.igPushStyleColorU32(c.ImGuiCol_ButtonHovered, d.color_hovered);
c.igPushStyleColorU32(c.ImGuiCol_ButtonActive, d.color);
var buf: [32]u8 = undefined;
_ = try std.fmt.bufPrint(&buf, "{}", .{roll.roll});
if (c.igButtonXY(&buf, 50, 50) and rolls_len > 1) {
var j: usize = i;
while (j < rolls_len - 1) : (j += 1) {
rolls[j] = rolls[j + 1];
}
rolls_len -= 1;
}
c.igPopStyleColor(3);
if (i + 1 < rolls_len) {
c.igSameLine(0, -1);
}
c.igPopID();
}
}
c.igPopID();
c.igText("Add dice");
c.igPushIDStr("Dice buttons");
for (dice) |d, i| {
c.igPushIDInt(@intCast(c_int, i));
c.igPushStyleColorU32(c.ImGuiCol_Button, d.color);
c.igPushStyleColorU32(c.ImGuiCol_ButtonHovered, d.color_hovered);
c.igPushStyleColorU32(c.ImGuiCol_ButtonActive, d.color);
var buf: [32]u8 = undefined;
_ = try std.fmt.bufPrint(&buf, "{}", .{d.sides});
if (c.igButtonXY(&buf, 50, 50)) {
std.debug.warn("Adding {}: #{}, {}\n", .{ rolls_len, i, d });
if (rolls_len < max_rolls) {
rolls[rolls_len] = .{
.roll = rand.random.uintLessThan(u32, d.sides) + 1,
.dice = i,
};
rolls_len += 1;
}
}
c.igPopStyleColor(3);
if (i < dice.len - 1) {
c.igSameLine(0, -1);
}
c.igPopID();
}
c.igPopID();
{
var total: u32 = 0;
var i: usize = 0;
while (i < rolls_len) : (i += 1) {
total += rolls[i].roll;
}
var buf: [32]u8 = undefined;
_ = try std.fmt.bufPrint(buf[0..], "Total: {}", .{total});
c.igText(buf[0..]);
}
if (c.igButtonXY("Roll", 0, 0)) {
doRoll();
}
c.igEnd();
}
pub fn main() !void {
try initRandom();
rolls[0] = .{
.roll = 0,
.dice = 2,
};
rolls_len = 1;
doRoll();
_ = c.glfwSetErrorCallback(errorCallback);
if (c.glfwInit() == c.GL_FALSE) {
panic("GLFW init failure\n", .{});
}
defer c.glfwTerminate();
c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MAJOR, 3);
c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MINOR, 2);
c.glfwWindowHint(c.GLFW_OPENGL_FORWARD_COMPAT, c.GL_TRUE);
c.glfwWindowHint(c.GLFW_OPENGL_DEBUG_CONTEXT, debug_gl.is_on);
c.glfwWindowHint(c.GLFW_OPENGL_PROFILE, c.GLFW_OPENGL_CORE_PROFILE);
// c.glfwWindowHint(c.GLFW_DEPTH_BITS, 0);
// c.glfwWindowHint(c.GLFW_STENCIL_BITS, 8);
c.glfwWindowHint(c.GLFW_RESIZABLE, c.GL_TRUE);
const window_width = 640;
const window_height = 480;
const window = c.glfwCreateWindow(window_width, window_height, "ImGUI Test", null, null) orelse {
panic("unable to create window\n", .{});
};
defer c.glfwDestroyWindow(window);
c.glfwMakeContextCurrent(window);
c.glfwSwapInterval(1);
const context = c.igCreateContext(null);
defer c.igDestroyContext(context);
const io = c.igGetIO();
io.*.ConfigFlags |= c.ImGuiConfigFlags_NavEnableKeyboard;
// io.*.ConfigFlags |= @enumToInt(c.ImGuiConfigFlags_DockingEnable);
// io.*.ConfigFlags |= @enumToInt(c.ImGuiConfigFlags_ViewportsEnable);
const style = c.igGetStyle();
c.igStyleColorsDark(style);
// if (false and io.*.ConfigFlags & c.ImGuiConfigFlags_ViewportsEnable != 0) {
// style.*.WindowRounding = 0.0;
// style.*.Colors[c.ImGuiCol_WindowBg].w = 1.0;
// }
glfw_impl.Init(window, true, glfw_impl.ClientApi.OpenGL);
defer glfw_impl.Shutdown();
gl3_impl.Init(); // #version 150
defer gl3_impl.Shutdown();
const start_time = c.glfwGetTime();
var prev_time = start_time;
while (c.glfwWindowShouldClose(window) == c.GL_FALSE) {
c.glfwPollEvents();
try gl3_impl.NewFrame();
glfw_impl.NewFrame();
c.igNewFrame();
try render();
// main part
// c.igShowDemoWindow(null);
c.igRender();
var w: c_int = undefined;
var h: c_int = undefined;
c.glfwGetFramebufferSize(window, &w, &h);
c.glViewport(0, 0, w, h);
c.glClearColor(0.0, 0.0, 0.0, 0.0);
c.glClear(c.GL_COLOR_BUFFER_BIT);
gl3_impl.RenderDrawData(c.igGetDrawData());
// const now_time = c.glfwGetTime();
// const elapsed = now_time - prev_time;
// prev_time = now_time;
// nextFrame(t, elapsed);
// draw(t, @This());
c.glfwSwapBuffers(window);
}
} | examples/imgui-dice-roller/src/main_original.zig |
const math3d = @import("math3d.zig");
const Mat4x4 = math3d.Mat4x4;
const Vec3 = math3d.Vec3;
const Vec4 = math3d.Vec4;
const Tetris = @import("tetris.zig").Tetris;
const std = @import("std");
const assert = std.debug.assert;
const bufPrint = std.fmt.bufPrint;
const c = @import("c.zig");
const debug_gl = @import("debug_gl.zig");
const AllShaders = @import("all_shaders.zig").AllShaders;
const StaticGeometry = @import("static_geometry.zig").StaticGeometry;
const pieces = @import("pieces.zig");
const Piece = pieces.Piece;
const Spritesheet = @import("spritesheet.zig").Spritesheet;
var window: *c.GLFWwindow = undefined;
var all_shaders: AllShaders = undefined;
var static_geometry: StaticGeometry = undefined;
var font: Spritesheet = undefined;
fn errorCallback(err: c_int, description: [*c]const u8) callconv(.C) void {
_ = err;
_ = c.printf("Error: %s\n", description);
c.abort();
}
fn keyCallback(
win: ?*c.GLFWwindow,
key: c_int,
scancode: c_int,
action: c_int,
mods: c_int,
) callconv(.C) void {
_ = mods;
_ = scancode;
const t = @ptrCast(*Tetris, @alignCast(@alignOf(Tetris), c.glfwGetWindowUserPointer(win).?));
const first_delay = 0.2;
if (action == c.GLFW_PRESS) {
switch (key) {
c.GLFW_KEY_ESCAPE => c.glfwSetWindowShouldClose(win, c.GL_TRUE),
c.GLFW_KEY_SPACE => t.userDropCurPiece(),
c.GLFW_KEY_DOWN => {
t.down_key_held = true;
t.down_move_time = c.glfwGetTime() + first_delay;
t.userCurPieceFall();
},
c.GLFW_KEY_LEFT => {
t.left_key_held = true;
t.left_move_time = c.glfwGetTime() + first_delay;
t.userMoveCurPiece(-1);
},
c.GLFW_KEY_RIGHT => {
t.right_key_held = true;
t.right_move_time = c.glfwGetTime() + first_delay;
t.userMoveCurPiece(1);
},
c.GLFW_KEY_UP => t.userRotateCurPiece(1),
c.GLFW_KEY_LEFT_SHIFT, c.GLFW_KEY_RIGHT_SHIFT => t.userRotateCurPiece(-1),
c.GLFW_KEY_R => t.restartGame(),
c.GLFW_KEY_P => t.userTogglePause(),
c.GLFW_KEY_LEFT_CONTROL, c.GLFW_KEY_RIGHT_CONTROL => t.userSetHoldPiece(),
else => {},
}
} else if (action == c.GLFW_RELEASE) {
switch (key) {
c.GLFW_KEY_DOWN => {
t.down_key_held = false;
},
c.GLFW_KEY_LEFT => {
t.left_key_held = false;
},
c.GLFW_KEY_RIGHT => {
t.right_key_held = false;
},
else => {},
}
}
}
var tetris_state: Tetris = undefined;
const font_png = @embedFile("../assets/font.png");
pub fn main() void {
main2() catch c.abort();
}
pub fn main2() !void {
_ = c.glfwSetErrorCallback(errorCallback);
if (c.glfwInit() == c.GL_FALSE) @panic("GLFW init failure");
defer c.glfwTerminate();
c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MAJOR, 3);
c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MINOR, 2);
c.glfwWindowHint(c.GLFW_OPENGL_FORWARD_COMPAT, c.GL_TRUE);
c.glfwWindowHint(c.GLFW_OPENGL_DEBUG_CONTEXT, debug_gl.is_on);
c.glfwWindowHint(c.GLFW_OPENGL_PROFILE, c.GLFW_OPENGL_CORE_PROFILE);
c.glfwWindowHint(c.GLFW_DEPTH_BITS, 0);
c.glfwWindowHint(c.GLFW_STENCIL_BITS, 8);
c.glfwWindowHint(c.GLFW_RESIZABLE, c.GL_FALSE);
window = c.glfwCreateWindow(Tetris.window_width, Tetris.window_height, "Tetris", null, null) orelse
@panic("unable to create window");
defer c.glfwDestroyWindow(window);
_ = c.glfwSetKeyCallback(window, keyCallback);
c.glfwMakeContextCurrent(window);
c.glfwSwapInterval(1);
// create and bind exactly one vertex array per context and use
// glVertexAttribPointer etc every frame.
var vertex_array_object: c.GLuint = undefined;
c.glGenVertexArrays(1, &vertex_array_object);
c.glBindVertexArray(vertex_array_object);
defer c.glDeleteVertexArrays(1, &vertex_array_object);
const t = &tetris_state;
c.glfwGetFramebufferSize(window, &t.framebuffer_width, &t.framebuffer_height);
assert(t.framebuffer_width >= Tetris.window_width);
assert(t.framebuffer_height >= Tetris.window_height);
all_shaders = try AllShaders.create();
defer all_shaders.destroy();
static_geometry = StaticGeometry.create();
defer static_geometry.destroy();
font.init(font_png, Tetris.font_char_width, Tetris.font_char_height) catch @panic("unable to read assets");
defer font.deinit();
c.srand(@truncate(c_uint, @bitCast(c_ulong, c.time(null))));
t.resetProjection();
t.restartGame();
c.glClearColor(0.0, 0.0, 0.0, 1.0);
c.glEnable(c.GL_BLEND);
c.glBlendFunc(c.GL_SRC_ALPHA, c.GL_ONE_MINUS_SRC_ALPHA);
c.glPixelStorei(c.GL_UNPACK_ALIGNMENT, 1);
c.glViewport(0, 0, t.framebuffer_width, t.framebuffer_height);
c.glfwSetWindowUserPointer(window, @ptrCast(*anyopaque, t));
debug_gl.assertNoError();
const start_time = c.glfwGetTime();
var prev_time = start_time;
while (c.glfwWindowShouldClose(window) == c.GL_FALSE) {
c.glClear(c.GL_COLOR_BUFFER_BIT | c.GL_DEPTH_BUFFER_BIT | c.GL_STENCIL_BUFFER_BIT);
const now_time = c.glfwGetTime();
const elapsed = now_time - prev_time;
prev_time = now_time;
t.doBiosKeys(now_time);
t.nextFrame(elapsed);
t.draw(@This());
c.glfwSwapBuffers(window);
c.glfwPollEvents();
}
debug_gl.assertNoError();
}
pub fn fillRectMvp(color: Vec4, mvp: Mat4x4) void {
all_shaders.primitive.bind();
all_shaders.primitive.setUniformVec4(all_shaders.primitive_uniform_color, color);
all_shaders.primitive.setUniformMat4x4(all_shaders.primitive_uniform_mvp, mvp);
c.glBindBuffer(c.GL_ARRAY_BUFFER, static_geometry.rect_2d_vertex_buffer);
c.glEnableVertexAttribArray(@intCast(c.GLuint, all_shaders.primitive_attrib_position));
c.glVertexAttribPointer(@intCast(c.GLuint, all_shaders.primitive_attrib_position), 3, c.GL_FLOAT, c.GL_FALSE, 0, null);
c.glDrawArrays(c.GL_TRIANGLE_STRIP, 0, 4);
}
pub fn drawParticle(t: *Tetris, p: Tetris.Particle) void {
const model = Mat4x4.identity.translateByVec(p.pos).rotate(p.angle, p.axis).scale(p.scale_w, p.scale_h, 0.0);
const mvp = t.projection.mult(model);
all_shaders.primitive.bind();
all_shaders.primitive.setUniformVec4(all_shaders.primitive_uniform_color, p.color);
all_shaders.primitive.setUniformMat4x4(all_shaders.primitive_uniform_mvp, mvp);
c.glBindBuffer(c.GL_ARRAY_BUFFER, static_geometry.triangle_2d_vertex_buffer);
c.glEnableVertexAttribArray(@intCast(c.GLuint, all_shaders.primitive_attrib_position));
c.glVertexAttribPointer(@intCast(c.GLuint, all_shaders.primitive_attrib_position), 3, c.GL_FLOAT, c.GL_FALSE, 0, null);
c.glDrawArrays(c.GL_TRIANGLE_STRIP, 0, 3);
}
pub fn drawText(t: *Tetris, text: []const u8, left: i32, top: i32, size: f32) void {
for (text) |col, i| {
if (col <= '~') {
const char_left = @intToFloat(f32, left) + @intToFloat(f32, i * Tetris.font_char_width) * size;
const model = Mat4x4.identity.translate(char_left, @intToFloat(f32, top), 0.0).scale(size, size, 0.0);
const mvp = t.projection.mult(model);
font.draw(all_shaders, col, mvp);
} else {
unreachable;
}
}
} | benchmarks/tetris/tetris/src/main.zig |
const vec = @import("vec-simd.zig");
const Vec2 = vec.Vec2;
const Vec3 = vec.Vec3;
const Vec4 = vec.Vec4;
const IVec3 = vec.IVec3;
const IVec4 = vec.IVec4;
const UVec4 = vec.UVec4;
const BVec3 = vec.BVec3;
const BVec4 = vec.BVec4;
export fn addN2(a: *Vec2.T, n: f32) *Vec2.T {
a.* = Vec2.addN(a.*, n);
return a;
}
export fn addN3(a: *Vec3.T, n: f32) *Vec3.T {
a.* = Vec3.addN(a.*, n);
return a;
}
export fn addN4(a: *Vec4.T, n: f32) *Vec4.T {
a.* = Vec4.addN(a.*, n);
return a;
}
export fn divN3(a: *Vec3.T, n: f32) *Vec3.T {
a.* = Vec3.divN(a.*, n);
return a;
}
export fn divNI4(a: *IVec4.T, n: i32) *IVec4.T {
a.* = IVec4.divN(a.*, n);
return a;
}
export fn divNU4(a: *UVec4.T, n: u32) *UVec4.T {
a.* = UVec4.divN(a.*, n);
return a;
}
export fn dot3(a: *const Vec3.T, b: *const Vec3.T) f32 {
return Vec3.dot(a.*, b.*);
}
export fn normalize3(a: *Vec3.T) *Vec3.T {
a.* = Vec3.normalize(a.*);
return a;
}
export fn maddN3(a: *Vec3.T, b: *const Vec3.T, c: f32) *Vec3.T {
a.* = Vec3.maddN(a.*, b.*, c);
return a;
}
export fn cross3(a: *Vec3.T, b: *const Vec3.T) *Vec3.T {
a.* = Vec3.cross(a.*, b.*);
return a;
}
export fn orthoNormal3(a: *Vec3.T, b: *const Vec3.T, c: *const Vec3.T) *Vec3.T {
a.* = Vec3.orthoNormal(a.*, b.*, c.*);
return a;
}
export fn min3(a: *Vec3.T, b: *const Vec3.T) *Vec3.T {
a.* = Vec3.min(a.*, b.*);
return a;
}
export fn eqDelta3(a: *const Vec3.T, b: *const Vec3.T) bool {
return Vec3.allEqDelta(a.*, b.*, 1e-6);
}
export fn isZero3(a: *const Vec3.T) bool {
return Vec3.isZero(a.*);
}
export fn isZero3E(a: *const Vec3.T) bool {
return Vec3.allEqDelta(a.*, Vec3.ZERO, 1e-6);
}
export fn swizzle(a: *const IVec3.T, b: *IVec3.T) *IVec3.T {
b.* = IVec3.zzy(a.*);
return b;
}
export fn clamp3(a: *Vec3.T, b: *const Vec3.T, c: *const Vec3.T) *Vec3.T {
a.* = Vec3.clamp(a.*, b.*, c.*);
return a;
}
export fn clamp3_01(a: *Vec3.T) *Vec3.T {
a.* = Vec3.clamp01(a.*);
return a;
}
export fn pow3(a: *Vec3.T, b: *Vec3.T) *Vec3.T {
a.* = Vec3.pow(a.*, b.*);
return a;
}
export fn sin3(a: *Vec3.T) *Vec3.T {
a.* = Vec3.sin(a.*);
return a;
}
export fn tan3(a: *Vec3.T) *Vec3.T {
a.* = Vec3.tan(a.*);
return a;
}
export fn smoothStep3(e0: *Vec3.T, e1: *Vec3.T, a: *Vec3.T) *Vec3.T {
a.* = Vec3.smoothStep(e0.*, e1.*, a.*);
return a;
}
export fn reflect3(a: *Vec3.T, b: *Vec3.T) *Vec3.T {
a.* = Vec3.reflect(a.*, b.*);
return a;
}
export fn refract3(a: *Vec3.T, b: *Vec3.T, c: f32) *Vec3.T {
a.* = Vec3.refract(a.*, b.*, c);
return a;
}
export fn standardize3(a: *Vec3.T) *Vec3.T {
a.* = Vec3.standardize(a.*);
return a;
}
export fn mod3(a: *Vec3.T, b: *Vec3.T) *Vec3.T {
a.* = Vec3.mod(a.*, b.*);
return a;
}
export fn minComp3(a: *Vec3.T) f32 {
return Vec3.minComp(a.*);
}
export fn argmin3(a: *Vec3.T) u32 {
return Vec3.argmin(a.*);
}
export fn fromIVec3(a: *IVec3.T, b: *Vec3.T) *Vec3.T {
b.* = Vec3.fromIVec(IVec3.C, a.*);
return b;
}
export fn fromBVec4(a: *BVec4.T, b: *Vec4.T) *Vec4.T {
b.* = Vec4.fromBVec(a.*);
return b;
}
export fn and4(a: *IVec4.T, b: *IVec4.T) *IVec4.T {
a.* = IVec4._and(a.*, b.*);
return a;
}
export fn andB4(a: *BVec4.T, b: *BVec4.T) *BVec4.T {
a.* = BVec4._and(a.*, b.*);
return a;
}
export fn any3(a: *BVec3.T) bool {
return BVec3.any(a.*);
}
export fn centroid(a: [*]Vec4.T, num: u32) [*]Vec4.T {
const buf = a[0..num];
a[0] = Vec4.centroid(buf);
return a;
} | src/exports.zig |
const testing = @import("std").testing;
const math = @import("std").math;
pub const v4 = struct {
x: f32,
y: f32,
z: f32,
w: f32,
/// initializes a v4 with x, y, z and w
pub fn init(x: f32, y: f32, z: f32, w: f32) v4 {
return v4 {
.x = x,
.y = y,
.z = z,
.w = w,
};
}
/// returns the component from an index
pub fn at(v: v4, i: u16) f32 {
return switch (i) {
0 => v.x,
1 => v.y,
2 => v.z,
3 => v.w,
else => @panic("invalid index value provided when accessing a v4 index"),
};
}
/// sets the component from an index
pub fn set(v: *v4, i: u16, val: f32) void {
switch (i) {
0 => v.x = val,
1 => v.y = val,
2 => v.z = val,
3 => v.w = val,
else => @panic("invalid index value provided when accessing a v4 index"),
}
}
/// returns the x, y, z and w of the v4 as a [4]f32 array.
/// to be used to pass to other stuff like opengl.
pub fn arr(v: v4) [4]f32 {
return .{v.x, v.y, v.z, v.w};
}
/// returns the length/magnitude of the vector
pub fn len(v: v4) f32 {
var sum: f32 = 0;
sum += v.x * v.x;
sum += v.y * v.y;
sum += v.z * v.z;
sum += v.w * v.w;
return math.sqrt(sum);
}
/// returns the normalized vector
pub fn normalized(v: v4) v4 {
const l = v.len();
if (l == 0) {
return v4.init(0, 0, 0, 0);
}
return divs(v, l);
}
/// returns the dot product of two v4
pub fn dot(a: v4, b: v4) f32 {
var res: f32 = 0;
res += a.x * b.x;
res += a.y * b.y;
res += a.z * b.z;
res += a.w * b.w;
return res;
}
/// returns the negated vector
pub fn neg(v: v4) v4 {
return v4.init(-v.x, -v.y, -v.z, -v.w);
}
/// divides the v4 with a scalar
pub fn divs(v: v4, s: f32) v4 {
return v4.init(v.x / s, v.y / s, v.z / s, v.w / s);
}
/// multiplies the v4 with a scalar
pub fn muls(v: v4, s: f32) v4 {
return v4.init(v.x * s, v.y * s, v.z * s, v.w * s);
}
/// sums the v4 with a scalar
pub fn sums(v: v4, s: f32) v4 {
return v4.init(v.x + s, v.y + s, v.z + s, v.w + s);
}
/// subtracts the v4 from a scalar
pub fn subs(v: v4, s: f32) v4 {
return v4.init(v.x - s, v.y - s, v.z - s, v.w - s);
}
/// sums the v4 with another v4
pub fn sumv(a: v4, b: v4) v4 {
return v4.init(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w);
}
/// subtracts the v4 from another v4
pub fn subv(a: v4, b: v4) v4 {
return v4.init(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w);
}
};
test "creating a v4" {
const x = v4.init(4, 8, 2, 6);
testing.expect(x.x == 4);
testing.expect(x.y == 8);
testing.expect(x.z == 2);
testing.expect(x.w == 6);
testing.expect(x.at(0) == 4);
testing.expect(x.at(1) == 8);
testing.expect(x.at(2) == 2);
testing.expect(x.at(3) == 6);
testing.expect(x.arr()[0] == 4);
testing.expect(x.arr()[1] == 8);
testing.expect(x.arr()[2] == 2);
testing.expect(x.arr()[3] == 6);
}
test "v4 length" {
const x = v4.init(4, 8, 2, 6);
testing.expect(math.approxEq(f32, x.len(), 10.95445115010332226914, math.f32_epsilon));
}
test "v4 operation" {
const x = v4.init(4, 8, 2, 6);
const y = v4.init(1, 3, 5, 7);
var res = v4.divs(x, 2);
testing.expect(res.x == 2);
testing.expect(res.y == 4);
testing.expect(res.z == 1);
testing.expect(res.w == 3);
res = v4.muls(x, 2);
testing.expect(res.x == 8);
testing.expect(res.y == 16);
testing.expect(res.z == 4);
testing.expect(res.w == 12);
res = v4.neg(x);
testing.expect(res.x == -4);
testing.expect(res.y == -8);
testing.expect(res.z == -2);
testing.expect(res.w == -6);
res = v4.sums(x, 2);
testing.expect(res.x == 6);
testing.expect(res.y == 10);
testing.expect(res.z == 4);
testing.expect(res.w == 8);
res = v4.subs(x, 2);
testing.expect(res.x == 2);
testing.expect(res.y == 6);
testing.expect(res.z == 0);
testing.expect(res.w == 4);
res = v4.sumv(x, y);
testing.expect(res.x == 5);
testing.expect(res.y == 11);
testing.expect(res.z == 7);
testing.expect(res.w == 13);
res = v4.subv(x, y);
testing.expect(res.x == 3);
testing.expect(res.y == 5);
testing.expect(res.z == -3);
testing.expect(res.w == -1);
}
test "v4 normalized" {
const a = v4.init(4, 8, 2, 6);
const x = v4.normalized(a);
testing.expect(math.approxEq(f32, x.x, 0.3651483716701107423, math.f32_epsilon));
testing.expect(math.approxEq(f32, x.y, 0.73029674334022148461, math.f32_epsilon));
testing.expect(math.approxEq(f32, x.z, 0.18257418583505537115, math.f32_epsilon));
testing.expect(math.approxEq(f32, x.w, 0.54772255750516611346, math.f32_epsilon));
}
test "v4 dot" {
const x = v4.init(4, 8, 2, 6);
const y = v4.init(1, 3, 5, 7);
const res = v4.dot(x, y);
testing.expect(res == 80);
} | src/vector4.zig |
const std = @import("std");
const json = std.json;
const magic = "i3-ipc";
pub const I3ipc = struct {
const Self = @This();
conn: std.net.Stream,
sock_path: ?[]const u8,
allocator: std.mem.Allocator,
pub fn init(sock_path: ?[]const u8, allocator: std.mem.Allocator) !I3ipc {
var path: []const u8 = undefined;
if (sock_path) |_| {
path = sock_path.?;
} else {
path = std.os.getenv("I3SOCK").?;
}
var sock = try std.net.connectUnixSocket(path);
return I3ipc{ .conn = sock, .sock_path = path, .allocator = allocator };
}
pub fn send_msg(self: *Self, msg_type: I3_Cmd, payload: ?[]const u8) !void {
//NOTE(kotto): std.mem.asBytes seems to be buggy according to ifreund on irc.
// the code would look like this:
// ```code zig
// const std = @import("std");
//
// const I3IpcHeader = packed struct { magic: [6]u8 = "i3-ipc".*, len: u32, type: u32 };
// pub fn main() anyerror!void {
// var sock_path = std.os.getenv("I3SOCK").?;
// var sock = try std.net.connectUnixSocket(sock_path);
// const msg = "workspace 3";
// var header = I3IpcHeader{ .len = msg.len, .type = 0 };
// _ = try sock.write(std.mem.asBytes(&header));
// _ = try sock.write(msg);
// }
// ```
const msg_len = magic.len + @sizeOf(@TypeOf(msg_type)) + 4 + if (payload) |p| p.len else 0;
// TODO: It might be better to just use a buf in the stack since, most
// of the time, only the GET_* commands should be used?
var msg = try self.allocator.alloc(u8, msg_len);
defer self.allocator.free(msg);
switch (msg_type) {
.RUN_COMMAND, .SEND_TICK, .SUBSCRIBE, .SYNC => {
std.mem.copy(u8, msg, magic);
// NOTE: i3-ipc uses the host endiannes
std.debug.assert(payload != null);
std.mem.writeIntNative(u32, msg[magic.len .. magic.len + 4], @intCast(u32, payload.?.len));
std.mem.writeIntNative(u32, msg[magic.len + 4 .. magic.len + 8], @enumToInt(msg_type));
std.mem.copy(u8, msg[magic.len + 8 ..], payload.?);
},
.GET_WORKSPACES, .GET_OUTPUTS, .GET_TREE, .GET_MARKS, .GET_BAR_CONFIG, .GET_VERSION, .GET_BINDING_MODES, .GET_CONFIG, .GET_BINDING_STATE => {
std.mem.copy(u8, msg, magic);
// NOTE: i3-ipc uses the host endiannes
std.mem.writeIntNative(u32, msg[magic.len .. magic.len + 4], 0);
std.mem.writeIntNative(u32, msg[magic.len + 4 .. magic.len + 8], @enumToInt(msg_type));
},
}
_ = try self.conn.write(msg);
}
pub fn get_msg(self: *Self) !I3_reply {
@setEvalBranchQuota(100000);
// magic len + 4bytes cmd payload len + 4bytes cmd type
var header: [magic.len + 8]u8 = undefined;
_ = try self.conn.read(&header);
// NOTE: if the magic change, than it means breacking changes happened and this lib is not aware of that!
std.debug.assert(std.mem.eql(u8, magic, header[0..magic.len]));
const len = std.mem.readIntSliceNative(u32, header[magic.len .. magic.len + 4]);
const cmd = @intToEnum(I3_reply_type, std.mem.readIntSliceNative(u32, header[magic.len + 4 .. magic.len + 8]));
const data = try self.allocator.alloc(u8, len);
defer self.allocator.free(data);
var payload_read = try self.conn.read(data);
while (payload_read < data.len) payload_read += try self.conn.read(data[payload_read..]);
switch (cmd) {
// NOTE: Using I3_reply.* so that Neovim/ZLS(?) can resolve references/declaration
I3_reply.I3_cmd => { // COMMAND | Run the payload as an i3 command (like the commands you can bind to keys).
var stream = json.TokenStream.init(data[0..]);
return I3_reply{ .I3_cmd = json.parse([]I3_Cmd_reply, &stream, .{ .allocator = self.allocator }) catch |err| {
std.log.err("ERROR: {}\n{s}", .{ err, data });
return err;
} };
},
I3_reply.I3_get_workspace => { // WORKSPACES | Get the list of current workspaces.
var stream2 = json.TokenStream.init(data[0..]);
return I3_reply{
.I3_get_workspace = json.parse([]I3_Get_Workspace_reply, &stream2, .{
.allocator = self.allocator, //.ignore_unknown_fields = true,
}) catch |err| {
std.log.err("ERROR: {}\n{s}", .{ err, data });
return err;
},
};
},
I3_reply.I3_subscribe => { // SUBSCRIBE | Subscribe this IPC connection to the event types specified in the message payload. See [events].
var stream2 = json.TokenStream.init(data[0..]);
return I3_reply{
.I3_subscribe = json.parse(I3_Subscribe_reply, &stream2, .{
.allocator = self.allocator, //.ignore_unknown_fields = true,
}) catch |err| {
std.log.err("ERROR: {}\n{s}", .{ err, data });
return err;
},
};
},
I3_reply.I3_get_output => { // OUTPUTS | Get the list of current outputs.
var stream2 = json.TokenStream.init(data[0..]);
return I3_reply{
.I3_get_output = json.parse([]I3_Get_Output_reply, &stream2, .{
.allocator = self.allocator, //.ignore_unknown_fields = true
}) catch |err| {
std.log.err("ERROR: {}\n{s}", .{ err, data });
return err;
},
};
},
I3_reply.I3_get_tree => { // TREE | Get the i3 layout tree.
var stream2 = json.TokenStream.init(data[0..]);
return I3_reply{
.I3_get_tree = json.parse([]I3_Tree_Node, &stream2, .{
.allocator = self.allocator, //.ignore_unknown_fields = true,
}) catch |err| {
std.log.err("ERROR: {}\n{s}", .{ err, data });
return err;
},
};
},
I3_reply.I3_get_mark => { // MARKS | Gets the names of all currently set marks.
var stream2 = json.TokenStream.init(data[0..]);
return I3_reply{
.I3_get_mark = json.parse([]I3_Get_Mark_reply, &stream2, .{
.allocator = self.allocator, //.ignore_unknown_fields = true,
}) catch |err| {
std.log.err("ERROR: {}\n{s}", .{ err, data });
return err;
},
};
},
I3_reply.I3_get_bar_config => { // BAR_CONFIG | Gets the specified bar configuration or the names of all bar configurations if payload is empty.
var stream2 = json.TokenStream.init(data[0..]);
return I3_reply{
.I3_get_bar_config = json.parse([]I3_Get_Bar_config_reply, &stream2, .{
.allocator = self.allocator, //.ignore_unknown_fields = true,
}) catch |err| {
std.log.err("ERROR: {}\n{s}", .{ err, data });
return err;
},
};
},
I3_reply.I3_get_version => { // VERSION | Gets the i3 version.
var stream2 = json.TokenStream.init(data[0..]);
return I3_reply{
.I3_get_version = json.parse(I3_Get_Version_reply, &stream2, .{
.allocator = self.allocator, //.ignore_unknown_fields = true,
}) catch |err| {
std.log.err("ERROR: {}\n{s}", .{ err, data });
return err;
},
};
},
I3_reply.I3_get_binding_modes => { // BINDING_MODES | Gets the names of all currently configured binding modes.
var stream2 = json.TokenStream.init(data[0..]);
return I3_reply{
.I3_get_binding_modes = json.parse(I3_Get_Binding_modes_reply, &stream2, .{
.allocator = self.allocator, //.ignore_unknown_fields = true,
}) catch |err| {
std.log.err("ERROR: {}\n{s}", .{ err, data });
return err;
},
};
},
I3_reply.I3_get_config => { // CONFIG | Returns the last loaded i3 config.
var stream2 = json.TokenStream.init(data[0..]);
return I3_reply{
.I3_get_config = json.parse(I3_Get_Config_reply, &stream2, .{
.allocator = self.allocator, //.ignore_unknown_fields = true,
}) catch |err| {
std.log.err("ERROR: {}\n{s}", .{ err, data });
return err;
},
};
},
I3_reply.I3_tick => { // TICK | Sends a tick event with the specified payload.
var stream2 = json.TokenStream.init(data[0..]);
return I3_reply{
.I3_tick = json.parse(I3_Tick_reply, &stream2, .{
.allocator = self.allocator, //.ignore_unknown_fields = true,
}) catch |err| {
std.log.err("ERROR: {}\n{s}", .{ err, data });
return err;
},
};
},
I3_reply.I3_sync => { // SYNC | Sends an i3 sync event with the specified random value to the specified window.
var stream2 = json.TokenStream.init(data[0..]);
return I3_reply{
.I3_sync = json.parse(I3_Sync_reply, &stream2, .{
.allocator = self.allocator, //.ignore_unknown_fields = true,
}) catch |err| {
std.log.err("ERROR: {}\n{s}", .{ err, data });
return err;
},
};
},
I3_reply.I3_get_binding_state => { //INDING_STATE | Request the current binding state, i.e. the currently active binding mode name.
var stream2 = json.TokenStream.init(data[0..]);
return I3_reply{
.I3_get_binding_state = json.parse(I3_Get_Binding_state_reply, &stream2, .{
.allocator = self.allocator, //.ignore_unknown_fields = true,
}) catch |err| {
std.log.err("ERROR: {}\n{s}", .{ err, data });
return err;
},
};
},
I3_reply.I3_event_workspace => {
var stream2 = json.TokenStream.init(data);
var rj = json.parse(I3_Event_Workspace, &stream2, .{
.allocator = self.allocator,
//.ignore_unknown_fields = true, //NOTE: It seems like some fields are undecumented?
}) catch |err| {
std.log.err("ERROR: {}\n{s}\n", .{ err, data });
return err;
};
return I3_reply{ .I3_event_workspace = rj };
},
I3_reply.I3_event_mode => {
var stream2 = json.TokenStream.init(data[0..]);
return I3_reply{
.I3_event_mode = json.parse(I3_Event_Mode, &stream2, .{
.allocator = self.allocator, //.ignore_unknown_fields = false,
}) catch |err| {
std.log.err("ERROR: {}\n{s}", .{ err, data });
return err;
},
};
},
I3_reply.I3_event_output => {
var stream2 = json.TokenStream.init(data[0..]);
return I3_reply{
.I3_event_mode = json.parse(I3_Event_Mode, &stream2, .{
.allocator = self.allocator, //.ignore_unknown_fields = false,
}) catch |err| {
std.log.err("ERROR: {}\n{s}", .{ err, data });
return err;
},
};
},
I3_reply.I3_event_window => {
var stream2 = json.TokenStream.init(data[0..]);
return I3_reply{
.I3_event_window = json.parse(I3_Event_Window, &stream2, .{
.allocator = self.allocator, //.ignore_unknown_fields = false,
}) catch |err| {
std.log.err("ERROR: {}\n{s}", .{ err, data });
return err;
},
};
},
I3_reply.I3_event_barconfig_update => {
var stream2 = json.TokenStream.init(data[0..]);
return I3_reply{
.I3_event_window = json.parse(I3_Event_Window, &stream2, .{
.allocator = self.allocator, //.ignore_unknown_fields = false,
}) catch |err| {
std.log.err("ERROR: {}\n{s}", .{ err, data });
return err;
},
};
},
I3_reply.I3_event_binding => {
var stream2 = json.TokenStream.init(data[0..]);
return I3_reply{
.I3_event_mode = json.parse(I3_Event_Mode, &stream2, .{
.allocator = self.allocator, //.ignore_unknown_fields = false,
}) catch |err| {
std.log.err("ERROR: {}\n{s}", .{ err, data });
return err;
},
};
},
I3_reply.I3_event_shutdown => {
var stream2 = json.TokenStream.init(data[0..]);
return I3_reply{
.I3_event_mode = json.parse(I3_Event_Mode, &stream2, .{
.allocator = self.allocator, //.ignore_unknown_fields = false,
}) catch |err| {
std.log.err("ERROR: {}\n{s}", .{ err, data });
return err;
},
};
},
I3_reply.I3_event_tick => {
var stream2 = json.TokenStream.init(data[0..]);
return I3_reply{
.I3_event_mode = json.parse(I3_Event_Mode, &stream2, .{
.allocator = self.allocator, //.ignore_unknown_fields = false,
}) catch |err| {
std.log.err("ERROR: {}\n{s}", .{ err, data });
return err;
},
};
},
}
return error.invalidMsgType;
}
};
pub const Error = error{
invalidMsgType,
};
pub const I3_Cmd = enum(u32) { // i3 ipc uses 4 bytes for the cmd/subscribe events type
// Type | Reply type | Purpose
RUN_COMMAND = 0, // | COMMAND | Run the payload as an i3 command (like the commands you can bind to keys).
GET_WORKSPACES = 1, // | WORKSPACES | Get the list of current workspaces.
SUBSCRIBE = 2, // | SUBSCRIBE | Subscribe this IPC connection to the event types specified in the message payload. See [events].
GET_OUTPUTS = 3, // | OUTPUTS | Get the list of current outputs.
GET_TREE = 4, // | TREE | Get the i3 layout tree.
GET_MARKS = 5, // | MARKS | Gets the names of all currently set marks.
GET_BAR_CONFIG = 6, // | BAR_CONFIG | Gets the specified bar configuration or the names of all bar configurations if payload is empty.
GET_VERSION = 7, // | VERSION | Gets the i3 version.
GET_BINDING_MODES = 8, // | BINDING_MODES | Gets the names of all currently configured binding modes.
GET_CONFIG = 9, // | CONFIG | Returns the last loaded i3 config.
SEND_TICK = 10, // | TICK | Sends a tick event with the specified payload.
SYNC = 11, // | SYNC | Sends an i3 sync event with the specified random value to the specified window.
GET_BINDING_STATE = 12, //| BINDING_STATE | Request the current binding state, i.e. the currently active binding mode name.
};
pub const I3_msg = struct {
magic: [magic.len]u8 = magic.*,
len: u32,
cmd: I3_Cmd_reply,
data: ?[]u8,
};
pub const I3_reply_type = enum(u32) {
I3_cmd = @enumToInt(I3_Cmd.RUN_COMMAND),
I3_get_workspace = @enumToInt(I3_Cmd.GET_WORKSPACES),
I3_subscribe = @enumToInt(I3_Cmd.SUBSCRIBE),
I3_get_output = @enumToInt(I3_Cmd.GET_OUTPUTS),
I3_get_tree = @enumToInt(I3_Cmd.GET_TREE),
I3_get_mark = @enumToInt(I3_Cmd.GET_MARKS),
I3_get_bar_config = @enumToInt(I3_Cmd.GET_BAR_CONFIG),
I3_get_version = @enumToInt(I3_Cmd.GET_VERSION),
I3_get_binding_modes = @enumToInt(I3_Cmd.GET_BINDING_MODES),
I3_get_config = @enumToInt(I3_Cmd.GET_CONFIG),
I3_tick = @enumToInt(I3_Cmd.SEND_TICK),
I3_sync = @enumToInt(I3_Cmd.SYNC),
I3_get_binding_state = @enumToInt(I3_Cmd.GET_BINDING_STATE),
I3_event_workspace = (1 << (@bitSizeOf(u32) - 1)) | 0,
I3_event_output = (1 << (@bitSizeOf(u32) - 1)) | 1,
I3_event_mode = (1 << (@bitSizeOf(u32) - 1)) | 2,
I3_event_window = (1 << (@bitSizeOf(u32) - 1)) | 3,
I3_event_barconfig_update = (1 << (@bitSizeOf(u32) - 1)) | 4,
I3_event_binding = (1 << (@bitSizeOf(u32) - 1)) | 5,
I3_event_shutdown = (1 << (@bitSizeOf(u32) - 1)) | 6,
I3_event_tick = (1 << (@bitSizeOf(u32) - 1)) | 7,
};
pub const I3_reply = union(I3_reply_type) {
/// Run the payload as an i3 command (like the commands you can bind to keys).
I3_cmd: []I3_Cmd_reply,
/// Get the list of current active workspaces.
I3_get_workspace: []I3_Get_Workspace_reply,
/// Subscribe this IPC connection to the event types specified in the message payload. See [events].
I3_subscribe: I3_Subscribe_reply,
/// Get the list of current outputs.
I3_get_output: []I3_Get_Output_reply,
/// Get the i3 layout tree.
I3_get_tree: []I3_Tree_Node, //TODO: check if this should use I3_tree or I3_Tree_Node.
/// Gets the names of all currently set marks.
I3_get_mark: []I3_Get_Mark_reply,
/// Gets the specified bar configuration or the names of all bar configurations if payload is empty.
I3_get_bar_config: []I3_Get_Bar_config_reply,
/// Gets the i3 version.
I3_get_version: I3_Get_Version_reply,
/// Gets the names of all currently configured binding modes.
I3_get_binding_modes: I3_Get_Binding_modes_reply,
/// Returns the last loaded i3 config.
I3_get_config: I3_Get_Config_reply,
/// Sends a tick event with the specified payload.
I3_tick: I3_Tick_reply,
/// Sends an i3 sync event with the specified random value to the specified window.
I3_sync: I3_Sync_reply,
/// Get the current binding state, i.e. the currently active binding mode name("default", "menu", "resize").
I3_get_binding_state: I3_Get_Binding_state_reply,
/// Sent when the user switches to a different workspace, when a new workspace is initialized or when a workspace is removed (because the last client vanished).
I3_event_workspace: I3_Event_Workspace,
/// Sent when RandR issues a change notification (of either screens, outputs, CRTCs or output properties).
// NOTE: currently EVENT_OUTPUT event does not output anything useful. it just return:
// { "change": "unspecified" }
I3_event_output: I3_Event_Output,
/// Sent whenever i3 changes its binding mode. Ex: "menu", "resize", "default"
I3_event_mode: I3_Event_Mode,
/// Sent when a client’s window is successfully reparented (that is when i3 has finished fitting it into a container), when a window received input focus or when certain properties of the window have changed.
//5.6. window event
// This event consists of a single serialized map containing a property
// change (string) which indicates the type of the change
// - new – the window has become managed by i3
// - close – the window has closed
// - focus – the window has received input focus
// - title – the window’s title has changed
// - fullscreen_mode – the window has entered or exited fullscreen mode
// - move – the window has changed its position in the tree
// - floating – the window has transitioned to or from floating
// - urgent – the window has become urgent or lost its urgent status
// - mark – a mark has been added to or removed from the window
// Additionally a container (object) field will be present, which consists of the window’s parent container. Be aware that for the "new" event, the container will hold the initial name of the newly reparented window (e.g. if you run urxvt with a shell that changes the title, you will still at this point get the window title as "urxvt").
I3_event_window: I3_Event_Window,
// Sent when the hidden_state or mode field in the barconfig of any bar instance was updated and when the config is reloaded.
/// This event consists of a single serialized map reporting on options from the barconfig of the specified bar_id that were updated in i3. This event is the same as a GET_BAR_CONFIG reply for the bar with the given id.
I3_event_barconfig_update: I3_event_barconfig_update,
// Sent when a configured command binding is triggered with the keyboard or mouse
/// This event consists of a single serialized map reporting on the details of a binding that ran a command because of user input. The change (string) field indicates what sort of binding event was triggered (right now it will always be "run" but may be expanded in the future).
/// The binding (object) field contains details about the binding that was run:
/// - command (string)
/// The i3 command that is configured to run for this binding.
/// - event_state_mask (array of strings)
/// The group and modifier keys that were configured with this binding.
/// - input_code (integer)
/// If the binding was configured with bindcode, this will be the key code that was given for the binding. If the binding is a mouse binding, it will be the number of the mouse button that was pressed. Otherwise it will be 0.
/// - symbol (string or null)
/// If this is a keyboard binding that was configured with bindsym, this field will contain the given symbol. Otherwise it will be null.
/// - input_type (string)
/// This will be "keyboard" or "mouse" depending on whether or not this was a keyboard or a mouse binding.
I3_event_binding: I3_event_binding,
// Sent when the ipc shuts down because of a restart or exit by user command
/// This event is triggered when the connection to the ipc is about to shutdown because of a user action such as a restart or exit command. The change (string) field indicates why the ipc is shutting down. It can be either "restart" or "exit".
I3_event_shutdown: I3_event_shutdown,
// Sent when the ipc client subscribes to the tick event (with "first": true) or when any ipc client sends a SEND_TICK message (with "first": false).
/// This event is triggered by a subscription to tick events or by a SEND_TICK message.
/// Example (upon subscription):
/// ```json
/// {
/// "first": true,
/// "payload": ""
/// }
/// ```
/// Example (upon SEND_TICK with a payload of arbitrary string):
/// ```json
/// {
/// "first": false,
/// "payload": "arbitrary string"
/// }
/// ```
I3_event_tick: I3_event_tick,
};
pub const I3_Cmd_reply = []struct { success: bool, parse_error: bool = false };
pub const I3_Get_Workspace_reply = struct {
id: u64,
num: i32,
name: ?[]u8,
visible: bool,
focused: bool,
rect: Rect,
output: ?[]u8,
urgent: bool,
};
const Rect = struct {
x: u32,
y: u32,
width: u32,
height: u32,
};
pub const I3_Get_Output_reply = struct {
/// name (string)
/// The name of this output (as seen in xrandr(1)). Encoded in UTF-8.
name: []u8,
/// active (boolean)
/// Whether this output is currently active (has a valid mode).
active: bool,
/// primary (boolean)
/// Whether this output is currently the primary output.
primary: bool,
/// current_workspace (string or null)
/// The name of the current workspace that is visible on this output. null if the output is not active.
current_workspace: ?[]u8,
/// rect (map)
/// The rectangle of this output (equals the rect of the output it is on), consists of x, y, width, height.
rect: Rect,
}; // | OUTPUTS | Get the list of current outputs.
pub const X11_WinProps = struct {
class: ?[]u8 = null,
instance: ?[]u8 = null,
window_role: ?[]u8 = null,
machine: ?[]u8 = null,
title: ?[]u8 = null,
// NOTE: It seems like this thing is an interger(not sure if uint).
transient_for: ?i32 = null, // TODO: check what this is used for.
};
/// The list of current outputs.
/// The reply consists of a serialized list of outputs. Each output has the following properties:
pub const I3_Tree = struct {
// The reply consists of a serialized tree. Each node in the tree (representing one container) has at least the properties listed below. While the nodes might have more properties, please do not use any properties which are not documented here. They are not yet finalized and will probably change!
nodes: *I3_Tree_Node,
};
pub const I3_Subscribe_reply = struct { success: bool }; // | SUBSCRIBE | Subscribe this IPC connection to the event types specified in the message payload. See [events].
/// i3 Eventsvs
pub const I3_Event_Workspace = struct {
/// change ("focus", "init", "empty", "urgent", "reload", "rename", "restored", "move")
change: []u8,
///A current (object) property will be present with the affected workspace whenever the type of event affects a workspace (otherwise, it will be null).
current: ?I3_Workspace_container,
//When the change is "focus", an old (object) property will be present with the previous workspace. When the first switch occurs (when i3 focuses the workspace visible at the beginning) there is no previous workspace, and the old property will be set to null. Also note that if the previous is empty it will get destroyed when switching, but will still be present in the "old" property.
old: ?I3_Workspace_container,
};
///NOTE: Very similar to the `I3_Tree_Node`, Just a feel things differents.
///It comes from the subscribe event of workspace changes.
pub const I3_Workspace_container = struct {
id: u64, //TODO: this might be platform dependent. check this.
// since this is a pointer to the container/windows/whatever.
type: ?[]u8 = null,
orientation: []u8,
scratchpad_state: []u8,
percent: ?f32,
urgent: bool,
marks: [][]u8,
focused: bool,
output: []u8,
layout: []u8,
workspace_layout: []u8,
last_split_layout: []u8,
border: []u8,
current_border_width: i32,
rect: Rect,
deco_rect: Rect,
window_rect: Rect,
geometry: Rect,
name: ?[]u8,
window_icon_padding: i32,
num: i32 = -1,
window: ?u32,
window_type: ?[]u8,
nodes: ?[]I3_Workspace_container,
floating_nodes: ?[]I3_Workspace_container,
focus: []u64,
fullscreen_mode: u3,
sticky: bool,
floating: []u8,
swallows: ?[]u8, //TODO: Figure out what this is supposed to be
window_properties: ?X11_WinProps = null, //for window events.
};
pub const I3_Event_Mode = struct {
change: []u8,
pango_markup: bool,
};
pub const I3_Event_Window = struct {
change: []u8,
container: I3_Workspace_container,
};
pub const I3_Event_Output = struct {
//TODO: Not implemented yet.
this: bool,
};
pub const I3_event_barconfig_update = struct {
//TODO: Not implemented yet.
this: bool,
};
pub const I3_event_binding = struct {
//TODO: Not implemented yet.
this: bool,
};
pub const I3_event_shutdown = struct {
change: []u8,
};
pub const I3_event_tick = struct {
//TODO: Not implemented yet.
this: bool,
};
pub const I3_Tree_Node = struct {
// id (integer)
// The internal ID (actually a C pointer value) of this container. Do not make any assumptions about it. You can use it to (re-)identify and address containers when talking to i3.
id: u64,
// name (string)
// The internal name of this container. For all containers which are part of the tree structure down to the workspace contents, this is set to a nice human-readable name of the container. For containers that have an X11 window, the content is the title (_NET_WM_NAME property) of that window. For all other containers, the content is not defined (yet).
name: []u8,
//num (integer) undocumented
//num: u32,
// type (string)
// Type of this container. Can be one of "root", "output", "con", "floating_con", "workspace" or "dockarea".
type: []u8,
// border (string)
// Can be either "normal", "none" or "pixel", depending on the container’s border style.
border: []u8,
// current_border_width (integer)
// Number of pixels of the border width.
current_border_width: i32,
// layout (string)
// Can be either "splith", "splitv", "stacked", "tabbed", "dockarea" or "output". Other values might be possible in the future, should we add new layouts.
layout: []u8,
last_split_layout: ?[]u8 = null,
workspace_layout: ?[]u8 = null,
// orientation (string)
// Can be either "none" (for non-split containers), "horizontal" or "vertical". THIS FIELD IS OBSOLETE. It is still present, but your code should not use it. Instead, rely on the layout field.
orientation: []u8,
// percent (float or null)
// The percentage which this container takes in its parent. A value of null means that the percent property does not make sense for this container, for example for the root container.
percent: ?f32,
// rect (map)
// The absolute display coordinates for this container. Display coordinates means that when you have two 1600x1200 monitors on a single X11 Display (the standard way), the coordinates of the first window on the second monitor are { "x": 1600, "y": 0, "width": 1600, "height": 1200 }.
rect: Rect,
// window_rect (map)
// The coordinates of the actual client window inside its container. These coordinates are relative to the container and do not include the window decoration (which is actually rendered on the parent container). So, when using the default layout, you will have a 2 pixel border on each side, making the window_rect { "x": 2, "y": 0, "width": 632, "height": 366 } (for example).
window_rect: Rect,
// deco_rect (map)
// The coordinates of the window decoration inside its container. These coordinates are relative to the container and do not include the actual client window.
deco_rect: Rect,
// geometry (map)
// The original geometry the window specified when i3 mapped it. Used when switching a window to floating mode, for example.
geometry: Rect,
// window (integer or null)
// The X11 window ID of the actual client window inside this container. This field is set to null for split containers or otherwise empty containers. This ID corresponds to what xwininfo(1) and other X11-related tools display (usually in hex).
window: ?u32,
// window_properties (map)
// This optional field contains all available X11 window properties from the following list: title, instance, class, window_role, machine and transient_for.
// NOTE: It seems like some windows have some properties missing. Set default values so the json can parse it fine.
window_properties: ?X11_WinProps = null,
// window_type (string)
// The window type (_NET_WM_WINDOW_TYPE). Possible values are undefined, normal, dialog, utility, toolbar, splash, menu, dropdown_menu, popup_menu, tooltip and notification.
window_type: ?[]u8,
//window_icon_padding (integer) undocmented
window_icon_padding: i32 = -1,
// urgent (bool)
// Whether this container (window, split container, floating container or workspace) has the urgency hint set, directly or indirectly. All parent containers up until the workspace container will be marked urgent if they have at least one urgent child.
urgent: bool,
// marks (array of string)
// List of marks assigned to container
marks: [][]u8,
// focused (bool)
// Whether this container is currently focused.
focused: bool,
// focus (array of integer)
// List of child node IDs (see nodes, floating_nodes and id) in focus order. Traversing the tree by following the first entry in this array will result in eventually reaching the one node with focused set to true.
focus: []u64, //NOTE: sizeOf pointer… maybe handle it better?
// fullscreen_mode (integer)
// Whether this container is in fullscreen state or not. Possible values are 0 (no fullscreen), 1 (fullscreened on output) or 2 (fullscreened globally). Note that all workspaces are considered fullscreened on their respective output.
fullscreen_mode: u3,
// floating (string)
// Floating state of container. Can be either "auto_on", "auto_off", "user_on" or "user_off"
floating: []u8,
// nodes (array of node)
/// The tiling (i.e. non-floating) child containers of this node.
nodes: ?[]I3_Tree_Node,
// floating_nodes (array of node)
/// The floating child containers of this node. Only non-empty on nodes with type workspace.
floating_nodes: ?[]I3_Tree_Node,
// scratchpad_state (string)
/// Whether the window is not in the scratchpad ("none"), freshly moved to the scratchpad but not yet resized ("fresh") or moved to the scratchpad and resized ("changed").
scratchpad_state: []u8,
swallows: ?[]u8 = null,
};
pub const I3_Get_Mark_reply = struct {
///TODO{kotto}: Not implemented
succes: bool,
}; // | MARKS | Gets the names of all currently set marks.
pub const I3_Get_Bar_config_reply = struct {
///TODO{kotto}: Not implemented
succes: bool,
}; // | BAR_CONFIG | Gets the specified bar configuration or the names of all bar configurations if payload is empty.
pub const I3_Get_Version_reply = struct {
///TODO{kotto}: Not implemented
succes: bool,
}; // | VERSION | Gets the i3 version.
pub const I3_Get_Binding_modes_reply = [][]u8; // | BINDING_MODES | Gets the names of all currently configured binding modes.
pub const I3_Get_Config_reply = struct {
///TODO{kotto}: Not implemented
succes: bool,
}; // | CONFIG | Returns the last loaded i3 config.
pub const I3_Tick_reply = struct {
///TODO{kotto}: Not implemented
succes: bool,
}; // | TICK | Sends a tick event with the specified payload.
pub const I3_Sync_reply = struct {
///TODO{kotto}: Not implemented
succes: bool,
}; // | SYNC | Sends an i3 sync event with the specified random value to the specified window.
pub const I3_Get_Binding_state_reply = struct {
///TODO{kotto}: Not implemented
succes: bool,
}; //| BINDING_STATE | Request the current binding state, i.e. the currently active binding mode name.
pub fn is_focused(nodes: ?[]I3_Workspace_container) bool {
for (nodes.?) |node| {
if (node.focused) return true;
}
return false;
}
const testing = std.testing;
test "handle I3_Event_Workspace" {
const str = @embedFile("../" ++ "test/json/i3_event_workspace.json");
@setEvalBranchQuota(100000);
var stream = std.json.TokenStream.init(str);
var rj = try std.json.parse(I3_Event_Workspace, &stream, .{
.allocator = testing.allocator,
//.ignore_unknown_fields = true, //NOTE: It seems like some fields are undecumented?
});
try testing.expect(std.mem.eql(u8, rj.change, "focus"));
} | src/i3-ipc.zig |
const std = @import("std");
const ComptimeStringHashMap = @import("comptime_hash_map/comptime_hash_map.zig").ComptimeStringHashMap;
const testing = std.testing;
/// Reverse compression codebook, used for decompression
const smaz_rcb = [_][]const u8{
" ", "the", "e", "t", "a", "of", "o", "and", "i", "n", "s", "e ", "r", " th",
" t", "in", "he", "th", "h", "he ", "to", "\r\n", "l", "s ", "d", " a", "an", "er",
"c", " o", "d ", "on", " of", "re", "of ", "t ", ", ", "is", "u", "at", " ", "n ",
"or", "which", "f", "m", "as", "it", "that", "\n", "was", "en", " ", " w", "es", " an",
" i", "\r", "f ", "g", "p", "nd", " s", "nd ", "ed ", "w", "ed", "http://", "for", "te",
"ing", "y ", "The", " c", "ti", "r ", "his", "st", " in", "ar", "nt", ",", " to", "y",
"ng", " h", "with", "le", "al", "to ", "b", "ou", "be", "were", " b", "se", "o ", "ent",
"ha", "ng ", "their", "\"", "hi", "from", " f", "in ", "de", "ion", "me", "v", ".", "ve",
"all", "re ", "ri", "ro", "is ", "co", "f t", "are", "ea", ". ", "her", " m", "er ", " p",
"es ", "by", "they", "di", "ra", "ic", "not", "s, ", "d t", "at ", "ce", "la", "h ", "ne",
"as ", "tio", "on ", "n t", "io", "we", " a ", "om", ", a", "s o", "ur", "li", "ll", "ch",
"had", "this", "e t", "g ", "e\r\n", " wh", "ere", " co", "e o", "a ", "us", " d", "ss", "\n\r\n",
"\r\n\r", "=\"", " be", " e", "s a", "ma", "one", "t t", "or ", "but", "el", "so", "l ", "e s",
"s,", "no", "ter", " wa", "iv", "ho", "e a", " r", "hat", "s t", "ns", "ch ", "wh", "tr",
"ut", "/", "have", "ly ", "ta", " ha", " on", "tha", "-", " l", "ati", "en ", "pe", " re",
"there", "ass", "si", " fo", "wa", "ec", "our", "who", "its", "z", "fo", "rs", ">", "ot",
"un", "<", "im", "th ", "nc", "ate", "><", "ver", "ad", " we", "ly", "ee", " n", "id",
" cl", "ac", "il", "</", "rt", " wi", "div", "e, ", " it", "whi", " ma", "ge", "x", "e c",
"men", ".com",
};
const smaz_cb_kvs = comptime blk: {
const KV = struct {
@"0": []const u8,
@"1": u8,
};
var result: []const KV = &[_]KV{};
for (smaz_rcb) |s, i| {
result = result ++ &[_]KV{KV{ .@"0" = s, .@"1" = i }};
}
break :blk result;
};
const smaz_cb = comptime blk: {
@setEvalBranchQuota(10000);
break :blk ComptimeStringHashMap(u8, smaz_cb_kvs);
};
fn flushVerbatim(writer: anytype, verb: []const u8) callconv(.Inline) !void {
if (verb.len == 0) {
return;
} else if (verb.len == 1) {
try writer.writeByte(254);
} else {
try writer.writeAll(&[_]u8{ 255, @intCast(u8, verb.len - 1) });
}
try writer.writeAll(verb);
}
pub fn compress(reader: anytype, writer: anytype) !void {
var verb: [256]u8 = undefined;
var verb_len: usize = 0;
var buf: [7]u8 = undefined;
var amt = try reader.read(&buf);
while (amt > 0) {
var len = amt;
search: while (len > 0) : (len -= 1) {
if (smaz_cb.get(buf[0..len])) |i| {
// Match found, flush verbatim buffer
try flushVerbatim(writer, verb[0..verb_len]);
verb_len = 0;
// Print
try writer.writeByte(@intCast(u8, i.*));
// Advance buffer
std.mem.copy(u8, buf[0 .. amt - len], buf[len..amt]);
amt -= len;
break :search;
}
} else {
if (verb_len < verb.len) {
verb[verb_len] = buf[0];
verb_len += 1;
} else {
try flushVerbatim(writer, &verb);
verb[0] = buf[0];
verb_len = 1;
}
std.mem.copy(u8, buf[0 .. amt - 1], buf[1..amt]);
amt -= 1;
}
// Try to fill up buffer
amt += try reader.read(buf[amt..]);
}
// Flush verbatim buffer
try flushVerbatim(writer, verb[0..verb_len]);
}
pub fn decompress(reader: anytype, writer: anytype) !void {
while (true) {
const c = reader.readByte() catch |err| switch (err) {
error.EndOfStream => return,
else => |e| return e,
};
switch (c) {
254 => {
const byte = reader.readByte() catch |err| switch (err) {
error.EndOfStream => return,
else => |e| return e,
};
try writer.writeByte(byte);
},
255 => {
var buf: [256]u8 = undefined;
const b = reader.readByte() catch |err| switch (err) {
error.EndOfStream => return,
else => |e| return e,
};
const len = @intCast(usize, b) + 1;
const amt = try reader.readAll(buf[0..len]);
if (amt < len) return;
try writer.writeAll(buf[0..len]);
},
else => try writer.writeAll(smaz_rcb[c]),
}
}
}
test "compress and decompress examples" {
const strings = @import("examples.zig").examples;
for (strings) |str| {
var compress_reader = std.io.fixedBufferStream(str);
var compress_buf: [1024]u8 = undefined;
var compress_writer = std.io.fixedBufferStream(&compress_buf);
try compress(compress_reader.reader(), compress_writer.writer());
const compressed = compress_writer.getWritten();
var decompress_reader = std.io.fixedBufferStream(compressed);
var decompress_buf: [1024]u8 = undefined;
var decompress_writer = std.io.fixedBufferStream(&decompress_buf);
try decompress(decompress_reader.reader(), decompress_writer.writer());
const decompressed = decompress_writer.getWritten();
testing.expectEqualSlices(u8, str, decompressed);
}
}
test "fuzzy testing" {
var rand_buf: [8]u8 = undefined;
try std.crypto.randomBytes(rand_buf[0..]);
const seed = std.mem.readIntLittle(u64, rand_buf[0..8]);
var r = std.rand.DefaultPrng.init(seed);
const n = 1000;
const max_len = 1000;
var buf: [max_len]u8 = undefined;
var i: usize = 0;
while (i < n) : (i += 1) {
const len = r.random.uintLessThan(usize, max_len);
for (buf[0..len]) |*x| x.* = r.random.int(u8);
const str = buf[0..len];
var compress_reader = std.io.fixedBufferStream(str);
var compress_buf: [4096]u8 = undefined;
var compress_writer = std.io.fixedBufferStream(&compress_buf);
try compress(compress_reader.reader(), compress_writer.writer());
const compressed = compress_writer.getWritten();
var decompress_reader = std.io.fixedBufferStream(compressed);
var decompress_buf: [4096]u8 = undefined;
var decompress_writer = std.io.fixedBufferStream(&decompress_buf);
try decompress(decompress_reader.reader(), decompress_writer.writer());
const decompressed = decompress_writer.getWritten();
testing.expectEqualSlices(u8, str, decompressed);
}
} | src/main.zig |
const std = @import("std");
const print = std.debug.print;
const data = @embedFile("../inputs/day17.txt");
pub fn main() anyerror!void {
const target_area = try parse(data);
print("Part 1: {d}\n", .{part1(target_area)});
print("Part 2: {d}\n", .{part2(target_area)});
}
const V = struct {
x: isize,
y: isize,
};
const Area = struct {
start_x: isize,
end_x: isize,
start_y: isize,
end_y: isize,
};
fn parse(input: []const u8) !Area {
var str = std.mem.trimLeft(u8, input, "target area: x=");
str = std.mem.trimRight(u8, str, "\n");
var it = std.mem.split(u8, str, ", y=");
var it_x = std.mem.split(u8, it.next().?, "..");
const start_x = try std.fmt.parseInt(isize, it_x.next().?, 10);
const end_x = try std.fmt.parseInt(isize, it_x.next().?, 10);
var it_y = std.mem.split(u8, it.next().?, "..");
const start_y = try std.fmt.parseInt(isize, it_y.next().?, 10);
const end_y = try std.fmt.parseInt(isize, it_y.next().?, 10);
return Area{
.start_x = start_x,
.end_x = end_x,
.start_y = start_y,
.end_y = end_y,
};
}
inline fn inside(pos: V, target: Area) bool {
const inside_x = target.start_x <= pos.x and pos.x <= target.end_x;
const inside_y = target.start_y <= pos.y and pos.y <= target.end_y;
return inside_x and inside_y;
}
const Probe = struct {
const Self = @This();
pos: V,
vel: V,
fn step(self: *Self) void {
self.pos.x += self.vel.x;
self.pos.y += self.vel.y;
if (self.vel.x > 0) {
self.vel.x -= 1;
} else if (self.vel.x < 0) {
self.vel.x += 1;
}
self.vel.y -= 1;
}
};
fn part1(target: Area) usize {
var highest_attempt: isize = 0;
var vy: isize = 0;
next_probe: while (true) : (vy += 1) {
// we don't really care about x, assume there is a way to pick an x so
// that the target can be reached with an x velocity of 0
var probe = Probe{
.pos = V{ .x = target.start_x, .y = 0 },
.vel = V{ .x = 0, .y = vy },
};
var highest: isize = 0;
var step_count: usize = 0;
var step_at_zero_altitude: usize = 0;
while (true) {
if (inside(probe.pos, target)) {
highest_attempt = std.math.max(highest_attempt, highest);
break;
} else if (probe.pos.y < target.start_y) {
// too low y
if (step_at_zero_altitude == step_count - 1) {
break :next_probe;
}
break;
}
highest = std.math.max(highest, probe.pos.y);
if (probe.pos.y == 0 and probe.vel.y < 0) {
step_at_zero_altitude = step_count;
}
probe.step();
step_count += 1;
}
}
return @intCast(usize, highest_attempt);
}
fn part2(target: Area) usize {
var inside_count: usize = 0;
var vx: isize = 0;
while (vx <= target.end_x) : (vx += 1) {
var vy: isize = target.start_y;
next_probe: while (true) : (vy += 1) {
var probe = Probe{
.pos = V{ .x = 0, .y = 0 },
.vel = V{ .x = vx, .y = vy },
};
var step_count: usize = 0;
var step_at_zero_altitude: usize = 0;
while (true) {
if (inside(probe.pos, target)) {
inside_count += 1;
break;
} else if (probe.pos.x > target.end_x) {
// too far x
break :next_probe;
} else if (probe.pos.y < target.start_y) {
// too low y
if (step_at_zero_altitude == step_count - 1) {
break :next_probe;
}
break;
}
if (probe.pos.y == 0 and probe.vel.y < 0) {
step_at_zero_altitude = step_count;
}
probe.step();
step_count += 1;
}
}
}
return inside_count;
}
test "probe shooting" {
const input = "target area: x=20..30, y=-10..-5";
const target_area = try parse(input);
try std.testing.expectEqual(@as(usize, 45), part1(target_area));
try std.testing.expectEqual(@as(usize, 112), part2(target_area));
} | src/day17.zig |
const Builder = @import("std").build.Builder;
const z = @import("std").zig;
const std = @import("std");
const builtin = std.builtin;
pub const PSPBuildInfo = struct{
//SDK Path
path_to_sdk: []const u8,
src_file: []const u8,
//Title
title: []const u8,
//Optional customizations
icon0: []const u8 = "NULL",
icon1: []const u8 = "NULL",
pic0: []const u8 = "NULL",
pic1: []const u8 = "NULL",
snd0: []const u8 = "NULL",
};
const append : []const u8 = switch(builtin.os.tag){
.windows => ".exe",
else => "",
};
pub fn build_psp(b: *Builder, comptime build_info: PSPBuildInfo) !void {
var feature_set : std.Target.Cpu.Feature.Set = std.Target.Cpu.Feature.Set.empty;
feature_set.addFeature(@enumToInt(std.Target.mips.Feature.single_float));
//PSP-Specific Build Options
const target = z.CrossTarget{
.cpu_arch = .mipsel,
.os_tag = .freestanding,
.cpu_model = .{ .explicit = &std.Target.mips.cpu.mips2 },
.cpu_features_add = feature_set
};
//All of the release modes work
//Debug Mode can cause issues with trap instructions - use ReleaseSafe for "Debug" builds
const mode = builtin.Mode.ReleaseSmall;
//Build from your main file!
const exe = b.addExecutable("main", build_info.src_file);
//Set mode & target
exe.setTarget(target);
exe.setBuildMode(mode);
exe.setLinkerScriptPath(build_info.path_to_sdk ++ "tools/linkfile.ld");
exe.link_eh_frame_hdr = true;
exe.link_emit_relocs = true;
exe.strip = true;
exe.single_threaded = true;
exe.install();
exe.setOutputDir("zig-cache/");
//Post-build actions
const hostTarget = b.standardTargetOptions(.{});
const prx = b.addExecutable("prxgen", build_info.path_to_sdk ++ "tools/prxgen/stub.zig");
prx.setTarget(hostTarget);
prx.addCSourceFile(build_info.path_to_sdk ++ "tools/prxgen/psp-prxgen.c", &[_][]const u8{"-std=c99", "-Wno-address-of-packed-member", "-D_CRT_SECURE_NO_WARNINGS"});
prx.linkLibC();
prx.setBuildMode(builtin.Mode.ReleaseFast);
prx.setOutputDir(build_info.path_to_sdk ++ "tools/bin");
prx.install();
prx.step.dependOn(&exe.step);
const generate_prx = b.addSystemCommand(&[_][]const u8{
build_info.path_to_sdk ++ "tools/bin/prxgen" ++ append,
"zig-cache/main",
"app.prx"
});
generate_prx.step.dependOn(&prx.step);
//Build SFO
const sfo = b.addExecutable("sfotool", build_info.path_to_sdk ++ "tools/sfo/src/main.zig");
sfo.setTarget(hostTarget);
sfo.setBuildMode(builtin.Mode.ReleaseFast);
sfo.setOutputDir(build_info.path_to_sdk ++ "tools/bin");
sfo.install();
sfo.step.dependOn(&generate_prx.step);
//Make the SFO file
const mk_sfo = b.addSystemCommand(&[_][]const u8{
build_info.path_to_sdk ++ "tools/bin/sfotool" ++ append, "write",
build_info.title,
"PARAM.SFO"
});
mk_sfo.step.dependOn(&sfo.step);
//Build PBP
const PBP = b.addExecutable("pbptool", build_info.path_to_sdk ++ "tools/pbp/src/main.zig");
PBP.setTarget(hostTarget);
PBP.setBuildMode(builtin.Mode.ReleaseFast);
PBP.setOutputDir(build_info.path_to_sdk ++ "tools/bin");
PBP.install();
PBP.step.dependOn(&mk_sfo.step);
//Pack the PBP executable
const pack_pbp = b.addSystemCommand(&[_][]const u8{
build_info.path_to_sdk ++ "tools/bin/pbptool" ++ append, "pack",
"EBOOT.PBP",
"PARAM.SFO",
build_info.icon0,
build_info.icon1,
build_info.pic0,
build_info.pic1,
build_info.snd0,
"app.prx",
"NULL" //DATA.PSAR not necessary.
});
pack_pbp.step.dependOn(&PBP.step);
//Enable the build
b.default_step.dependOn(&pack_pbp.step);
} | build-psp.zig |
const std = @import("std");
pub const FlagType = enum {
short,
long,
};
pub const Flag = struct {
name: []const u8,
kind: FlagType,
pub fn is(self: Flag, other: []const u8) bool {
return std.mem.eql(u8, self.name, other);
}
pub fn isLong(self: Flag, other: []const u8) bool {
return self.is(other) and self.kind == .long;
}
pub fn isShort(self: Flag, other: []const u8) bool {
return self.is(other) and self.kind == .short;
}
};
pub const Token = union(enum) {
flag: Flag,
arg: []const u8,
unexpected_value: []const u8,
};
pub const Options = struct {
auto_double_dash: bool = true,
};
const State = union(enum) {
// Nothing is buffered.
default: void,
// In the middle of parsing short flags.
short: []const u8,
// After observing an equal sign.
value: ValueState,
};
const ValueState = struct {
// This points to the value (i.e. whatever is after the = sign)
value: []const u8,
// This points to the key+value (e.g. `-m=message`).
full: []const u8,
};
pub fn Parser(comptime T: type) type {
return struct {
const Self = @This();
source: T,
options: Options,
state: State = .default,
skip_flag_parsing: bool = false,
pub fn init(source: T, options: Options) Self {
return Self{ .source = source, .options = options };
}
pub fn deinit(self: *Self) void {
if (@hasDecl(T, "deinit")) {
self.source.deinit();
}
self.* = undefined;
}
pub fn next(self: *Self) ?Token {
switch (self.state) {
.default => {
const arg = self.pull() orelse return null;
if (self.skip_flag_parsing) {
return Token{ .arg = arg };
}
if (std.mem.startsWith(u8, arg, "--")) {
if (arg.len == 2) {
if (self.options.auto_double_dash) {
self.skip_flag_parsing = true;
return self.next();
} else {
return Token{ .arg = arg };
}
}
if (std.mem.indexOfScalar(u8, arg, '=')) |value_pos| {
self.state = .{
.value = .{
.full = arg[2..],
.value = arg[value_pos + 1 ..],
},
};
return Token{ .flag = .{ .name = arg[2..value_pos], .kind = .long } };
}
return Token{ .flag = .{ .name = arg[2..], .kind = .long } };
}
if (arg.len > 1 and std.mem.startsWith(u8, arg, "-")) {
self.proceedShort(arg[1..]);
return Token{ .flag = .{ .name = arg[1..2], .kind = .short } };
}
return Token{ .arg = arg };
},
.short => |arg| {
self.proceedShort(arg);
return Token{ .flag = .{ .name = arg[0..1], .kind = .short } };
},
.value => |v| {
self.state = .default;
return Token{ .unexpected_value = v.full };
},
}
return null;
}
/// nextValue should be invoked after you've observed a long/short flag and expect a value.
/// This correctly handles both `--long=value`, `--long value`, `-svalue`, `-s=value` and `-s value`.
pub fn nextValue(self: *Self) ?[]const u8 {
switch (self.state) {
.default => return self.pull(),
.short => |buf| return buf,
.value => |v| {
self.state = .default;
return v.value;
},
}
}
/// skipFlagParsing turns off flag parsing and causes all the next tokens to be returned as `arg`.
pub fn skipFlagParsing(self: *Self) void {
self.skip_flag_parsing = true;
}
fn pull(self: *Self) ?[]const u8 {
return @as(?[]const u8, self.source.next());
}
/// proceedShort sets up the state after a short flag has been seen.
fn proceedShort(self: *Self, data: []const u8) void {
if (data.len == 1) {
// No more data in this slice => Go back to default mode.
self.state = .default;
} else if (data[1] == '=') {
// We found a value!
self.state = .{
.value = .{
.full = data,
.value = data[2..],
},
};
} else {
// There's more short flags.
self.state = .{ .short = data[1..] };
}
}
};
}
pub fn parse(source: anytype, options: Options) Parser(@TypeOf(source)) {
return Parser(@TypeOf(source)).init(source, options);
}
pub const SliceIter = struct {
items: []const []const u8,
idx: usize = 0,
pub fn next(self: *SliceIter) ?[]const u8 {
defer self.idx += 1;
if (self.idx < self.items.len) {
return self.items[self.idx];
} else {
return null;
}
}
};
pub fn parseSlice(slice: []const []const u8, options: Options) Parser(SliceIter) {
return parse(SliceIter{ .items = slice }, options);
}
pub fn parseProcess(allocator: std.mem.Allocator, options: Options) !Parser(std.process.ArgIterator) {
return parse(try std.process.argsWithAllocator(allocator), options);
}
const testing = std.testing;
fn expectShort(arg: ?Token) !u8 {
if (arg) |a| {
switch (a) {
.flag => |flag| if (flag.kind == .short) return flag.name[0],
else => {},
}
}
return error.TestExpectedLong;
}
fn expectLong(arg: ?Token) ![]const u8 {
if (arg) |a| {
switch (a) {
.flag => |flag| if (flag.kind == .long) return flag.name,
else => {},
}
}
return error.TestExpectedLong;
}
fn expectArg(arg: ?Token) ![]const u8 {
if (arg) |a| {
switch (a) {
.arg => |name| return name,
else => {},
}
}
return error.TestExpectedValue;
}
fn expectUnexpectedValue(arg: ?Token) ![]const u8 {
if (arg) |a| {
switch (a) {
.unexpected_value => |name| return name,
else => {},
}
}
return error.TestExpectedUnexpectedValue;
}
fn expectNull(arg: ?Token) !void {
return testing.expectEqual(@as(?Token, null), arg);
}
test "parse values" {
var parser = parseSlice(&[_][]const u8{ "hello", "world" }, .{});
defer parser.deinit();
try testing.expectEqualStrings("hello", try expectArg(parser.next()));
try testing.expectEqualStrings("world", try expectArg(parser.next()));
try expectNull(parser.next());
}
test "parse short flags" {
var parser = parseSlice(&[_][]const u8{ "-abc", "-def" }, .{});
defer parser.deinit();
for ("abcdef") |flag| {
try testing.expectEqual(flag, try expectShort(parser.next()));
}
try expectNull(parser.next());
}
test "parse short with values" {
// -a=1
{
var parser = parseSlice(&[_][]const u8{"-a=1"}, .{});
defer parser.deinit();
try testing.expectEqual(@as(u8, 'a'), try expectShort(parser.next()));
try testing.expectEqualStrings("1", parser.nextValue() orelse unreachable);
try expectNull(parser.next());
}
// -a1
{
var parser = parseSlice(&[_][]const u8{"-a=1"}, .{});
defer parser.deinit();
try testing.expectEqual(@as(u8, 'a'), try expectShort(parser.next()));
try testing.expectEqualStrings("1", parser.nextValue() orelse unreachable);
try expectNull(parser.next());
}
// -a 1
{
var parser = parseSlice(&[_][]const u8{ "-a", "1" }, .{});
defer parser.deinit();
try testing.expectEqual(@as(u8, 'a'), try expectShort(parser.next()));
try testing.expectEqualStrings("1", parser.nextValue() orelse unreachable);
try expectNull(parser.next());
}
}
test "parse long" {
var parser = parseSlice(&[_][]const u8{ "--force", "--author" }, .{});
defer parser.deinit();
try testing.expectEqualStrings("force", try expectLong(parser.next()));
try testing.expectEqualStrings("author", try expectLong(parser.next()));
try expectNull(parser.next());
}
test "parse long with value" {
// --name=bob
{
var parser = parseSlice(&[_][]const u8{"--name=bob"}, .{});
defer parser.deinit();
try testing.expectEqualStrings("name", try expectLong(parser.next()));
try testing.expectEqualStrings("bob", parser.nextValue() orelse unreachable);
try expectNull(parser.next());
}
// --name bob
{
var parser = parseSlice(&[_][]const u8{ "--name", "bob" }, .{});
defer parser.deinit();
try testing.expectEqualStrings("name", try expectLong(parser.next()));
try testing.expectEqualStrings("bob", parser.nextValue() orelse unreachable);
try expectNull(parser.next());
}
}
test "unexpected value" {
// --name=bob
{
var parser = parseSlice(&[_][]const u8{"--name=bob"}, .{});
defer parser.deinit();
try testing.expectEqualStrings("name", try expectLong(parser.next()));
try testing.expectEqualStrings("name=bob", try expectUnexpectedValue(parser.next()));
try expectNull(parser.next());
}
// -ab=bob
{
var parser = parseSlice(&[_][]const u8{"-ab=bob"}, .{});
defer parser.deinit();
try testing.expectEqual(@as(u8, 'a'), try expectShort(parser.next()));
try testing.expectEqual(@as(u8, 'b'), try expectShort(parser.next()));
try testing.expectEqualStrings("b=bob", try expectUnexpectedValue(parser.next()));
try expectNull(parser.next());
}
}
test "unexpected value followed by flag" {
var parser = parseSlice(&[_][]const u8{ "--name=bob", "--file" }, .{});
defer parser.deinit();
try testing.expectEqualStrings("name", try expectLong(parser.next()));
try testing.expectEqualStrings("name=bob", try expectUnexpectedValue(parser.next()));
try testing.expectEqualStrings("file", try expectLong(parser.next()));
try expectNull(parser.next());
}
test "empty long value" {
var parser = parseSlice(&[_][]const u8{"--name="}, .{});
defer parser.deinit();
try testing.expectEqualStrings("name", try expectLong(parser.next()));
try testing.expectEqualStrings("", parser.nextValue() orelse unreachable);
try expectNull(parser.next());
}
test "empty short value" {
var parser = parseSlice(&[_][]const u8{"-a="}, .{});
defer parser.deinit();
try testing.expectEqual(@as(u8, 'a'), try expectShort(parser.next()));
try testing.expectEqualStrings("", parser.nextValue() orelse unreachable);
try expectNull(parser.next());
}
test "single dash" {
var parser = parseSlice(&[_][]const u8{ "--hello", "world", "-" }, .{});
defer parser.deinit();
try testing.expectEqualStrings("hello", try expectLong(parser.next()));
try testing.expectEqualStrings("world", try expectArg(parser.next()));
try testing.expectEqualStrings("-", try expectArg(parser.next()));
try expectNull(parser.next());
}
test "double dash" {
var parser = parseSlice(&[_][]const u8{ "--hello", "world", "--", "--hello" }, .{});
defer parser.deinit();
try testing.expectEqualStrings("hello", try expectLong(parser.next()));
try testing.expectEqualStrings("world", try expectArg(parser.next()));
try testing.expectEqualStrings("--hello", try expectArg(parser.next()));
try expectNull(parser.next());
}
test "manual dash" {
var parser = parseSlice(&[_][]const u8{ "--hello", "world", "--", "--hello" }, .{ .auto_double_dash = false });
defer parser.deinit();
try testing.expectEqualStrings("hello", try expectLong(parser.next()));
try testing.expectEqualStrings("world", try expectArg(parser.next()));
try testing.expectEqualStrings("--", try expectArg(parser.next()));
try testing.expectEqualStrings("hello", try expectLong(parser.next()));
try expectNull(parser.next());
}
test "manual skip" {
var parser = parseSlice(&[_][]const u8{ "--hello", "--world", "-a" }, .{});
defer parser.deinit();
try testing.expectEqualStrings("hello", try expectLong(parser.next()));
parser.skipFlagParsing();
try testing.expectEqualStrings("--world", try expectArg(parser.next()));
try testing.expectEqualStrings("-a", try expectArg(parser.next()));
try expectNull(parser.next());
}
test "manual skip during value" {
var parser = parseSlice(&[_][]const u8{ "--hello=world", "--name" }, .{});
defer parser.deinit();
try testing.expectEqualStrings("hello", try expectLong(parser.next()));
parser.skipFlagParsing();
try testing.expectEqualStrings("hello=world", try expectUnexpectedValue(parser.next()));
try testing.expectEqualStrings("--name", try expectArg(parser.next()));
try expectNull(parser.next());
}
test "manual skip during short" {
var parser = parseSlice(&[_][]const u8{ "-abc", "--file" }, .{});
defer parser.deinit();
try testing.expectEqual(@as(u8, 'a'), try expectShort(parser.next()));
parser.skipFlagParsing();
try testing.expectEqual(@as(u8, 'b'), try expectShort(parser.next()));
try testing.expectEqual(@as(u8, 'c'), try expectShort(parser.next()));
try testing.expectEqualStrings("--file", try expectArg(parser.next()));
try expectNull(parser.next());
} | src/parser.zig |
const std = @import("std");
const warn = std.debug.warn;
const maxInt = std.math.maxInt;
const Allocator = std.mem.Allocator;
const Scanner = @import("./scanner.zig").Scanner;
const Token = @import("./scanner.zig").Token;
const TokenType = @import("./scanner.zig").TokenType;
const VM = @import("./vm.zig").VM;
const Chunk = @import("./chunk.zig").Chunk;
const OpCode = @import("./chunk.zig").OpCode;
const Value = @import("./value.zig").Value;
const Obj = @import("./object.zig").Obj;
const debug = @import("./debug.zig");
pub fn compile(vm: *VM, source: []const u8) !*Obj.Function {
var compiler = try Compiler.init(vm, .Script, null);
defer compiler.deinit();
var parser = try Parser.init(vm, &compiler, source);
// Register the parser with the VM. Need to do this so that the
// garbage collector can reach the parser's current compiler.
vm.parser = &parser;
defer vm.parser = null;
try parser.advance();
while (!(try parser.match(.Eof))) {
try parser.declaration();
}
try parser.consume(.Eof, "Expect end of expression.");
const fun = try parser.end();
if (parser.hadError) return error.CompileError;
return fun;
}
const FunctionType = enum {
Function, Initializer, Method, Script
};
const Upvalue = struct {
index: u8,
isLocal: bool,
};
pub const Compiler = struct {
enclosing: ?*Compiler,
function: *Obj.Function,
functionType: FunctionType,
locals: std.ArrayList(Local),
upvalues: std.ArrayList(Upvalue),
scopeDepth: usize,
pub fn init(vm: *VM, functionType: FunctionType, enclosing: ?*Compiler) !Compiler {
var locals = std.ArrayList(Local).init(vm.allocator);
// First local is reserved to represent the current function
// value on the stack. Give it a name of "" to make sure it
// can't actually be referenced by local variables.
try locals.append(Local{
.depth = 0,
.isCaptured = false,
.name = if (functionType == .Function) "" else "this",
});
return Compiler{
.enclosing = enclosing,
// NOTE, book warns we should initialize function to null
// and set it later for GC reasons, but that doesn't appear
// necessary to me.
.function = try Obj.Function.create(vm),
.functionType = functionType,
.locals = locals,
.upvalues = std.ArrayList(Upvalue).init(vm.allocator),
.scopeDepth = 0,
};
}
pub fn deinit(self: *Compiler) void {
self.locals.deinit();
self.upvalues.deinit();
}
};
const ClassCompiler = struct {
enclosing: ?*ClassCompiler,
name: []const u8,
hasSuperclass: bool,
};
pub const Local = struct {
name: []const u8,
depth: isize,
isCaptured: bool,
};
const Precedence = enum(u8) {
None,
Assignment, // =
Or, // or
And, // and
Equality, // == !=
Comparison, // < > <= >=
Term, // + -
Factor, // * /
Unary, // ! -
Call, // . ()
Primary,
pub fn next(self: Precedence) Precedence {
return @intToEnum(Precedence, @enumToInt(self) + 1);
}
};
// NOTE, have to spell this out explicitly right now because zig has
// trouble inferring error sets for recursive functions.
//
// See https://github.com/ziglang/zig/issues/2971
const CompilerErrors = error{OutOfMemory} || std.os.WriteError;
fn getPrecedence(tokenType: TokenType) Precedence {
return switch (tokenType) {
// Single-character tokens.
.LeftParen => .Call,
.RightParen, .LeftBrace, .RightBrace, .Comma => .None,
.Dot => .Call,
.Minus, .Plus => .Term,
.Semicolon => .None,
.Slash, .Star => .Factor,
// One or two character tokens.
.BangEqual, .EqualEqual => .Equality,
.Greater, .GreaterEqual, .Less, .LessEqual => .Comparison,
.Bang, .Equal => .None,
// Literals.
.Identifier, .String, .Number => .None,
// Keywords.
.And => .And,
.Or => .Or,
.Class, .Else, .False, .For, .Fun, .If, .Nil => .None,
.Print, .Return, .Super, .This, .True, .Var, .While, .Error => .None,
.Eof => .None,
};
}
pub const Parser = struct {
vm: *VM,
scanner: Scanner,
current: Token,
previous: Token,
hadError: bool,
panicMode: bool,
compiler: *Compiler,
currentClass: ?*ClassCompiler,
pub fn init(vm: *VM, compiler: *Compiler, source: []const u8) !Parser {
return Parser{
.vm = vm,
.scanner = Scanner.init(source),
.current = undefined,
.currentClass = null,
.previous = undefined,
.hadError = false,
.panicMode = false,
.compiler = compiler,
};
}
pub fn currentChunk(self: *Parser) *Chunk {
return &self.compiler.function.chunk;
}
fn advance(self: *Parser) !void {
self.previous = self.current;
while (true) {
self.current = self.scanner.scanToken();
if (!self.check(.Error)) break;
try self.errorAtCurrent(self.current.lexeme);
}
}
fn check(self: *Parser, tokenType: TokenType) bool {
return self.current.tokenType == tokenType;
}
fn consume(self: *Parser, tokenType: TokenType, message: []const u8) !void {
if (self.check(tokenType)) {
try self.advance();
} else {
try self.errorAtCurrent(message);
}
}
fn match(self: *Parser, tokenType: TokenType) !bool {
if (!self.check(tokenType)) return false;
try self.advance();
return true;
}
fn errorAtCurrent(self: *Parser, message: []const u8) !void {
try self.errorAt(&self.current, message);
}
fn err(self: *Parser, message: []const u8) !void {
try self.errorAt(&self.previous, message);
}
fn prefixError(self: *Parser) !void {
try self.err("Expect expression.");
}
fn infixError(self: *Parser) !void {
try self.err("Expect expression.");
}
fn errorAt(self: *Parser, token: *Token, message: []const u8) !void {
if (self.panicMode) return;
self.panicMode = true;
try self.vm.errWriter.print("[line {}] Error", .{token.line});
switch (token.tokenType) {
.Eof => {
try self.vm.errWriter.print(" at end", .{});
},
.Error => {},
else => {
try self.vm.errWriter.print(" at '{s}'", .{token.lexeme});
},
}
try self.vm.errWriter.print(": {s}\n", .{message});
self.hadError = true;
}
fn emitJump(self: *Parser, op: OpCode) !usize {
try self.emitOp(op);
// Dummy operands that will be patched later
try self.emitByte(0xff);
try self.emitByte(0xff);
return self.currentChunk().code.items.len - 2;
}
fn patchJump(self: *Parser, offset: usize) !void {
const jump = self.currentChunk().code.items.len - offset - 2;
if (jump > maxInt(u16)) {
try self.err("Too much code to jump over.");
}
self.currentChunk().code.items[offset] = @intCast(u8, (jump >> 8) & 0xff);
self.currentChunk().code.items[offset + 1] = @intCast(u8, jump & 0xff);
}
fn emitLoop(self: *Parser, loopStart: usize) !void {
try self.emitOp(.Loop);
const offset = self.currentChunk().code.items.len - loopStart + 2;
if (offset > maxInt(u16)) try self.err("Loop body too large.");
try self.emitByte(@intCast(u8, (offset >> 8) & 0xff));
try self.emitByte(@intCast(u8, offset & 0xff));
}
fn emitByte(self: *Parser, byte: u8) !void {
try self.currentChunk().write(byte, self.previous.line);
}
fn emitOp(self: *Parser, op: OpCode) !void {
try self.currentChunk().writeOp(op, self.previous.line);
}
fn emitUnaryOp(self: *Parser, op: OpCode, byte: u8) !void {
try self.emitOp(op);
try self.emitByte(byte);
}
fn emitConstant(self: *Parser, value: Value) !void {
try self.emitUnaryOp(.Constant, try self.makeConstant(value));
}
fn emitReturn(self: *Parser) !void {
switch (self.compiler.functionType) {
.Initializer => try self.emitUnaryOp(.GetLocal, 0),
.Function, .Method, .Script => try self.emitOp(.Nil),
}
try self.emitOp(.Return);
}
fn end(self: *Parser) !*Obj.Function {
try self.emitReturn();
if (debug.PRINT_CODE) {
if (!self.hadError) {
const maybeName = self.compiler.function.name;
const name = if (maybeName) |o| o.bytes else "<script>";
self.currentChunk().disassemble(name);
}
}
const fun = self.compiler.function;
if (self.compiler.enclosing) |compiler| {
self.compiler = compiler;
}
return fun;
}
fn makeConstant(self: *Parser, value: Value) !u8 {
// Make sure value is visible to the GC while addConstant
// allocates
self.vm.push(value);
const constant = try self.currentChunk().addConstant(value);
_ = self.vm.pop();
if (constant > maxInt(u8)) {
try self.err("Too many constants in one chunk.");
return 0;
}
return @intCast(u8, constant);
}
fn declaration(self: *Parser) !void {
if (try self.match(.Class)) {
try self.classDeclaration();
} else if (try self.match(.Fun)) {
try self.funDeclaration();
} else if (try self.match(.Var)) {
try self.varDeclaration();
} else {
try self.statement();
}
if (self.panicMode) try self.synchronize();
}
fn statement(self: *Parser) !void {
if (try self.match(.Print)) {
try self.printStatement();
} else if (try self.match(.Return)) {
try self.returnStatement();
} else if (try self.match(.If)) {
try self.ifStatement();
} else if (try self.match(.While)) {
try self.whileStatement();
} else if (try self.match(.For)) {
try self.forStatement();
} else if (try self.match(.LeftBrace)) {
self.beginScope();
try self.block();
try self.endScope();
} else {
try self.expressionStatement();
}
}
fn beginScope(self: *Parser) void {
self.compiler.scopeDepth += 1;
}
fn endScope(self: *Parser) !void {
self.compiler.scopeDepth -= 1;
var locals = &self.compiler.locals;
while (locals.items.len > 0 and
locals.items[locals.items.len - 1].depth > self.compiler.scopeDepth)
{
if (locals.items[locals.items.len - 1].isCaptured) {
try self.emitOp(.CloseUpvalue);
} else {
try self.emitOp(.Pop);
}
_ = locals.pop();
}
}
fn expression(self: *Parser) !void {
try self.parsePrecedence(.Assignment);
}
fn block(self: *Parser) CompilerErrors!void {
while (!self.check(.RightBrace) and !self.check(.Eof)) {
try self.declaration();
}
try self.consume(.RightBrace, "Expect '}' after block.");
}
fn function(self: *Parser, functionType: FunctionType) !void {
var compiler = try Compiler.init(self.vm, functionType, self.compiler);
defer compiler.deinit();
self.compiler = &compiler;
self.compiler.function.name = try Obj.String.copy(self.vm, self.previous.lexeme);
self.beginScope();
// Compile the parameter list
try self.consume(.LeftParen, "Expect '(' after function name.");
if (!self.check(.RightParen)) {
while (true) {
if (self.compiler.function.arity == 255) {
try self.errorAtCurrent("Cannot have more than 255 parameters.");
}
self.compiler.function.arity += 1;
const paramConstant = try self.parseVariable("Expect parameter name.");
try self.defineVariable(paramConstant);
if (!try self.match(.Comma)) break;
}
}
try self.consume(.RightParen, "Expect ')' after parameters.");
// The body.
try self.consume(.LeftBrace, "Expect '{' before function body.");
try self.block();
const fun = try self.end();
try self.emitUnaryOp(.Closure, try self.makeConstant(fun.obj.value()));
for (compiler.upvalues.items) |upvalue| {
try self.emitByte(if (upvalue.isLocal) 1 else 0);
try self.emitByte(upvalue.index);
}
}
fn method(self: *Parser) !void {
try self.consume(.Identifier, "Expect method name.");
const constant = try self.identifierConstant(self.previous.lexeme);
const isInit = std.mem.eql(u8, self.previous.lexeme, "init");
try self.function(if (isInit) .Initializer else .Method);
try self.emitUnaryOp(.Method, constant);
}
fn classDeclaration(self: *Parser) !void {
try self.consume(.Identifier, "Expect class name.");
const className = self.previous.lexeme;
const nameConstant = try self.identifierConstant(className);
try self.declareVariable();
try self.emitUnaryOp(.Class, nameConstant);
try self.defineVariable(nameConstant);
var classCompiler = ClassCompiler{
.name = className,
.enclosing = self.currentClass,
.hasSuperclass = false,
};
self.currentClass = &classCompiler;
defer self.currentClass = self.currentClass.?.enclosing;
if (try self.match(.Less)) {
try self.consume(.Identifier, "Expect superclass name.");
try self.variable(false);
if (std.mem.eql(u8, className, self.previous.lexeme)) {
try self.err("A class cannot inherit from itself.");
}
self.beginScope();
try self.addLocal("super");
try self.defineVariable(0);
try self.namedVariable(className, false);
try self.emitOp(.Inherit);
classCompiler.hasSuperclass = true;
}
try self.namedVariable(className, false);
try self.consume(.LeftBrace, "Expect '{' before class body.");
while (!self.check(.RightBrace) and !self.check(.Eof)) {
try self.method();
}
try self.consume(.RightBrace, "Expect '}' after class body.");
// Pop the class now that we're done adding methods
try self.emitOp(.Pop);
if (classCompiler.hasSuperclass) try self.endScope();
}
fn funDeclaration(self: *Parser) !void {
const global = try self.parseVariable("Expect function name.");
self.markInitialized();
try self.function(.Function);
try self.defineVariable(global);
}
fn varDeclaration(self: *Parser) !void {
const global: u8 = try self.parseVariable("Expect variable name.");
if (try self.match(.Equal)) {
try self.expression();
} else {
try self.emitOp(.Nil);
}
try self.consume(.Semicolon, "Expect ';' after variable declaration.");
try self.defineVariable(global);
}
fn printStatement(self: *Parser) !void {
try self.expression();
try self.consume(.Semicolon, "Expect ';' after value.");
try self.emitOp(.Print);
}
fn returnStatement(self: *Parser) !void {
if (self.compiler.functionType == .Script) {
return try self.err("Cannot return from top-level code.");
}
if (try self.match(.Semicolon)) {
try self.emitReturn();
} else {
if (self.compiler.functionType == .Initializer) {
try self.err("Cannot return a value from an initializer.");
}
try self.expression();
try self.consume(.Semicolon, "Expect ';' after return value.");
try self.emitOp(.Return);
}
}
fn ifStatement(self: *Parser) CompilerErrors!void {
try self.consume(.LeftParen, "Expect '(' after 'if'.");
try self.expression();
try self.consume(.RightParen, "Expect ')' after condition.");
const thenJump = try self.emitJump(.JumpIfFalse);
try self.emitOp(.Pop);
try self.statement();
const elseJump = try self.emitJump(.Jump);
try self.patchJump(thenJump);
try self.emitOp(.Pop);
if (try self.match(.Else)) try self.statement();
try self.patchJump(elseJump);
}
fn whileStatement(self: *Parser) CompilerErrors!void {
const loopStart = self.currentChunk().code.items.len;
try self.consume(.LeftParen, "Expect '(' after 'while'.");
try self.expression();
try self.consume(.RightParen, "Expect ')' after condition.");
const exitJump = try self.emitJump(.JumpIfFalse);
try self.emitOp(.Pop);
try self.statement();
try self.emitLoop(loopStart);
try self.patchJump(exitJump);
try self.emitOp(.Pop);
}
fn forStatement(self: *Parser) CompilerErrors!void {
self.beginScope();
try self.consume(.LeftParen, "Expect '(' after 'for'.");
if (try self.match(.Semicolon)) {
// No initializer
} else if (try self.match(.Var)) {
try self.varDeclaration();
} else {
try self.expressionStatement();
}
var loopStart = self.currentChunk().code.items.len;
var maybeExitJump: ?usize = null;
if (!try self.match(.Semicolon)) {
try self.expression();
try self.consume(.Semicolon, "Expect ';' after loop condition.");
// Jump out of the loop if the condition is false
maybeExitJump = try self.emitJump(.JumpIfFalse);
try self.emitOp(.Pop); // Condition
}
if (!try self.match(.RightParen)) {
const bodyJump = try self.emitJump(.Jump);
const incrementStart = self.currentChunk().code.items.len;
try self.expression();
try self.emitOp(.Pop);
try self.consume(.RightParen, "Expect ')' after for clauses.");
try self.emitLoop(loopStart);
loopStart = incrementStart;
try self.patchJump(bodyJump);
}
try self.statement();
try self.emitLoop(loopStart);
if (maybeExitJump) |exitJump| {
try self.patchJump(exitJump);
try self.emitOp(.Pop);
}
try self.endScope();
}
fn expressionStatement(self: *Parser) !void {
try self.expression();
try self.consume(.Semicolon, "Expect ';' after expression.");
try self.emitOp(.Pop);
}
fn synchronize(self: *Parser) !void {
self.panicMode = false;
while (!self.check(.Eof)) {
if (self.previous.tokenType == .Semicolon) return;
switch (self.current.tokenType) {
.Class, .Fun, .Var, .For, .If, .While, .Print, .Return => return,
else => try self.advance(),
}
}
}
fn parsePrecedence(self: *Parser, precedence: Precedence) CompilerErrors!void {
try self.advance();
const canAssign = @enumToInt(precedence) <= @enumToInt(Precedence.Assignment);
try self.prefix(self.previous.tokenType, canAssign);
while (@enumToInt(precedence) <= @enumToInt(getPrecedence(self.current.tokenType))) {
try self.advance();
try self.infix(self.previous.tokenType, canAssign);
}
if (canAssign and try self.match(.Equal)) {
try self.err("Invalid assignment target.");
}
}
fn parseVariable(self: *Parser, message: []const u8) !u8 {
try self.consume(.Identifier, message);
try self.declareVariable();
if (self.compiler.scopeDepth > 0) return 0;
return try self.identifierConstant(self.previous.lexeme);
}
fn defineVariable(self: *Parser, global: u8) !void {
if (self.compiler.scopeDepth > 0) {
self.markInitialized();
return;
}
try self.emitUnaryOp(.DefineGlobal, global);
}
fn and_(self: *Parser) !void {
const endJump = try self.emitJump(.JumpIfFalse);
try self.emitOp(.Pop);
try self.parsePrecedence(.And);
try self.patchJump(endJump);
}
fn or_(self: *Parser) !void {
const elseJump = try self.emitJump(.JumpIfFalse);
const endJump = try self.emitJump(.Jump);
try self.patchJump(elseJump);
try self.emitOp(.Pop);
try self.parsePrecedence(.Or);
try self.patchJump(endJump);
}
fn markInitialized(self: *Parser) void {
const depth = self.compiler.scopeDepth;
if (depth == 0) return;
var locals = &self.compiler.locals;
locals.items[locals.items.len - 1].depth = @intCast(isize, depth);
}
fn identifierConstant(self: *Parser, name: []const u8) !u8 {
return try self.makeConstant(try self.stringValue(name));
}
fn declareVariable(self: *Parser) !void {
if (self.compiler.scopeDepth == 0) return;
const name = self.previous.lexeme;
var i: usize = 0;
while (i < self.compiler.locals.items.len) : (i += 1) {
const local = self.compiler.locals.items[self.compiler.locals.items.len - 1 - i];
if (local.depth != -1 and local.depth < self.compiler.scopeDepth) break;
if (std.mem.eql(u8, name, local.name)) {
try self.err("Variable with this name already declared in this scope.");
}
}
try self.addLocal(name);
}
fn addUpvalue(self: *Parser, compiler: *Compiler, index: u8, isLocal: bool) !usize {
for (compiler.upvalues.items) |upvalue, i| {
if (upvalue.index == index and upvalue.isLocal == isLocal) {
return i;
}
}
if (compiler.upvalues.items.len > maxInt(u8)) {
try self.err("Too many closure variables in function.");
return 0;
}
try compiler.upvalues.append(Upvalue{
.isLocal = isLocal,
.index = index,
});
compiler.function.upvalueCount += 1;
return compiler.upvalues.items.len - 1;
}
fn resolveLocal(self: *Parser, compiler: *Compiler, name: []const u8) !isize {
var locals = &compiler.locals;
var i: usize = 0;
while (i < locals.items.len) : (i += 1) {
const local = locals.items[locals.items.len - 1 - i];
if (std.mem.eql(u8, name, local.name)) {
if (local.depth == -1) {
try self.err("Cannot read local variable in its own initializer.");
}
return @intCast(isize, locals.items.len - 1 - i);
}
}
return -1;
}
fn resolveUpvalue(self: *Parser, compiler: *Compiler, name: []const u8) CompilerErrors!isize {
if (compiler.enclosing) |enclosing| {
const local = try self.resolveLocal(enclosing, name);
if (local != -1) {
enclosing.locals.items[@intCast(u8, local)].isCaptured = true;
const index = try self.addUpvalue(compiler, @intCast(u8, local), true);
return @intCast(isize, index);
}
const upvalue = try self.resolveUpvalue(enclosing, name);
if (upvalue != -1) {
const index = try self.addUpvalue(compiler, @intCast(u8, upvalue), false);
return @intCast(isize, index);
}
}
return -1;
}
fn addLocal(self: *Parser, name: []const u8) !void {
if (self.compiler.locals.items.len > maxInt(u8)) {
try self.err("Too many local variables in function.");
return;
}
const local = Local{
.name = name,
.depth = -1,
.isCaptured = false,
};
try self.compiler.locals.append(local);
}
fn prefix(self: *Parser, tokenType: TokenType, canAssign: bool) !void {
switch (tokenType) {
// Single-character tokens.
.LeftParen => try self.grouping(),
.Minus => try self.unary(),
.RightParen, .LeftBrace, .RightBrace, .Comma, .Dot => try self.prefixError(),
.Plus, .Semicolon, .Slash, .Star => try self.prefixError(),
// One or two character tokens.
.Bang => try self.unary(),
.Equal, .BangEqual, .EqualEqual, .Greater, .GreaterEqual => try self.prefixError(),
.Less, .LessEqual => try self.prefixError(),
// Literals.
.Identifier => try self.variable(canAssign),
.String => try self.string(),
.Number => try self.number(),
// Keywords.
.Nil, .True, .False => try self.literal(),
.This => try self.this(),
.Super => try self.super(),
.And, .Class, .Else, .For, .Fun, .If, .Or => try self.prefixError(),
.Print, .Return, .Var, .While, .Error, .Eof => try self.prefixError(),
}
}
fn infix(self: *Parser, tokenType: TokenType, canAssign: bool) !void {
switch (tokenType) {
// Single-character tokens.
.Minus, .Plus, .Slash, .Star => try self.binary(),
.LeftParen => try self.call(),
.Dot => try self.dot(canAssign),
.RightParen, .LeftBrace, .RightBrace, .Comma, .Semicolon => try self.infixError(),
// One or two character tokens.
.BangEqual, .EqualEqual, .Greater, .GreaterEqual => try self.binary(),
.Less, .LessEqual => try self.binary(),
.Bang, .Equal => try self.infixError(),
// Literals.
.Identifier, .String, .Number => try self.infixError(),
// Keywords.
.And => try self.and_(),
.Or => try self.or_(),
.Class, .Else, .False, .For, .Fun, .If, .Nil => try self.infixError(),
.Print, .Return, .Super, .This, .True, .Var, .While, .Error, .Eof => try self.infixError(),
}
}
fn number(self: *Parser) !void {
if (std.fmt.parseFloat(f64, self.previous.lexeme)) |value| {
try self.emitConstant(Value.fromNumber(value));
} else |e| switch (e) {
error.InvalidCharacter => {
try self.err("Could not parse number");
return;
},
}
}
fn literal(self: *Parser) !void {
switch (self.previous.tokenType) {
.Nil => try self.emitOp(.Nil),
.True => try self.emitOp(.True),
.False => try self.emitOp(.False),
else => try self.err("Unexpected literal"), // unreachable
}
}
fn stringValue(self: *Parser, source: []const u8) !Value {
return (try Obj.String.copy(self.vm, source)).obj.value();
}
fn string(self: *Parser) !void {
const source = self.previous.lexeme[1 .. self.previous.lexeme.len - 1];
try self.emitConstant(try self.stringValue(source));
}
fn variable(self: *Parser, canAssign: bool) !void {
try self.namedVariable(self.previous.lexeme, canAssign);
}
fn this(self: *Parser) !void {
if (self.currentClass == null) {
try self.err("Cannot use 'this' outside of a class.");
return;
}
try self.variable(false);
}
fn super(self: *Parser) !void {
if (self.currentClass) |currentClass| {
if (!currentClass.hasSuperclass) {
try self.err("Cannot use 'super' in a class with no superclass.");
}
} else {
try self.err("Cannot use 'super' outside of a class.");
}
try self.consume(.Dot, "Expect '.' after 'super'.");
try self.consume(.Identifier, "Expect superclass method name.");
const name = try self.identifierConstant(self.previous.lexeme);
try self.namedVariable("this", false);
if (try self.match(.LeftParen)) {
const argCount = try self.argumentList();
try self.namedVariable("super", false);
try self.emitUnaryOp(.SuperInvoke, name);
try self.emitByte(argCount);
} else {
try self.namedVariable("super", false);
try self.emitUnaryOp(.GetSuper, name);
}
}
fn namedVariable(self: *Parser, name: []const u8, canAssign: bool) !void {
var getOp: OpCode = undefined;
var setOp: OpCode = undefined;
var arg: u8 = undefined;
var resolvedArg = try self.resolveLocal(self.compiler, name);
if (resolvedArg != -1) {
arg = @intCast(u8, resolvedArg);
getOp = .GetLocal;
setOp = .SetLocal;
} else {
const maybeArg = try self.resolveUpvalue(self.compiler, name);
if (maybeArg != -1) {
arg = @intCast(u8, maybeArg);
getOp = .GetUpvalue;
setOp = .SetUpvalue;
} else {
arg = try self.identifierConstant(name);
getOp = .GetGlobal;
setOp = .SetGlobal;
}
}
if (canAssign and (try self.match(.Equal))) {
try self.expression();
try self.emitUnaryOp(setOp, arg);
} else {
try self.emitUnaryOp(getOp, arg);
}
}
fn grouping(self: *Parser) !void {
try self.expression();
try self.consume(.RightParen, "Expect ')' after expression.");
}
fn unary(self: *Parser) !void {
const operatorType = self.previous.tokenType;
// Compile the operand
try self.parsePrecedence(.Unary);
// Emit the operator instruction
switch (operatorType) {
.Bang => try self.emitOp(.Not),
.Minus => try self.emitOp(.Negate),
else => try self.err("Unexpected unary operator"), // unreachable
}
}
fn binary(self: *Parser) !void {
const operatorType = self.previous.tokenType;
try self.parsePrecedence(getPrecedence(operatorType).next());
switch (operatorType) {
.BangEqual => {
try self.emitOp(.Equal);
try self.emitOp(.Not);
},
.EqualEqual => try self.emitOp(.Equal),
.Greater => try self.emitOp(.Greater),
.GreaterEqual => {
// Note, incorrect IEEE semantics for NaN, same as book
try self.emitOp(.Less);
try self.emitOp(.Not);
},
.Less => try self.emitOp(.Less),
.LessEqual => {
// Note, incorrect IEEE semantics for NaN, same as book
try self.emitOp(.Greater);
try self.emitOp(.Not);
},
.Plus => try self.emitOp(.Add),
.Minus => try self.emitOp(.Subtract),
.Star => try self.emitOp(.Multiply),
.Slash => try self.emitOp(.Divide),
else => try self.err("Unexpected binary operator"), // unreachable
}
}
fn call(self: *Parser) !void {
const argCount = try self.argumentList();
try self.emitUnaryOp(.Call, argCount);
}
fn dot(self: *Parser, canAssign: bool) !void {
try self.consume(.Identifier, "Expect property name after '.'.");
const name = try self.identifierConstant(self.previous.lexeme);
if (canAssign and try self.match(.Equal)) {
try self.expression();
try self.emitUnaryOp(.SetProperty, name);
} else if (try self.match(.LeftParen)) {
const argCount = try self.argumentList();
try self.emitUnaryOp(.Invoke, name);
try self.emitByte(argCount);
} else {
try self.emitUnaryOp(.GetProperty, name);
}
}
fn argumentList(self: *Parser) !u8 {
var argCount: u8 = 0;
if (!self.check(.RightParen)) {
while (true) {
try self.expression();
if (argCount == 255) {
try self.err("Cannot have more than 255 arguments.");
break;
}
argCount += 1;
if (!try self.match(.Comma)) break;
}
}
try self.consume(.RightParen, "Expect ')' after arguments.");
return argCount;
}
}; | src/compiler.zig |
const std = @import("std");
const Coff = @import("Coff.zig");
const mem = std.mem;
const io = std.io;
var gpa_allocator = std.heap.GeneralPurposeAllocator(.{}){};
const gpa = gpa_allocator.allocator();
pub fn log(
comptime level: std.log.Level,
comptime scope: @TypeOf(.EnumLiteral),
comptime format: []const u8,
args: anytype,
) void {
if (@import("build_flags").enable_logging) {
std.log.defaultLog(level, scope, format, args);
}
}
const usage =
\\Usage: coff [options] [files...]
\\
\\Options:
\\-H, --help Print this help and exit
\\-h, --headers Print the section headers of the object file
\\-t, --syms Print the symbol table
\\-r, --relocs Print all relocations
;
pub fn main() !void {
defer if (@import("builtin").mode == .Debug) {
_ = gpa_allocator.deinit();
};
// we use arena for the arguments and its parsing
var arena_allocator = std.heap.ArenaAllocator.init(gpa);
defer arena_allocator.deinit();
const arena = arena_allocator.allocator();
const process_args = try std.process.argsAlloc(arena);
defer std.process.argsFree(arena, process_args);
const args = process_args[1..]; // exclude 'coff' binary
if (args.len == 0) {
printHelpAndExit();
}
var positionals = std.ArrayList([]const u8).init(arena);
var display_headers: bool = false;
var display_symtable: bool = false;
var display_relocations: bool = false;
var i: usize = 0;
while (i < args.len) : (i += 1) {
const arg = args[i];
if (mem.eql(u8, arg, "-H") or mem.eql(u8, arg, "--help")) {
printHelpAndExit();
} else if (mem.eql(u8, arg, "-t") or mem.eql(u8, arg, "--syms")) {
display_symtable = true;
} else if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--headers")) {
display_headers = true;
} else if (mem.eql(u8, arg, "-r") or mem.eql(u8, arg, "--relocs")) {
display_relocations = true;
} else if (mem.startsWith(u8, arg, "--")) {
printErrorAndExit("Unknown argument '{s}'", .{arg});
} else {
try positionals.append(arg);
}
}
if (positionals.items.len == 0) {
printErrorAndExit("Expected one or more object files, none were given", .{});
}
for (positionals.items) |path| {
const file = try std.fs.cwd().openFile(path, .{});
defer file.close();
var coff = Coff.init(arena, file, path);
defer coff.deinit();
try coff.parse();
try printDetails(coff);
if (display_headers) try printHeaders(coff);
if (display_symtable) try printSymtable(coff);
if (display_relocations) try printRelocs(coff);
}
}
fn printHelpAndExit() noreturn {
io.getStdOut().writer().print("{s}\n", .{usage}) catch {};
std.process.exit(0);
}
fn printErrorAndExit(comptime fmt: []const u8, args: anytype) noreturn {
const writer = io.getStdErr().writer();
writer.print(fmt, args) catch {};
writer.writeByte('\n') catch {};
std.process.exit(1);
}
fn printDetails(coff: Coff) !void {
const writer = io.getStdOut().writer();
try writer.print("\nFile content for '{s}':\n", .{coff.name});
}
fn printHeaders(coff: Coff) !void {
const writer = io.getStdOut().writer();
try writer.writeAll("\nSections:\n");
try writer.print("{s} {s: <13} {s: <8}\n", .{ "Idx", "Name", "Size" });
for (coff.section_table.items) |section_header, index| {
try writer.print("{d: >3} {s: <13} {x:0>8}\n", .{
index,
section_header.getName(&coff),
section_header.size_of_raw_data,
});
}
}
fn printSymtable(coff: Coff) !void {
const writer = io.getStdOut().writer();
try writer.writeAll("\nSymbol table:\n");
var index: u32 = 0;
while (index < coff.symbols.items.len) : (index += 1) {
const symbol = coff.symbols.items[index];
try writer.print("[{d: >3}](sec {d})(ty {x: >4})(scl {d: >3}) 0x{x:0>16} {s}\n", .{
index,
symbol.section_number,
symbol.sym_type,
@enumToInt(symbol.storage_class),
symbol.value,
symbol.getName(&coff),
});
index += symbol.number_aux_symbols;
}
}
fn printRelocs(coff: Coff) !void {
const writer = io.getStdOut().writer();
try writer.writeAll("\nRelocations:\n");
var it = coff.relocations.iterator();
while (it.next()) |entry| {
const section_header = coff.section_table.items[entry.key_ptr.*];
for (entry.value_ptr.*) |relocation| {
try writer.print("{s: >13} {x:0>16} {x:0>4} {s}\n", .{
section_header.getName(&coff),
relocation.virtual_address,
relocation.tag,
coff.symbols.items[relocation.symbol_table_index].getName(&coff),
});
}
}
} | src/main.zig |
const std = @import("std");
const builtin = @import("builtin");
const Scope = @import("scope.zig").Scope;
const Compilation = @import("compilation.zig").Compilation;
const ObjectFile = @import("codegen.zig").ObjectFile;
const llvm = @import("llvm.zig");
const Buffer = std.Buffer;
const assert = std.debug.assert;
/// Values are ref-counted, heap-allocated, and copy-on-write
/// If there is only 1 ref then write need not copy
pub const Value = struct {
id: Id,
typ: *Type,
ref_count: std.atomic.Int(usize),
/// Thread-safe
pub fn ref(base: *Value) void {
_ = base.ref_count.incr();
}
/// Thread-safe
pub fn deref(base: *Value, comp: *Compilation) void {
if (base.ref_count.decr() == 1) {
base.typ.base.deref(comp);
switch (base.id) {
Id.Type => @fieldParentPtr(Type, "base", base).destroy(comp),
Id.Fn => @fieldParentPtr(Fn, "base", base).destroy(comp),
Id.FnProto => @fieldParentPtr(FnProto, "base", base).destroy(comp),
Id.Void => @fieldParentPtr(Void, "base", base).destroy(comp),
Id.Bool => @fieldParentPtr(Bool, "base", base).destroy(comp),
Id.NoReturn => @fieldParentPtr(NoReturn, "base", base).destroy(comp),
Id.Ptr => @fieldParentPtr(Ptr, "base", base).destroy(comp),
Id.Int => @fieldParentPtr(Int, "base", base).destroy(comp),
Id.Array => @fieldParentPtr(Array, "base", base).destroy(comp),
}
}
}
pub fn setType(base: *Value, new_type: *Type, comp: *Compilation) void {
base.typ.base.deref(comp);
new_type.base.ref();
base.typ = new_type;
}
pub fn getRef(base: *Value) *Value {
base.ref();
return base;
}
pub fn cast(base: *Value, comptime T: type) ?*T {
if (base.id != @field(Id, @typeName(T))) return null;
return @fieldParentPtr(T, "base", base);
}
pub fn dump(base: *const Value) void {
std.debug.warn("{}", @tagName(base.id));
}
pub fn getLlvmConst(base: *Value, ofile: *ObjectFile) (error{OutOfMemory}!?llvm.ValueRef) {
switch (base.id) {
Id.Type => unreachable,
Id.Fn => return @fieldParentPtr(Fn, "base", base).getLlvmConst(ofile),
Id.FnProto => return @fieldParentPtr(FnProto, "base", base).getLlvmConst(ofile),
Id.Void => return null,
Id.Bool => return @fieldParentPtr(Bool, "base", base).getLlvmConst(ofile),
Id.NoReturn => unreachable,
Id.Ptr => return @fieldParentPtr(Ptr, "base", base).getLlvmConst(ofile),
Id.Int => return @fieldParentPtr(Int, "base", base).getLlvmConst(ofile),
Id.Array => return @fieldParentPtr(Array, "base", base).getLlvmConst(ofile),
}
}
pub fn derefAndCopy(self: *Value, comp: *Compilation) (error{OutOfMemory}!*Value) {
if (self.ref_count.get() == 1) {
// ( ͡° ͜ʖ ͡°)
return self;
}
assert(self.ref_count.decr() != 1);
return self.copy(comp);
}
pub fn copy(base: *Value, comp: *Compilation) (error{OutOfMemory}!*Value) {
switch (base.id) {
Id.Type => unreachable,
Id.Fn => unreachable,
Id.FnProto => unreachable,
Id.Void => unreachable,
Id.Bool => unreachable,
Id.NoReturn => unreachable,
Id.Ptr => unreachable,
Id.Array => unreachable,
Id.Int => return &(try @fieldParentPtr(Int, "base", base).copy(comp)).base,
}
}
pub const Parent = union(enum) {
None,
BaseStruct: BaseStruct,
BaseArray: BaseArray,
BaseUnion: *Value,
BaseScalar: *Value,
pub const BaseStruct = struct {
val: *Value,
field_index: usize,
};
pub const BaseArray = struct {
val: *Value,
elem_index: usize,
};
};
pub const Id = enum {
Type,
Fn,
Void,
Bool,
NoReturn,
Array,
Ptr,
Int,
FnProto,
};
pub const Type = @import("type.zig").Type;
pub const FnProto = struct {
base: Value,
/// The main external name that is used in the .o file.
/// TODO https://github.com/ziglang/zig/issues/265
symbol_name: Buffer,
pub fn create(comp: *Compilation, fn_type: *Type.Fn, symbol_name: Buffer) !*FnProto {
const self = try comp.gpa().create(FnProto);
self.* = FnProto{
.base = Value{
.id = Value.Id.FnProto,
.typ = &fn_type.base,
.ref_count = std.atomic.Int(usize).init(1),
},
.symbol_name = symbol_name,
};
fn_type.base.base.ref();
return self;
}
pub fn destroy(self: *FnProto, comp: *Compilation) void {
self.symbol_name.deinit();
comp.gpa().destroy(self);
}
pub fn getLlvmConst(self: *FnProto, ofile: *ObjectFile) !?llvm.ValueRef {
const llvm_fn_type = try self.base.typ.getLlvmType(ofile.arena, ofile.context);
const llvm_fn = llvm.AddFunction(
ofile.module,
self.symbol_name.ptr(),
llvm_fn_type,
) orelse return error.OutOfMemory;
// TODO port more logic from codegen.cpp:fn_llvm_value
return llvm_fn;
}
};
pub const Fn = struct {
base: Value,
/// The main external name that is used in the .o file.
/// TODO https://github.com/ziglang/zig/issues/265
symbol_name: Buffer,
/// parent should be the top level decls or container decls
fndef_scope: *Scope.FnDef,
/// parent is scope for last parameter
child_scope: *Scope,
/// parent is child_scope
block_scope: ?*Scope.Block,
/// Path to the object file that contains this function
containing_object: Buffer,
link_set_node: *std.LinkedList(?*Value.Fn).Node,
/// Creates a Fn value with 1 ref
/// Takes ownership of symbol_name
pub fn create(comp: *Compilation, fn_type: *Type.Fn, fndef_scope: *Scope.FnDef, symbol_name: Buffer) !*Fn {
const link_set_node = try comp.gpa().create(Compilation.FnLinkSet.Node);
link_set_node.* = Compilation.FnLinkSet.Node{
.data = null,
.next = undefined,
.prev = undefined,
};
errdefer comp.gpa().destroy(link_set_node);
const self = try comp.gpa().create(Fn);
self.* = Fn{
.base = Value{
.id = Value.Id.Fn,
.typ = &fn_type.base,
.ref_count = std.atomic.Int(usize).init(1),
},
.fndef_scope = fndef_scope,
.child_scope = &fndef_scope.base,
.block_scope = null,
.symbol_name = symbol_name,
.containing_object = Buffer.initNull(comp.gpa()),
.link_set_node = link_set_node,
};
fn_type.base.base.ref();
fndef_scope.fn_val = self;
fndef_scope.base.ref();
return self;
}
pub fn destroy(self: *Fn, comp: *Compilation) void {
// remove with a tombstone so that we do not have to grab a lock
if (self.link_set_node.data != null) {
// it's now the job of the link step to find this tombstone and
// deallocate it.
self.link_set_node.data = null;
} else {
comp.gpa().destroy(self.link_set_node);
}
self.containing_object.deinit();
self.fndef_scope.base.deref(comp);
self.symbol_name.deinit();
comp.gpa().destroy(self);
}
/// We know that the function definition will end up in an .o file somewhere.
/// Here, all we have to do is generate a global prototype.
/// TODO cache the prototype per ObjectFile
pub fn getLlvmConst(self: *Fn, ofile: *ObjectFile) !?llvm.ValueRef {
const llvm_fn_type = try self.base.typ.getLlvmType(ofile.arena, ofile.context);
const llvm_fn = llvm.AddFunction(
ofile.module,
self.symbol_name.ptr(),
llvm_fn_type,
) orelse return error.OutOfMemory;
// TODO port more logic from codegen.cpp:fn_llvm_value
return llvm_fn;
}
};
pub const Void = struct {
base: Value,
pub fn get(comp: *Compilation) *Void {
comp.void_value.base.ref();
return comp.void_value;
}
pub fn destroy(self: *Void, comp: *Compilation) void {
comp.gpa().destroy(self);
}
};
pub const Bool = struct {
base: Value,
x: bool,
pub fn get(comp: *Compilation, x: bool) *Bool {
if (x) {
comp.true_value.base.ref();
return comp.true_value;
} else {
comp.false_value.base.ref();
return comp.false_value;
}
}
pub fn destroy(self: *Bool, comp: *Compilation) void {
comp.gpa().destroy(self);
}
pub fn getLlvmConst(self: *Bool, ofile: *ObjectFile) ?llvm.ValueRef {
const llvm_type = llvm.Int1TypeInContext(ofile.context);
if (self.x) {
return llvm.ConstAllOnes(llvm_type);
} else {
return llvm.ConstNull(llvm_type);
}
}
};
pub const NoReturn = struct {
base: Value,
pub fn get(comp: *Compilation) *NoReturn {
comp.noreturn_value.base.ref();
return comp.noreturn_value;
}
pub fn destroy(self: *NoReturn, comp: *Compilation) void {
comp.gpa().destroy(self);
}
};
pub const Ptr = struct {
base: Value,
special: Special,
mut: Mut,
pub const Mut = enum {
CompTimeConst,
CompTimeVar,
RunTime,
};
pub const Special = union(enum) {
Scalar: *Value,
BaseArray: BaseArray,
BaseStruct: BaseStruct,
HardCodedAddr: u64,
Discard,
};
pub const BaseArray = struct {
val: *Value,
elem_index: usize,
};
pub const BaseStruct = struct {
val: *Value,
field_index: usize,
};
pub async fn createArrayElemPtr(
comp: *Compilation,
array_val: *Array,
mut: Type.Pointer.Mut,
size: Type.Pointer.Size,
elem_index: usize,
) !*Ptr {
array_val.base.ref();
errdefer array_val.base.deref(comp);
const elem_type = array_val.base.typ.cast(Type.Array).?.key.elem_type;
const ptr_type = try await (async Type.Pointer.get(comp, Type.Pointer.Key{
.child_type = elem_type,
.mut = mut,
.vol = Type.Pointer.Vol.Non,
.size = size,
.alignment = Type.Pointer.Align.Abi,
}) catch unreachable);
var ptr_type_consumed = false;
errdefer if (!ptr_type_consumed) ptr_type.base.base.deref(comp);
const self = try comp.gpa().create(Value.Ptr);
self.* = Value.Ptr{
.base = Value{
.id = Value.Id.Ptr,
.typ = &ptr_type.base,
.ref_count = std.atomic.Int(usize).init(1),
},
.special = Special{
.BaseArray = BaseArray{
.val = &array_val.base,
.elem_index = 0,
},
},
.mut = Mut.CompTimeConst,
};
ptr_type_consumed = true;
errdefer comp.gpa().destroy(self);
return self;
}
pub fn destroy(self: *Ptr, comp: *Compilation) void {
comp.gpa().destroy(self);
}
pub fn getLlvmConst(self: *Ptr, ofile: *ObjectFile) !?llvm.ValueRef {
const llvm_type = self.base.typ.getLlvmType(ofile.arena, ofile.context);
// TODO carefully port the logic from codegen.cpp:gen_const_val_ptr
switch (self.special) {
Special.Scalar => |scalar| @panic("TODO"),
Special.BaseArray => |base_array| {
// TODO put this in one .o file only, and after that, generate extern references to it
const array_llvm_value = (try base_array.val.getLlvmConst(ofile)).?;
const ptr_bit_count = ofile.comp.target_ptr_bits;
const usize_llvm_type = llvm.IntTypeInContext(ofile.context, ptr_bit_count) orelse return error.OutOfMemory;
const indices = []llvm.ValueRef{
llvm.ConstNull(usize_llvm_type) orelse return error.OutOfMemory,
llvm.ConstInt(usize_llvm_type, base_array.elem_index, 0) orelse return error.OutOfMemory,
};
return llvm.ConstInBoundsGEP(
array_llvm_value,
&indices,
@intCast(c_uint, indices.len),
) orelse return error.OutOfMemory;
},
Special.BaseStruct => |base_struct| @panic("TODO"),
Special.HardCodedAddr => |addr| @panic("TODO"),
Special.Discard => unreachable,
}
}
};
pub const Array = struct {
base: Value,
special: Special,
pub const Special = union(enum) {
Undefined,
OwnedBuffer: []u8,
Explicit: Data,
};
pub const Data = struct {
parent: Parent,
elements: []*Value,
};
/// Takes ownership of buffer
pub async fn createOwnedBuffer(comp: *Compilation, buffer: []u8) !*Array {
const u8_type = Type.Int.get_u8(comp);
defer u8_type.base.base.deref(comp);
const array_type = try await (async Type.Array.get(comp, Type.Array.Key{
.elem_type = &u8_type.base,
.len = buffer.len,
}) catch unreachable);
errdefer array_type.base.base.deref(comp);
const self = try comp.gpa().create(Value.Array);
self.* = Value.Array{
.base = Value{
.id = Value.Id.Array,
.typ = &array_type.base,
.ref_count = std.atomic.Int(usize).init(1),
},
.special = Special{ .OwnedBuffer = buffer },
};
errdefer comp.gpa().destroy(self);
return self;
}
pub fn destroy(self: *Array, comp: *Compilation) void {
switch (self.special) {
Special.Undefined => {},
Special.OwnedBuffer => |buf| {
comp.gpa().free(buf);
},
Special.Explicit => {},
}
comp.gpa().destroy(self);
}
pub fn getLlvmConst(self: *Array, ofile: *ObjectFile) !?llvm.ValueRef {
switch (self.special) {
Special.Undefined => {
const llvm_type = try self.base.typ.getLlvmType(ofile.arena, ofile.context);
return llvm.GetUndef(llvm_type);
},
Special.OwnedBuffer => |buf| {
const dont_null_terminate = 1;
const llvm_str_init = llvm.ConstStringInContext(
ofile.context,
buf.ptr,
@intCast(c_uint, buf.len),
dont_null_terminate,
) orelse return error.OutOfMemory;
const str_init_type = llvm.TypeOf(llvm_str_init);
const global = llvm.AddGlobal(ofile.module, str_init_type, c"") orelse return error.OutOfMemory;
llvm.SetInitializer(global, llvm_str_init);
llvm.SetLinkage(global, llvm.PrivateLinkage);
llvm.SetGlobalConstant(global, 1);
llvm.SetUnnamedAddr(global, 1);
llvm.SetAlignment(global, llvm.ABIAlignmentOfType(ofile.comp.target_data_ref, str_init_type));
return global;
},
Special.Explicit => @panic("TODO"),
}
//{
// uint64_t len = type_entry->data.array.len;
// if (const_val->data.x_array.special == ConstArraySpecialUndef) {
// return LLVMGetUndef(type_entry->type_ref);
// }
// LLVMValueRef *values = allocate<LLVMValueRef>(len);
// LLVMTypeRef element_type_ref = type_entry->data.array.child_type->type_ref;
// bool make_unnamed_struct = false;
// for (uint64_t i = 0; i < len; i += 1) {
// ConstExprValue *elem_value = &const_val->data.x_array.s_none.elements[i];
// LLVMValueRef val = gen_const_val(g, elem_value, "");
// values[i] = val;
// make_unnamed_struct = make_unnamed_struct || is_llvm_value_unnamed_type(elem_value->type, val);
// }
// if (make_unnamed_struct) {
// return LLVMConstStruct(values, len, true);
// } else {
// return LLVMConstArray(element_type_ref, values, (unsigned)len);
// }
//}
}
};
pub const Int = struct {
base: Value,
big_int: std.math.big.Int,
pub fn createFromString(comp: *Compilation, typ: *Type, base: u8, value: []const u8) !*Int {
const self = try comp.gpa().create(Value.Int);
self.* = Value.Int{
.base = Value{
.id = Value.Id.Int,
.typ = typ,
.ref_count = std.atomic.Int(usize).init(1),
},
.big_int = undefined,
};
typ.base.ref();
errdefer comp.gpa().destroy(self);
self.big_int = try std.math.big.Int.init(comp.gpa());
errdefer self.big_int.deinit();
try self.big_int.setString(base, value);
return self;
}
pub fn getLlvmConst(self: *Int, ofile: *ObjectFile) !?llvm.ValueRef {
switch (self.base.typ.id) {
Type.Id.Int => {
const type_ref = try self.base.typ.getLlvmType(ofile.arena, ofile.context);
if (self.big_int.len == 0) {
return llvm.ConstNull(type_ref);
}
const unsigned_val = if (self.big_int.len == 1) blk: {
break :blk llvm.ConstInt(type_ref, self.big_int.limbs[0], @boolToInt(false));
} else if (@sizeOf(std.math.big.Limb) == @sizeOf(u64)) blk: {
break :blk llvm.ConstIntOfArbitraryPrecision(
type_ref,
@intCast(c_uint, self.big_int.len),
@ptrCast([*]u64, self.big_int.limbs.ptr),
);
} else {
@compileError("std.math.Big.Int.Limb size does not match LLVM");
};
return if (self.big_int.positive) unsigned_val else llvm.ConstNeg(unsigned_val);
},
Type.Id.ComptimeInt => unreachable,
else => unreachable,
}
}
pub fn copy(old: *Int, comp: *Compilation) !*Int {
old.base.typ.base.ref();
errdefer old.base.typ.base.deref(comp);
const new = try comp.gpa().create(Value.Int);
new.* = Value.Int{
.base = Value{
.id = Value.Id.Int,
.typ = old.base.typ,
.ref_count = std.atomic.Int(usize).init(1),
},
.big_int = undefined,
};
errdefer comp.gpa().destroy(new);
new.big_int = try old.big_int.clone();
errdefer new.big_int.deinit();
return new;
}
pub fn destroy(self: *Int, comp: *Compilation) void {
self.big_int.deinit();
comp.gpa().destroy(self);
}
};
}; | src-self-hosted/value.zig |
const std = @import("std");
const mach = @import("mach");
const gpu = @import("gpu");
const glfw = @import("glfw");
const zm = @import("zmath");
const Vertex = @import("cube_mesh.zig").Vertex;
const vertices = @import("cube_mesh.zig").vertices;
const App = @This();
const UniformBufferObject = struct {
mat: zm.Mat,
};
var timer: mach.Timer = undefined;
pipeline: gpu.RenderPipeline,
queue: gpu.Queue,
vertex_buffer: gpu.Buffer,
uniform_buffer: gpu.Buffer,
bind_group: gpu.BindGroup,
depth_texture: ?gpu.Texture,
depth_texture_view: gpu.TextureView,
cube_texture: gpu.Texture,
cube_texture_view: gpu.TextureView,
cube_texture_render: gpu.Texture,
cube_texture_view_render: gpu.TextureView,
sampler: gpu.Sampler,
bgl: gpu.BindGroupLayout,
pub fn init(app: *App, engine: *mach.Engine) !void {
timer = try mach.Timer.start();
try engine.core.setSizeLimits(.{ .width = 20, .height = 20 }, .{ .width = null, .height = null });
const vs_module = engine.gpu_driver.device.createShaderModule(&.{
.label = "my vertex shader",
.code = .{ .wgsl = @embedFile("vert.wgsl") },
});
const vertex_attributes = [_]gpu.VertexAttribute{
.{ .format = .float32x4, .offset = @offsetOf(Vertex, "pos"), .shader_location = 0 },
.{ .format = .float32x2, .offset = @offsetOf(Vertex, "uv"), .shader_location = 1 },
};
const vertex_buffer_layout = gpu.VertexBufferLayout{
.array_stride = @sizeOf(Vertex),
.step_mode = .vertex,
.attribute_count = vertex_attributes.len,
.attributes = &vertex_attributes,
};
const fs_module = engine.gpu_driver.device.createShaderModule(&.{
.label = "my fragment shader",
.code = .{ .wgsl = @embedFile("frag.wgsl") },
});
const blend = gpu.BlendState{
.color = .{
.operation = .add,
.src_factor = .one,
.dst_factor = .zero,
},
.alpha = .{
.operation = .add,
.src_factor = .one,
.dst_factor = .zero,
},
};
const color_target = gpu.ColorTargetState{
.format = engine.gpu_driver.swap_chain_format,
.blend = &blend,
.write_mask = gpu.ColorWriteMask.all,
};
const fragment = gpu.FragmentState{
.module = fs_module,
.entry_point = "main",
.targets = &.{color_target},
.constants = null,
};
const bgle_buffer = gpu.BindGroupLayout.Entry.buffer(0, .{ .vertex = true }, .uniform, true, 0);
const bgle_sampler = gpu.BindGroupLayout.Entry.sampler(1, .{ .fragment = true }, .filtering);
const bgle_textureview = gpu.BindGroupLayout.Entry.texture(2, .{ .fragment = true }, .float, .dimension_2d, false);
const bgl = engine.gpu_driver.device.createBindGroupLayout(
&gpu.BindGroupLayout.Descriptor{
.entries = &.{ bgle_buffer, bgle_sampler, bgle_textureview },
},
);
const bind_group_layouts = [_]gpu.BindGroupLayout{bgl};
const pipeline_layout = engine.gpu_driver.device.createPipelineLayout(&.{
.bind_group_layouts = &bind_group_layouts,
});
const pipeline_descriptor = gpu.RenderPipeline.Descriptor{
.fragment = &fragment,
.layout = pipeline_layout,
.depth_stencil = &.{
.format = .depth24_plus,
.depth_write_enabled = true,
.depth_compare = .less,
},
.vertex = .{
.module = vs_module,
.entry_point = "main",
.buffers = &.{vertex_buffer_layout},
},
.multisample = .{
.count = 1,
.mask = 0xFFFFFFFF,
.alpha_to_coverage_enabled = false,
},
.primitive = .{
.front_face = .ccw,
.cull_mode = .back,
.topology = .triangle_list,
.strip_index_format = .none,
},
};
const vertex_buffer = engine.gpu_driver.device.createBuffer(&.{
.usage = .{ .vertex = true },
.size = @sizeOf(Vertex) * vertices.len,
.mapped_at_creation = true,
});
var vertex_mapped = vertex_buffer.getMappedRange(Vertex, 0, vertices.len);
std.mem.copy(Vertex, vertex_mapped, vertices[0..]);
vertex_buffer.unmap();
const uniform_buffer = engine.gpu_driver.device.createBuffer(&.{
.usage = .{ .copy_dst = true, .uniform = true },
.size = @sizeOf(UniformBufferObject),
.mapped_at_creation = false,
});
// The texture to put on the cube
const cube_texture = engine.gpu_driver.device.createTexture(&gpu.Texture.Descriptor{
.usage = .{ .texture_binding = true, .copy_dst = true },
.size = .{ .width = engine.gpu_driver.current_desc.width, .height = engine.gpu_driver.current_desc.height },
.format = engine.gpu_driver.swap_chain_format,
});
// The texture on which we render
const cube_texture_render = engine.gpu_driver.device.createTexture(&gpu.Texture.Descriptor{
.usage = .{ .render_attachment = true, .copy_src = true },
.size = .{ .width = engine.gpu_driver.current_desc.width, .height = engine.gpu_driver.current_desc.height },
.format = engine.gpu_driver.swap_chain_format,
});
const sampler = engine.gpu_driver.device.createSampler(&gpu.Sampler.Descriptor{
.mag_filter = .linear,
.min_filter = .linear,
});
const cube_texture_view = cube_texture.createView(&gpu.TextureView.Descriptor{
.format = engine.gpu_driver.swap_chain_format,
.dimension = .dimension_2d,
.mip_level_count = 1,
.array_layer_count = 1,
});
const cube_texture_view_render = cube_texture_render.createView(&gpu.TextureView.Descriptor{
.format = engine.gpu_driver.swap_chain_format,
.dimension = .dimension_2d,
.mip_level_count = 1,
.array_layer_count = 1,
});
const bind_group = engine.gpu_driver.device.createBindGroup(
&gpu.BindGroup.Descriptor{
.layout = bgl,
.entries = &.{
gpu.BindGroup.Entry.buffer(0, uniform_buffer, 0, @sizeOf(UniformBufferObject)),
gpu.BindGroup.Entry.sampler(1, sampler),
gpu.BindGroup.Entry.textureView(2, cube_texture_view),
},
},
);
app.pipeline = engine.gpu_driver.device.createRenderPipeline(&pipeline_descriptor);
app.queue = engine.gpu_driver.device.getQueue();
app.vertex_buffer = vertex_buffer;
app.uniform_buffer = uniform_buffer;
app.bind_group = bind_group;
app.depth_texture = null;
app.depth_texture_view = undefined;
app.cube_texture = cube_texture;
app.cube_texture_view = cube_texture_view;
app.cube_texture_render = cube_texture_render;
app.cube_texture_view_render = cube_texture_view_render;
app.sampler = sampler;
app.bgl = bgl;
vs_module.release();
fs_module.release();
pipeline_layout.release();
}
pub fn deinit(app: *App, _: *mach.Engine) void {
app.bgl.release();
app.vertex_buffer.release();
app.uniform_buffer.release();
app.cube_texture.release();
app.cube_texture_render.release();
app.sampler.release();
app.cube_texture_view.release();
app.cube_texture_view_render.release();
app.bind_group.release();
app.depth_texture.?.release();
app.depth_texture_view.release();
}
pub fn update(app: *App, engine: *mach.Engine) !bool {
while (engine.core.pollEvent()) |event| {
switch (event) {
.key_press => |ev| {
if (ev.key == .space)
engine.core.setShouldClose(true);
},
else => {},
}
}
const cube_view = app.cube_texture_view_render;
const back_buffer_view = engine.gpu_driver.swap_chain.?.getCurrentTextureView();
const cube_color_attachment = gpu.RenderPassColorAttachment{
.view = cube_view,
.resolve_target = null,
.clear_value = gpu.Color{ .r = 0.5, .g = 0.5, .b = 0.5, .a = 1 },
.load_op = .clear,
.store_op = .store,
};
const color_attachment = gpu.RenderPassColorAttachment{
.view = back_buffer_view,
.resolve_target = null,
.clear_value = gpu.Color{ .r = 0.5, .g = 0.5, .b = 0.5, .a = 1 },
.load_op = .clear,
.store_op = .store,
};
const depth_stencil_attachment = gpu.RenderPassDepthStencilAttachment{
.view = app.depth_texture_view,
.depth_load_op = .clear,
.depth_store_op = .store,
.depth_clear_value = 1.0,
.stencil_load_op = .none,
.stencil_store_op = .none,
};
const encoder = engine.gpu_driver.device.createCommandEncoder(null);
const cube_render_pass_info = gpu.RenderPassEncoder.Descriptor{
.color_attachments = &.{cube_color_attachment},
.depth_stencil_attachment = &depth_stencil_attachment,
};
const render_pass_info = gpu.RenderPassEncoder.Descriptor{
.color_attachments = &.{color_attachment},
.depth_stencil_attachment = &depth_stencil_attachment,
};
{
const time = timer.read();
const model = zm.mul(zm.rotationX(time * (std.math.pi / 2.0)), zm.rotationZ(time * (std.math.pi / 2.0)));
const view = zm.lookAtRh(
zm.f32x4(0, -4, 0, 1),
zm.f32x4(0, 0, 0, 1),
zm.f32x4(0, 0, 1, 0),
);
const proj = zm.perspectiveFovRh(
(std.math.pi * 2.0 / 5.0),
@intToFloat(f32, engine.gpu_driver.current_desc.width) / @intToFloat(f32, engine.gpu_driver.current_desc.height),
1,
100,
);
const ubo = UniformBufferObject{
.mat = zm.transpose(zm.mul(zm.mul(model, view), proj)),
};
encoder.writeBuffer(app.uniform_buffer, 0, UniformBufferObject, &.{ubo});
}
const pass = encoder.beginRenderPass(&render_pass_info);
pass.setPipeline(app.pipeline);
pass.setBindGroup(0, app.bind_group, &.{0});
pass.setVertexBuffer(0, app.vertex_buffer, 0, @sizeOf(Vertex) * vertices.len);
pass.draw(vertices.len, 1, 0, 0);
pass.end();
pass.release();
encoder.copyTextureToTexture(
&gpu.ImageCopyTexture{
.texture = app.cube_texture_render,
},
&gpu.ImageCopyTexture{
.texture = app.cube_texture,
},
&.{ .width = engine.gpu_driver.current_desc.width, .height = engine.gpu_driver.current_desc.height },
);
const cube_pass = encoder.beginRenderPass(&cube_render_pass_info);
cube_pass.setPipeline(app.pipeline);
cube_pass.setBindGroup(0, app.bind_group, &.{0});
cube_pass.setVertexBuffer(0, app.vertex_buffer, 0, @sizeOf(Vertex) * vertices.len);
cube_pass.draw(vertices.len, 1, 0, 0);
cube_pass.end();
cube_pass.release();
var command = encoder.finish(null);
encoder.release();
app.queue.submit(&.{command});
command.release();
engine.gpu_driver.swap_chain.?.present();
back_buffer_view.release();
return true;
}
pub fn resize(app: *App, engine: *mach.Engine, width: u32, height: u32) !void {
if (app.depth_texture != null) {
app.depth_texture.?.release();
app.depth_texture = engine.gpu_driver.device.createTexture(&gpu.Texture.Descriptor{
.usage = .{ .render_attachment = true },
.size = .{ .width = width, .height = height },
.format = .depth24_plus,
});
app.cube_texture.release();
app.cube_texture = engine.gpu_driver.device.createTexture(&gpu.Texture.Descriptor{
.usage = .{ .texture_binding = true, .copy_dst = true },
.size = .{ .width = width, .height = height },
.format = engine.gpu_driver.swap_chain_format,
});
app.cube_texture_render.release();
app.cube_texture_render = engine.gpu_driver.device.createTexture(&gpu.Texture.Descriptor{
.usage = .{ .render_attachment = true, .copy_src = true },
.size = .{ .width = width, .height = height },
.format = engine.gpu_driver.swap_chain_format,
});
app.depth_texture_view.release();
app.depth_texture_view = app.depth_texture.?.createView(&gpu.TextureView.Descriptor{
.format = .depth24_plus,
.dimension = .dimension_2d,
.array_layer_count = 1,
.mip_level_count = 1,
});
app.cube_texture_view.release();
app.cube_texture_view = app.cube_texture.createView(&gpu.TextureView.Descriptor{
.format = engine.gpu_driver.swap_chain_format,
.dimension = .dimension_2d,
.mip_level_count = 1,
.array_layer_count = 1,
});
app.cube_texture_view_render.release();
app.cube_texture_view_render = app.cube_texture_render.createView(&gpu.TextureView.Descriptor{
.format = engine.gpu_driver.swap_chain_format,
.dimension = .dimension_2d,
.mip_level_count = 1,
.array_layer_count = 1,
});
app.bind_group.release();
app.bind_group = engine.gpu_driver.device.createBindGroup(
&gpu.BindGroup.Descriptor{
.layout = app.bgl,
.entries = &.{
gpu.BindGroup.Entry.buffer(0, app.uniform_buffer, 0, @sizeOf(UniformBufferObject)),
gpu.BindGroup.Entry.sampler(1, app.sampler),
gpu.BindGroup.Entry.textureView(2, app.cube_texture_view),
},
},
);
} else {
app.depth_texture = engine.gpu_driver.device.createTexture(&gpu.Texture.Descriptor{
.usage = .{ .render_attachment = true },
.size = .{ .width = width, .height = height },
.format = .depth24_plus,
});
app.depth_texture_view = app.depth_texture.?.createView(&gpu.TextureView.Descriptor{
.format = .depth24_plus,
.dimension = .dimension_2d,
.array_layer_count = 1,
.mip_level_count = 1,
});
}
} | examples/fractal-cube/main.zig |
const builtin = @import("builtin");
const std = @import("std");
const time = std.time;
const testing = std.testing;
const Allocator = std.mem.Allocator;
const heap = std.heap;
const Hash = @import("hash.zig").H;
const o = @import("ops.zig");
const Op = o.Op;
const OpTag = o.OpTag;
const U = @import("util.zig");
const Merk = @import("merk.zig").Merk;
fn buildBatch(allocator: *Allocator, ops: []Op, comptime loop: usize, counter: usize) !void {
var i: usize = 0;
var buffer: [100]u8 = undefined;
while (i < loop) : (i += 1) {
// key
const key = Hash.init(U.intToString(&buffer, @as(u64, (i + loop * counter))));
var key_buf = try std.ArrayList(u8).initCapacity(allocator, key.inner.len);
defer key_buf.deinit();
try key_buf.appendSlice(&key.inner);
// val
var buf: [255]u8 = undefined;
const val = buf[0..U.randRepeatString(&buf, 98, 255, u8, @as(u64, i))];
var val_buf = try std.ArrayList(u8).initCapacity(allocator, val.len);
defer val_buf.deinit();
try val_buf.appendSlice(val);
ops[i] = Op{ .op = OpTag.Put, .key = key_buf.toOwnedSlice(), .val = val_buf.toOwnedSlice() };
}
}
fn fromInitToDeint(allocator: *Allocator, timer: *time.Timer, ops: []Op, i: usize) !u128 {
var merk = try Merk.init(allocator, "dbtest");
if (i == 0) merk.tree = null; // init
timer.reset();
try merk.apply(ops);
try merk.commit();
const runtime = timer.read();
std.debug.print("counter: {}, runtime: {}\n", .{ i, runtime });
merk.deinit();
return runtime;
}
fn hashing(timer: *time.Timer, i: usize) !u128 {
timer.reset();
var buffer: [100]u8 = undefined;
// _ = std.hash.Wyhash.hash(i, U.intToString(&buffer, @as(u64, (i))));
_ = Hash.init(U.intToString(&buffer, @as(u64, (i))));
const runtime = timer.read();
return runtime;
}
test "benchmark: kv hashing" {
@setRuntimeSafety(false);
var timer = try time.Timer.start();
var runtime_sum: u128 = 0;
var i: usize = 0;
var loop: usize = 1000;
while (i < loop) : (i += 1) {
runtime_sum += try hashing(&timer, i);
doNotOptimize(hashing);
}
const runtime_mean = runtime_sum / loop;
std.debug.print("Iterations: {}, Mean(ns): {}\n", .{ loop, runtime_mean });
}
test "benchmark: add and put with no commit" {
var batch_buf: [8_000_000]u8 = undefined;
var batch_fixed_buf = heap.FixedBufferAllocator.init(&batch_buf);
var merk_buf: [8_000_000]u8 = undefined;
var merk_fixed_buf = heap.FixedBufferAllocator.init(&merk_buf);
const batch_size: usize = 1_000;
var ops: [batch_size]Op = undefined;
var timer = try time.Timer.start();
var runtime_sum: u128 = 0;
var i: usize = 0;
var loop: usize = 10;
while (i < loop) : (i += 1) {
// prepare batch
var batch_arena = heap.ArenaAllocator.init(&batch_fixed_buf.allocator);
try buildBatch(&batch_arena.allocator, &ops, batch_size, i);
o.sortBatch(&ops);
var merk_arena = heap.ArenaAllocator.init(&merk_fixed_buf.allocator);
runtime_sum += try fromInitToDeint(&merk_arena.allocator, &timer, &ops, i);
doNotOptimize(fromInitToDeint);
merk_arena.deinit();
batch_arena.deinit();
}
const runtime_mean = runtime_sum / loop;
std.debug.print("Iterations: {}, Mean(ns): {}\n", .{ loop, runtime_mean });
}
/// Pretend to use the value so the optimizer cant optimize it out.
fn doNotOptimize(val: anytype) void {
const T = @TypeOf(val);
var store: T = undefined;
@ptrCast(*volatile T, &store).* = val;
} | src/benchmark.zig |
const std = @import("std");
const fs = std.fs;
const io = std.io;
const mem = std.mem;
const Allocator = mem.Allocator;
const Target = std.Target;
const target = @import("target.zig");
const assert = std.debug.assert;
const glibc = @import("glibc.zig");
const introspect = @import("introspect.zig");
const fatal = @import("main.zig").fatal;
pub fn cmdTargets(
allocator: *Allocator,
args: []const []const u8,
/// Output stream
stdout: anytype,
native_target: Target,
) !void {
var zig_lib_directory = introspect.findZigLibDir(allocator) catch |err| {
fatal("unable to find zig installation directory: {s}\n", .{@errorName(err)});
};
defer zig_lib_directory.handle.close();
defer allocator.free(zig_lib_directory.path.?);
const glibc_abi = try glibc.loadMetaData(allocator, zig_lib_directory.handle);
defer glibc_abi.destroy(allocator);
var bos = io.bufferedOutStream(stdout);
const bos_stream = bos.outStream();
var jws = std.json.WriteStream(@TypeOf(bos_stream), 6).init(bos_stream);
try jws.beginObject();
try jws.objectField("arch");
try jws.beginArray();
{
inline for (@typeInfo(Target.Cpu.Arch).Enum.fields) |field| {
try jws.arrayElem();
try jws.emitString(field.name);
}
}
try jws.endArray();
try jws.objectField("os");
try jws.beginArray();
inline for (@typeInfo(Target.Os.Tag).Enum.fields) |field| {
try jws.arrayElem();
try jws.emitString(field.name);
}
try jws.endArray();
try jws.objectField("abi");
try jws.beginArray();
inline for (@typeInfo(Target.Abi).Enum.fields) |field| {
try jws.arrayElem();
try jws.emitString(field.name);
}
try jws.endArray();
try jws.objectField("libc");
try jws.beginArray();
for (target.available_libcs) |libc| {
const tmp = try std.fmt.allocPrint(allocator, "{s}-{s}-{s}", .{
@tagName(libc.arch), @tagName(libc.os), @tagName(libc.abi),
});
defer allocator.free(tmp);
try jws.arrayElem();
try jws.emitString(tmp);
}
try jws.endArray();
try jws.objectField("glibc");
try jws.beginArray();
for (glibc_abi.all_versions) |ver| {
try jws.arrayElem();
const tmp = try std.fmt.allocPrint(allocator, "{}", .{ver});
defer allocator.free(tmp);
try jws.emitString(tmp);
}
try jws.endArray();
try jws.objectField("cpus");
try jws.beginObject();
inline for (@typeInfo(Target.Cpu.Arch).Enum.fields) |field| {
try jws.objectField(field.name);
try jws.beginObject();
const arch = @field(Target.Cpu.Arch, field.name);
for (arch.allCpuModels()) |model| {
try jws.objectField(model.name);
try jws.beginArray();
for (arch.allFeaturesList()) |feature, i| {
if (model.features.isEnabled(@intCast(u8, i))) {
try jws.arrayElem();
try jws.emitString(feature.name);
}
}
try jws.endArray();
}
try jws.endObject();
}
try jws.endObject();
try jws.objectField("cpuFeatures");
try jws.beginObject();
inline for (@typeInfo(Target.Cpu.Arch).Enum.fields) |field| {
try jws.objectField(field.name);
try jws.beginArray();
const arch = @field(Target.Cpu.Arch, field.name);
for (arch.allFeaturesList()) |feature| {
try jws.arrayElem();
try jws.emitString(feature.name);
}
try jws.endArray();
}
try jws.endObject();
try jws.objectField("native");
try jws.beginObject();
{
const triple = try native_target.zigTriple(allocator);
defer allocator.free(triple);
try jws.objectField("triple");
try jws.emitString(triple);
}
{
try jws.objectField("cpu");
try jws.beginObject();
try jws.objectField("arch");
try jws.emitString(@tagName(native_target.cpu.arch));
try jws.objectField("name");
const cpu = native_target.cpu;
try jws.emitString(cpu.model.name);
{
try jws.objectField("features");
try jws.beginArray();
for (native_target.cpu.arch.allFeaturesList()) |feature, i_usize| {
const index = @intCast(Target.Cpu.Feature.Set.Index, i_usize);
if (cpu.features.isEnabled(index)) {
try jws.arrayElem();
try jws.emitString(feature.name);
}
}
try jws.endArray();
}
try jws.endObject();
}
try jws.objectField("os");
try jws.emitString(@tagName(native_target.os.tag));
try jws.objectField("abi");
try jws.emitString(@tagName(native_target.abi));
try jws.endObject();
try jws.endObject();
try bos_stream.writeByte('\n');
return bos.flush();
} | src/print_targets.zig |
//--------------------------------------------------------------------------------
// Section: Types (14)
//--------------------------------------------------------------------------------
// TODO: this type is limited to platform 'windows6.1'
const IID_IAudioEndpointFormatControl_Value = Guid.initString("784cfd40-9f89-456e-a1a6-873b006a664e");
pub const IID_IAudioEndpointFormatControl = &IID_IAudioEndpointFormatControl_Value;
pub const IAudioEndpointFormatControl = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
ResetToDefault: fn(
self: *const IAudioEndpointFormatControl,
ResetFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioEndpointFormatControl_ResetToDefault(self: *const T, ResetFlags: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioEndpointFormatControl.VTable, self.vtable).ResetToDefault(@ptrCast(*const IAudioEndpointFormatControl, self), ResetFlags);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const EndpointConnectorType = enum(i32) {
HostProcessConnector = 0,
OffloadConnector = 1,
LoopbackConnector = 2,
KeywordDetectorConnector = 3,
ConnectorCount = 4,
};
pub const eHostProcessConnector = EndpointConnectorType.HostProcessConnector;
pub const eOffloadConnector = EndpointConnectorType.OffloadConnector;
pub const eLoopbackConnector = EndpointConnectorType.LoopbackConnector;
pub const eKeywordDetectorConnector = EndpointConnectorType.KeywordDetectorConnector;
pub const eConnectorCount = EndpointConnectorType.ConnectorCount;
pub const AUDIO_ENDPOINT_SHARED_CREATE_PARAMS = extern struct {
u32Size: u32,
u32TSSessionId: u32,
targetEndpointConnectorType: EndpointConnectorType,
wfxDeviceFormat: WAVEFORMATEX,
};
const IID_IAudioEndpointOffloadStreamVolume_Value = Guid.initString("64f1dd49-71ca-4281-8672-3a9eddd1d0b6");
pub const IID_IAudioEndpointOffloadStreamVolume = &IID_IAudioEndpointOffloadStreamVolume_Value;
pub const IAudioEndpointOffloadStreamVolume = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetVolumeChannelCount: fn(
self: *const IAudioEndpointOffloadStreamVolume,
pu32ChannelCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetChannelVolumes: fn(
self: *const IAudioEndpointOffloadStreamVolume,
u32ChannelCount: u32,
pf32Volumes: ?*f32,
u32CurveType: AUDIO_CURVE_TYPE,
pCurveDuration: ?*i64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetChannelVolumes: fn(
self: *const IAudioEndpointOffloadStreamVolume,
u32ChannelCount: u32,
pf32Volumes: ?*f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioEndpointOffloadStreamVolume_GetVolumeChannelCount(self: *const T, pu32ChannelCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioEndpointOffloadStreamVolume.VTable, self.vtable).GetVolumeChannelCount(@ptrCast(*const IAudioEndpointOffloadStreamVolume, self), pu32ChannelCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioEndpointOffloadStreamVolume_SetChannelVolumes(self: *const T, u32ChannelCount: u32, pf32Volumes: ?*f32, u32CurveType: AUDIO_CURVE_TYPE, pCurveDuration: ?*i64) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioEndpointOffloadStreamVolume.VTable, self.vtable).SetChannelVolumes(@ptrCast(*const IAudioEndpointOffloadStreamVolume, self), u32ChannelCount, pf32Volumes, u32CurveType, pCurveDuration);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioEndpointOffloadStreamVolume_GetChannelVolumes(self: *const T, u32ChannelCount: u32, pf32Volumes: ?*f32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioEndpointOffloadStreamVolume.VTable, self.vtable).GetChannelVolumes(@ptrCast(*const IAudioEndpointOffloadStreamVolume, self), u32ChannelCount, pf32Volumes);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IAudioEndpointOffloadStreamMute_Value = Guid.initString("dfe21355-5ec2-40e0-8d6b-710ac3c00249");
pub const IID_IAudioEndpointOffloadStreamMute = &IID_IAudioEndpointOffloadStreamMute_Value;
pub const IAudioEndpointOffloadStreamMute = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetMute: fn(
self: *const IAudioEndpointOffloadStreamMute,
bMuted: u8,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetMute: fn(
self: *const IAudioEndpointOffloadStreamMute,
pbMuted: ?*u8,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioEndpointOffloadStreamMute_SetMute(self: *const T, bMuted: u8) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioEndpointOffloadStreamMute.VTable, self.vtable).SetMute(@ptrCast(*const IAudioEndpointOffloadStreamMute, self), bMuted);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioEndpointOffloadStreamMute_GetMute(self: *const T, pbMuted: ?*u8) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioEndpointOffloadStreamMute.VTable, self.vtable).GetMute(@ptrCast(*const IAudioEndpointOffloadStreamMute, self), pbMuted);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IAudioEndpointOffloadStreamMeter_Value = Guid.initString("e1546dce-9dd1-418b-9ab2-348ced161c86");
pub const IID_IAudioEndpointOffloadStreamMeter = &IID_IAudioEndpointOffloadStreamMeter_Value;
pub const IAudioEndpointOffloadStreamMeter = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetMeterChannelCount: fn(
self: *const IAudioEndpointOffloadStreamMeter,
pu32ChannelCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetMeteringData: fn(
self: *const IAudioEndpointOffloadStreamMeter,
u32ChannelCount: u32,
pf32PeakValues: ?*f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioEndpointOffloadStreamMeter_GetMeterChannelCount(self: *const T, pu32ChannelCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioEndpointOffloadStreamMeter.VTable, self.vtable).GetMeterChannelCount(@ptrCast(*const IAudioEndpointOffloadStreamMeter, self), pu32ChannelCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioEndpointOffloadStreamMeter_GetMeteringData(self: *const T, u32ChannelCount: u32, pf32PeakValues: ?*f32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioEndpointOffloadStreamMeter.VTable, self.vtable).GetMeteringData(@ptrCast(*const IAudioEndpointOffloadStreamMeter, self), u32ChannelCount, pf32PeakValues);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.1'
const IID_IAudioEndpointLastBufferControl_Value = Guid.initString("f8520dd3-8f9d-4437-9861-62f584c33dd6");
pub const IID_IAudioEndpointLastBufferControl = &IID_IAudioEndpointLastBufferControl_Value;
pub const IAudioEndpointLastBufferControl = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
IsLastBufferControlSupported: fn(
self: *const IAudioEndpointLastBufferControl,
) callconv(@import("std").os.windows.WINAPI) BOOL,
ReleaseOutputDataPointerForLastBuffer: fn(
self: *const IAudioEndpointLastBufferControl,
pConnectionProperty: ?*const APO_CONNECTION_PROPERTY,
) callconv(@import("std").os.windows.WINAPI) void,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioEndpointLastBufferControl_IsLastBufferControlSupported(self: *const T) callconv(.Inline) BOOL {
return @ptrCast(*const IAudioEndpointLastBufferControl.VTable, self.vtable).IsLastBufferControlSupported(@ptrCast(*const IAudioEndpointLastBufferControl, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioEndpointLastBufferControl_ReleaseOutputDataPointerForLastBuffer(self: *const T, pConnectionProperty: ?*const APO_CONNECTION_PROPERTY) callconv(.Inline) void {
return @ptrCast(*const IAudioEndpointLastBufferControl.VTable, self.vtable).ReleaseOutputDataPointerForLastBuffer(@ptrCast(*const IAudioEndpointLastBufferControl, self), pConnectionProperty);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IAudioLfxControl_Value = Guid.initString("076a6922-d802-4f83-baf6-409d9ca11bfe");
pub const IID_IAudioLfxControl = &IID_IAudioLfxControl_Value;
pub const IAudioLfxControl = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetLocalEffectsState: fn(
self: *const IAudioLfxControl,
bEnabled: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLocalEffectsState: fn(
self: *const IAudioLfxControl,
pbEnabled: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioLfxControl_SetLocalEffectsState(self: *const T, bEnabled: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioLfxControl.VTable, self.vtable).SetLocalEffectsState(@ptrCast(*const IAudioLfxControl, self), bEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioLfxControl_GetLocalEffectsState(self: *const T, pbEnabled: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioLfxControl.VTable, self.vtable).GetLocalEffectsState(@ptrCast(*const IAudioLfxControl, self), pbEnabled);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IHardwareAudioEngineBase_Value = Guid.initString("eddce3e4-f3c1-453a-b461-223563cbd886");
pub const IID_IHardwareAudioEngineBase = &IID_IHardwareAudioEngineBase_Value;
pub const IHardwareAudioEngineBase = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetAvailableOffloadConnectorCount: fn(
self: *const IHardwareAudioEngineBase,
_pwstrDeviceId: ?PWSTR,
_uConnectorId: u32,
_pAvailableConnectorInstanceCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetEngineFormat: fn(
self: *const IHardwareAudioEngineBase,
pDevice: ?*IMMDevice,
_bRequestDeviceFormat: BOOL,
_ppwfxFormat: ?*?*WAVEFORMATEX,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetEngineDeviceFormat: fn(
self: *const IHardwareAudioEngineBase,
pDevice: ?*IMMDevice,
_pwfxFormat: ?*WAVEFORMATEX,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetGfxState: fn(
self: *const IHardwareAudioEngineBase,
pDevice: ?*IMMDevice,
_bEnable: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetGfxState: fn(
self: *const IHardwareAudioEngineBase,
pDevice: ?*IMMDevice,
_pbEnable: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IHardwareAudioEngineBase_GetAvailableOffloadConnectorCount(self: *const T, _pwstrDeviceId: ?PWSTR, _uConnectorId: u32, _pAvailableConnectorInstanceCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IHardwareAudioEngineBase.VTable, self.vtable).GetAvailableOffloadConnectorCount(@ptrCast(*const IHardwareAudioEngineBase, self), _pwstrDeviceId, _uConnectorId, _pAvailableConnectorInstanceCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IHardwareAudioEngineBase_GetEngineFormat(self: *const T, pDevice: ?*IMMDevice, _bRequestDeviceFormat: BOOL, _ppwfxFormat: ?*?*WAVEFORMATEX) callconv(.Inline) HRESULT {
return @ptrCast(*const IHardwareAudioEngineBase.VTable, self.vtable).GetEngineFormat(@ptrCast(*const IHardwareAudioEngineBase, self), pDevice, _bRequestDeviceFormat, _ppwfxFormat);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IHardwareAudioEngineBase_SetEngineDeviceFormat(self: *const T, pDevice: ?*IMMDevice, _pwfxFormat: ?*WAVEFORMATEX) callconv(.Inline) HRESULT {
return @ptrCast(*const IHardwareAudioEngineBase.VTable, self.vtable).SetEngineDeviceFormat(@ptrCast(*const IHardwareAudioEngineBase, self), pDevice, _pwfxFormat);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IHardwareAudioEngineBase_SetGfxState(self: *const T, pDevice: ?*IMMDevice, _bEnable: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IHardwareAudioEngineBase.VTable, self.vtable).SetGfxState(@ptrCast(*const IHardwareAudioEngineBase, self), pDevice, _bEnable);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IHardwareAudioEngineBase_GetGfxState(self: *const T, pDevice: ?*IMMDevice, _pbEnable: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IHardwareAudioEngineBase.VTable, self.vtable).GetGfxState(@ptrCast(*const IHardwareAudioEngineBase, self), pDevice, _pbEnable);
}
};}
pub usingnamespace MethodMixin(@This());
};
const CLSID_DEVINTERFACE_AUDIOENDPOINTPLUGIN_Value = Guid.initString("9f2f7b66-65ac-4fa6-8ae4-123c78b89313");
pub const CLSID_DEVINTERFACE_AUDIOENDPOINTPLUGIN = &CLSID_DEVINTERFACE_AUDIOENDPOINTPLUGIN_Value;
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IAudioEndpointVolumeCallback_Value = Guid.initString("657804fa-d6ad-4496-8a60-352752af4f89");
pub const IID_IAudioEndpointVolumeCallback = &IID_IAudioEndpointVolumeCallback_Value;
pub const IAudioEndpointVolumeCallback = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
OnNotify: fn(
self: *const IAudioEndpointVolumeCallback,
pNotify: ?*AUDIO_VOLUME_NOTIFICATION_DATA,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioEndpointVolumeCallback_OnNotify(self: *const T, pNotify: ?*AUDIO_VOLUME_NOTIFICATION_DATA) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioEndpointVolumeCallback.VTable, self.vtable).OnNotify(@ptrCast(*const IAudioEndpointVolumeCallback, self), pNotify);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IAudioEndpointVolume_Value = Guid.initString("5cdf2c82-841e-4546-9722-0cf74078229a");
pub const IID_IAudioEndpointVolume = &IID_IAudioEndpointVolume_Value;
pub const IAudioEndpointVolume = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
RegisterControlChangeNotify: fn(
self: *const IAudioEndpointVolume,
pNotify: ?*IAudioEndpointVolumeCallback,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UnregisterControlChangeNotify: fn(
self: *const IAudioEndpointVolume,
pNotify: ?*IAudioEndpointVolumeCallback,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetChannelCount: fn(
self: *const IAudioEndpointVolume,
pnChannelCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetMasterVolumeLevel: fn(
self: *const IAudioEndpointVolume,
fLevelDB: f32,
pguidEventContext: ?*const Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetMasterVolumeLevelScalar: fn(
self: *const IAudioEndpointVolume,
fLevel: f32,
pguidEventContext: ?*const Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetMasterVolumeLevel: fn(
self: *const IAudioEndpointVolume,
pfLevelDB: ?*f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetMasterVolumeLevelScalar: fn(
self: *const IAudioEndpointVolume,
pfLevel: ?*f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetChannelVolumeLevel: fn(
self: *const IAudioEndpointVolume,
nChannel: u32,
fLevelDB: f32,
pguidEventContext: ?*const Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetChannelVolumeLevelScalar: fn(
self: *const IAudioEndpointVolume,
nChannel: u32,
fLevel: f32,
pguidEventContext: ?*const Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetChannelVolumeLevel: fn(
self: *const IAudioEndpointVolume,
nChannel: u32,
pfLevelDB: ?*f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetChannelVolumeLevelScalar: fn(
self: *const IAudioEndpointVolume,
nChannel: u32,
pfLevel: ?*f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetMute: fn(
self: *const IAudioEndpointVolume,
bMute: BOOL,
pguidEventContext: ?*const Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetMute: fn(
self: *const IAudioEndpointVolume,
pbMute: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetVolumeStepInfo: fn(
self: *const IAudioEndpointVolume,
pnStep: ?*u32,
pnStepCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
VolumeStepUp: fn(
self: *const IAudioEndpointVolume,
pguidEventContext: ?*const Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
VolumeStepDown: fn(
self: *const IAudioEndpointVolume,
pguidEventContext: ?*const Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryHardwareSupport: fn(
self: *const IAudioEndpointVolume,
pdwHardwareSupportMask: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetVolumeRange: fn(
self: *const IAudioEndpointVolume,
pflVolumeMindB: ?*f32,
pflVolumeMaxdB: ?*f32,
pflVolumeIncrementdB: ?*f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioEndpointVolume_RegisterControlChangeNotify(self: *const T, pNotify: ?*IAudioEndpointVolumeCallback) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioEndpointVolume.VTable, self.vtable).RegisterControlChangeNotify(@ptrCast(*const IAudioEndpointVolume, self), pNotify);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioEndpointVolume_UnregisterControlChangeNotify(self: *const T, pNotify: ?*IAudioEndpointVolumeCallback) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioEndpointVolume.VTable, self.vtable).UnregisterControlChangeNotify(@ptrCast(*const IAudioEndpointVolume, self), pNotify);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioEndpointVolume_GetChannelCount(self: *const T, pnChannelCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioEndpointVolume.VTable, self.vtable).GetChannelCount(@ptrCast(*const IAudioEndpointVolume, self), pnChannelCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioEndpointVolume_SetMasterVolumeLevel(self: *const T, fLevelDB: f32, pguidEventContext: ?*const Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioEndpointVolume.VTable, self.vtable).SetMasterVolumeLevel(@ptrCast(*const IAudioEndpointVolume, self), fLevelDB, pguidEventContext);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioEndpointVolume_SetMasterVolumeLevelScalar(self: *const T, fLevel: f32, pguidEventContext: ?*const Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioEndpointVolume.VTable, self.vtable).SetMasterVolumeLevelScalar(@ptrCast(*const IAudioEndpointVolume, self), fLevel, pguidEventContext);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioEndpointVolume_GetMasterVolumeLevel(self: *const T, pfLevelDB: ?*f32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioEndpointVolume.VTable, self.vtable).GetMasterVolumeLevel(@ptrCast(*const IAudioEndpointVolume, self), pfLevelDB);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioEndpointVolume_GetMasterVolumeLevelScalar(self: *const T, pfLevel: ?*f32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioEndpointVolume.VTable, self.vtable).GetMasterVolumeLevelScalar(@ptrCast(*const IAudioEndpointVolume, self), pfLevel);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioEndpointVolume_SetChannelVolumeLevel(self: *const T, nChannel: u32, fLevelDB: f32, pguidEventContext: ?*const Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioEndpointVolume.VTable, self.vtable).SetChannelVolumeLevel(@ptrCast(*const IAudioEndpointVolume, self), nChannel, fLevelDB, pguidEventContext);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioEndpointVolume_SetChannelVolumeLevelScalar(self: *const T, nChannel: u32, fLevel: f32, pguidEventContext: ?*const Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioEndpointVolume.VTable, self.vtable).SetChannelVolumeLevelScalar(@ptrCast(*const IAudioEndpointVolume, self), nChannel, fLevel, pguidEventContext);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioEndpointVolume_GetChannelVolumeLevel(self: *const T, nChannel: u32, pfLevelDB: ?*f32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioEndpointVolume.VTable, self.vtable).GetChannelVolumeLevel(@ptrCast(*const IAudioEndpointVolume, self), nChannel, pfLevelDB);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioEndpointVolume_GetChannelVolumeLevelScalar(self: *const T, nChannel: u32, pfLevel: ?*f32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioEndpointVolume.VTable, self.vtable).GetChannelVolumeLevelScalar(@ptrCast(*const IAudioEndpointVolume, self), nChannel, pfLevel);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioEndpointVolume_SetMute(self: *const T, bMute: BOOL, pguidEventContext: ?*const Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioEndpointVolume.VTable, self.vtable).SetMute(@ptrCast(*const IAudioEndpointVolume, self), bMute, pguidEventContext);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioEndpointVolume_GetMute(self: *const T, pbMute: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioEndpointVolume.VTable, self.vtable).GetMute(@ptrCast(*const IAudioEndpointVolume, self), pbMute);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioEndpointVolume_GetVolumeStepInfo(self: *const T, pnStep: ?*u32, pnStepCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioEndpointVolume.VTable, self.vtable).GetVolumeStepInfo(@ptrCast(*const IAudioEndpointVolume, self), pnStep, pnStepCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioEndpointVolume_VolumeStepUp(self: *const T, pguidEventContext: ?*const Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioEndpointVolume.VTable, self.vtable).VolumeStepUp(@ptrCast(*const IAudioEndpointVolume, self), pguidEventContext);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioEndpointVolume_VolumeStepDown(self: *const T, pguidEventContext: ?*const Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioEndpointVolume.VTable, self.vtable).VolumeStepDown(@ptrCast(*const IAudioEndpointVolume, self), pguidEventContext);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioEndpointVolume_QueryHardwareSupport(self: *const T, pdwHardwareSupportMask: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioEndpointVolume.VTable, self.vtable).QueryHardwareSupport(@ptrCast(*const IAudioEndpointVolume, self), pdwHardwareSupportMask);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioEndpointVolume_GetVolumeRange(self: *const T, pflVolumeMindB: ?*f32, pflVolumeMaxdB: ?*f32, pflVolumeIncrementdB: ?*f32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioEndpointVolume.VTable, self.vtable).GetVolumeRange(@ptrCast(*const IAudioEndpointVolume, self), pflVolumeMindB, pflVolumeMaxdB, pflVolumeIncrementdB);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.1'
const IID_IAudioEndpointVolumeEx_Value = Guid.initString("66e11784-f695-4f28-a505-a7080081a78f");
pub const IID_IAudioEndpointVolumeEx = &IID_IAudioEndpointVolumeEx_Value;
pub const IAudioEndpointVolumeEx = extern struct {
pub const VTable = extern struct {
base: IAudioEndpointVolume.VTable,
GetVolumeRangeChannel: fn(
self: *const IAudioEndpointVolumeEx,
iChannel: u32,
pflVolumeMindB: ?*f32,
pflVolumeMaxdB: ?*f32,
pflVolumeIncrementdB: ?*f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IAudioEndpointVolume.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioEndpointVolumeEx_GetVolumeRangeChannel(self: *const T, iChannel: u32, pflVolumeMindB: ?*f32, pflVolumeMaxdB: ?*f32, pflVolumeIncrementdB: ?*f32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioEndpointVolumeEx.VTable, self.vtable).GetVolumeRangeChannel(@ptrCast(*const IAudioEndpointVolumeEx, self), iChannel, pflVolumeMindB, pflVolumeMaxdB, pflVolumeIncrementdB);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IAudioMeterInformation_Value = Guid.initString("c02216f6-8c67-4b5b-9d00-d008e73e0064");
pub const IID_IAudioMeterInformation = &IID_IAudioMeterInformation_Value;
pub const IAudioMeterInformation = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetPeakValue: fn(
self: *const IAudioMeterInformation,
pfPeak: ?*f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetMeteringChannelCount: fn(
self: *const IAudioMeterInformation,
pnChannelCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetChannelsPeakValues: fn(
self: *const IAudioMeterInformation,
u32ChannelCount: u32,
afPeakValues: [*]f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryHardwareSupport: fn(
self: *const IAudioMeterInformation,
pdwHardwareSupportMask: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioMeterInformation_GetPeakValue(self: *const T, pfPeak: ?*f32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioMeterInformation.VTable, self.vtable).GetPeakValue(@ptrCast(*const IAudioMeterInformation, self), pfPeak);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioMeterInformation_GetMeteringChannelCount(self: *const T, pnChannelCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioMeterInformation.VTable, self.vtable).GetMeteringChannelCount(@ptrCast(*const IAudioMeterInformation, self), pnChannelCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioMeterInformation_GetChannelsPeakValues(self: *const T, u32ChannelCount: u32, afPeakValues: [*]f32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioMeterInformation.VTable, self.vtable).GetChannelsPeakValues(@ptrCast(*const IAudioMeterInformation, self), u32ChannelCount, afPeakValues);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioMeterInformation_QueryHardwareSupport(self: *const T, pdwHardwareSupportMask: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioMeterInformation.VTable, self.vtable).QueryHardwareSupport(@ptrCast(*const IAudioMeterInformation, self), pdwHardwareSupportMask);
}
};}
pub usingnamespace MethodMixin(@This());
};
//--------------------------------------------------------------------------------
// Section: Functions (0)
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (0)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../../zig.zig").unicode_mode) {
.ansi => struct {
},
.wide => struct {
},
.unspecified => if (@import("builtin").is_test) struct {
} else struct {
},
};
//--------------------------------------------------------------------------------
// Section: Imports (10)
//--------------------------------------------------------------------------------
const Guid = @import("../../zig.zig").Guid;
const APO_CONNECTION_PROPERTY = @import("../../media/audio/apo.zig").APO_CONNECTION_PROPERTY;
const AUDIO_CURVE_TYPE = @import("../../media/kernel_streaming.zig").AUDIO_CURVE_TYPE;
const AUDIO_VOLUME_NOTIFICATION_DATA = @import("../../media/audio.zig").AUDIO_VOLUME_NOTIFICATION_DATA;
const BOOL = @import("../../foundation.zig").BOOL;
const HRESULT = @import("../../foundation.zig").HRESULT;
const IMMDevice = @import("../../media/audio.zig").IMMDevice;
const IUnknown = @import("../../system/com.zig").IUnknown;
const PWSTR = @import("../../foundation.zig").PWSTR;
const WAVEFORMATEX = @import("../../media/audio.zig").WAVEFORMATEX;
test {
@setEvalBranchQuota(
@import("std").meta.declarations(@This()).len * 3
);
// reference all the pub declarations
if (!@import("builtin").is_test) return;
inline for (@import("std").meta.declarations(@This())) |decl| {
if (decl.is_pub) {
_ = decl;
}
}
} | win32/media/audio/endpoints.zig |
const std = @import("std");
const mem = std.mem;
const print = std.debug.print;
const fs = std.fs;
const ChildProcess = std.ChildProcess;
const process = std.process;
const render_utils = @import("render_utils.zig");
pub const RunCommand = struct {
expected_outcome: union(enum) { Success, Failure: []const u8 } = .Success,
max_doc_file_size: usize = 1024 * 1024 * 1, // 1MB TODO: change?
// TODO: arguments?
};
pub fn runExe(
allocator: *mem.Allocator,
path_to_exe: []const u8,
out: anytype,
env_map: *std.BufMap,
cmd: RunCommand,
) !void {
const run_args = &[_][]const u8{path_to_exe};
var exited_with_signal = false;
const result = if (cmd.expected_outcome == .Failure) ko: {
const result = try ChildProcess.exec(.{
.allocator = allocator,
.argv = run_args,
.env_map = env_map,
.max_output_bytes = cmd.max_doc_file_size,
});
switch (result.term) {
.Exited => |exit_code| {
if (exit_code == 0) {
print("{s}\nThe following command incorrectly succeeded:\n", .{result.stderr});
render_utils.dumpArgs(run_args);
// return parseError(tokenizer, code.source_token, "example incorrectly compiled", .{});
return;
}
},
.Signal => exited_with_signal = true,
else => {},
}
break :ko result;
} else ok: {
break :ok try render_utils.exec(allocator, env_map, cmd.max_doc_file_size, run_args);
};
const escaped_stderr = try render_utils.escapeHtml(allocator, result.stderr);
const escaped_stdout = try render_utils.escapeHtml(allocator, result.stdout);
const colored_stderr = try render_utils.termColor(allocator, escaped_stderr);
const colored_stdout = try render_utils.termColor(allocator, escaped_stdout);
try out.print("\n$ ./{s}\n{s}{s}", .{ fs.path.basename(path_to_exe), colored_stdout, colored_stderr });
if (exited_with_signal) {
try out.print("(process terminated by signal)", .{});
}
try out.print("</code></pre>\n", .{});
} | src/doctest/run.zig |
const std = @import("std");
const mem = std.mem;
const Allocator = mem.Allocator;
const ArrayList = std.ArrayList;
const wasm = @import("wasm.zig");
const errors = @import("errors.zig");
const fastly = errors.fastly;
const FastlyError = errors.FastlyError;
const Uri = @import("zuri/zuri.zig").Uri;
const RequestHeaders = struct {
handle: wasm.RequestHandle,
/// Return the full list of header names.
pub fn names(self: RequestHeaders, allocator: Allocator) ![][]const u8 {
var names_list = ArrayList([]const u8).init(allocator);
var cursor: u32 = 0;
var cursor_next: i64 = 0;
while (true) {
var name_len_max: usize = 64;
var name_buf = try allocator.alloc(u8, name_len_max);
var name_len: usize = undefined;
while (true) {
name_len = ~@as(usize, 0);
const ret = fastly(wasm.FastlyHttpReq.header_names_get(self.handle, name_buf.ptr, name_len_max, cursor, &cursor_next, &name_len));
var retry = name_len == ~@as(usize, 0);
ret catch |err| {
if (err != FastlyError.FastlyBufferTooSmall) {
return err;
}
retry = true;
};
if (!retry) break;
name_len_max *= 2;
name_buf = try allocator.realloc(name_buf, name_len_max);
}
if (name_len == 0) {
break;
}
if (name_buf[name_len - 1] != 0) {
return FastlyError.FastlyGenericError;
}
const name = name_buf[0 .. name_len - 1];
try names_list.append(name);
if (cursor_next < 0) {
break;
}
cursor = @intCast(u32, cursor_next);
}
return names_list.items;
}
/// Return the value for a header.
pub fn get(self: RequestHeaders, allocator: Allocator, name: []const u8) ![]const u8 {
var value_len_max: usize = 64;
var value_buf = try allocator.alloc(u8, value_len_max);
var value_len: usize = undefined;
while (true) {
const ret = wasm.FastlyHttpReq.header_value_get(self.handle, name.ptr, name.len, value_buf.ptr, value_len_max, &value_len);
if (ret) break else |err| {
if (err != FastlyError.FastlyBufferTooSmall) {
return err;
}
value_len_max *= 2;
value_buf = try allocator.realloc(value_buf, value_len_max);
}
}
return value_buf[0..value_len];
}
/// Return all the values for a header.
pub fn getAll(self: RequestHeaders, allocator: Allocator, name: []const u8) ![][]const u8 {
var values_list = ArrayList([]const u8).init(allocator);
var cursor: u32 = 0;
var cursor_next: i64 = 0;
while (true) {
var value_len_max: usize = 64;
var value_buf = try allocator.alloc(u8, value_len_max);
var value_len: usize = undefined;
while (true) {
value_len = ~@as(usize, 0);
const ret = fastly(wasm.FastlyHttpReq.header_values_get(self.handle, name.ptr, name.len, value_buf.ptr, value_len_max, cursor, &cursor_next, &value_len));
var retry = value_len == ~@as(usize, 0);
ret catch |err| {
if (err != FastlyError.FastlyBufferTooSmall) {
return err;
}
retry = true;
};
if (!retry) break;
value_len_max *= 2;
value_buf = try allocator.realloc(value_buf, value_len_max);
}
if (value_len == 0) {
break;
}
if (value_buf[value_len - 1] != 0) {
return FastlyError.FastlyGenericError;
}
const value = value_buf[0 .. value_len - 1];
try values_list.append(value);
if (cursor_next < 0) {
break;
}
cursor = @intCast(u32, cursor_next);
}
return values_list.items;
}
/// Set the value for a header.
pub fn set(self: *RequestHeaders, name: []const u8, value: []const u8) !void {
try fastly(wasm.FastlyHttpReq.header_insert(self.handle, name.ptr, name.len, value.ptr, value.len));
}
/// Append a value to a header.
pub fn append(self: *RequestHeaders, allocator: Allocator, name: []const u8, value: []const u8) !void {
var value0 = try allocator.alloc(u8, value.len + 1);
mem.copy(u8, value0[0..value.len], value);
value0[value.len] = 0;
try fastly(wasm.FastlyHttpReq.header_append(self.handle, name.ptr, name.len, value0.ptr, value0.len));
}
/// Remove a header.
pub fn remove(self: *RequestHeaders, name: []const u8) !void {
try fastly(wasm.FastlyHttpReq.header_remove(self.handle, name.ptr, name.len));
}
};
const Body = struct {
handle: wasm.BodyHandle,
/// Possibly partial read of the body content.
/// An empty slice is returned when no data has to be read any more.
pub fn read(self: *Body, buf: []u8) ![]u8 {
var buf_len: usize = undefined;
try fastly(wasm.FastlyHttpBody.read(self.handle, buf.ptr, buf.len, &buf_len));
return buf[0..buf_len];
}
/// Read all the body content. This requires an allocator.
pub fn readAll(self: *Body, allocator: Allocator, max_length: usize) ![]u8 {
const chunk_size: usize = mem.page_size;
var buf_len = chunk_size;
var pos: usize = 0;
var buf = try allocator.alloc(u8, buf_len);
while (true) {
var chunk = try self.read(buf[pos..]);
if (chunk.len == 0) {
return buf[0..pos];
}
pos += chunk.len;
if (max_length > 0 and pos >= max_length) {
return buf[0..max_length];
}
if (buf_len - pos <= chunk_size) {
buf_len += chunk_size;
buf = try allocator.realloc(buf, buf_len);
}
}
}
/// Add body content. The number of bytes that could be written is returned.
pub fn write(self: *Body, buf: []const u8) !usize {
var written: usize = undefined;
try fastly(wasm.FastlyHttpBody.write(self.handle, buf.ptr, buf.len, wasm.BodyWriteEnd.BACK, &written));
return written;
}
/// Add body content. The entire buffer is written.
pub fn writeAll(self: *Body, buf: []const u8) !void {
var pos: usize = 0;
while (pos < buf.len) {
const written = try self.write(buf[pos..]);
pos += written;
}
}
/// Close the body.
pub fn close(self: *Body) !void {
try fastly(wasm.FastlyHttpBody.close(self.handle));
}
};
/// An HTTP request.
pub const Request = struct {
/// The request headers.
headers: RequestHeaders,
/// The request body.
body: Body,
/// Return the initial request made to the proxy.
pub fn downstream() !Request {
var req_handle: wasm.RequestHandle = undefined;
var body_handle: wasm.BodyHandle = undefined;
try fastly(wasm.FastlyHttpReq.body_downstream_get(&req_handle, &body_handle));
return Request{
.headers = RequestHeaders{ .handle = req_handle },
.body = Body{ .handle = body_handle },
};
}
/// Copy the HTTP method used by this request.
pub fn getMethod(self: Request, method: []u8) ![]u8 {
var method_len: usize = undefined;
try fastly(wasm.FastlyHttpReq.method_get(self.headers.handle, method.ptr, method.len, &method_len));
return method[0..method_len];
}
/// Return `true` if the request uses the `GET` method.
pub fn isGet(self: Request) !bool {
var method_buf: [64]u8 = undefined;
const method = try self.getMethod(&method_buf);
return mem.eql(u8, method, "GET");
}
/// Return `true` if the request uses the `POST` method.
pub fn isPost(self: Request) !bool {
var method_buf: [64]u8 = undefined;
const method = try self.getMethod(&method_buf);
return mem.eql(u8, method, "POST");
}
/// Set the method of a request.
pub fn setMethod(self: Request, method: []const u8) !void {
try fastly(wasm.FastlyHttpReq.method_set(self.headers.handle, method.ptr, method.len));
}
/// Get the request URI.
/// `uri` is a buffer that should be large enough to store the URI.
/// The function returns the slice containing the actual string.
/// Individual components can be extracted with `Uri.parse()`.
pub fn getUriString(self: Request, uri: []u8) ![]u8 {
var uri_len: usize = undefined;
try fastly(wasm.FastlyHttpReq.uri_get(self.headers.handle, uri.ptr, uri.len, &uri_len));
return uri[0..uri_len];
}
/// Set the request URI.
pub fn setUriString(self: Request, uri: []const u8) !void {
try fastly(wasm.FastlyHttpReq.uri_set(self.headers.handle, uri.ptr, uri.len));
}
/// Create a new request.
pub fn new(method: []const u8, uri: []const u8) !Request {
var req_handle: wasm.RequestHandle = undefined;
var body_handle: wasm.BodyHandle = undefined;
try fastly(wasm.FastlyHttpReq.new(&req_handle));
try fastly(wasm.FastlyHttpBody.new(&body_handle));
var request = Request{
.headers = RequestHeaders{ .handle = req_handle },
.body = Body{ .handle = body_handle },
};
try request.setMethod(method);
try request.setUriString(uri);
return request;
}
/// Send a request.
pub fn send(self: *Request, backend: []const u8) !IncomingResponse {
var resp_handle: wasm.ResponseHandle = undefined;
var resp_body_handle: wasm.BodyHandle = undefined;
try fastly(wasm.FastlyHttpReq.send(self.headers.handle, self.body.handle, backend.ptr, backend.len, &resp_handle, &resp_body_handle));
return IncomingResponse{
.handle = resp_handle,
.headers = ResponseHeaders{ .handle = resp_handle },
.body = Body{ .handle = resp_body_handle },
};
}
/// Caching policy
pub const CachingPolicy = struct {
/// Bypass the cache
no_cache: bool = false,
/// Enforce a sepcific TTL
ttl: ?u32 = null,
/// Return stale content up to this TTL if the origin is unreachable
serve_stale: ?u32 = null,
/// Activate PCI restrictions
pci: bool = false,
/// Cache with a surrogate key
surrogate_key: []const u8 = "",
};
/// Force a caching policy for this request
pub fn setCachingPolicy(self: *Request, policy: CachingPolicy) !void {
var wasm_policy: wasm.CacheOverrideTag = 0;
if (policy.no_cache) {
wasm_policy |= wasm.CACHE_OVERRIDE_TAG_PASS;
}
if (policy.ttl) |_| {
wasm_policy |= wasm.CACHE_OVERRIDE_TAG_TTL;
}
if (policy.serve_stale) |_| {
wasm_policy |= wasm.CACHE_OVERRIDE_TAG_STALE_WHILE_REVALIDATE;
}
if (policy.pci) {
wasm_policy |= wasm.CACHE_OVERRIDE_TAG_PCI;
}
try fastly(wasm.FastlyHttpReq.cache_override_v2_set(self.headers.handle, wasm_policy, policy.ttl orelse 0, policy.serve_stale orelse 0, policy.surrogate_key.ptr, policy.surrogate_key.len));
}
/// Automatically decompress the body of the request.
pub fn setAutoDecompressResponse(self: *Request, enable: bool) !void {
const encodings = if (enable) wasm.CONTENT_ENCODINGS_GZIP else 0;
try fastly(wasm.FastlyHttpReq.auto_decompress_response_set(self.headers.handle, encodings));
}
/// Close the request prematurely.
pub fn close(self: *Request) !void {
try fastly(wasm.FastlyHttpReq.close(self.headers.handle));
}
};
const ResponseHeaders = struct {
handle: wasm.ResponseHandle,
/// Return the full list of header names.
pub fn names(self: ResponseHeaders, allocator: Allocator) ![][]const u8 {
var names_list = ArrayList([]const u8).init(allocator);
var cursor: u32 = 0;
var cursor_next: i64 = 0;
while (true) {
var name_len_max: usize = 64;
var name_buf = try allocator.alloc(u8, name_len_max);
var name_len: usize = undefined;
while (true) {
name_len = ~@as(usize, 0);
const ret = fastly(wasm.FastlyHttpResp.header_names_get(self.handle, name_buf.ptr, name_len_max, cursor, &cursor_next, &name_len));
var retry = name_len == ~@as(usize, 0);
ret catch |err| {
if (err != FastlyError.FastlyBufferTooSmall) {
return err;
}
retry = true;
};
if (!retry) break;
name_len_max *= 2;
name_buf = try allocator.realloc(name_buf, name_len_max);
}
if (name_len == 0) {
break;
}
if (name_buf[name_len - 1] != 0) {
return FastlyError.FastlyGenericError;
}
const name = name_buf[0 .. name_len - 1];
try names_list.append(name);
if (cursor_next < 0) {
break;
}
cursor = @intCast(u32, cursor_next);
}
return names_list.items;
}
/// Return the value for a header.
pub fn get(self: ResponseHeaders, allocator: Allocator, name: []const u8) ![]const u8 {
var value_len_max: usize = 64;
var value_buf = try allocator.alloc(u8, value_len_max);
var value_len: usize = undefined;
while (true) {
const ret = wasm.FastlyHttpResp.header_value_get(self.handle, name.ptr, name.len, value_buf.ptr, value_len_max, &value_len);
if (ret) break else |err| {
if (err != FastlyError.FastlyBufferTooSmall) {
return err;
}
value_len_max *= 2;
value_buf = try allocator.realloc(value_buf, value_len_max);
}
}
return value_buf[0..value_len];
}
/// Return all the values for a header.
pub fn getAll(self: RequestHeaders, allocator: Allocator, name: []const u8) ![][]const u8 {
var values_list = ArrayList([]const u8).init(allocator);
var cursor: u32 = 0;
var cursor_next: i64 = 0;
while (true) {
var value_len_max: usize = 64;
var value_buf = try allocator.alloc(u8, value_len_max);
var value_len: usize = undefined;
while (true) {
value_len = ~@as(usize, 0);
const ret = fastly(wasm.FastlyHttpResp.header_values_get(self.handle, name.ptr, name.len, value_buf.ptr, value_len_max, cursor, &cursor_next, &value_len));
var retry = value_len == ~@as(usize, 0);
ret catch |err| {
if (err != FastlyError.FastlyBufferTooSmall) {
return err;
}
retry = true;
};
if (!retry) break;
value_len_max *= 2;
value_buf = try allocator.realloc(value_buf, value_len_max);
}
if (value_len == 0) {
break;
}
if (value_buf[value_len - 1] != 0) {
return FastlyError.FastlyGenericError;
}
const value = value_buf[0 .. value_len - 1];
try values_list.append(value);
if (cursor_next < 0) {
break;
}
cursor = @intCast(u32, cursor_next);
}
return values_list.items;
}
/// Set a header to a value.
pub fn set(self: *ResponseHeaders, name: []const u8, value: []const u8) !void {
try fastly(wasm.FastlyHttpResp.header_insert(self.handle, name.ptr, name.len, value.ptr, value.len));
}
/// Append a value to a header.
pub fn append(self: *ResponseHeaders, allocator: Allocator, name: []const u8, value: []const u8) !void {
var value0 = try allocator.alloc(u8, value.len + 1);
mem.copy(u8, value0[0..value.len], value);
value0[value.len] = 0;
try fastly(wasm.FastlyHttpResp.header_append(self.handle, name.ptr, name.len, value0.ptr, value0.len));
}
/// Remove a header.
pub fn remove(self: *ResponseHeaders, name: []const u8) !void {
try fastly(wasm.FastlyHttpResp.header_remove(self.handle, name.ptr, name.len));
}
};
const OutgoingResponse = struct {
handle: wasm.ResponseHandle,
headers: ResponseHeaders,
body: Body,
/// The response to the initial query sent to the proxy.
pub fn downstream() !OutgoingResponse {
var resp_handle: wasm.ResponseHandle = undefined;
var body_handle: wasm.BodyHandle = undefined;
try fastly(wasm.FastlyHttpResp.new(&resp_handle));
try fastly(wasm.FastlyHttpBody.new(&body_handle));
return OutgoingResponse{
.handle = resp_handle,
.headers = ResponseHeaders{ .handle = resp_handle },
.body = Body{ .handle = body_handle },
};
}
/// Send a buffered response, but doesn't close the stream.
pub fn flush(self: *OutgoingResponse) !void {
try fastly(wasm.FastlyHttpResp.send_downstream(self.handle, self.body.handle, 1));
}
/// Send a buffered response and close the stream - Calling this function is required.
pub fn finish(self: *OutgoingResponse) !void {
try fastly(wasm.FastlyHttpResp.send_downstream(self.handle, self.body.handle, 1));
try self.body.close();
}
/// Get a the status code of a response.
pub fn getStatus(self: OutgoingResponse) !u16 {
var status: wasm.HttpStatus = undefined;
try fastly(wasm.FastlyHttpResp.status_get(self.handle, &status));
return @intCast(u16, status);
}
/// Change the status code of a response.
pub fn setStatus(self: *OutgoingResponse, status: u16) !void {
try fastly(wasm.FastlyHttpResp.status_set(self.handle, @intCast(wasm.HttpStatus, status)));
}
/// Zero-copy the content of an incoming response.
/// The status from the incoming response is copied if `copy_status` is set to `true`,
/// and the headers are copied if `copy_headers` is set to `true`.
pub fn pipe(self: *OutgoingResponse, incoming: *IncomingResponse, copy_status: bool, copy_headers: bool) !void {
if (copy_status) {
try self.setStatus(try incoming.getStatus());
}
try fastly(wasm.FastlyHttpResp.send_downstream(if (copy_headers) incoming.handle else self.handle, incoming.body.handle, 0));
}
/// Prematurely close the response without sending potentially buffered data.
pub fn cancel(self: *Request) !void {
try fastly(wasm.FastlyHttpResp.close(self.handle));
}
};
const IncomingResponse = struct {
handle: wasm.ResponseHandle,
headers: ResponseHeaders,
body: Body,
/// Get the status code of a response.
pub fn getStatus(self: IncomingResponse) !u16 {
var status: wasm.HttpStatus = undefined;
try fastly(wasm.FastlyHttpResp.status_get(self.handle, &status));
return @intCast(u16, status);
}
/// Close the response after use.
pub fn close(self: *IncomingResponse) !void {
try fastly(wasm.FastlyHttpResp.close(self.handle));
}
};
const Downstream = struct {
/// Initial request sent to the proxy.
request: Request,
/// Response to the initial request sent to the proxy.
response: OutgoingResponse,
/// Redirect to a different URI, with the given status code (usually 301 or 302)
pub fn redirect(self: *Downstream, status: u16, uri: []const u8) !void {
var response = self.response;
try response.setStatus(status);
try response.headers.set("Location", uri);
try response.flush();
}
/// Proxy the request and its response to the origin, optionally changing the Host header field
pub fn proxy(self: *Downstream, backend: []const u8, host_header: ?[]const u8) !void {
if (host_header) |host| {
try self.request.headers.set("Host", host);
}
try fastly(wasm.FastlyHttpReq.send(self.request.headers.handle, self.request.body.handle, backend.ptr, backend.len, &self.response.handle, &self.response.body.handle));
try self.response.flush();
}
};
/// The initial connection to the proxy.
pub fn downstream() !Downstream {
return Downstream{
.request = try Request.downstream(),
.response = try OutgoingResponse.downstream(),
};
} | src/zigly/http.zig |
const std = @import("std");
const http = @import("apple_pie");
const fs = http.FileServer;
const router = http.router;
pub const io_mode = .evented;
const Context = struct {
last_route: ?[]const u8,
};
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
try fs.init(allocator, .{ .dir_path = "src", .base_path = "files" });
defer fs.deinit();
var context: Context = .{ .last_route = null };
const builder = router.Builder(*Context);
try http.listenAndServe(
allocator,
try std.net.Address.parseIp("127.0.0.1", 8080),
&context,
comptime router.Router(*Context, &.{
builder.get("/", null, index),
builder.get("/headers", null, headers),
builder.get("/files/*", null, serveFs),
builder.get("/hello/:name", []const u8, hello),
builder.get("/route", null, route),
builder.get("/posts/:post/messages/:message", struct {
post: []const u8,
message: []const u8,
}, messages),
}),
);
}
/// Very basic text-based response, it's up to implementation to set
/// the correct content type of the message
fn index(ctx: *Context, response: *http.Response, request: http.Request, captures: ?*const anyopaque) !void {
std.debug.assert(captures == null);
_ = request;
ctx.last_route = "Index";
try response.writer().writeAll("Hello Zig!\n");
}
fn route(ctx: *Context, resp: *http.Response, request: http.Request, captures: ?*const anyopaque) !void {
std.debug.assert(captures == null);
_ = request;
defer ctx.last_route = null;
if (ctx.last_route) |last_route| {
try resp.writer().print("Last route: {s}\n", .{last_route});
} else {
try resp.writer().writeAll("The index route hasn't been visited yet\n");
}
}
fn headers(ctx: *Context, response: *http.Response, request: http.Request, captures: ?*const anyopaque) !void {
std.debug.assert(captures == null);
_ = ctx;
try response.writer().print("Path: {s}\n", .{request.path()});
var it = request.iterator();
while (it.next()) |header| {
try response.writer().print("{s}: {s}\n", .{ header.key, header.value });
}
}
/// Shows "Hello {name}" where {name} is /hello/:name
fn hello(ctx: *Context, resp: *http.Response, req: http.Request, captures: ?*const anyopaque) !void {
_ = req;
_ = ctx;
const name = @ptrCast(
*const []const u8,
@alignCast(
@alignOf(*const []const u8),
captures,
),
);
try resp.writer().print("Hello {s}\n", .{name.*});
}
/// Serves a file
fn serveFs(ctx: *Context, resp: *http.Response, req: http.Request, captures: ?*const anyopaque) !void {
std.debug.assert(captures == null);
_ = ctx;
try fs.serve({}, resp, req);
}
/// Shows the post number and message text
fn messages(ctx: *Context, resp: *http.Response, req: http.Request, captures: ?*const anyopaque) !void {
_ = ctx;
_ = req;
const Args = struct { post: usize, message: []const u8 };
const args = @ptrCast(*const Args, @alignCast(@alignOf(*const Args), captures));
try resp.writer().print("Post {d}, message: '{s}'\n", .{
args.post,
args.message,
});
} | examples/router.zig |
const std = @import("std");
const builtin = @import("builtin");
const deps = @import("deps.zig");
const libgit2 = deps.build_pkgs.libgit2;
const mbedtls = deps.build_pkgs.mbedtls;
const libssh2 = deps.build_pkgs.libssh2;
const zlib = deps.build_pkgs.zlib;
const libcurl = deps.build_pkgs.libcurl;
const Builder = std.build.Builder;
const LibExeObjStep = std.build.LibExeObjStep;
const Pkg = std.build.Pkg;
pub fn build(b: *Builder) !void {
const target = b.standardTargetOptions(.{
.default_target = std.zig.CrossTarget{
.abi = if (builtin.os.tag == .linux) .musl else null,
},
});
const mode = b.standardReleaseOptions();
if (target.isLinux() and target.isGnuLibC()) {
std.log.err("glibc builds don't work right now, use musl instead. The issue is tracked here: https://github.com/ziglang/zig/issues/9485", .{});
return error.WaitingOnFix;
}
const z = zlib.create(b, target, mode);
const tls = mbedtls.create(b, target, mode);
const ssh2 = libssh2.create(b, target, mode);
tls.link(ssh2.step);
const curl = try libcurl.create(b, target, mode);
ssh2.link(curl.step);
tls.link(curl.step);
z.link(curl.step, .{});
const git2 = try libgit2.create(b, target, mode);
z.link(git2.step, .{});
tls.link(git2.step);
ssh2.link(git2.step);
const gyro = b.addExecutable("gyro", "src/main.zig");
gyro.setTarget(target);
gyro.setBuildMode(mode);
z.link(gyro, .{});
tls.link(gyro);
ssh2.link(gyro);
git2.link(gyro);
curl.link(gyro, .{ .import_name = "curl" });
deps.pkgs.addAllTo(gyro);
gyro.install();
// release-* builds for windows end up missing a _tls_index symbol, turning
// off lto fixes this *shrug*
if (target.isWindows())
gyro.want_lto = false;
const tests = b.addTest("src/main.zig");
tests.setBuildMode(mode);
tests.setTarget(target);
deps.pkgs.addAllTo(tests);
const test_step = b.step("test", "Run tests");
test_step.dependOn(&tests.step);
const run_cmd = gyro.run();
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
} | build.zig |
const std = @import("std");
const mem = std.mem;
const Writer = std.fs.File.Writer;
const Reader = std.fs.File.Reader;
const Allocator = mem.Allocator;
const Model = @import("model.zig");
const SerialModel = Model.SerialModel;
const ChildRefs = Model.ChildRefs;
const MaterialInfo = Model.MaterialInfo;
const magic = "asdf-box";
const version = "0.1.0";
pub fn load(allocator: *Allocator, filename: []const u8) !SerialModel {
var file = try std.fs.cwd().openFile(filename, .{ .read = true, .write = false, .lock = .None });
defer file.close();
var reader = file.reader();
if (!expect(&reader, magic)) return error.FormatInvalid;
if (!expect(&reader, version)) return error.FormatNotSupported;
const treelength = @intCast(usize, try reader.readIntLittle(i32));
var model = SerialModel{
.tree = undefined,
.values = undefined,
.material = undefined,
.width = @intCast(u32, try reader.readIntLittle(i32)),
.height = @intCast(u32, try reader.readIntLittle(i32)),
};
model.tree = try allocator.alloc(ChildRefs, treelength);
errdefer allocator.free(model.tree);
model.material = try allocator.alloc(MaterialInfo, treelength);
errdefer allocator.free(model.material);
try reader.readNoEof(mem.sliceAsBytes(model.tree));
try reader.readNoEof(mem.sliceAsBytes(model.material));
for (model.tree) |*node| {
for (node.*) |*v| {
v.* = mem.littleToNative(i32, v.*);
}
}
for (model.material) |*mat| {
mat.* = mem.littleToNative(u32, mat.*);
}
model.values = try allocator.alloc(u8, model.width * model.height * @import("model.zig").valres);
errdefer allocator.free(model.values);
try reader.readNoEof(model.values);
return model;
}
fn expect(read: *Reader, expected: []const u8) bool {
return read.isBytes(expected) catch |err| false;
}
pub fn save(model: SerialModel, filename: []const u8) !void {
var file = try std.fs.cwd().createFile(filename, .{ .read = false, .exclusive = false, .lock = .Exclusive });
defer file.close();
var writer = file.writer();
try writer.writeAll(magic ++ version);
try write(&writer, @intCast(i32, model.tree.len));
try write(&writer, @intCast(i32, model.width));
try write(&writer, @intCast(i32, model.height));
for (model.tree) |*node| {
for (node.*) |*v| {
v.* = mem.nativeToLittle(i32, v.*);
}
}
for (model.material) |*mat| {
mat.* = mem.nativeToLittle(u32, mat.*);
}
defer {
for (model.tree) |*node| {
for (node.*) |*v| {
v.* = mem.littleToNative(i32, v.*);
}
}
for (model.material) |*mat| {
mat.* = mem.littleToNative(u32, mat.*);
}
}
try writer.writeAll(mem.sliceAsBytes(model.tree));
try writer.writeAll(mem.sliceAsBytes(model.material));
try writer.writeAll(model.values);
}
fn write(w: *Writer, i: i32) !void {
try w.writeIntLittle(i32, i);
} | src/load_adf.zig |
const std = @import("std");
pub const c = @import("./c.zig").c;
pub usingnamespace @import("./units.zig");
pub usingnamespace @import("./audio.zig");
const WIN_MARGIN = 200;
const SDL_Error = error{
SDL_Init,
SDL_CreateWindow,
SDL_CreateRenderer,
SDL_CreateRGBSurfaceFrom,
SDL_CreateTextureFromSurface,
SDL_GetCurrentDisplayMode,
SDL_SetRenderDrawBlendMode,
};
pub fn initSDL() SDL_Error!void {
if (c.SDL_Init(c.SDL_INIT_VIDEO | c.SDL_INIT_AUDIO) != 0) {
return SDL_Error.SDL_Init;
}
}
pub fn deinitSDL() void {
c.SDL_Quit();
}
pub fn getTick() Tick {
return c.SDL_GetTicks();
}
pub const Game = struct {
const KeycodeTickMap = std.AutoHashMap(Keycode, Tick);
const DrawOptions = struct {
flipX: bool = false,
flipY: bool = false,
color: Color = RGB(255, 255, 255),
};
alloc: *std.mem.Allocator,
w: UUnit, // Game width
h: UUnit, // Game height
winW: UUnit,
winH: UUnit,
scale: UUnit,
wnd: *c.SDL_Window,
rnd: *c.SDL_Renderer,
tick: Tick,
fps: struct {
fps: u32 = 0,
counter: u32 = 0,
lastTick: Tick,
},
mouse: struct {
const MouseButtonState = struct {
down: bool = false,
pressed: bool = false,
};
x: SUnit = 0,
y: SUnit = 0,
scrollDeltaX: i16 = 0,
scrollDeltaY: i16 = 0,
left: MouseButtonState = .{},
middle: MouseButtonState = .{},
right: MouseButtonState = .{},
} = .{},
keyUpdates: struct {
pressed: KeycodeTickMap,
released: KeycodeTickMap,
},
// -- Init & Deinit --
pub fn createZ(alloc: *std.mem.Allocator, title: [:0]const u8, w: UUnit, h: UUnit) SDL_Error!Game {
var dm: c.SDL_DisplayMode = undefined;
if (c.SDL_GetCurrentDisplayMode(0, &dm) != 0) {
return SDL_Error.SDL_GetCurrentDisplayMode;
}
const scale = @intCast(UUnit, std.math.min(@divTrunc(dm.w - WIN_MARGIN, w), @divTrunc(dm.h - WIN_MARGIN, h)));
const winW = @intCast(UUnit, w * scale);
const winH = @intCast(UUnit, h * scale);
const wnd = c.SDL_CreateWindow(title, c.SDL_WINDOWPOS_CENTERED, c.SDL_WINDOWPOS_CENTERED, winW, winH, c.SDL_WINDOW_RESIZABLE);
if (wnd == null) {
return SDL_Error.SDL_CreateWindow;
}
const rnd = c.SDL_CreateRenderer(wnd, -1, c.SDL_RENDERER_ACCELERATED | c.SDL_RENDERER_PRESENTVSYNC);
if (rnd == null) {
return SDL_Error.SDL_CreateRenderer;
}
if (c.SDL_SetRenderDrawBlendMode(rnd, c.SDL_BLENDMODE_BLEND) != 0) {
return SDL_Error.SDL_SetRenderDrawBlendMode;
}
return Game{
.alloc = alloc,
.w = w,
.h = h,
.winW = winW,
.winH = winH,
.scale = scale,
.wnd = wnd.?,
.rnd = rnd.?,
.tick = getTick(),
.fps = .{
.lastTick = getTick(),
},
.keyUpdates = .{
.pressed = Game.KeycodeTickMap.init(alloc),
.released = Game.KeycodeTickMap.init(alloc),
}
};
}
pub fn create(alloc: *std.mem.Allocator, comptime title: []const u8, w: UUnit, h: UUnit) !Game {
return createZ(alloc, title ++ "\x00", w, h);
}
pub fn deinit(self: *Game) void {
self.keyUpdates.pressed.deinit();
self.keyUpdates.released.deinit();
c.SDL_DestroyRenderer(self.rnd);
c.SDL_DestroyWindow(self.wnd);
self.* = undefined;
}
// -- Private methods --
inline fn setColor(self: *const Game, color: Color) void {
_ = c.SDL_SetRenderDrawColor(self.rnd, color.r, color.g, color.b, color.a);
}
inline fn scaleRect(self: *const Game, r: Rect) Rect {
return .{
.x = r.x * self.scale + @divTrunc(self.winW - self.w * self.scale, 2),
.y = r.y * self.scale + @divTrunc(self.winH - self.h * self.scale, 2),
.w = r.w * self.scale,
.h = r.h * self.scale,
};
}
inline fn unscalePoint(self: *const Game, x: SUnit, y: SUnit) struct { x: SUnit, y: SUnit } {
return .{
.x = @divTrunc(x - @divTrunc(self.winW - self.w * self.scale, 2), self.scale),
.y = @divTrunc(y - @divTrunc(self.winH - self.h * self.scale, 2), self.scale),
};
}
fn loadTextureFromRGBA(self: *const Game, pixels: []const u8, w: UUnit, h: UUnit) SDL_Error!Texture {
// NOTE: uses hacky pointer conversion because we can guarantee the data won't be written to
const surf = c.SDL_CreateRGBSurfaceFrom(@intToPtr(*c_void, @ptrToInt(pixels.ptr)), w, h, 32, w * 4, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000);
if (surf == null) {
return SDL_Error.SDL_CreateRGBSurfaceFrom;
}
defer c.SDL_FreeSurface(surf);
const tx = c.SDL_CreateTextureFromSurface(self.rnd, surf);
if (tx == null) {
return SDL_Error.SDL_CreateTextureFromSurface;
}
return Texture{ .tx = tx.?, .w = w, .h = h };
}
inline fn renderTextureOptions(self: *Game, tx: *c.SDL_Texture, srcRect: ?URect, dstRect: ?Rect, options: *const DrawOptions) void {
_ = c.SDL_SetTextureAlphaMod(tx, options.color.a);
_ = c.SDL_SetTextureColorMod(tx, options.color.r, options.color.g, options.color.b);
const flip = @bitCast(c.SDL_RendererFlip,
(if (options.flipX) c.SDL_FLIP_HORIZONTAL else c.SDL_FLIP_NONE)
| (if (options.flipY) c.SDL_FLIP_HORIZONTAL else c.SDL_FLIP_NONE));
_ = c.SDL_RenderCopyEx(self.rnd, tx,
if (srcRect == null) null else &srcRect.?.toSDL(),
if (dstRect == null) null else &self.scaleRect(dstRect.?).toSDL(),
0, null, flip);
}
// -- Public methods --
pub fn getFPS(self: *const Game) usize {
return self.fps.fps;
}
pub fn clear(self: *Game, clearColor: Color) void {
self.setColor(clearColor);
// should never error
_ = c.SDL_RenderClear(self.rnd);
}
pub fn render(self: *Game, borderColor: Color) void {
// Calculate FPS
self.fps.counter += 1;
if (self.tick - self.fps.lastTick >= 1000) {
self.fps.fps = self.fps.counter;
self.fps.counter = 0;
self.fps.lastTick = self.tick;
}
// Draw borders
self.setColor(borderColor);
const vp = self.scaleRect(.{ .x = 0, .y = 0, .w = self.w, .h = self.h });
_ = c.SDL_RenderFillRect(self.rnd, &.{ .x = 0, .y = 0, .w = self.winW, .h = @intCast(UUnit, vp.y) });
_ = c.SDL_RenderFillRect(self.rnd, &.{ .x = 0, .y = vp.y + vp.h, .w = self.winW, .h = self.winH - @intCast(UUnit, vp.y) });
_ = c.SDL_RenderFillRect(self.rnd, &.{ .x = vp.x + vp.w, .y = vp.y, .w = self.winW - @intCast(UUnit, vp.x), .h = self.winH - @intCast(UUnit, vp.y) });
_ = c.SDL_RenderFillRect(self.rnd, &.{ .x = 0, .y = vp.y, .w = @intCast(UUnit, vp.x), .h = self.winH - @intCast(UUnit, vp.y) });
// Render
c.SDL_RenderPresent(self.rnd);
}
pub fn drawRect(self: *Game, color: Color, rect: Rect) void {
self.setColor(color);
_ = c.SDL_RenderFillRect(self.rnd, &self.scaleRect(rect).toSDL());
}
pub fn drawTexture(self: *Game, tx: *c.SDL_Texture, x: SUnit, y: SUnit, w: UUnit, h: UUnit, options: DrawOptions) void {
// TODO: this trusts that the user has perfect scaling of width and height or it will render incorrectly, maybe there's a better approach?
self.renderTextureOptions(tx, null, Rect{ .x = x, .y = y, .w = w, .h = h }, &options);
}
pub fn drawSprite(self: *Game, sprite: Sprite, x: SUnit, y: SUnit, scale: UUnit, options: DrawOptions) void {
const dstRect = Rect{ .x = x, .y = y, .w = sprite.srcRect.w * scale, .h = sprite.srcRect.h * scale };
self.renderTextureOptions(sprite.atlas.tx, sprite.srcRect, dstRect, &options);
}
pub fn drawAnim(self: *Game, animState: *AnimState, x: SUnit, y: SUnit, scale: UUnit, options: DrawOptions) void {
// TODO: math
while (self.tick - animState.frameTime >= animState.anim.frames[animState.currentFrame].duration) {
animState.frameTime += animState.anim.frames[animState.currentFrame].duration;
animState.currentFrame += 1;
if (animState.currentFrame == animState.anim.frames.len) {
animState.currentFrame = 0;
if (animState.nextAnim != null) {
animState.anim = animState.nextAnim.?;
animState.nextAnim = null;
}
}
}
self.drawSprite(animState.anim.frames[animState.currentFrame].sprite, x, y, scale, options);
}
pub fn drawMap(self: *Game, map: *const Map, x: SUnit, y: UUnit, scale: UUnit) void {
var ty: usize = 0;
while (ty < map.w) : (ty += 1) {
var tx: usize = 0;
while (tx < map.w) : (tx += 1) {
// TODO: skip those out of bounds
for (map.layers) |layer| {
const tile = layer[ty * map.w + tx];
if (tile > 0) {
self.drawSprite(map.tiles[tile - 1], x + @intCast(SUnit, tx * map.tileW * scale), y + @intCast(SUnit, ty * map.tileH * scale), scale, .{});
}
}
}
}
}
// TODO: "drawTextEx" version that returns location of where the text stopped to make continuation possible
pub fn drawText(game: *Game, font: *const Font, str: []const u8, color: Color, x: SUnit, y: SUnit, scale: UUnit) void {
var tx: SUnit = 0;
var ty: SUnit = 0;
var iter = std.unicode.Utf8Iterator{.bytes = str, .i = 0};
while (iter.nextCodepoint()) |cp| {
const idx = font.mapGlyph(cp);
if (idx == null) {
// TODO: handle other cases
tx += font.glyphW * scale;
} else {
game.drawSprite(font.sheet[idx.?], x + tx, y + ty, scale, .{ .color = color });
tx += (font.glyphW + font.marginX) * scale;
}
// TODO: wrapping
}
}
/// Returns true to keep running, false to exit
pub fn loop(self: *Game) bool {
// Clean up from last iteration
self.mouse.scrollDeltaX = 0;
self.mouse.scrollDeltaY = 0;
self.mouse.left.pressed = false;
self.mouse.right.pressed = false;
self.mouse.middle.pressed = false;
self.keyUpdates.pressed.clearRetainingCapacity();
self.keyUpdates.released.clearRetainingCapacity();
// Handle events
var e: c.SDL_Event = undefined;
while (c.SDL_PollEvent(&e) > 0) {
switch (e.type) {
c.SDL_QUIT => return false,
c.SDL_WINDOWEVENT => {
if (e.window.event == c.SDL_WINDOWEVENT_RESIZED) {
self.winW = @intCast(UUnit, e.window.data1);
self.winH = @intCast(UUnit, e.window.data2);
self.scale = std.math.min(@divTrunc(self.winW, self.w), @divTrunc(self.winH, self.h));
if (self.scale == 0) {
std.log.warn("Window too small!", .{});
// TODO: rather than doing this (which will make the game work but render incorrectly), make the window red or something
self.winW = self.w;
self.winH = self.h;
self.scale = 1;
}
}
},
c.SDL_MOUSEWHEEL => {
self.mouse.scrollDeltaX += @intCast(i16, e.wheel.x);
self.mouse.scrollDeltaY += @intCast(i16, e.wheel.y);
},
c.SDL_MOUSEMOTION => {
const p = self.unscalePoint(e.motion.x, e.motion.y);
self.mouse.x = p.x;
self.mouse.y = p.y;
},
c.SDL_MOUSEBUTTONDOWN => {
if (e.button.button == c.SDL_BUTTON_LEFT) {
self.mouse.left.down = true;
self.mouse.left.pressed = true;
} else if (e.button.button == c.SDL_BUTTON_RIGHT) {
self.mouse.right.down = true;
self.mouse.right.pressed = true;
} else if (e.button.button == c.SDL_BUTTON_MIDDLE) {
self.mouse.middle.down = true;
self.mouse.middle.pressed = true;
}
},
c.SDL_MOUSEBUTTONUP => {
if (e.button.button == c.SDL_BUTTON_LEFT) {
self.mouse.left.down = false;
} else if (e.button.button == c.SDL_BUTTON_RIGHT) {
self.mouse.right.down = false;
} else if (e.button.button == c.SDL_BUTTON_MIDDLE) {
self.mouse.middle.down = false;
}
},
c.SDL_KEYDOWN => self.keyUpdates.pressed.put(@intCast(Keycode, e.key.keysym.sym), e.key.timestamp) catch unreachable,
c.SDL_KEYUP => self.keyUpdates.released.put(@intCast(Keycode, e.key.keysym.sym), e.key.timestamp) catch unreachable,
else => {},
}
}
// Update tick
self.tick = getTick();
return true;
}
/// To be ran after `Game.loop`. Will updated the given KeyStates structs according to `keybinds`.
pub fn updateKeys(self: *Game, comptime KeyStates: type, keybinds: anytype, held: ?*KeyStates, pressed: ?*KeyStates, released: ?*KeyStates) void {
const keys = comptime std.meta.fieldNames(KeyStates);
inline for (keys) |key| {
if (self.keyUpdates.pressed.contains(@field(keybinds, key))) {
if (held == null or !@field(held.?, key)) {
@field(held.?, key) = true;
if (pressed != null) {
@field(pressed.?, key) = true;
}
}
} else if (pressed != null) {
@field(pressed.?, key) = false;
}
if (self.keyUpdates.released.contains(@field(keybinds, key))) {
if (held == null or @field(held.?, key)) {
@field(held.?, key) = false;
if (released != null) {
@field(released.?, key) = true;
}
}
} else if (released != null) {
@field(released.?, key) = false;
}
}
}
// -- Asset methods --
pub fn loadAssets(self: *Game, comptime assetBin: []const u8) !assetsType(assetBin) {
const ass = comptime AssetMetadata.parse(assetBin);
var assets: assetsType(assetBin) = undefined;
assets.alloc = self.alloc;
// Decompress asset data
var assZ = try self.alloc.alloc(u8, ass.decompressedDataSize);
if (c.ZSTD_isError(c.ZSTD_decompress(assZ.ptr, assZ.len, ass.compressedData.ptr, ass.compressedData.len)) != 0) {
return error.zstd_decompression;
}
defer self.alloc.free(assZ);
var byteI: usize = 0;
// Load atlases
assets.atlases = try self.alloc.alloc(Texture, ass.atlasCount);
var atlasI: usize = 0;
while (atlasI < ass.atlasCount) : (atlasI += 1) {
const w = std.mem.readIntSliceBig(u16, assZ[byteI .. byteI + 2]);
const h = std.mem.readIntSliceBig(u16, assZ[byteI + 2 .. byteI + 4]);
assets.atlases[atlasI] = try self.loadTextureFromRGBA(assZ[byteI + 4 .. byteI + @as(usize, w) * @as(usize, h) * 4 + 4], w, h);
byteI += @as(usize, w) * @as(usize, h) * 4 + 4;
}
// Load images
inline for (ass.imageNames) |name| {
@field(assets.images, name) = Sprite.readFromBinary(assets.atlases, assZ[byteI .. byteI + 10]);
byteI += 10;
}
// Load spritesheets
inline for (ass.sheetNames) |name| {
const spriteCount = std.mem.readIntSliceBig(u16, assZ[byteI .. byteI + 2]);
byteI += 2;
var sprites = try self.alloc.alloc(Sprite, spriteCount);
var spriteI: u16 = 0;
while (spriteI < spriteCount) : (spriteI += 1) {
sprites[spriteI] = Sprite.readFromBinary(assets.atlases, assZ[byteI .. byteI + 10]);
byteI += 10;
}
@field(assets.sheets, name) = sprites;
}
// Load animations
inline for (ass.animNames) |name| {
const frameCount = std.mem.readIntSliceBig(u16, assZ[byteI .. byteI + 2]);
byteI += 2;
var frames = try self.alloc.alloc(Anim.Frame, frameCount);
var frameI: u16 = 0;
while (frameI < frameCount) : (frameI += 1) {
frames[frameI].sprite = Sprite.readFromBinary(assets.atlases, assZ[byteI .. byteI + 10]);
frames[frameI].duration = std.mem.readIntSliceBig(u16, assZ[byteI + 10 .. byteI + 12]);
byteI += 12;
}
@field(assets.anims, name).frames = frames;
}
// Load sounds
inline for (ass.soundNames) |name| {
const sz = std.mem.readIntSliceBig(u32, assZ[byteI .. byteI + 4]);
@field(assets.sounds, name) = try self.alloc.dupe(u8, assZ[byteI + 4 .. byteI + 4 + sz]);
byteI += sz + 4;
}
// Load maps
inline for (ass.mapNames) |name| {
const mapWidth = std.mem.readIntSliceBig(u16, assZ[byteI .. byteI + 2]);
const mapHeight = std.mem.readIntSliceBig(u16, assZ[byteI + 2 .. byteI + 4]);
const layerCount = std.mem.readIntSliceBig(u16, assZ[byteI + 4 .. byteI + 6]);
byteI += 6;
@field(assets.maps, name).w = mapWidth;
@field(assets.maps, name).h = mapHeight;
@field(assets.maps, name).tiles = @field(assets.sheets, name ++ "_tiles");
@field(assets.maps, name).tileW = @field(assets.maps, name).tiles[0].srcRect.w;
@field(assets.maps, name).tileH = @field(assets.maps, name).tiles[0].srcRect.h;
var layers = try self.alloc.alloc([]const u16, layerCount);
var i: usize = 0;
while (i < layerCount) : (i += 1) {
var layer = try self.alloc.alloc(u16, mapWidth * mapHeight);
std.mem.set(u16, layer, 0);
var y: usize = 0;
while (y < mapWidth) : (y += 1) {
var x: usize = 0;
while (x < mapHeight) : (x += 1) {
layer[y * mapWidth + x] = std.mem.readIntSliceBig(u16, assZ[byteI .. byteI + 2]);
byteI += 2;
}
}
layers[i] = layer;
}
@field(assets.maps, name).layers = layers;
}
return assets;
}
};
const AssetMetadata = struct {
atlasCount: u16,
imageNames: []const []const u8,
sheetNames: []const []const u8,
animNames: []const []const u8,
soundNames: []const []const u8,
mapNames: []const []const u8,
decompressedDataSize: u32,
compressedData: []const u8,
fn parseNames(comptime data: []const u8, byteI: *usize) []const []const u8 {
const count = std.mem.readIntSliceBig(u16, data[byteI.* .. byteI.* + 2]);
byteI.* += 2;
var names: []const []const u8 = &.{};
var i: usize = 0;
while (i < count) : (i += 1) {
const strlen = std.mem.readIntSliceBig(u16, data[byteI.* .. byteI.* + 2]);
names = names ++ [1][]const u8{data[byteI.* + 2 .. byteI.* + 2 + strlen]};
byteI.* += strlen + 2;
}
return names;
}
fn parse(comptime data: []const u8) AssetMetadata {
const atlasCount = std.mem.readIntSliceBig(u16, data[0..2]);
var byteI: usize = 2;
const imageNames = parseNames(data, &byteI);
const sheetNames = parseNames(data, &byteI);
const animNames = parseNames(data, &byteI);
const soundNames = parseNames(data, &byteI);
const mapNames = parseNames(data, &byteI);
const decompressedDataSize = std.mem.readIntSliceBig(u32, data[byteI .. byteI + 4]);
const compressedDataSize = std.mem.readIntSliceBig(u32, data[byteI + 4 .. byteI + 8]);
byteI += 8;
return AssetMetadata{
.atlasCount = atlasCount,
.imageNames = imageNames,
.sheetNames = sheetNames,
.animNames = animNames,
.soundNames = soundNames,
.mapNames = mapNames,
.compressedData = data[byteI .. byteI + compressedDataSize],
.decompressedDataSize = decompressedDataSize,
};
}
};
pub fn assetsType(comptime assetBin: []const u8) type {
const ass = AssetMetadata.parse(assetBin);
return struct {
alloc: *std.mem.Allocator,
atlases: []Texture,
images: makeStruct(ass.imageNames, Sprite, null),
sheets: makeStruct(ass.sheetNames, []const Sprite, null),
anims: makeStruct(ass.animNames, Anim, null),
sounds: makeStruct(ass.soundNames, []const u8, null),
maps: makeStruct(ass.mapNames, Map, null),
pub fn deinit(self: *@This()) void {
for (self.atlases) |_, i| {
self.atlases[i].deinit();
}
self.alloc.free(self.atlases);
inline for (ass.sheetNames) |name| {
self.alloc.free(@field(self.sheets, name));
}
inline for (ass.animNames) |name| {
self.alloc.free(@field(self.anims, name).frames);
}
inline for (ass.soundNames) |name| {
self.alloc.free(@field(self.sounds, name));
}
inline for (ass.mapNames) |name| {
for (@field(self.maps, name).layers) |layer| {
self.alloc.free(layer);
}
self.alloc.free(@field(self.maps, name).layers);
}
self.* = undefined;
}
};
}
const Texture = struct {
tx: *c.SDL_Texture,
w: UUnit,
h: UUnit,
pub fn deinit(self: *@This()) void {
c.SDL_DestroyTexture(self.tx);
self.* = undefined;
}
};
pub const Sprite = struct {
atlas: *const Texture,
srcRect: URect,
/// Consumes 10 bytes
fn readFromBinary(atlases: []const Texture, data: []u8) Sprite {
return Sprite{
.atlas = &atlases[std.mem.readIntSliceBig(u16, data[0..2])],
.srcRect = URect{
.x = std.mem.readIntSliceBig(u16, data[2..4]),
.y = std.mem.readIntSliceBig(u16, data[4..6]),
.w = std.mem.readIntSliceBig(u16, data[6..8]),
.h = std.mem.readIntSliceBig(u16, data[8..10]),
}
};
}
};
pub const Anim = struct {
pub const Frame = struct {
sprite: Sprite,
duration: Tick,
};
frames: []Frame,
};
pub const AnimState = struct {
anim: *const Anim,
nextAnim: ?*const Anim = null,
currentFrame: usize = 0,
frameTime: Tick = 0,
};
pub const Map = struct {
w: u16,
h: u16,
tileW: u16,
tileH: u16,
layers: []const []const u16,
tiles: []const Sprite, // set to `<map name> ++ "_tiles"`
};
pub const Font = struct {
sheet: []const Sprite,
glyphW: UUnit,
glyphH: UUnit,
marginX: UUnit = 1,
marginY: UUnit = 1,
mapGlyph: fn(codepoint: u21) ?usize, // TODO: negative enum for newline and space
};
/// Convenience function for not having to create the KeyStates struct yourself
pub fn makeKeyStates(comptime keybindContainerType: type) type {
for (std.meta.fields(keybindContainerType)) |field| {
if (field.field_type != Keycode) {
@compileError("field '" ++ field.name ++ "' isn't of type Keycode");
}
}
return makeStruct(std.meta.fieldNames(keybindContainerType), bool, false);
}
/// Create a KeyMap struct out of defaults, loading config into it for values that exist
pub fn loadKeyConfig(filename: []const u8, comptime defaults: anytype) keymapFromDefaults(defaults) {
var out: keymapFromDefaults(defaults) = defaults;
var f = std.fs.cwd().openFile(filename, .{}) catch return out;
defer f.close();
var reader = f.reader();
var i: usize = 0;
var line: [1024]u8 = undefined;
while (true) {
const char = reader.readByte() catch null;
if (char == null or char.? == '\n') {
if (i > 0) {
line[i] = 0; // Null-term
var split = std.mem.split(line[0..i], ":");
i = 0;
const fieldName = split.next() orelse continue;
const keyName = split.rest();
const kc = c.SDL_GetKeyFromName(keyName.ptr);
if (kc == c.SDLK_UNKNOWN) {
std.log.warn("unknown key '{s}', using default", .{std.mem.spanZ(keyName)});
continue;
}
inline for (comptime std.meta.fieldNames(@TypeOf(out))) |name| {
if (std.mem.eql(u8, name, fieldName)) {
@field(out, name) = @intCast(Keycode, kc);
}
}
}
if (char == null) {
break;
}
} else if (char.? != ' ' and char.? != '\r') {
line[i] = char.?;
i += 1;
if (i == line.len - 1) {
std.log.warn("key config lines too long, aborting read", .{});
return out;
}
}
}
return out;
}
fn keymapFromDefaults(comptime defaults: anytype) type {
return makeStruct(std.meta.fieldNames(@TypeOf(defaults)), Keycode, @intCast(Keycode, c.SDLK_UNKNOWN));
}
pub fn saveKeyConfig(filename: []const u8, keys: anytype) !void {
var f = try std.fs.cwd().createFile(filename, .{});
defer f.close();
var writer = f.writer();
inline for (comptime std.meta.fieldNames(@TypeOf(keys))) |name| {
try std.fmt.format(writer, "{s}:{s}\n", .{ name, c.SDL_GetKeyName(@intCast(i32, @field(keys, name))) });
}
}
fn makeStruct(comptime names: []const []const u8, comptime valueType: type, comptime defaultValue: anytype) type {
var fields: [names.len]std.builtin.TypeInfo.StructField = undefined;
var i = 0;
while (i < names.len) : (i += 1) {
fields[i].name = names[i];
fields[i].field_type = valueType;
fields[i].default_value = defaultValue;
fields[i].is_comptime = false;
fields[i].alignment = 0;
}
return @Type(std.builtin.TypeInfo{ .Struct = .{
.layout = .Auto,
.fields = &fields,
.decls = &.{},
.is_tuple = false,
} });
} | src/sdlb.zig |
const utils = @import("./_utils.zig");
/// XREAD [COUNT count] [BLOCK milliseconds] STREAMS key [key ...] ID [id ...]
pub const XREAD = struct {
count: Count = .NoCount,
block: Block = .NoBlock,
streams: []const []const u8,
ids: []const []const u8,
/// Instantiates a new XREAD command.
pub fn init(count: Count, block: Block, streams: []const []const u8, ids: []const []const u8) XREAD {
return .{
.count = count,
.block = block,
.streams = streams,
.ids = ids,
};
}
/// Validates if the command is syntactically correct.
pub fn validate(self: XREAD) !void {
// Zero means blocking forever, use `.Forever` in such case.
switch (self.block) {
else => {},
.Milliseconds => |m| if (m == 0) return error.ZeroMeansBlockingForever,
}
// Check if the number of parameters is correct
if (self.streams.len == 0) return error.StreamsArrayIsEmpty;
if (self.streams.len != self.ids.len) return error.StreamsAndIDsLenMismatch;
// Check the individual stream/id entries
var i: usize = 0;
while (i < self.streams.len) : (i += 1) {
if (self.streams[i].len == 0) return error.EmptyKeyName;
if (!utils.isValidStreamID(.XREAD, self.ids[i])) return error.InvalidID;
}
}
pub const RedisCommand = struct {
pub fn serialize(self: XREAD, comptime rootSerializer: type, msg: anytype) !void {
return rootSerializer.serializeCommand(msg, .{
"XREAD",
self.count,
self.block,
"STREAMS",
self.streams,
self.ids,
});
}
};
pub const Count = union(enum) {
NoCount,
Count: usize,
pub const RedisArguments = struct {
pub fn count(self: Count) usize {
return switch (self) {
.NoCount => 0,
.Count => 2,
};
}
pub fn serialize(self: Count, comptime rootSerializer: type, msg: anytype) !void {
switch (self) {
.NoCount => {},
.Count => |c| {
try rootSerializer.serializeArgument(msg, []const u8, "COUNT");
try rootSerializer.serializeArgument(msg, u64, c);
},
}
}
};
};
pub const Block = union(enum) {
NoBlock,
Forever,
Milliseconds: usize,
pub const RedisArguments = struct {
pub fn count(self: Block) usize {
return switch (self) {
.NoBlock => 0,
else => 2,
};
}
pub fn serialize(self: Block, comptime rootSerializer: type, msg: anytype) !void {
switch (self) {
.NoBlock => {},
.Forever => {
try rootSerializer.serializeArgument(msg, []const u8, "BLOCK");
try rootSerializer.serializeArgument(msg, u64, 0);
},
.Milliseconds => |m| {
try rootSerializer.serializeArgument(msg, []const u8, "BLOCK");
try rootSerializer.serializeArgument(msg, u64, m);
},
}
}
};
};
};
test "basic usage" {
const cmd = XREAD.init(
.NoCount,
.NoBlock,
&[_][]const u8{ "stream1", "stream2" },
&[_][]const u8{ "123-123", "$" },
);
try cmd.validate();
}
test "serializer" {
const std = @import("std");
const serializer = @import("../../serializer.zig").CommandSerializer;
var correctBuf: [1000]u8 = undefined;
var correctMsg = std.io.fixedBufferStream(correctBuf[0..]);
var testBuf: [1000]u8 = undefined;
var testMsg = std.io.fixedBufferStream(testBuf[0..]);
{
correctMsg.reset();
testMsg.reset();
try serializer.serializeCommand(
testMsg.writer(),
XREAD.init(
.NoCount,
.NoBlock,
&[_][]const u8{ "key1", "key2" },
&[_][]const u8{ "$", "$" },
),
);
try serializer.serializeCommand(
correctMsg.writer(),
.{ "XREAD", "STREAMS", "key1", "key2", "$", "$" },
);
try std.testing.expectEqualSlices(u8, correctMsg.getWritten(), testMsg.getWritten());
}
} | src/commands/streams/xread.zig |
pub const RPC_C_BINDING_INFINITE_TIMEOUT = @as(u32, 10);
pub const RPC_C_BINDING_MIN_TIMEOUT = @as(u32, 0);
pub const RPC_C_BINDING_DEFAULT_TIMEOUT = @as(u32, 5);
pub const RPC_C_BINDING_MAX_TIMEOUT = @as(u32, 9);
pub const RPC_C_CANCEL_INFINITE_TIMEOUT = @as(i32, -1);
pub const RPC_C_LISTEN_MAX_CALLS_DEFAULT = @as(u32, 1234);
pub const RPC_C_PROTSEQ_MAX_REQS_DEFAULT = @as(u32, 10);
pub const RPC_C_BIND_TO_ALL_NICS = @as(u32, 1);
pub const RPC_C_USE_INTERNET_PORT = @as(u32, 1);
pub const RPC_C_USE_INTRANET_PORT = @as(u32, 2);
pub const RPC_C_DONT_FAIL = @as(u32, 4);
pub const RPC_C_RPCHTTP_USE_LOAD_BALANCE = @as(u32, 8);
pub const RPC_C_MQ_TEMPORARY = @as(u32, 0);
pub const RPC_C_MQ_PERMANENT = @as(u32, 1);
pub const RPC_C_MQ_CLEAR_ON_OPEN = @as(u32, 2);
pub const RPC_C_MQ_USE_EXISTING_SECURITY = @as(u32, 4);
pub const RPC_C_MQ_AUTHN_LEVEL_NONE = @as(u32, 0);
pub const RPC_C_MQ_AUTHN_LEVEL_PKT_INTEGRITY = @as(u32, 8);
pub const RPC_C_MQ_AUTHN_LEVEL_PKT_PRIVACY = @as(u32, 16);
pub const RPC_C_MQ_EXPRESS = @as(u32, 0);
pub const RPC_C_MQ_RECOVERABLE = @as(u32, 1);
pub const RPC_C_MQ_JOURNAL_NONE = @as(u32, 0);
pub const RPC_C_MQ_JOURNAL_DEADLETTER = @as(u32, 1);
pub const RPC_C_MQ_JOURNAL_ALWAYS = @as(u32, 2);
pub const RPC_C_OPT_MQ_DELIVERY = @as(u32, 1);
pub const RPC_C_OPT_MQ_PRIORITY = @as(u32, 2);
pub const RPC_C_OPT_MQ_JOURNAL = @as(u32, 3);
pub const RPC_C_OPT_MQ_ACKNOWLEDGE = @as(u32, 4);
pub const RPC_C_OPT_MQ_AUTHN_SERVICE = @as(u32, 5);
pub const RPC_C_OPT_MQ_AUTHN_LEVEL = @as(u32, 6);
pub const RPC_C_OPT_MQ_TIME_TO_REACH_QUEUE = @as(u32, 7);
pub const RPC_C_OPT_MQ_TIME_TO_BE_RECEIVED = @as(u32, 8);
pub const RPC_C_OPT_BINDING_NONCAUSAL = @as(u32, 9);
pub const RPC_C_OPT_SECURITY_CALLBACK = @as(u32, 10);
pub const RPC_C_OPT_UNIQUE_BINDING = @as(u32, 11);
pub const RPC_C_OPT_MAX_OPTIONS = @as(u32, 12);
pub const RPC_C_OPT_CALL_TIMEOUT = @as(u32, 12);
pub const RPC_C_OPT_DONT_LINGER = @as(u32, 13);
pub const RPC_C_OPT_TRANS_SEND_BUFFER_SIZE = @as(u32, 5);
pub const RPC_C_OPT_TRUST_PEER = @as(u32, 14);
pub const RPC_C_OPT_ASYNC_BLOCK = @as(u32, 15);
pub const RPC_C_OPT_OPTIMIZE_TIME = @as(u32, 16);
pub const RPC_C_FULL_CERT_CHAIN = @as(u32, 1);
pub const RPC_C_STATS_CALLS_IN = @as(u32, 0);
pub const RPC_C_STATS_CALLS_OUT = @as(u32, 1);
pub const RPC_C_STATS_PKTS_IN = @as(u32, 2);
pub const RPC_C_STATS_PKTS_OUT = @as(u32, 3);
pub const RPC_C_AUTHN_NONE = @as(u32, 0);
pub const RPC_C_AUTHN_DCE_PRIVATE = @as(u32, 1);
pub const RPC_C_AUTHN_DCE_PUBLIC = @as(u32, 2);
pub const RPC_C_AUTHN_DEC_PUBLIC = @as(u32, 4);
pub const RPC_C_AUTHN_GSS_NEGOTIATE = @as(u32, 9);
pub const RPC_C_AUTHN_WINNT = @as(u32, 10);
pub const RPC_C_AUTHN_GSS_SCHANNEL = @as(u32, 14);
pub const RPC_C_AUTHN_GSS_KERBEROS = @as(u32, 16);
pub const RPC_C_AUTHN_DPA = @as(u32, 17);
pub const RPC_C_AUTHN_MSN = @as(u32, 18);
pub const RPC_C_AUTHN_DIGEST = @as(u32, 21);
pub const RPC_C_AUTHN_KERNEL = @as(u32, 20);
pub const RPC_C_AUTHN_NEGO_EXTENDER = @as(u32, 30);
pub const RPC_C_AUTHN_PKU2U = @as(u32, 31);
pub const RPC_C_AUTHN_LIVE_SSP = @as(u32, 32);
pub const RPC_C_AUTHN_LIVEXP_SSP = @as(u32, 35);
pub const RPC_C_AUTHN_CLOUD_AP = @as(u32, 36);
pub const RPC_C_AUTHN_MSONLINE = @as(u32, 82);
pub const RPC_C_AUTHN_MQ = @as(u32, 100);
pub const RPC_C_AUTHN_DEFAULT = @as(i32, -1);
pub const RPC_C_SECURITY_QOS_VERSION = @as(i32, 1);
pub const RPC_C_SECURITY_QOS_VERSION_1 = @as(i32, 1);
pub const RPC_C_SECURITY_QOS_VERSION_2 = @as(i32, 2);
pub const RPC_C_HTTP_AUTHN_SCHEME_BASIC = @as(u32, 1);
pub const RPC_C_HTTP_AUTHN_SCHEME_NTLM = @as(u32, 2);
pub const RPC_C_HTTP_AUTHN_SCHEME_PASSPORT = @as(u32, 4);
pub const RPC_C_HTTP_AUTHN_SCHEME_DIGEST = @as(u32, 8);
pub const RPC_C_HTTP_AUTHN_SCHEME_NEGOTIATE = @as(u32, 16);
pub const RPC_C_HTTP_AUTHN_SCHEME_CERT = @as(u32, 65536);
pub const RPC_C_SECURITY_QOS_VERSION_3 = @as(i32, 3);
pub const RPC_C_SECURITY_QOS_VERSION_4 = @as(i32, 4);
pub const RPC_C_SECURITY_QOS_VERSION_5 = @as(i32, 5);
pub const RPC_PROTSEQ_TCP = @as(u32, 1);
pub const RPC_PROTSEQ_NMP = @as(u32, 2);
pub const RPC_PROTSEQ_LRPC = @as(u32, 3);
pub const RPC_PROTSEQ_HTTP = @as(u32, 4);
pub const RPC_BHT_OBJECT_UUID_VALID = @as(u32, 1);
pub const RPC_BHO_EXCLUSIVE_AND_GUARANTEED = @as(u32, 4);
pub const RPC_C_AUTHZ_NONE = @as(u32, 0);
pub const RPC_C_AUTHZ_NAME = @as(u32, 1);
pub const RPC_C_AUTHZ_DCE = @as(u32, 2);
pub const RPC_C_AUTHZ_DEFAULT = @as(u32, 4294967295);
pub const DCE_C_ERROR_STRING_LEN = @as(u32, 256);
pub const RPC_C_EP_ALL_ELTS = @as(u32, 0);
pub const RPC_C_EP_MATCH_BY_IF = @as(u32, 1);
pub const RPC_C_EP_MATCH_BY_OBJ = @as(u32, 2);
pub const RPC_C_EP_MATCH_BY_BOTH = @as(u32, 3);
pub const RPC_C_VERS_ALL = @as(u32, 1);
pub const RPC_C_VERS_COMPATIBLE = @as(u32, 2);
pub const RPC_C_VERS_EXACT = @as(u32, 3);
pub const RPC_C_VERS_MAJOR_ONLY = @as(u32, 4);
pub const RPC_C_VERS_UPTO = @as(u32, 5);
pub const RPC_C_MGMT_INQ_IF_IDS = @as(u32, 0);
pub const RPC_C_MGMT_INQ_PRINC_NAME = @as(u32, 1);
pub const RPC_C_MGMT_INQ_STATS = @as(u32, 2);
pub const RPC_C_MGMT_IS_SERVER_LISTEN = @as(u32, 3);
pub const RPC_C_MGMT_STOP_SERVER_LISTEN = @as(u32, 4);
pub const RPC_C_PARM_MAX_PACKET_LENGTH = @as(u32, 1);
pub const RPC_C_PARM_BUFFER_LENGTH = @as(u32, 2);
pub const RPC_IF_AUTOLISTEN = @as(u32, 1);
pub const RPC_IF_OLE = @as(u32, 2);
pub const RPC_IF_ALLOW_UNKNOWN_AUTHORITY = @as(u32, 4);
pub const RPC_IF_ALLOW_SECURE_ONLY = @as(u32, 8);
pub const RPC_IF_ALLOW_CALLBACKS_WITH_NO_AUTH = @as(u32, 16);
pub const RPC_IF_ALLOW_LOCAL_ONLY = @as(u32, 32);
pub const RPC_IF_SEC_NO_CACHE = @as(u32, 64);
pub const RPC_IF_SEC_CACHE_PER_PROC = @as(u32, 128);
pub const RPC_IF_ASYNC_CALLBACK = @as(u32, 256);
pub const RPC_FW_IF_FLAG_DCOM = @as(u32, 1);
pub const RPC_C_NOTIFY_ON_SEND_COMPLETE = @as(u32, 1);
pub const MaxNumberOfEEInfoParams = @as(u32, 4);
pub const RPC_EEINFO_VERSION = @as(u32, 1);
pub const EEInfoPreviousRecordsMissing = @as(u32, 1);
pub const EEInfoNextRecordsMissing = @as(u32, 2);
pub const EEInfoUseFileTime = @as(u32, 4);
pub const EEInfoGCCOM = @as(u32, 11);
pub const EEInfoGCFRS = @as(u32, 12);
pub const RPC_CALL_ATTRIBUTES_VERSION = @as(u32, 2);
pub const RPC_QUERY_SERVER_PRINCIPAL_NAME = @as(u32, 2);
pub const RPC_QUERY_CLIENT_PRINCIPAL_NAME = @as(u32, 4);
pub const RPC_QUERY_CALL_LOCAL_ADDRESS = @as(u32, 8);
pub const RPC_QUERY_CLIENT_PID = @as(u32, 16);
pub const RPC_QUERY_IS_CLIENT_LOCAL = @as(u32, 32);
pub const RPC_QUERY_NO_AUTH_REQUIRED = @as(u32, 64);
pub const RPC_QUERY_CLIENT_ID = @as(u32, 128);
pub const RPC_CALL_STATUS_CANCELLED = @as(u32, 1);
pub const RPC_CALL_STATUS_DISCONNECTED = @as(u32, 2);
pub const RPC_CONTEXT_HANDLE_DEFAULT_FLAGS = @as(u32, 0);
pub const RPC_CONTEXT_HANDLE_FLAGS = @as(u32, 805306368);
pub const RPC_CONTEXT_HANDLE_SERIALIZE = @as(u32, 268435456);
pub const RPC_CONTEXT_HANDLE_DONT_SERIALIZE = @as(u32, 536870912);
pub const RPC_TYPE_STRICT_CONTEXT_HANDLE = @as(u32, 1073741824);
pub const RPC_TYPE_DISCONNECT_EVENT_CONTEXT_HANDLE = @as(u32, 2147483648);
pub const RPC_NCA_FLAGS_DEFAULT = @as(u32, 0);
pub const RPC_NCA_FLAGS_IDEMPOTENT = @as(u32, 1);
pub const RPC_NCA_FLAGS_BROADCAST = @as(u32, 2);
pub const RPC_NCA_FLAGS_MAYBE = @as(u32, 4);
pub const RPCFLG_HAS_GUARANTEE = @as(u32, 16);
pub const RPCFLG_WINRT_REMOTE_ASYNC = @as(u32, 32);
pub const RPC_BUFFER_COMPLETE = @as(u32, 4096);
pub const RPC_BUFFER_PARTIAL = @as(u32, 8192);
pub const RPC_BUFFER_EXTRA = @as(u32, 16384);
pub const RPC_BUFFER_ASYNC = @as(u32, 32768);
pub const RPC_BUFFER_NONOTIFY = @as(u32, 65536);
pub const RPCFLG_MESSAGE = @as(u32, 16777216);
pub const RPCFLG_AUTO_COMPLETE = @as(u32, 134217728);
pub const RPCFLG_LOCAL_CALL = @as(u32, 268435456);
pub const RPCFLG_INPUT_SYNCHRONOUS = @as(u32, 536870912);
pub const RPCFLG_ASYNCHRONOUS = @as(u32, 1073741824);
pub const RPCFLG_NON_NDR = @as(u32, 2147483648);
pub const RPCFLG_HAS_MULTI_SYNTAXES = @as(u32, 33554432);
pub const RPCFLG_HAS_CALLBACK = @as(u32, 67108864);
pub const RPCFLG_ACCESSIBILITY_BIT1 = @as(u32, 1048576);
pub const RPCFLG_ACCESSIBILITY_BIT2 = @as(u32, 2097152);
pub const RPCFLG_ACCESS_LOCAL = @as(u32, 4194304);
pub const NDR_CUSTOM_OR_DEFAULT_ALLOCATOR = @as(u32, 268435456);
pub const NDR_DEFAULT_ALLOCATOR = @as(u32, 536870912);
pub const RPCFLG_NDR64_CONTAINS_ARM_LAYOUT = @as(u32, 67108864);
pub const RPCFLG_SENDER_WAITING_FOR_REPLY = @as(u32, 8388608);
pub const RPC_FLAGS_VALID_BIT = @as(u32, 32768);
pub const NT351_INTERFACE_SIZE = @as(u32, 64);
pub const RPC_INTERFACE_HAS_PIPES = @as(u32, 1);
pub const RPC_SYSTEM_HANDLE_FREE_UNRETRIEVED = @as(u32, 1);
pub const RPC_SYSTEM_HANDLE_FREE_RETRIEVED = @as(u32, 2);
pub const RPC_SYSTEM_HANDLE_FREE_ALL = @as(u32, 3);
pub const RPC_SYSTEM_HANDLE_FREE_ERROR_ON_CLOSE = @as(u32, 4);
pub const TRANSPORT_TYPE_CN = @as(u32, 1);
pub const TRANSPORT_TYPE_DG = @as(u32, 2);
pub const TRANSPORT_TYPE_LPC = @as(u32, 4);
pub const TRANSPORT_TYPE_WMSG = @as(u32, 8);
pub const RPC_P_ADDR_FORMAT_TCP_IPV4 = @as(u32, 1);
pub const RPC_P_ADDR_FORMAT_TCP_IPV6 = @as(u32, 2);
pub const RPC_C_OPT_SESSION_ID = @as(u32, 6);
pub const RPC_C_OPT_COOKIE_AUTH = @as(u32, 7);
pub const RPC_C_OPT_RESOURCE_TYPE_UUID = @as(u32, 8);
pub const RPC_PROXY_CONNECTION_TYPE_IN_PROXY = @as(u32, 0);
pub const RPC_PROXY_CONNECTION_TYPE_OUT_PROXY = @as(u32, 1);
pub const RPC_C_OPT_PRIVATE_SUPPRESS_WAKE = @as(u32, 1);
pub const RPC_C_OPT_PRIVATE_DO_NOT_DISTURB = @as(u32, 2);
pub const RPC_C_OPT_PRIVATE_BREAK_ON_SUSPEND = @as(u32, 3);
pub const RPC_C_PROFILE_DEFAULT_ELT = @as(u32, 0);
pub const RPC_C_PROFILE_ALL_ELT = @as(u32, 1);
pub const RPC_C_PROFILE_MATCH_BY_IF = @as(u32, 2);
pub const RPC_C_PROFILE_MATCH_BY_MBR = @as(u32, 3);
pub const RPC_C_PROFILE_MATCH_BY_BOTH = @as(u32, 4);
pub const RPC_C_NS_DEFAULT_EXP_AGE = @as(i32, -1);
pub const TARGET_IS_NT100_OR_LATER = @as(u32, 1);
pub const TARGET_IS_NT63_OR_LATER = @as(u32, 1);
pub const TARGET_IS_NT62_OR_LATER = @as(u32, 1);
pub const TARGET_IS_NT61_OR_LATER = @as(u32, 1);
pub const TARGET_IS_NT60_OR_LATER = @as(u32, 1);
pub const TARGET_IS_NT51_OR_LATER = @as(u32, 1);
pub const TARGET_IS_NT50_OR_LATER = @as(u32, 1);
pub const TARGET_IS_NT40_OR_LATER = @as(u32, 1);
pub const TARGET_IS_NT351_OR_WIN95_OR_LATER = @as(u32, 1);
pub const USER_CALL_IS_ASYNC = @as(u32, 256);
pub const USER_CALL_NEW_CORRELATION_DESC = @as(u32, 512);
pub const USER_MARSHAL_FC_BYTE = @as(u32, 1);
pub const USER_MARSHAL_FC_CHAR = @as(u32, 2);
pub const USER_MARSHAL_FC_SMALL = @as(u32, 3);
pub const USER_MARSHAL_FC_USMALL = @as(u32, 4);
pub const USER_MARSHAL_FC_WCHAR = @as(u32, 5);
pub const USER_MARSHAL_FC_SHORT = @as(u32, 6);
pub const USER_MARSHAL_FC_USHORT = @as(u32, 7);
pub const USER_MARSHAL_FC_LONG = @as(u32, 8);
pub const USER_MARSHAL_FC_ULONG = @as(u32, 9);
pub const USER_MARSHAL_FC_FLOAT = @as(u32, 10);
pub const USER_MARSHAL_FC_HYPER = @as(u32, 11);
pub const USER_MARSHAL_FC_DOUBLE = @as(u32, 12);
pub const MidlInterceptionInfoVersionOne = @as(i32, 1);
pub const MidlWinrtTypeSerializationInfoVersionOne = @as(i32, 1);
//--------------------------------------------------------------------------------
// Section: Types (171)
//--------------------------------------------------------------------------------
pub const NDR_SCONTEXT_1 = extern struct {
pad: [2]?*c_void,
userContext: ?*c_void,
};
pub const RPC_C_QOS_CAPABILITIES = enum(u32) {
DEFAULT = 0,
MUTUAL_AUTH = 1,
MAKE_FULLSIC = 2,
ANY_AUTHORITY = 4,
IGNORE_DELEGATE_FAILURE = 8,
LOCAL_MA_HINT = 16,
SCHANNEL_FULL_AUTH_IDENTITY = 32,
_,
pub fn initFlags(o: struct {
DEFAULT: u1 = 0,
MUTUAL_AUTH: u1 = 0,
MAKE_FULLSIC: u1 = 0,
ANY_AUTHORITY: u1 = 0,
IGNORE_DELEGATE_FAILURE: u1 = 0,
LOCAL_MA_HINT: u1 = 0,
SCHANNEL_FULL_AUTH_IDENTITY: u1 = 0,
}) RPC_C_QOS_CAPABILITIES {
return @intToEnum(RPC_C_QOS_CAPABILITIES,
(if (o.DEFAULT == 1) @enumToInt(RPC_C_QOS_CAPABILITIES.DEFAULT) else 0)
| (if (o.MUTUAL_AUTH == 1) @enumToInt(RPC_C_QOS_CAPABILITIES.MUTUAL_AUTH) else 0)
| (if (o.MAKE_FULLSIC == 1) @enumToInt(RPC_C_QOS_CAPABILITIES.MAKE_FULLSIC) else 0)
| (if (o.ANY_AUTHORITY == 1) @enumToInt(RPC_C_QOS_CAPABILITIES.ANY_AUTHORITY) else 0)
| (if (o.IGNORE_DELEGATE_FAILURE == 1) @enumToInt(RPC_C_QOS_CAPABILITIES.IGNORE_DELEGATE_FAILURE) else 0)
| (if (o.LOCAL_MA_HINT == 1) @enumToInt(RPC_C_QOS_CAPABILITIES.LOCAL_MA_HINT) else 0)
| (if (o.SCHANNEL_FULL_AUTH_IDENTITY == 1) @enumToInt(RPC_C_QOS_CAPABILITIES.SCHANNEL_FULL_AUTH_IDENTITY) else 0)
);
}
};
pub const RPC_C_QOS_CAPABILITIES_DEFAULT = RPC_C_QOS_CAPABILITIES.DEFAULT;
pub const RPC_C_QOS_CAPABILITIES_MUTUAL_AUTH = RPC_C_QOS_CAPABILITIES.MUTUAL_AUTH;
pub const RPC_C_QOS_CAPABILITIES_MAKE_FULLSIC = RPC_C_QOS_CAPABILITIES.MAKE_FULLSIC;
pub const RPC_C_QOS_CAPABILITIES_ANY_AUTHORITY = RPC_C_QOS_CAPABILITIES.ANY_AUTHORITY;
pub const RPC_C_QOS_CAPABILITIES_IGNORE_DELEGATE_FAILURE = RPC_C_QOS_CAPABILITIES.IGNORE_DELEGATE_FAILURE;
pub const RPC_C_QOS_CAPABILITIES_LOCAL_MA_HINT = RPC_C_QOS_CAPABILITIES.LOCAL_MA_HINT;
pub const RPC_C_QOS_CAPABILITIES_SCHANNEL_FULL_AUTH_IDENTITY = RPC_C_QOS_CAPABILITIES.SCHANNEL_FULL_AUTH_IDENTITY;
pub const RPC_C_QOS_IDENTITY = enum(u32) {
STATIC = 0,
DYNAMIC = 1,
};
pub const RPC_C_QOS_IDENTITY_STATIC = RPC_C_QOS_IDENTITY.STATIC;
pub const RPC_C_QOS_IDENTITY_DYNAMIC = RPC_C_QOS_IDENTITY.DYNAMIC;
pub const RPC_C_AUTHN_INFO_TYPE = enum(u32) {
NONE = 0,
TYPE_HTTP = 1,
};
pub const RPC_C_AUTHN_INFO_NONE = RPC_C_AUTHN_INFO_TYPE.NONE;
pub const RPC_C_AUTHN_INFO_TYPE_HTTP = RPC_C_AUTHN_INFO_TYPE.TYPE_HTTP;
pub const RPC_C_HTTP_FLAGS = enum(u32) {
USE_SSL = 1,
USE_FIRST_AUTH_SCHEME = 2,
IGNORE_CERT_CN_INVALID = 8,
ENABLE_CERT_REVOCATION_CHECK = 16,
_,
pub fn initFlags(o: struct {
USE_SSL: u1 = 0,
USE_FIRST_AUTH_SCHEME: u1 = 0,
IGNORE_CERT_CN_INVALID: u1 = 0,
ENABLE_CERT_REVOCATION_CHECK: u1 = 0,
}) RPC_C_HTTP_FLAGS {
return @intToEnum(RPC_C_HTTP_FLAGS,
(if (o.USE_SSL == 1) @enumToInt(RPC_C_HTTP_FLAGS.USE_SSL) else 0)
| (if (o.USE_FIRST_AUTH_SCHEME == 1) @enumToInt(RPC_C_HTTP_FLAGS.USE_FIRST_AUTH_SCHEME) else 0)
| (if (o.IGNORE_CERT_CN_INVALID == 1) @enumToInt(RPC_C_HTTP_FLAGS.IGNORE_CERT_CN_INVALID) else 0)
| (if (o.ENABLE_CERT_REVOCATION_CHECK == 1) @enumToInt(RPC_C_HTTP_FLAGS.ENABLE_CERT_REVOCATION_CHECK) else 0)
);
}
};
pub const RPC_C_HTTP_FLAG_USE_SSL = RPC_C_HTTP_FLAGS.USE_SSL;
pub const RPC_C_HTTP_FLAG_USE_FIRST_AUTH_SCHEME = RPC_C_HTTP_FLAGS.USE_FIRST_AUTH_SCHEME;
pub const RPC_C_HTTP_FLAG_IGNORE_CERT_CN_INVALID = RPC_C_HTTP_FLAGS.IGNORE_CERT_CN_INVALID;
pub const RPC_C_HTTP_FLAG_ENABLE_CERT_REVOCATION_CHECK = RPC_C_HTTP_FLAGS.ENABLE_CERT_REVOCATION_CHECK;
pub const RPC_C_HTTP_AUTHN_TARGET = enum(u32) {
SERVER = 1,
PROXY = 2,
_,
pub fn initFlags(o: struct {
SERVER: u1 = 0,
PROXY: u1 = 0,
}) RPC_C_HTTP_AUTHN_TARGET {
return @intToEnum(RPC_C_HTTP_AUTHN_TARGET,
(if (o.SERVER == 1) @enumToInt(RPC_C_HTTP_AUTHN_TARGET.SERVER) else 0)
| (if (o.PROXY == 1) @enumToInt(RPC_C_HTTP_AUTHN_TARGET.PROXY) else 0)
);
}
};
pub const RPC_C_HTTP_AUTHN_TARGET_SERVER = RPC_C_HTTP_AUTHN_TARGET.SERVER;
pub const RPC_C_HTTP_AUTHN_TARGET_PROXY = RPC_C_HTTP_AUTHN_TARGET.PROXY;
pub const RPC_STATUS = enum(i32) {
RPC_S_INVALID_STRING_BINDING = 1700,
RPC_S_WRONG_KIND_OF_BINDING = 1701,
RPC_S_INVALID_BINDING = 1702,
RPC_S_PROTSEQ_NOT_SUPPORTED = 1703,
RPC_S_INVALID_RPC_PROTSEQ = 1704,
RPC_S_INVALID_STRING_UUID = 1705,
RPC_S_INVALID_ENDPOINT_FORMAT = 1706,
RPC_S_INVALID_NET_ADDR = 1707,
RPC_S_NO_ENDPOINT_FOUND = 1708,
RPC_S_INVALID_TIMEOUT = 1709,
RPC_S_OBJECT_NOT_FOUND = 1710,
RPC_S_ALREADY_REGISTERED = 1711,
RPC_S_TYPE_ALREADY_REGISTERED = 1712,
RPC_S_ALREADY_LISTENING = 1713,
RPC_S_NO_PROTSEQS_REGISTERED = 1714,
RPC_S_NOT_LISTENING = 1715,
RPC_S_UNKNOWN_MGR_TYPE = 1716,
RPC_S_UNKNOWN_IF = 1717,
RPC_S_NO_BINDINGS = 1718,
RPC_S_NO_PROTSEQS = 1719,
RPC_S_CANT_CREATE_ENDPOINT = 1720,
RPC_S_OUT_OF_RESOURCES = 1721,
RPC_S_SERVER_UNAVAILABLE = 1722,
RPC_S_SERVER_TOO_BUSY = 1723,
RPC_S_INVALID_NETWORK_OPTIONS = 1724,
RPC_S_NO_CALL_ACTIVE = 1725,
RPC_S_CALL_FAILED = 1726,
RPC_S_CALL_FAILED_DNE = 1727,
RPC_S_PROTOCOL_ERROR = 1728,
RPC_S_PROXY_ACCESS_DENIED = 1729,
RPC_S_UNSUPPORTED_TRANS_SYN = 1730,
RPC_S_UNSUPPORTED_TYPE = 1732,
RPC_S_INVALID_TAG = 1733,
RPC_S_INVALID_BOUND = 1734,
RPC_S_NO_ENTRY_NAME = 1735,
RPC_S_INVALID_NAME_SYNTAX = 1736,
RPC_S_UNSUPPORTED_NAME_SYNTAX = 1737,
RPC_S_UUID_NO_ADDRESS = 1739,
RPC_S_DUPLICATE_ENDPOINT = 1740,
RPC_S_UNKNOWN_AUTHN_TYPE = 1741,
RPC_S_MAX_CALLS_TOO_SMALL = 1742,
RPC_S_STRING_TOO_LONG = 1743,
RPC_S_PROTSEQ_NOT_FOUND = 1744,
RPC_S_PROCNUM_OUT_OF_RANGE = 1745,
RPC_S_BINDING_HAS_NO_AUTH = 1746,
RPC_S_UNKNOWN_AUTHN_SERVICE = 1747,
RPC_S_UNKNOWN_AUTHN_LEVEL = 1748,
RPC_S_INVALID_AUTH_IDENTITY = 1749,
RPC_S_UNKNOWN_AUTHZ_SERVICE = 1750,
EPT_S_INVALID_ENTRY = 1751,
EPT_S_CANT_PERFORM_OP = 1752,
EPT_S_NOT_REGISTERED = 1753,
RPC_S_NOTHING_TO_EXPORT = 1754,
RPC_S_INCOMPLETE_NAME = 1755,
RPC_S_INVALID_VERS_OPTION = 1756,
RPC_S_NO_MORE_MEMBERS = 1757,
RPC_S_NOT_ALL_OBJS_UNEXPORTED = 1758,
RPC_S_INTERFACE_NOT_FOUND = 1759,
RPC_S_ENTRY_ALREADY_EXISTS = 1760,
RPC_S_ENTRY_NOT_FOUND = 1761,
RPC_S_NAME_SERVICE_UNAVAILABLE = 1762,
RPC_S_INVALID_NAF_ID = 1763,
RPC_S_CANNOT_SUPPORT = 1764,
RPC_S_NO_CONTEXT_AVAILABLE = 1765,
RPC_S_INTERNAL_ERROR = 1766,
RPC_S_ZERO_DIVIDE = 1767,
RPC_S_ADDRESS_ERROR = 1768,
RPC_S_FP_DIV_ZERO = 1769,
RPC_S_FP_UNDERFLOW = 1770,
RPC_S_FP_OVERFLOW = 1771,
RPC_S_CALL_IN_PROGRESS = 1791,
RPC_S_NO_MORE_BINDINGS = 1806,
RPC_S_NO_INTERFACES = 1817,
RPC_S_CALL_CANCELLED = 1818,
RPC_S_BINDING_INCOMPLETE = 1819,
RPC_S_COMM_FAILURE = 1820,
RPC_S_UNSUPPORTED_AUTHN_LEVEL = 1821,
RPC_S_NO_PRINC_NAME = 1822,
RPC_S_NOT_RPC_ERROR = 1823,
RPC_S_UUID_LOCAL_ONLY = 1824,
RPC_S_SEC_PKG_ERROR = 1825,
RPC_S_NOT_CANCELLED = 1826,
RPC_S_COOKIE_AUTH_FAILED = 1833,
RPC_S_DO_NOT_DISTURB = 1834,
RPC_S_SYSTEM_HANDLE_COUNT_EXCEEDED = 1835,
RPC_S_SYSTEM_HANDLE_TYPE_MISMATCH = 1836,
RPC_S_GROUP_MEMBER_NOT_FOUND = 1898,
EPT_S_CANT_CREATE = 1899,
RPC_S_INVALID_OBJECT = 1900,
RPC_S_SEND_INCOMPLETE = 1913,
RPC_S_INVALID_ASYNC_HANDLE = 1914,
RPC_S_INVALID_ASYNC_CALL = 1915,
RPC_S_ENTRY_TYPE_MISMATCH = 1922,
RPC_S_NOT_ALL_OBJS_EXPORTED = 1923,
RPC_S_INTERFACE_NOT_EXPORTED = 1924,
RPC_S_PROFILE_NOT_ADDED = 1925,
RPC_S_PRF_ELT_NOT_ADDED = 1926,
RPC_S_PRF_ELT_NOT_REMOVED = 1927,
RPC_S_GRP_ELT_NOT_ADDED = 1928,
RPC_S_GRP_ELT_NOT_REMOVED = 1929,
};
pub const RPC_S_INVALID_STRING_BINDING = RPC_STATUS.RPC_S_INVALID_STRING_BINDING;
pub const RPC_S_WRONG_KIND_OF_BINDING = RPC_STATUS.RPC_S_WRONG_KIND_OF_BINDING;
pub const RPC_S_INVALID_BINDING = RPC_STATUS.RPC_S_INVALID_BINDING;
pub const RPC_S_PROTSEQ_NOT_SUPPORTED = RPC_STATUS.RPC_S_PROTSEQ_NOT_SUPPORTED;
pub const RPC_S_INVALID_RPC_PROTSEQ = RPC_STATUS.RPC_S_INVALID_RPC_PROTSEQ;
pub const RPC_S_INVALID_STRING_UUID = RPC_STATUS.RPC_S_INVALID_STRING_UUID;
pub const RPC_S_INVALID_ENDPOINT_FORMAT = RPC_STATUS.RPC_S_INVALID_ENDPOINT_FORMAT;
pub const RPC_S_INVALID_NET_ADDR = RPC_STATUS.RPC_S_INVALID_NET_ADDR;
pub const RPC_S_NO_ENDPOINT_FOUND = RPC_STATUS.RPC_S_NO_ENDPOINT_FOUND;
pub const RPC_S_INVALID_TIMEOUT = RPC_STATUS.RPC_S_INVALID_TIMEOUT;
pub const RPC_S_OBJECT_NOT_FOUND = RPC_STATUS.RPC_S_OBJECT_NOT_FOUND;
pub const RPC_S_ALREADY_REGISTERED = RPC_STATUS.RPC_S_ALREADY_REGISTERED;
pub const RPC_S_TYPE_ALREADY_REGISTERED = RPC_STATUS.RPC_S_TYPE_ALREADY_REGISTERED;
pub const RPC_S_ALREADY_LISTENING = RPC_STATUS.RPC_S_ALREADY_LISTENING;
pub const RPC_S_NO_PROTSEQS_REGISTERED = RPC_STATUS.RPC_S_NO_PROTSEQS_REGISTERED;
pub const RPC_S_NOT_LISTENING = RPC_STATUS.RPC_S_NOT_LISTENING;
pub const RPC_S_UNKNOWN_MGR_TYPE = RPC_STATUS.RPC_S_UNKNOWN_MGR_TYPE;
pub const RPC_S_UNKNOWN_IF = RPC_STATUS.RPC_S_UNKNOWN_IF;
pub const RPC_S_NO_BINDINGS = RPC_STATUS.RPC_S_NO_BINDINGS;
pub const RPC_S_NO_PROTSEQS = RPC_STATUS.RPC_S_NO_PROTSEQS;
pub const RPC_S_CANT_CREATE_ENDPOINT = RPC_STATUS.RPC_S_CANT_CREATE_ENDPOINT;
pub const RPC_S_OUT_OF_RESOURCES = RPC_STATUS.RPC_S_OUT_OF_RESOURCES;
pub const RPC_S_SERVER_UNAVAILABLE = RPC_STATUS.RPC_S_SERVER_UNAVAILABLE;
pub const RPC_S_SERVER_TOO_BUSY = RPC_STATUS.RPC_S_SERVER_TOO_BUSY;
pub const RPC_S_INVALID_NETWORK_OPTIONS = RPC_STATUS.RPC_S_INVALID_NETWORK_OPTIONS;
pub const RPC_S_NO_CALL_ACTIVE = RPC_STATUS.RPC_S_NO_CALL_ACTIVE;
pub const RPC_S_CALL_FAILED = RPC_STATUS.RPC_S_CALL_FAILED;
pub const RPC_S_CALL_FAILED_DNE = RPC_STATUS.RPC_S_CALL_FAILED_DNE;
pub const RPC_S_PROTOCOL_ERROR = RPC_STATUS.RPC_S_PROTOCOL_ERROR;
pub const RPC_S_PROXY_ACCESS_DENIED = RPC_STATUS.RPC_S_PROXY_ACCESS_DENIED;
pub const RPC_S_UNSUPPORTED_TRANS_SYN = RPC_STATUS.RPC_S_UNSUPPORTED_TRANS_SYN;
pub const RPC_S_UNSUPPORTED_TYPE = RPC_STATUS.RPC_S_UNSUPPORTED_TYPE;
pub const RPC_S_INVALID_TAG = RPC_STATUS.RPC_S_INVALID_TAG;
pub const RPC_S_INVALID_BOUND = RPC_STATUS.RPC_S_INVALID_BOUND;
pub const RPC_S_NO_ENTRY_NAME = RPC_STATUS.RPC_S_NO_ENTRY_NAME;
pub const RPC_S_INVALID_NAME_SYNTAX = RPC_STATUS.RPC_S_INVALID_NAME_SYNTAX;
pub const RPC_S_UNSUPPORTED_NAME_SYNTAX = RPC_STATUS.RPC_S_UNSUPPORTED_NAME_SYNTAX;
pub const RPC_S_UUID_NO_ADDRESS = RPC_STATUS.RPC_S_UUID_NO_ADDRESS;
pub const RPC_S_DUPLICATE_ENDPOINT = RPC_STATUS.RPC_S_DUPLICATE_ENDPOINT;
pub const RPC_S_UNKNOWN_AUTHN_TYPE = RPC_STATUS.RPC_S_UNKNOWN_AUTHN_TYPE;
pub const RPC_S_MAX_CALLS_TOO_SMALL = RPC_STATUS.RPC_S_MAX_CALLS_TOO_SMALL;
pub const RPC_S_STRING_TOO_LONG = RPC_STATUS.RPC_S_STRING_TOO_LONG;
pub const RPC_S_PROTSEQ_NOT_FOUND = RPC_STATUS.RPC_S_PROTSEQ_NOT_FOUND;
pub const RPC_S_PROCNUM_OUT_OF_RANGE = RPC_STATUS.RPC_S_PROCNUM_OUT_OF_RANGE;
pub const RPC_S_BINDING_HAS_NO_AUTH = RPC_STATUS.RPC_S_BINDING_HAS_NO_AUTH;
pub const RPC_S_UNKNOWN_AUTHN_SERVICE = RPC_STATUS.RPC_S_UNKNOWN_AUTHN_SERVICE;
pub const RPC_S_UNKNOWN_AUTHN_LEVEL = RPC_STATUS.RPC_S_UNKNOWN_AUTHN_LEVEL;
pub const RPC_S_INVALID_AUTH_IDENTITY = RPC_STATUS.RPC_S_INVALID_AUTH_IDENTITY;
pub const RPC_S_UNKNOWN_AUTHZ_SERVICE = RPC_STATUS.RPC_S_UNKNOWN_AUTHZ_SERVICE;
pub const EPT_S_INVALID_ENTRY = RPC_STATUS.EPT_S_INVALID_ENTRY;
pub const EPT_S_CANT_PERFORM_OP = RPC_STATUS.EPT_S_CANT_PERFORM_OP;
pub const EPT_S_NOT_REGISTERED = RPC_STATUS.EPT_S_NOT_REGISTERED;
pub const RPC_S_NOTHING_TO_EXPORT = RPC_STATUS.RPC_S_NOTHING_TO_EXPORT;
pub const RPC_S_INCOMPLETE_NAME = RPC_STATUS.RPC_S_INCOMPLETE_NAME;
pub const RPC_S_INVALID_VERS_OPTION = RPC_STATUS.RPC_S_INVALID_VERS_OPTION;
pub const RPC_S_NO_MORE_MEMBERS = RPC_STATUS.RPC_S_NO_MORE_MEMBERS;
pub const RPC_S_NOT_ALL_OBJS_UNEXPORTED = RPC_STATUS.RPC_S_NOT_ALL_OBJS_UNEXPORTED;
pub const RPC_S_INTERFACE_NOT_FOUND = RPC_STATUS.RPC_S_INTERFACE_NOT_FOUND;
pub const RPC_S_ENTRY_ALREADY_EXISTS = RPC_STATUS.RPC_S_ENTRY_ALREADY_EXISTS;
pub const RPC_S_ENTRY_NOT_FOUND = RPC_STATUS.RPC_S_ENTRY_NOT_FOUND;
pub const RPC_S_NAME_SERVICE_UNAVAILABLE = RPC_STATUS.RPC_S_NAME_SERVICE_UNAVAILABLE;
pub const RPC_S_INVALID_NAF_ID = RPC_STATUS.RPC_S_INVALID_NAF_ID;
pub const RPC_S_CANNOT_SUPPORT = RPC_STATUS.RPC_S_CANNOT_SUPPORT;
pub const RPC_S_NO_CONTEXT_AVAILABLE = RPC_STATUS.RPC_S_NO_CONTEXT_AVAILABLE;
pub const RPC_S_INTERNAL_ERROR = RPC_STATUS.RPC_S_INTERNAL_ERROR;
pub const RPC_S_ZERO_DIVIDE = RPC_STATUS.RPC_S_ZERO_DIVIDE;
pub const RPC_S_ADDRESS_ERROR = RPC_STATUS.RPC_S_ADDRESS_ERROR;
pub const RPC_S_FP_DIV_ZERO = RPC_STATUS.RPC_S_FP_DIV_ZERO;
pub const RPC_S_FP_UNDERFLOW = RPC_STATUS.RPC_S_FP_UNDERFLOW;
pub const RPC_S_FP_OVERFLOW = RPC_STATUS.RPC_S_FP_OVERFLOW;
pub const RPC_S_CALL_IN_PROGRESS = RPC_STATUS.RPC_S_CALL_IN_PROGRESS;
pub const RPC_S_NO_MORE_BINDINGS = RPC_STATUS.RPC_S_NO_MORE_BINDINGS;
pub const RPC_S_NO_INTERFACES = RPC_STATUS.RPC_S_NO_INTERFACES;
pub const RPC_S_CALL_CANCELLED = RPC_STATUS.RPC_S_CALL_CANCELLED;
pub const RPC_S_BINDING_INCOMPLETE = RPC_STATUS.RPC_S_BINDING_INCOMPLETE;
pub const RPC_S_COMM_FAILURE = RPC_STATUS.RPC_S_COMM_FAILURE;
pub const RPC_S_UNSUPPORTED_AUTHN_LEVEL = RPC_STATUS.RPC_S_UNSUPPORTED_AUTHN_LEVEL;
pub const RPC_S_NO_PRINC_NAME = RPC_STATUS.RPC_S_NO_PRINC_NAME;
pub const RPC_S_NOT_RPC_ERROR = RPC_STATUS.RPC_S_NOT_RPC_ERROR;
pub const RPC_S_UUID_LOCAL_ONLY = RPC_STATUS.RPC_S_UUID_LOCAL_ONLY;
pub const RPC_S_SEC_PKG_ERROR = RPC_STATUS.RPC_S_SEC_PKG_ERROR;
pub const RPC_S_NOT_CANCELLED = RPC_STATUS.RPC_S_NOT_CANCELLED;
pub const RPC_S_COOKIE_AUTH_FAILED = RPC_STATUS.RPC_S_COOKIE_AUTH_FAILED;
pub const RPC_S_DO_NOT_DISTURB = RPC_STATUS.RPC_S_DO_NOT_DISTURB;
pub const RPC_S_SYSTEM_HANDLE_COUNT_EXCEEDED = RPC_STATUS.RPC_S_SYSTEM_HANDLE_COUNT_EXCEEDED;
pub const RPC_S_SYSTEM_HANDLE_TYPE_MISMATCH = RPC_STATUS.RPC_S_SYSTEM_HANDLE_TYPE_MISMATCH;
pub const RPC_S_GROUP_MEMBER_NOT_FOUND = RPC_STATUS.RPC_S_GROUP_MEMBER_NOT_FOUND;
pub const EPT_S_CANT_CREATE = RPC_STATUS.EPT_S_CANT_CREATE;
pub const RPC_S_INVALID_OBJECT = RPC_STATUS.RPC_S_INVALID_OBJECT;
pub const RPC_S_SEND_INCOMPLETE = RPC_STATUS.RPC_S_SEND_INCOMPLETE;
pub const RPC_S_INVALID_ASYNC_HANDLE = RPC_STATUS.RPC_S_INVALID_ASYNC_HANDLE;
pub const RPC_S_INVALID_ASYNC_CALL = RPC_STATUS.RPC_S_INVALID_ASYNC_CALL;
pub const RPC_S_ENTRY_TYPE_MISMATCH = RPC_STATUS.RPC_S_ENTRY_TYPE_MISMATCH;
pub const RPC_S_NOT_ALL_OBJS_EXPORTED = RPC_STATUS.RPC_S_NOT_ALL_OBJS_EXPORTED;
pub const RPC_S_INTERFACE_NOT_EXPORTED = RPC_STATUS.RPC_S_INTERFACE_NOT_EXPORTED;
pub const RPC_S_PROFILE_NOT_ADDED = RPC_STATUS.RPC_S_PROFILE_NOT_ADDED;
pub const RPC_S_PRF_ELT_NOT_ADDED = RPC_STATUS.RPC_S_PRF_ELT_NOT_ADDED;
pub const RPC_S_PRF_ELT_NOT_REMOVED = RPC_STATUS.RPC_S_PRF_ELT_NOT_REMOVED;
pub const RPC_S_GRP_ELT_NOT_ADDED = RPC_STATUS.RPC_S_GRP_ELT_NOT_ADDED;
pub const RPC_S_GRP_ELT_NOT_REMOVED = RPC_STATUS.RPC_S_GRP_ELT_NOT_REMOVED;
pub const GROUP_NAME_SYNTAX = enum(u32) {
EFAULT = 0,
CE = 3,
};
pub const RPC_C_NS_SYNTAX_DEFAULT = GROUP_NAME_SYNTAX.EFAULT;
pub const RPC_C_NS_SYNTAX_DCE = GROUP_NAME_SYNTAX.CE;
pub const SEC_WINNT_AUTH_IDENTITY = enum(u32) {
ANSI = 1,
UNICODE = 2,
};
pub const SEC_WINNT_AUTH_IDENTITY_ANSI = SEC_WINNT_AUTH_IDENTITY.ANSI;
pub const SEC_WINNT_AUTH_IDENTITY_UNICODE = SEC_WINNT_AUTH_IDENTITY.UNICODE;
pub const RPC_BINDING_HANDLE_OPTIONS_FLAGS = enum(u32) {
NONCAUSAL = 1,
DONTLINGER = 2,
_,
pub fn initFlags(o: struct {
NONCAUSAL: u1 = 0,
DONTLINGER: u1 = 0,
}) RPC_BINDING_HANDLE_OPTIONS_FLAGS {
return @intToEnum(RPC_BINDING_HANDLE_OPTIONS_FLAGS,
(if (o.NONCAUSAL == 1) @enumToInt(RPC_BINDING_HANDLE_OPTIONS_FLAGS.NONCAUSAL) else 0)
| (if (o.DONTLINGER == 1) @enumToInt(RPC_BINDING_HANDLE_OPTIONS_FLAGS.DONTLINGER) else 0)
);
}
};
pub const RPC_BHO_NONCAUSAL = RPC_BINDING_HANDLE_OPTIONS_FLAGS.NONCAUSAL;
pub const RPC_BHO_DONTLINGER = RPC_BINDING_HANDLE_OPTIONS_FLAGS.DONTLINGER;
pub const _NDR_ASYNC_MESSAGE = extern struct {
placeholder: usize, // TODO: why is this type empty?
};
pub const _NDR_CORRELATION_INFO = extern struct {
placeholder: usize, // TODO: why is this type empty?
};
pub const NDR_ALLOC_ALL_NODES_CONTEXT = extern struct {
placeholder: usize, // TODO: why is this type empty?
};
pub const NDR_POINTER_QUEUE_STATE = extern struct {
placeholder: usize, // TODO: why is this type empty?
};
pub const _NDR_PROC_CONTEXT = extern struct {
placeholder: usize, // TODO: why is this type empty?
};
pub const RPC_BINDING_VECTOR = extern struct {
Count: u32,
BindingH: [1]?*c_void,
};
pub const UUID_VECTOR = extern struct {
Count: u32,
Uuid: [1]?*Guid,
};
pub const RPC_IF_ID = extern struct {
Uuid: Guid,
VersMajor: u16,
VersMinor: u16,
};
pub const RPC_PROTSEQ_VECTORA = extern struct {
Count: u32,
Protseq: [1]?*u8,
};
pub const RPC_PROTSEQ_VECTORW = extern struct {
Count: u32,
Protseq: [1]?*u16,
};
pub const RPC_POLICY = extern struct {
Length: u32,
EndpointFlags: u32,
NICFlags: u32,
};
pub const RPC_OBJECT_INQ_FN = fn(
ObjectUuid: ?*Guid,
TypeUuid: ?*Guid,
Status: ?*RPC_STATUS,
) callconv(@import("std").os.windows.WINAPI) void;
pub const RPC_IF_CALLBACK_FN = fn(
InterfaceUuid: ?*c_void,
Context: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub const RPC_SECURITY_CALLBACK_FN = fn(
Context: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub const RPC_STATS_VECTOR = extern struct {
Count: u32,
Stats: [1]u32,
};
pub const RPC_IF_ID_VECTOR = extern struct {
Count: u32,
IfId: [1]?*RPC_IF_ID,
};
pub const RPC_SECURITY_QOS = extern struct {
Version: u32,
Capabilities: RPC_C_QOS_CAPABILITIES,
IdentityTracking: RPC_C_QOS_IDENTITY,
ImpersonationType: RPC_C_IMP_LEVEL,
};
pub const SEC_WINNT_AUTH_IDENTITY_W = extern struct {
User: ?*u16,
UserLength: u32,
Domain: ?*u16,
DomainLength: u32,
Password: <PASSWORD>,
PasswordLength: u32,
Flags: SEC_WINNT_AUTH_IDENTITY,
};
pub const SEC_WINNT_AUTH_IDENTITY_A = extern struct {
User: ?*u8,
UserLength: u32,
Domain: ?*u8,
DomainLength: u32,
Password: <PASSWORD>,
PasswordLength: u32,
Flags: SEC_WINNT_AUTH_IDENTITY,
};
pub const RPC_HTTP_TRANSPORT_CREDENTIALS_W = extern struct {
TransportCredentials: ?*SEC_WINNT_AUTH_IDENTITY_W,
Flags: RPC_C_HTTP_FLAGS,
AuthenticationTarget: RPC_C_HTTP_AUTHN_TARGET,
NumberOfAuthnSchemes: u32,
AuthnSchemes: ?*u32,
ServerCertificateSubject: ?*u16,
};
pub const RPC_HTTP_TRANSPORT_CREDENTIALS_A = extern struct {
TransportCredentials: ?*SEC_WINNT_AUTH_IDENTITY_A,
Flags: RPC_C_HTTP_FLAGS,
AuthenticationTarget: RPC_C_HTTP_AUTHN_TARGET,
NumberOfAuthnSchemes: u32,
AuthnSchemes: ?*u32,
ServerCertificateSubject: ?*u8,
};
pub const RPC_HTTP_TRANSPORT_CREDENTIALS_V2_W = extern struct {
TransportCredentials: ?*SEC_WINNT_AUTH_IDENTITY_W,
Flags: RPC_C_HTTP_FLAGS,
AuthenticationTarget: RPC_C_HTTP_AUTHN_TARGET,
NumberOfAuthnSchemes: u32,
AuthnSchemes: ?*u32,
ServerCertificateSubject: ?*u16,
ProxyCredentials: ?*SEC_WINNT_AUTH_IDENTITY_W,
NumberOfProxyAuthnSchemes: u32,
ProxyAuthnSchemes: ?*u32,
};
pub const RPC_HTTP_TRANSPORT_CREDENTIALS_V2_A = extern struct {
TransportCredentials: ?*SEC_WINNT_AUTH_IDENTITY_A,
Flags: RPC_C_HTTP_FLAGS,
AuthenticationTarget: RPC_C_HTTP_AUTHN_TARGET,
NumberOfAuthnSchemes: u32,
AuthnSchemes: ?*u32,
ServerCertificateSubject: ?*u8,
ProxyCredentials: ?*SEC_WINNT_AUTH_IDENTITY_A,
NumberOfProxyAuthnSchemes: u32,
ProxyAuthnSchemes: ?*u32,
};
pub const RPC_HTTP_TRANSPORT_CREDENTIALS_V3_W = extern struct {
TransportCredentials: ?*c_void,
Flags: RPC_C_HTTP_FLAGS,
AuthenticationTarget: RPC_C_HTTP_AUTHN_TARGET,
NumberOfAuthnSchemes: u32,
AuthnSchemes: ?*u32,
ServerCertificateSubject: ?*u16,
ProxyCredentials: ?*c_void,
NumberOfProxyAuthnSchemes: u32,
ProxyAuthnSchemes: ?*u32,
};
pub const RPC_HTTP_TRANSPORT_CREDENTIALS_V3_A = extern struct {
TransportCredentials: ?*c_void,
Flags: RPC_C_HTTP_FLAGS,
AuthenticationTarget: RPC_C_HTTP_AUTHN_TARGET,
NumberOfAuthnSchemes: u32,
AuthnSchemes: ?*u32,
ServerCertificateSubject: ?*u8,
ProxyCredentials: ?*c_void,
NumberOfProxyAuthnSchemes: u32,
ProxyAuthnSchemes: ?*u32,
};
pub const RPC_SECURITY_QOS_V2_W = extern struct {
Version: u32,
Capabilities: RPC_C_QOS_CAPABILITIES,
IdentityTracking: RPC_C_QOS_IDENTITY,
ImpersonationType: RPC_C_IMP_LEVEL,
AdditionalSecurityInfoType: RPC_C_AUTHN_INFO_TYPE,
u: extern union {
HttpCredentials: ?*RPC_HTTP_TRANSPORT_CREDENTIALS_W,
},
};
pub const RPC_SECURITY_QOS_V2_A = extern struct {
Version: u32,
Capabilities: RPC_C_QOS_CAPABILITIES,
IdentityTracking: RPC_C_QOS_IDENTITY,
ImpersonationType: RPC_C_IMP_LEVEL,
AdditionalSecurityInfoType: RPC_C_AUTHN_INFO_TYPE,
u: extern union {
HttpCredentials: ?*RPC_HTTP_TRANSPORT_CREDENTIALS_A,
},
};
pub const RPC_SECURITY_QOS_V3_W = extern struct {
Version: u32,
Capabilities: RPC_C_QOS_CAPABILITIES,
IdentityTracking: RPC_C_QOS_IDENTITY,
ImpersonationType: RPC_C_IMP_LEVEL,
AdditionalSecurityInfoType: RPC_C_AUTHN_INFO_TYPE,
u: extern union {
HttpCredentials: ?*RPC_HTTP_TRANSPORT_CREDENTIALS_W,
},
Sid: ?*c_void,
};
pub const RPC_SECURITY_QOS_V3_A = extern struct {
Version: u32,
Capabilities: RPC_C_QOS_CAPABILITIES,
IdentityTracking: RPC_C_QOS_IDENTITY,
ImpersonationType: RPC_C_IMP_LEVEL,
AdditionalSecurityInfoType: RPC_C_AUTHN_INFO_TYPE,
u: extern union {
HttpCredentials: ?*RPC_HTTP_TRANSPORT_CREDENTIALS_A,
},
Sid: ?*c_void,
};
pub const RPC_SECURITY_QOS_V4_W = extern struct {
Version: u32,
Capabilities: RPC_C_QOS_CAPABILITIES,
IdentityTracking: RPC_C_QOS_IDENTITY,
ImpersonationType: RPC_C_IMP_LEVEL,
AdditionalSecurityInfoType: RPC_C_AUTHN_INFO_TYPE,
u: extern union {
HttpCredentials: ?*RPC_HTTP_TRANSPORT_CREDENTIALS_W,
},
Sid: ?*c_void,
EffectiveOnly: u32,
};
pub const RPC_SECURITY_QOS_V4_A = extern struct {
Version: u32,
Capabilities: RPC_C_QOS_CAPABILITIES,
IdentityTracking: RPC_C_QOS_IDENTITY,
ImpersonationType: RPC_C_IMP_LEVEL,
AdditionalSecurityInfoType: RPC_C_AUTHN_INFO_TYPE,
u: extern union {
HttpCredentials: ?*RPC_HTTP_TRANSPORT_CREDENTIALS_A,
},
Sid: ?*c_void,
EffectiveOnly: u32,
};
pub const RPC_SECURITY_QOS_V5_W = extern struct {
Version: u32,
Capabilities: RPC_C_QOS_CAPABILITIES,
IdentityTracking: RPC_C_QOS_IDENTITY,
ImpersonationType: RPC_C_IMP_LEVEL,
AdditionalSecurityInfoType: RPC_C_AUTHN_INFO_TYPE,
u: extern union {
HttpCredentials: ?*RPC_HTTP_TRANSPORT_CREDENTIALS_W,
},
Sid: ?*c_void,
EffectiveOnly: u32,
ServerSecurityDescriptor: ?*c_void,
};
pub const RPC_SECURITY_QOS_V5_A = extern struct {
Version: u32,
Capabilities: RPC_C_QOS_CAPABILITIES,
IdentityTracking: RPC_C_QOS_IDENTITY,
ImpersonationType: RPC_C_IMP_LEVEL,
AdditionalSecurityInfoType: RPC_C_AUTHN_INFO_TYPE,
u: extern union {
HttpCredentials: ?*RPC_HTTP_TRANSPORT_CREDENTIALS_A,
},
Sid: ?*c_void,
EffectiveOnly: u32,
ServerSecurityDescriptor: ?*c_void,
};
pub const RPC_BINDING_HANDLE_TEMPLATE_V1_W = extern struct {
Version: u32,
Flags: u32,
ProtocolSequence: u32,
NetworkAddress: ?*u16,
StringEndpoint: ?*u16,
u1: extern union {
Reserved: ?*u16,
},
ObjectUuid: Guid,
};
pub const RPC_BINDING_HANDLE_TEMPLATE_V1_A = extern struct {
Version: u32,
Flags: u32,
ProtocolSequence: u32,
NetworkAddress: ?*u8,
StringEndpoint: ?*u8,
u1: extern union {
Reserved: ?*u8,
},
ObjectUuid: Guid,
};
pub const RPC_BINDING_HANDLE_SECURITY_V1_W = extern struct {
Version: u32,
ServerPrincName: ?*u16,
AuthnLevel: u32,
AuthnSvc: u32,
AuthIdentity: ?*SEC_WINNT_AUTH_IDENTITY_W,
SecurityQos: ?*RPC_SECURITY_QOS,
};
pub const RPC_BINDING_HANDLE_SECURITY_V1_A = extern struct {
Version: u32,
ServerPrincName: ?*u8,
AuthnLevel: u32,
AuthnSvc: u32,
AuthIdentity: ?*SEC_WINNT_AUTH_IDENTITY_A,
SecurityQos: ?*RPC_SECURITY_QOS,
};
pub const RPC_BINDING_HANDLE_OPTIONS_V1 = extern struct {
Version: u32,
Flags: RPC_BINDING_HANDLE_OPTIONS_FLAGS,
ComTimeout: u32,
CallTimeout: u32,
};
pub const RPC_HTTP_REDIRECTOR_STAGE = enum(i32) {
REDIRECT = 1,
ACCESS_1 = 2,
SESSION = 3,
ACCESS_2 = 4,
INTERFACE = 5,
};
pub const RPCHTTP_RS_REDIRECT = RPC_HTTP_REDIRECTOR_STAGE.REDIRECT;
pub const RPCHTTP_RS_ACCESS_1 = RPC_HTTP_REDIRECTOR_STAGE.ACCESS_1;
pub const RPCHTTP_RS_SESSION = RPC_HTTP_REDIRECTOR_STAGE.SESSION;
pub const RPCHTTP_RS_ACCESS_2 = RPC_HTTP_REDIRECTOR_STAGE.ACCESS_2;
pub const RPCHTTP_RS_INTERFACE = RPC_HTTP_REDIRECTOR_STAGE.INTERFACE;
pub const RPC_NEW_HTTP_PROXY_CHANNEL = fn(
RedirectorStage: RPC_HTTP_REDIRECTOR_STAGE,
ServerName: ?*u16,
ServerPort: ?*u16,
RemoteUser: ?*u16,
AuthType: ?*u16,
ResourceUuid: ?*c_void,
SessionId: ?*c_void,
Interface: ?*c_void,
Reserved: ?*c_void,
Flags: u32,
NewServerName: ?*?*u16,
NewServerPort: ?*?*u16,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub const RPC_HTTP_PROXY_FREE_STRING = fn(
String: ?*u16,
) callconv(@import("std").os.windows.WINAPI) void;
pub const RPC_AUTH_KEY_RETRIEVAL_FN = fn(
Arg: ?*c_void,
ServerPrincName: ?*u16,
KeyVer: u32,
Key: ?*?*c_void,
Status: ?*RPC_STATUS,
) callconv(@import("std").os.windows.WINAPI) void;
pub const RPC_CLIENT_INFORMATION1 = extern struct {
UserName: ?*u8,
ComputerName: ?*u8,
Privilege: u16,
AuthFlags: u32,
};
pub const RPC_MGMT_AUTHORIZATION_FN = fn(
ClientBinding: ?*c_void,
RequestedMgmtOperation: u32,
Status: ?*RPC_STATUS,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const RPC_ENDPOINT_TEMPLATEW = extern struct {
Version: u32,
ProtSeq: ?*u16,
Endpoint: ?*u16,
SecurityDescriptor: ?*c_void,
Backlog: u32,
};
pub const RPC_ENDPOINT_TEMPLATEA = extern struct {
Version: u32,
ProtSeq: ?*u8,
Endpoint: ?*u8,
SecurityDescriptor: ?*c_void,
Backlog: u32,
};
pub const RPC_INTERFACE_TEMPLATEA = extern struct {
Version: u32,
IfSpec: ?*c_void,
MgrTypeUuid: ?*Guid,
MgrEpv: ?*c_void,
Flags: u32,
MaxCalls: u32,
MaxRpcSize: u32,
IfCallback: ?RPC_IF_CALLBACK_FN,
UuidVector: ?*UUID_VECTOR,
Annotation: ?*u8,
SecurityDescriptor: ?*c_void,
};
pub const RPC_INTERFACE_TEMPLATEW = extern struct {
Version: u32,
IfSpec: ?*c_void,
MgrTypeUuid: ?*Guid,
MgrEpv: ?*c_void,
Flags: u32,
MaxCalls: u32,
MaxRpcSize: u32,
IfCallback: ?RPC_IF_CALLBACK_FN,
UuidVector: ?*UUID_VECTOR,
Annotation: ?*u16,
SecurityDescriptor: ?*c_void,
};
pub const RPC_INTERFACE_GROUP_IDLE_CALLBACK_FN = fn(
IfGroup: ?*c_void,
IdleCallbackContext: ?*c_void,
IsGroupIdle: u32,
) callconv(@import("std").os.windows.WINAPI) void;
pub const RPC_VERSION = extern struct {
MajorVersion: u16,
MinorVersion: u16,
};
pub const RPC_SYNTAX_IDENTIFIER = extern struct {
SyntaxGUID: Guid,
SyntaxVersion: RPC_VERSION,
};
pub const RPC_MESSAGE = extern struct {
Handle: ?*c_void,
DataRepresentation: u32,
Buffer: ?*c_void,
BufferLength: u32,
ProcNum: u32,
TransferSyntax: ?*RPC_SYNTAX_IDENTIFIER,
RpcInterfaceInformation: ?*c_void,
ReservedForRuntime: ?*c_void,
ManagerEpv: ?*c_void,
ImportContext: ?*c_void,
RpcFlags: u32,
};
pub const RPC_FORWARD_FUNCTION = fn(
InterfaceId: ?*Guid,
InterfaceVersion: ?*RPC_VERSION,
ObjectId: ?*Guid,
Rpcpro: ?*u8,
ppDestEndpoint: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub const RPC_ADDRESS_CHANGE_TYPE = enum(i32) {
NOT_LOADED = 1,
LOADED = 2,
ADDRESS_CHANGE = 3,
};
pub const PROTOCOL_NOT_LOADED = RPC_ADDRESS_CHANGE_TYPE.NOT_LOADED;
pub const PROTOCOL_LOADED = RPC_ADDRESS_CHANGE_TYPE.LOADED;
pub const PROTOCOL_ADDRESS_CHANGE = RPC_ADDRESS_CHANGE_TYPE.ADDRESS_CHANGE;
pub const RPC_ADDRESS_CHANGE_FN = fn(
arg: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub const RPC_DISPATCH_FUNCTION = fn(
Message: ?*RPC_MESSAGE,
) callconv(@import("std").os.windows.WINAPI) void;
pub const RPC_DISPATCH_TABLE = extern struct {
DispatchTableCount: u32,
DispatchTable: ?RPC_DISPATCH_FUNCTION,
Reserved: isize,
};
pub const RPC_PROTSEQ_ENDPOINT = extern struct {
RpcProtocolSequence: ?*u8,
Endpoint: ?*u8,
};
pub const RPC_SERVER_INTERFACE = extern struct {
Length: u32,
InterfaceId: RPC_SYNTAX_IDENTIFIER,
TransferSyntax: RPC_SYNTAX_IDENTIFIER,
DispatchTable: ?*RPC_DISPATCH_TABLE,
RpcProtseqEndpointCount: u32,
RpcProtseqEndpoint: ?*RPC_PROTSEQ_ENDPOINT,
DefaultManagerEpv: ?*c_void,
InterpreterInfo: ?*const c_void,
Flags: u32,
};
pub const RPC_CLIENT_INTERFACE = extern struct {
Length: u32,
InterfaceId: RPC_SYNTAX_IDENTIFIER,
TransferSyntax: RPC_SYNTAX_IDENTIFIER,
DispatchTable: ?*RPC_DISPATCH_TABLE,
RpcProtseqEndpointCount: u32,
RpcProtseqEndpoint: ?*RPC_PROTSEQ_ENDPOINT,
Reserved: usize,
InterpreterInfo: ?*const c_void,
Flags: u32,
};
pub const LRPC_SYSTEM_HANDLE_MARSHAL_DIRECTION = enum(i32) {
Marshal = 0,
Unmarshal = 1,
};
pub const MarshalDirectionMarshal = LRPC_SYSTEM_HANDLE_MARSHAL_DIRECTION.Marshal;
pub const MarshalDirectionUnmarshal = LRPC_SYSTEM_HANDLE_MARSHAL_DIRECTION.Unmarshal;
pub const PRPC_RUNDOWN = fn(
AssociationContext: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub const RPC_SEC_CONTEXT_KEY_INFO = extern struct {
EncryptAlgorithm: u32,
KeySize: u32,
SignatureAlgorithm: u32,
};
pub const RPC_TRANSFER_SYNTAX = extern struct {
Uuid: Guid,
VersMajor: u16,
VersMinor: u16,
};
pub const RPCLT_PDU_FILTER_FUNC = fn(
Buffer: ?*c_void,
BufferLength: u32,
fDatagram: i32,
) callconv(@import("std").os.windows.WINAPI) void;
pub const RPC_SETFILTER_FUNC = fn(
pfnFilter: ?RPCLT_PDU_FILTER_FUNC,
) callconv(@import("std").os.windows.WINAPI) void;
pub const RPC_BLOCKING_FN = fn(
hWnd: ?*c_void,
Context: ?*c_void,
hSyncEvent: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub const RPC_C_OPT_COOKIE_AUTH_DESCRIPTOR = extern struct {
BufferSize: u32,
Buffer: ?PSTR,
};
pub const RDR_CALLOUT_STATE = extern struct {
LastError: RPC_STATUS,
LastEEInfo: ?*c_void,
LastCalledStage: RPC_HTTP_REDIRECTOR_STAGE,
ServerName: ?*u16,
ServerPort: ?*u16,
RemoteUser: ?*u16,
AuthType: ?*u16,
ResourceTypePresent: u8,
SessionIdPresent: u8,
InterfacePresent: u8,
ResourceType: Guid,
SessionId: Guid,
Interface: RPC_SYNTAX_IDENTIFIER,
CertContext: ?*c_void,
};
pub const I_RpcProxyIsValidMachineFn = fn(
Machine: ?*u16,
DotMachine: ?*u16,
PortNumber: u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub const I_RpcProxyGetClientAddressFn = fn(
Context: ?*c_void,
Buffer: ?PSTR,
BufferLength: ?*u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub const I_RpcProxyGetConnectionTimeoutFn = fn(
ConnectionTimeout: ?*u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub const I_RpcPerformCalloutFn = fn(
Context: ?*c_void,
CallOutState: ?*RDR_CALLOUT_STATE,
Stage: RPC_HTTP_REDIRECTOR_STAGE,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub const I_RpcFreeCalloutStateFn = fn(
CallOutState: ?*RDR_CALLOUT_STATE,
) callconv(@import("std").os.windows.WINAPI) void;
pub const I_RpcProxyGetClientSessionAndResourceUUID = fn(
Context: ?*c_void,
SessionIdPresent: ?*i32,
SessionId: ?*Guid,
ResourceIdPresent: ?*i32,
ResourceId: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub const I_RpcProxyFilterIfFn = fn(
Context: ?*c_void,
IfUuid: ?*Guid,
IfMajorVersion: u16,
fAllow: ?*i32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub const RpcProxyPerfCounters = enum(i32) {
CurrentUniqueUser = 1,
BackEndConnectionAttempts = 2,
BackEndConnectionFailed = 3,
RequestsPerSecond = 4,
IncomingConnections = 5,
IncomingBandwidth = 6,
OutgoingBandwidth = 7,
AttemptedLbsDecisions = 8,
FailedLbsDecisions = 9,
AttemptedLbsMessages = 10,
FailedLbsMessages = 11,
LastCounter = 12,
};
pub const RpcCurrentUniqueUser = RpcProxyPerfCounters.CurrentUniqueUser;
pub const RpcBackEndConnectionAttempts = RpcProxyPerfCounters.BackEndConnectionAttempts;
pub const RpcBackEndConnectionFailed = RpcProxyPerfCounters.BackEndConnectionFailed;
pub const RpcRequestsPerSecond = RpcProxyPerfCounters.RequestsPerSecond;
pub const RpcIncomingConnections = RpcProxyPerfCounters.IncomingConnections;
pub const RpcIncomingBandwidth = RpcProxyPerfCounters.IncomingBandwidth;
pub const RpcOutgoingBandwidth = RpcProxyPerfCounters.OutgoingBandwidth;
pub const RpcAttemptedLbsDecisions = RpcProxyPerfCounters.AttemptedLbsDecisions;
pub const RpcFailedLbsDecisions = RpcProxyPerfCounters.FailedLbsDecisions;
pub const RpcAttemptedLbsMessages = RpcProxyPerfCounters.AttemptedLbsMessages;
pub const RpcFailedLbsMessages = RpcProxyPerfCounters.FailedLbsMessages;
pub const RpcLastCounter = RpcProxyPerfCounters.LastCounter;
pub const I_RpcProxyUpdatePerfCounterFn = fn(
Counter: RpcProxyPerfCounters,
ModifyTrend: i32,
Size: u32,
) callconv(@import("std").os.windows.WINAPI) void;
pub const I_RpcProxyUpdatePerfCounterBackendServerFn = fn(
MachineName: ?*u16,
IsConnectEvent: i32,
) callconv(@import("std").os.windows.WINAPI) void;
pub const I_RpcProxyCallbackInterface = extern struct {
IsValidMachineFn: ?I_RpcProxyIsValidMachineFn,
GetClientAddressFn: ?I_RpcProxyGetClientAddressFn,
GetConnectionTimeoutFn: ?I_RpcProxyGetConnectionTimeoutFn,
PerformCalloutFn: ?I_RpcPerformCalloutFn,
FreeCalloutStateFn: ?I_RpcFreeCalloutStateFn,
GetClientSessionAndResourceUUIDFn: ?I_RpcProxyGetClientSessionAndResourceUUID,
ProxyFilterIfFn: ?I_RpcProxyFilterIfFn,
RpcProxyUpdatePerfCounterFn: ?I_RpcProxyUpdatePerfCounterFn,
RpcProxyUpdatePerfCounterBackendServerFn: ?I_RpcProxyUpdatePerfCounterBackendServerFn,
};
pub const RPC_NOTIFICATION_TYPES = enum(i32) {
None = 0,
Event = 1,
Apc = 2,
Ioc = 3,
Hwnd = 4,
Callback = 5,
};
pub const RpcNotificationTypeNone = RPC_NOTIFICATION_TYPES.None;
pub const RpcNotificationTypeEvent = RPC_NOTIFICATION_TYPES.Event;
pub const RpcNotificationTypeApc = RPC_NOTIFICATION_TYPES.Apc;
pub const RpcNotificationTypeIoc = RPC_NOTIFICATION_TYPES.Ioc;
pub const RpcNotificationTypeHwnd = RPC_NOTIFICATION_TYPES.Hwnd;
pub const RpcNotificationTypeCallback = RPC_NOTIFICATION_TYPES.Callback;
pub const RPC_ASYNC_EVENT = enum(i32) {
CallComplete = 0,
SendComplete = 1,
ReceiveComplete = 2,
ClientDisconnect = 3,
ClientCancel = 4,
};
pub const RpcCallComplete = RPC_ASYNC_EVENT.CallComplete;
pub const RpcSendComplete = RPC_ASYNC_EVENT.SendComplete;
pub const RpcReceiveComplete = RPC_ASYNC_EVENT.ReceiveComplete;
pub const RpcClientDisconnect = RPC_ASYNC_EVENT.ClientDisconnect;
pub const RpcClientCancel = RPC_ASYNC_EVENT.ClientCancel;
pub const PFN_RPCNOTIFICATION_ROUTINE = fn(
pAsync: ?*RPC_ASYNC_STATE,
Context: ?*c_void,
Event: RPC_ASYNC_EVENT,
) callconv(@import("std").os.windows.WINAPI) void;
pub const RPC_ASYNC_NOTIFICATION_INFO = extern union {
APC: extern struct {
NotificationRoutine: ?PFN_RPCNOTIFICATION_ROUTINE,
hThread: ?HANDLE,
},
IOC: extern struct {
hIOPort: ?HANDLE,
dwNumberOfBytesTransferred: u32,
dwCompletionKey: usize,
lpOverlapped: ?*OVERLAPPED,
},
IntPtr: extern struct {
hWnd: ?HWND,
Msg: u32,
},
hEvent: ?HANDLE,
NotificationRoutine: ?PFN_RPCNOTIFICATION_ROUTINE,
};
pub const RPC_ASYNC_STATE = extern struct {
Size: u32,
Signature: u32,
Lock: i32,
Flags: u32,
StubInfo: ?*c_void,
UserInfo: ?*c_void,
RuntimeInfo: ?*c_void,
Event: RPC_ASYNC_EVENT,
NotificationType: RPC_NOTIFICATION_TYPES,
u: RPC_ASYNC_NOTIFICATION_INFO,
Reserved: [4]isize,
};
pub const ExtendedErrorParamTypes = enum(i32) {
AnsiString = 1,
UnicodeString = 2,
LongVal = 3,
ShortVal = 4,
PointerVal = 5,
None = 6,
Binary = 7,
};
pub const eeptAnsiString = ExtendedErrorParamTypes.AnsiString;
pub const eeptUnicodeString = ExtendedErrorParamTypes.UnicodeString;
pub const eeptLongVal = ExtendedErrorParamTypes.LongVal;
pub const eeptShortVal = ExtendedErrorParamTypes.ShortVal;
pub const eeptPointerVal = ExtendedErrorParamTypes.PointerVal;
pub const eeptNone = ExtendedErrorParamTypes.None;
pub const eeptBinary = ExtendedErrorParamTypes.Binary;
pub const BinaryParam = extern struct {
Buffer: ?*c_void,
Size: i16,
};
pub const RPC_EE_INFO_PARAM = extern struct {
ParameterType: ExtendedErrorParamTypes,
u: extern union {
AnsiString: ?PSTR,
UnicodeString: ?PWSTR,
LVal: i32,
SVal: i16,
PVal: u64,
BVal: BinaryParam,
},
};
pub const RPC_EXTENDED_ERROR_INFO = extern struct {
Version: u32,
ComputerName: ?PWSTR,
ProcessID: u32,
u: extern union {
SystemTime: SYSTEMTIME,
FileTime: FILETIME,
},
GeneratingComponent: u32,
Status: u32,
DetectionLocation: u16,
Flags: u16,
NumberOfParameters: i32,
Parameters: [4]RPC_EE_INFO_PARAM,
};
pub const RPC_ERROR_ENUM_HANDLE = extern struct {
Signature: u32,
CurrentPos: ?*c_void,
Head: ?*c_void,
};
pub const RpcLocalAddressFormat = enum(i32) {
nvalid = 0,
Pv4 = 1,
Pv6 = 2,
};
pub const rlafInvalid = RpcLocalAddressFormat.nvalid;
pub const rlafIPv4 = RpcLocalAddressFormat.Pv4;
pub const rlafIPv6 = RpcLocalAddressFormat.Pv6;
pub const RPC_CALL_LOCAL_ADDRESS_V1 = extern struct {
Version: u32,
Buffer: ?*c_void,
BufferSize: u32,
AddressFormat: RpcLocalAddressFormat,
};
pub const RPC_CALL_ATTRIBUTES_V1_W = extern struct {
Version: u32,
Flags: u32,
ServerPrincipalNameBufferLength: u32,
ServerPrincipalName: ?*u16,
ClientPrincipalNameBufferLength: u32,
ClientPrincipalName: ?*u16,
AuthenticationLevel: u32,
AuthenticationService: u32,
NullSession: BOOL,
};
pub const RPC_CALL_ATTRIBUTES_V1_A = extern struct {
Version: u32,
Flags: u32,
ServerPrincipalNameBufferLength: u32,
ServerPrincipalName: ?*u8,
ClientPrincipalNameBufferLength: u32,
ClientPrincipalName: ?*u8,
AuthenticationLevel: u32,
AuthenticationService: u32,
NullSession: BOOL,
};
pub const RpcCallType = enum(i32) {
Invalid = 0,
Normal = 1,
Training = 2,
Guaranteed = 3,
};
pub const rctInvalid = RpcCallType.Invalid;
pub const rctNormal = RpcCallType.Normal;
pub const rctTraining = RpcCallType.Training;
pub const rctGuaranteed = RpcCallType.Guaranteed;
pub const RpcCallClientLocality = enum(i32) {
Invalid = 0,
Local = 1,
Remote = 2,
ClientUnknownLocality = 3,
};
pub const rcclInvalid = RpcCallClientLocality.Invalid;
pub const rcclLocal = RpcCallClientLocality.Local;
pub const rcclRemote = RpcCallClientLocality.Remote;
pub const rcclClientUnknownLocality = RpcCallClientLocality.ClientUnknownLocality;
pub const RPC_CALL_ATTRIBUTES_V2_W = extern struct {
Version: u32,
Flags: u32,
ServerPrincipalNameBufferLength: u32,
ServerPrincipalName: ?*u16,
ClientPrincipalNameBufferLength: u32,
ClientPrincipalName: ?*u16,
AuthenticationLevel: u32,
AuthenticationService: u32,
NullSession: BOOL,
KernelModeCaller: BOOL,
ProtocolSequence: u32,
IsClientLocal: RpcCallClientLocality,
ClientPID: ?HANDLE,
CallStatus: u32,
CallType: RpcCallType,
CallLocalAddress: ?*RPC_CALL_LOCAL_ADDRESS_V1,
OpNum: u16,
InterfaceUuid: Guid,
};
pub const RPC_CALL_ATTRIBUTES_V2_A = extern struct {
Version: u32,
Flags: u32,
ServerPrincipalNameBufferLength: u32,
ServerPrincipalName: ?*u8,
ClientPrincipalNameBufferLength: u32,
ClientPrincipalName: ?*u8,
AuthenticationLevel: u32,
AuthenticationService: u32,
NullSession: BOOL,
KernelModeCaller: BOOL,
ProtocolSequence: u32,
IsClientLocal: u32,
ClientPID: ?HANDLE,
CallStatus: u32,
CallType: RpcCallType,
CallLocalAddress: ?*RPC_CALL_LOCAL_ADDRESS_V1,
OpNum: u16,
InterfaceUuid: Guid,
};
pub const RPC_CALL_ATTRIBUTES_V3_W = extern struct {
Version: u32,
Flags: u32,
ServerPrincipalNameBufferLength: u32,
ServerPrincipalName: ?*u16,
ClientPrincipalNameBufferLength: u32,
ClientPrincipalName: ?*u16,
AuthenticationLevel: u32,
AuthenticationService: u32,
NullSession: BOOL,
KernelModeCaller: BOOL,
ProtocolSequence: u32,
IsClientLocal: RpcCallClientLocality,
ClientPID: ?HANDLE,
CallStatus: u32,
CallType: RpcCallType,
CallLocalAddress: ?*RPC_CALL_LOCAL_ADDRESS_V1,
OpNum: u16,
InterfaceUuid: Guid,
ClientIdentifierBufferLength: u32,
ClientIdentifier: ?*u8,
};
pub const RPC_CALL_ATTRIBUTES_V3_A = extern struct {
Version: u32,
Flags: u32,
ServerPrincipalNameBufferLength: u32,
ServerPrincipalName: ?*u8,
ClientPrincipalNameBufferLength: u32,
ClientPrincipalName: ?*u8,
AuthenticationLevel: u32,
AuthenticationService: u32,
NullSession: BOOL,
KernelModeCaller: BOOL,
ProtocolSequence: u32,
IsClientLocal: u32,
ClientPID: ?HANDLE,
CallStatus: u32,
CallType: RpcCallType,
CallLocalAddress: ?*RPC_CALL_LOCAL_ADDRESS_V1,
OpNum: u16,
InterfaceUuid: Guid,
ClientIdentifierBufferLength: u32,
ClientIdentifier: ?*u8,
};
pub const RPC_NOTIFICATIONS = enum(i32) {
allNone = 0,
lientDisconnect = 1,
allCancel = 2,
};
pub const RpcNotificationCallNone = RPC_NOTIFICATIONS.allNone;
pub const RpcNotificationClientDisconnect = RPC_NOTIFICATIONS.lientDisconnect;
pub const RpcNotificationCallCancel = RPC_NOTIFICATIONS.allCancel;
pub const __AnonymousRecord_rpcndr_L275_C9 = extern struct {
pad: [2]?*c_void,
userContext: ?*c_void,
};
pub const NDR_RUNDOWN = fn(
context: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub const NDR_NOTIFY_ROUTINE = fn(
) callconv(@import("std").os.windows.WINAPI) void;
pub const NDR_NOTIFY2_ROUTINE = fn(
flag: u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub const SCONTEXT_QUEUE = extern struct {
NumberOfObjects: u32,
ArrayOfObjects: ?*?*NDR_SCONTEXT_1,
};
pub const EXPR_EVAL = fn(
param0: ?*MIDL_STUB_MESSAGE,
) callconv(@import("std").os.windows.WINAPI) void;
pub const ARRAY_INFO = extern struct {
Dimension: i32,
BufferConformanceMark: ?*u32,
BufferVarianceMark: ?*u32,
MaxCountArray: ?*u32,
OffsetArray: ?*u32,
ActualCountArray: ?*u32,
};
pub const MIDL_STUB_MESSAGE = extern struct {
RpcMsg: ?*RPC_MESSAGE,
Buffer: ?*u8,
BufferStart: ?*u8,
BufferEnd: ?*u8,
BufferMark: ?*u8,
BufferLength: u32,
MemorySize: u32,
Memory: ?*u8,
IsClient: u8,
Pad: u8,
uFlags2: u16,
ReuseBuffer: i32,
pAllocAllNodesContext: ?*NDR_ALLOC_ALL_NODES_CONTEXT,
pPointerQueueState: ?*NDR_POINTER_QUEUE_STATE,
IgnoreEmbeddedPointers: i32,
PointerBufferMark: ?*u8,
CorrDespIncrement: u8,
uFlags: u8,
UniquePtrCount: u16,
MaxCount: usize,
Offset: u32,
ActualCount: u32,
pfnAllocate: isize,
pfnFree: isize,
StackTop: ?*u8,
pPresentedType: ?*u8,
pTransmitType: ?*u8,
SavedHandle: ?*c_void,
StubDesc: ?*const MIDL_STUB_DESC,
FullPtrXlatTables: ?*FULL_PTR_XLAT_TABLES,
FullPtrRefId: u32,
PointerLength: u32,
_bitfield: i32,
dwDestContext: u32,
pvDestContext: ?*c_void,
SavedContextHandles: ?*?*NDR_SCONTEXT_1,
ParamNumber: i32,
pRpcChannelBuffer: ?*IRpcChannelBuffer,
pArrayInfo: ?*ARRAY_INFO,
SizePtrCountArray: ?*u32,
SizePtrOffsetArray: ?*u32,
SizePtrLengthArray: ?*u32,
pArgQueue: ?*c_void,
dwStubPhase: u32,
LowStackMark: ?*c_void,
pAsyncMsg: ?*_NDR_ASYNC_MESSAGE,
pCorrInfo: ?*_NDR_CORRELATION_INFO,
pCorrMemory: ?*u8,
pMemoryList: ?*c_void,
pCSInfo: isize,
ConformanceMark: ?*u8,
VarianceMark: ?*u8,
Unused: isize,
pContext: ?*_NDR_PROC_CONTEXT,
ContextHandleHash: ?*c_void,
pUserMarshalList: ?*c_void,
Reserved51_3: isize,
Reserved51_4: isize,
Reserved51_5: isize,
};
pub const GENERIC_BINDING_ROUTINE = fn(
param0: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) ?*c_void;
pub const GENERIC_UNBIND_ROUTINE = fn(
param0: ?*c_void,
param1: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub const GENERIC_BINDING_ROUTINE_PAIR = extern struct {
pfnBind: ?GENERIC_BINDING_ROUTINE,
pfnUnbind: ?GENERIC_UNBIND_ROUTINE,
};
pub const GENERIC_BINDING_INFO = extern struct {
pObj: ?*c_void,
Size: u32,
pfnBind: ?GENERIC_BINDING_ROUTINE,
pfnUnbind: ?GENERIC_UNBIND_ROUTINE,
};
pub const XMIT_HELPER_ROUTINE = fn(
param0: ?*MIDL_STUB_MESSAGE,
) callconv(@import("std").os.windows.WINAPI) void;
pub const XMIT_ROUTINE_QUINTUPLE = extern struct {
pfnTranslateToXmit: ?XMIT_HELPER_ROUTINE,
pfnTranslateFromXmit: ?XMIT_HELPER_ROUTINE,
pfnFreeXmit: ?XMIT_HELPER_ROUTINE,
pfnFreeInst: ?XMIT_HELPER_ROUTINE,
};
pub const USER_MARSHAL_SIZING_ROUTINE = fn(
param0: ?*u32,
param1: u32,
param2: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const USER_MARSHAL_MARSHALLING_ROUTINE = fn(
param0: ?*u32,
param1: ?*u8,
param2: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub const USER_MARSHAL_UNMARSHALLING_ROUTINE = fn(
param0: ?*u32,
param1: ?*u8,
param2: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub const USER_MARSHAL_FREEING_ROUTINE = fn(
param0: ?*u32,
param1: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub const USER_MARSHAL_ROUTINE_QUADRUPLE = extern struct {
pfnBufferSize: ?USER_MARSHAL_SIZING_ROUTINE,
pfnMarshall: ?USER_MARSHAL_MARSHALLING_ROUTINE,
pfnUnmarshall: ?USER_MARSHAL_UNMARSHALLING_ROUTINE,
pfnFree: ?USER_MARSHAL_FREEING_ROUTINE,
};
pub const USER_MARSHAL_CB_TYPE = enum(i32) {
BUFFER_SIZE = 0,
MARSHALL = 1,
UNMARSHALL = 2,
FREE = 3,
};
pub const USER_MARSHAL_CB_BUFFER_SIZE = USER_MARSHAL_CB_TYPE.BUFFER_SIZE;
pub const USER_MARSHAL_CB_MARSHALL = USER_MARSHAL_CB_TYPE.MARSHALL;
pub const USER_MARSHAL_CB_UNMARSHALL = USER_MARSHAL_CB_TYPE.UNMARSHALL;
pub const USER_MARSHAL_CB_FREE = USER_MARSHAL_CB_TYPE.FREE;
pub const USER_MARSHAL_CB = extern struct {
Flags: u32,
pStubMsg: ?*MIDL_STUB_MESSAGE,
pReserve: ?*u8,
Signature: u32,
CBType: USER_MARSHAL_CB_TYPE,
pFormat: ?*u8,
pTypeFormat: ?*u8,
};
pub const MALLOC_FREE_STRUCT = extern struct {
pfnAllocate: isize,
pfnFree: isize,
};
pub const COMM_FAULT_OFFSETS = extern struct {
CommOffset: i16,
FaultOffset: i16,
};
pub const IDL_CS_CONVERT = enum(i32) {
NO_CONVERT = 0,
IN_PLACE_CONVERT = 1,
NEW_BUFFER_CONVERT = 2,
};
pub const IDL_CS_NO_CONVERT = IDL_CS_CONVERT.NO_CONVERT;
pub const IDL_CS_IN_PLACE_CONVERT = IDL_CS_CONVERT.IN_PLACE_CONVERT;
pub const IDL_CS_NEW_BUFFER_CONVERT = IDL_CS_CONVERT.NEW_BUFFER_CONVERT;
pub const CS_TYPE_NET_SIZE_ROUTINE = fn(
hBinding: ?*c_void,
ulNetworkCodeSet: u32,
ulLocalBufferSize: u32,
conversionType: ?*IDL_CS_CONVERT,
pulNetworkBufferSize: ?*u32,
pStatus: ?*u32,
) callconv(@import("std").os.windows.WINAPI) void;
pub const CS_TYPE_LOCAL_SIZE_ROUTINE = fn(
hBinding: ?*c_void,
ulNetworkCodeSet: u32,
ulNetworkBufferSize: u32,
conversionType: ?*IDL_CS_CONVERT,
pulLocalBufferSize: ?*u32,
pStatus: ?*u32,
) callconv(@import("std").os.windows.WINAPI) void;
pub const CS_TYPE_TO_NETCS_ROUTINE = fn(
hBinding: ?*c_void,
ulNetworkCodeSet: u32,
pLocalData: ?*c_void,
ulLocalDataLength: u32,
pNetworkData: ?*u8,
pulNetworkDataLength: ?*u32,
pStatus: ?*u32,
) callconv(@import("std").os.windows.WINAPI) void;
pub const CS_TYPE_FROM_NETCS_ROUTINE = fn(
hBinding: ?*c_void,
ulNetworkCodeSet: u32,
pNetworkData: ?*u8,
ulNetworkDataLength: u32,
ulLocalBufferSize: u32,
pLocalData: ?*c_void,
pulLocalDataLength: ?*u32,
pStatus: ?*u32,
) callconv(@import("std").os.windows.WINAPI) void;
pub const CS_TAG_GETTING_ROUTINE = fn(
hBinding: ?*c_void,
fServerSide: i32,
pulSendingTag: ?*u32,
pulDesiredReceivingTag: ?*u32,
pulReceivingTag: ?*u32,
pStatus: ?*u32,
) callconv(@import("std").os.windows.WINAPI) void;
pub const NDR_CS_SIZE_CONVERT_ROUTINES = extern struct {
pfnNetSize: ?CS_TYPE_NET_SIZE_ROUTINE,
pfnToNetCs: ?CS_TYPE_TO_NETCS_ROUTINE,
pfnLocalSize: ?CS_TYPE_LOCAL_SIZE_ROUTINE,
pfnFromNetCs: ?CS_TYPE_FROM_NETCS_ROUTINE,
};
pub const NDR_CS_ROUTINES = extern struct {
pSizeConvertRoutines: ?*NDR_CS_SIZE_CONVERT_ROUTINES,
pTagGettingRoutines: ?*?CS_TAG_GETTING_ROUTINE,
};
pub const NDR_EXPR_DESC = extern struct {
pOffset: ?*const u16,
pFormatExpr: ?*u8,
};
pub const MIDL_STUB_DESC = extern struct {
RpcInterfaceInformation: ?*c_void,
pfnAllocate: isize,
pfnFree: isize,
IMPLICIT_HANDLE_INFO: extern union {
pAutoHandle: ?*?*c_void,
pPrimitiveHandle: ?*?*c_void,
pGenericBindingInfo: ?*GENERIC_BINDING_INFO,
},
apfnNdrRundownRoutines: ?*const ?NDR_RUNDOWN,
aGenericBindingRoutinePairs: ?*const GENERIC_BINDING_ROUTINE_PAIR,
apfnExprEval: ?*const ?EXPR_EVAL,
aXmitQuintuple: ?*const XMIT_ROUTINE_QUINTUPLE,
pFormatTypes: ?*const u8,
fCheckBounds: i32,
Version: u32,
pMallocFreeStruct: ?*MALLOC_FREE_STRUCT,
MIDLVersion: i32,
CommFaultOffsets: ?*const COMM_FAULT_OFFSETS,
aUserMarshalQuadruple: ?*const USER_MARSHAL_ROUTINE_QUADRUPLE,
NotifyRoutineTable: ?*const ?NDR_NOTIFY_ROUTINE,
mFlags: usize,
CsRoutineTables: ?*const NDR_CS_ROUTINES,
ProxyServerInfo: ?*c_void,
pExprInfo: ?*const NDR_EXPR_DESC,
};
pub const MIDL_FORMAT_STRING = extern struct {
Pad: i16,
Format: [1]u8,
};
pub const STUB_THUNK = fn(
param0: ?*MIDL_STUB_MESSAGE,
) callconv(@import("std").os.windows.WINAPI) void;
pub const SERVER_ROUTINE = fn(
) callconv(@import("std").os.windows.WINAPI) i32;
pub const MIDL_METHOD_PROPERTY = extern struct {
Id: u32,
Value: usize,
};
pub const MIDL_METHOD_PROPERTY_MAP = extern struct {
Count: u32,
Properties: ?*const MIDL_METHOD_PROPERTY,
};
pub const MIDL_INTERFACE_METHOD_PROPERTIES = extern struct {
MethodCount: u16,
MethodProperties: ?*const ?*MIDL_METHOD_PROPERTY_MAP,
};
pub const MIDL_SERVER_INFO = extern struct {
pStubDesc: ?*MIDL_STUB_DESC,
DispatchTable: ?*const ?SERVER_ROUTINE,
ProcString: ?*u8,
FmtStringOffset: ?*const u16,
ThunkTable: ?*const ?STUB_THUNK,
pTransferSyntax: ?*RPC_SYNTAX_IDENTIFIER,
nCount: usize,
pSyntaxInfo: ?*MIDL_SYNTAX_INFO,
};
pub const MIDL_STUBLESS_PROXY_INFO = extern struct {
pStubDesc: ?*MIDL_STUB_DESC,
ProcFormatString: ?*u8,
FormatStringOffset: ?*const u16,
pTransferSyntax: ?*RPC_SYNTAX_IDENTIFIER,
nCount: usize,
pSyntaxInfo: ?*MIDL_SYNTAX_INFO,
};
pub const MIDL_SYNTAX_INFO = extern struct {
TransferSyntax: RPC_SYNTAX_IDENTIFIER,
DispatchTable: ?*RPC_DISPATCH_TABLE,
ProcString: ?*u8,
FmtStringOffset: ?*const u16,
TypeString: ?*u8,
aUserMarshalQuadruple: ?*const c_void,
pMethodProperties: ?*const MIDL_INTERFACE_METHOD_PROPERTIES,
pReserved2: usize,
};
pub const CLIENT_CALL_RETURN = extern union {
Pointer: ?*c_void,
Simple: isize,
};
pub const XLAT_SIDE = enum(i32) {
SERVER = 1,
CLIENT = 2,
};
pub const XLAT_SERVER = XLAT_SIDE.SERVER;
pub const XLAT_CLIENT = XLAT_SIDE.CLIENT;
pub const FULL_PTR_XLAT_TABLES = extern struct {
RefIdToPointer: ?*c_void,
PointerToRefId: ?*c_void,
NextRefId: u32,
XlatSide: XLAT_SIDE,
};
pub const system_handle_t = enum(i32) {
FILE = 0,
SEMAPHORE = 1,
EVENT = 2,
MUTEX = 3,
PROCESS = 4,
TOKEN = 5,
SECTION = 6,
REG_KEY = 7,
THREAD = 8,
COMPOSITION_OBJECT = 9,
SOCKET = 10,
JOB = 11,
PIPE = 12,
// MAX = 12, this enum value conflicts with PIPE
INVALID = 255,
};
pub const SYSTEM_HANDLE_FILE = system_handle_t.FILE;
pub const SYSTEM_HANDLE_SEMAPHORE = system_handle_t.SEMAPHORE;
pub const SYSTEM_HANDLE_EVENT = system_handle_t.EVENT;
pub const SYSTEM_HANDLE_MUTEX = system_handle_t.MUTEX;
pub const SYSTEM_HANDLE_PROCESS = system_handle_t.PROCESS;
pub const SYSTEM_HANDLE_TOKEN = system_handle_t.TOKEN;
pub const SYSTEM_HANDLE_SECTION = system_handle_t.SECTION;
pub const SYSTEM_HANDLE_REG_KEY = system_handle_t.REG_KEY;
pub const SYSTEM_HANDLE_THREAD = system_handle_t.THREAD;
pub const SYSTEM_HANDLE_COMPOSITION_OBJECT = system_handle_t.COMPOSITION_OBJECT;
pub const SYSTEM_HANDLE_SOCKET = system_handle_t.SOCKET;
pub const SYSTEM_HANDLE_JOB = system_handle_t.JOB;
pub const SYSTEM_HANDLE_PIPE = system_handle_t.PIPE;
pub const SYSTEM_HANDLE_MAX = system_handle_t.PIPE;
pub const SYSTEM_HANDLE_INVALID = system_handle_t.INVALID;
pub const MIDL_INTERCEPTION_INFO = extern struct {
Version: u32,
ProcString: ?*u8,
ProcFormatOffsetTable: ?*const u16,
ProcCount: u32,
TypeString: ?*u8,
};
pub const MIDL_WINRT_TYPE_SERIALIZATION_INFO = extern struct {
Version: u32,
TypeFormatString: ?*u8,
FormatStringSize: u16,
TypeOffset: u16,
StubDesc: ?*MIDL_STUB_DESC,
};
pub const STUB_PHASE = enum(i32) {
UNMARSHAL = 0,
CALL_SERVER = 1,
MARSHAL = 2,
CALL_SERVER_NO_HRESULT = 3,
};
pub const STUB_UNMARSHAL = STUB_PHASE.UNMARSHAL;
pub const STUB_CALL_SERVER = STUB_PHASE.CALL_SERVER;
pub const STUB_MARSHAL = STUB_PHASE.MARSHAL;
pub const STUB_CALL_SERVER_NO_HRESULT = STUB_PHASE.CALL_SERVER_NO_HRESULT;
pub const PROXY_PHASE = enum(i32) {
CALCSIZE = 0,
GETBUFFER = 1,
MARSHAL = 2,
SENDRECEIVE = 3,
UNMARSHAL = 4,
};
pub const PROXY_CALCSIZE = PROXY_PHASE.CALCSIZE;
pub const PROXY_GETBUFFER = PROXY_PHASE.GETBUFFER;
pub const PROXY_MARSHAL = PROXY_PHASE.MARSHAL;
pub const PROXY_SENDRECEIVE = PROXY_PHASE.SENDRECEIVE;
pub const PROXY_UNMARSHAL = PROXY_PHASE.UNMARSHAL;
pub const RPC_CLIENT_ALLOC = fn(
Size: usize,
) callconv(@import("std").os.windows.WINAPI) ?*c_void;
pub const RPC_CLIENT_FREE = fn(
Ptr: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub const NDR_USER_MARSHAL_INFO_LEVEL1 = extern struct {
Buffer: ?*c_void,
BufferSize: u32,
pfnAllocate: isize,
pfnFree: isize,
pRpcChannelBuffer: ?*IRpcChannelBuffer,
Reserved: [5]usize,
};
pub const NDR_USER_MARSHAL_INFO = extern struct {
InformationLevel: u32,
Anonymous: extern union {
Level1: NDR_USER_MARSHAL_INFO_LEVEL1,
},
};
pub const MIDL_ES_CODE = enum(i32) {
ENCODE = 0,
DECODE = 1,
ENCODE_NDR64 = 2,
};
pub const MES_ENCODE = MIDL_ES_CODE.ENCODE;
pub const MES_DECODE = MIDL_ES_CODE.DECODE;
pub const MES_ENCODE_NDR64 = MIDL_ES_CODE.ENCODE_NDR64;
pub const MIDL_ES_HANDLE_STYLE = enum(i32) {
INCREMENTAL_HANDLE = 0,
FIXED_BUFFER_HANDLE = 1,
DYNAMIC_BUFFER_HANDLE = 2,
};
pub const MES_INCREMENTAL_HANDLE = MIDL_ES_HANDLE_STYLE.INCREMENTAL_HANDLE;
pub const MES_FIXED_BUFFER_HANDLE = MIDL_ES_HANDLE_STYLE.FIXED_BUFFER_HANDLE;
pub const MES_DYNAMIC_BUFFER_HANDLE = MIDL_ES_HANDLE_STYLE.DYNAMIC_BUFFER_HANDLE;
pub const MIDL_ES_ALLOC = fn(
state: ?*c_void,
pbuffer: ?*?*i8,
psize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) void;
pub const MIDL_ES_WRITE = fn(
state: ?*c_void,
buffer: ?PSTR,
size: u32,
) callconv(@import("std").os.windows.WINAPI) void;
pub const MIDL_ES_READ = fn(
state: ?*c_void,
pbuffer: ?*?*i8,
psize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) void;
pub const MIDL_TYPE_PICKLING_INFO = extern struct {
Version: u32,
Flags: u32,
Reserved: [3]usize,
};
//--------------------------------------------------------------------------------
// Section: Functions (503)
//--------------------------------------------------------------------------------
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn IUnknown_QueryInterface_Proxy(
This: ?*IUnknown,
riid: ?*const Guid,
ppvObject: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn IUnknown_AddRef_Proxy(
This: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn IUnknown_Release_Proxy(
This: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcBindingCopy(
SourceBinding: ?*c_void,
DestinationBinding: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcBindingFree(
Binding: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcBindingSetOption(
hBinding: ?*c_void,
option: u32,
optionValue: usize,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcBindingInqOption(
hBinding: ?*c_void,
option: u32,
pOptionValue: ?*usize,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcBindingFromStringBindingA(
StringBinding: ?*u8,
Binding: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcBindingFromStringBindingW(
StringBinding: ?*u16,
Binding: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn RpcSsGetContextBinding(
ContextHandle: ?*c_void,
Binding: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcBindingInqObject(
Binding: ?*c_void,
ObjectUuid: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcBindingReset(
Binding: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcBindingSetObject(
Binding: ?*c_void,
ObjectUuid: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcMgmtInqDefaultProtectLevel(
AuthnSvc: u32,
AuthnLevel: ?*u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcBindingToStringBindingA(
Binding: ?*c_void,
StringBinding: ?*?*u8,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcBindingToStringBindingW(
Binding: ?*c_void,
StringBinding: ?*?*u16,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcBindingVectorFree(
BindingVector: ?*?*RPC_BINDING_VECTOR,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcStringBindingComposeA(
ObjUuid: ?*u8,
ProtSeq: ?*u8,
NetworkAddr: ?*u8,
Endpoint: ?*u8,
Options: ?*u8,
StringBinding: ?*?*u8,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcStringBindingComposeW(
ObjUuid: ?*u16,
ProtSeq: ?*u16,
NetworkAddr: ?*u16,
Endpoint: ?*u16,
Options: ?*u16,
StringBinding: ?*?*u16,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcStringBindingParseA(
StringBinding: ?*u8,
ObjUuid: ?*?*u8,
Protseq: ?*?*u8,
NetworkAddr: ?*?*u8,
Endpoint: ?*?*u8,
NetworkOptions: ?*?*u8,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcStringBindingParseW(
StringBinding: ?*u16,
ObjUuid: ?*?*u16,
Protseq: ?*?*u16,
NetworkAddr: ?*?*u16,
Endpoint: ?*?*u16,
NetworkOptions: ?*?*u16,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcStringFreeA(
String: ?*?*u8,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcStringFreeW(
String: ?*?*u16,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcIfInqId(
RpcIfHandle: ?*c_void,
RpcIfId: ?*RPC_IF_ID,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcNetworkIsProtseqValidA(
Protseq: ?*u8,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcNetworkIsProtseqValidW(
Protseq: ?*u16,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcMgmtInqComTimeout(
Binding: ?*c_void,
Timeout: ?*u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcMgmtSetComTimeout(
Binding: ?*c_void,
Timeout: u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcMgmtSetCancelTimeout(
Timeout: i32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcNetworkInqProtseqsA(
ProtseqVector: ?*?*RPC_PROTSEQ_VECTORA,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcNetworkInqProtseqsW(
ProtseqVector: ?*?*RPC_PROTSEQ_VECTORW,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcObjectInqType(
ObjUuid: ?*Guid,
TypeUuid: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcObjectSetInqFn(
InquiryFn: ?RPC_OBJECT_INQ_FN,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcObjectSetType(
ObjUuid: ?*Guid,
TypeUuid: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcProtseqVectorFreeA(
ProtseqVector: ?*?*RPC_PROTSEQ_VECTORA,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcProtseqVectorFreeW(
ProtseqVector: ?*?*RPC_PROTSEQ_VECTORW,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcServerInqBindings(
BindingVector: ?*?*RPC_BINDING_VECTOR,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn RpcServerInqBindingsEx(
SecurityDescriptor: ?*c_void,
BindingVector: ?*?*RPC_BINDING_VECTOR,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcServerInqIf(
IfSpec: ?*c_void,
MgrTypeUuid: ?*Guid,
MgrEpv: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcServerListen(
MinimumCallThreads: u32,
MaxCalls: u32,
DontWait: u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcServerRegisterIf(
IfSpec: ?*c_void,
MgrTypeUuid: ?*Guid,
MgrEpv: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "RPCRT4" fn RpcServerRegisterIfEx(
IfSpec: ?*c_void,
MgrTypeUuid: ?*Guid,
MgrEpv: ?*c_void,
Flags: u32,
MaxCalls: u32,
IfCallback: ?RPC_IF_CALLBACK_FN,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcServerRegisterIf2(
IfSpec: ?*c_void,
MgrTypeUuid: ?*Guid,
MgrEpv: ?*c_void,
Flags: u32,
MaxCalls: u32,
MaxRpcSize: u32,
IfCallbackFn: ?RPC_IF_CALLBACK_FN,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows8.0'
pub extern "RPCRT4" fn RpcServerRegisterIf3(
IfSpec: ?*c_void,
MgrTypeUuid: ?*Guid,
MgrEpv: ?*c_void,
Flags: u32,
MaxCalls: u32,
MaxRpcSize: u32,
IfCallback: ?RPC_IF_CALLBACK_FN,
SecurityDescriptor: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcServerUnregisterIf(
IfSpec: ?*c_void,
MgrTypeUuid: ?*Guid,
WaitForCallsToComplete: u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "RPCRT4" fn RpcServerUnregisterIfEx(
IfSpec: ?*c_void,
MgrTypeUuid: ?*Guid,
RundownContextHandles: i32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcServerUseAllProtseqs(
MaxCalls: u32,
SecurityDescriptor: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcServerUseAllProtseqsEx(
MaxCalls: u32,
SecurityDescriptor: ?*c_void,
Policy: ?*RPC_POLICY,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcServerUseAllProtseqsIf(
MaxCalls: u32,
IfSpec: ?*c_void,
SecurityDescriptor: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "RPCRT4" fn RpcServerUseAllProtseqsIfEx(
MaxCalls: u32,
IfSpec: ?*c_void,
SecurityDescriptor: ?*c_void,
Policy: ?*RPC_POLICY,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcServerUseProtseqA(
Protseq: ?*u8,
MaxCalls: u32,
SecurityDescriptor: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcServerUseProtseqExA(
Protseq: ?*u8,
MaxCalls: u32,
SecurityDescriptor: ?*c_void,
Policy: ?*RPC_POLICY,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcServerUseProtseqW(
Protseq: ?*u16,
MaxCalls: u32,
SecurityDescriptor: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcServerUseProtseqExW(
Protseq: ?*u16,
MaxCalls: u32,
SecurityDescriptor: ?*c_void,
Policy: ?*RPC_POLICY,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcServerUseProtseqEpA(
Protseq: ?*u8,
MaxCalls: u32,
Endpoint: ?*u8,
SecurityDescriptor: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcServerUseProtseqEpExA(
Protseq: ?*u8,
MaxCalls: u32,
Endpoint: ?*u8,
SecurityDescriptor: ?*c_void,
Policy: ?*RPC_POLICY,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcServerUseProtseqEpW(
Protseq: ?*u16,
MaxCalls: u32,
Endpoint: ?*u16,
SecurityDescriptor: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcServerUseProtseqEpExW(
Protseq: ?*u16,
MaxCalls: u32,
Endpoint: ?*u16,
SecurityDescriptor: ?*c_void,
Policy: ?*RPC_POLICY,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcServerUseProtseqIfA(
Protseq: ?*u8,
MaxCalls: u32,
IfSpec: ?*c_void,
SecurityDescriptor: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "RPCRT4" fn RpcServerUseProtseqIfExA(
Protseq: ?*u8,
MaxCalls: u32,
IfSpec: ?*c_void,
SecurityDescriptor: ?*c_void,
Policy: ?*RPC_POLICY,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcServerUseProtseqIfW(
Protseq: ?*u16,
MaxCalls: u32,
IfSpec: ?*c_void,
SecurityDescriptor: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "RPCRT4" fn RpcServerUseProtseqIfExW(
Protseq: ?*u16,
MaxCalls: u32,
IfSpec: ?*c_void,
SecurityDescriptor: ?*c_void,
Policy: ?*RPC_POLICY,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn RpcServerYield(
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcMgmtStatsVectorFree(
StatsVector: ?*?*RPC_STATS_VECTOR,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcMgmtInqStats(
Binding: ?*c_void,
Statistics: ?*?*RPC_STATS_VECTOR,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcMgmtIsServerListening(
Binding: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcMgmtStopServerListening(
Binding: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcMgmtWaitServerListen(
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcMgmtSetServerStackSize(
ThreadStackSize: u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcSsDontSerializeContext(
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcMgmtEnableIdleCleanup(
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcMgmtInqIfIds(
Binding: ?*c_void,
IfIdVector: ?*?*RPC_IF_ID_VECTOR,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcIfIdVectorFree(
IfIdVector: ?*?*RPC_IF_ID_VECTOR,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcMgmtInqServerPrincNameA(
Binding: ?*c_void,
AuthnSvc: u32,
ServerPrincName: ?*?*u8,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcMgmtInqServerPrincNameW(
Binding: ?*c_void,
AuthnSvc: u32,
ServerPrincName: ?*?*u16,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcServerInqDefaultPrincNameA(
AuthnSvc: u32,
PrincName: ?*?*u8,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcServerInqDefaultPrincNameW(
AuthnSvc: u32,
PrincName: ?*?*u16,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcEpResolveBinding(
Binding: ?*c_void,
IfSpec: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcNsBindingInqEntryNameA(
Binding: ?*c_void,
EntryNameSyntax: u32,
EntryName: ?*?*u8,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcNsBindingInqEntryNameW(
Binding: ?*c_void,
EntryNameSyntax: u32,
EntryName: ?*?*u16,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "RPCRT4" fn RpcBindingCreateA(
Template: ?*RPC_BINDING_HANDLE_TEMPLATE_V1_A,
Security: ?*RPC_BINDING_HANDLE_SECURITY_V1_A,
Options: ?*RPC_BINDING_HANDLE_OPTIONS_V1,
Binding: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "RPCRT4" fn RpcBindingCreateW(
Template: ?*RPC_BINDING_HANDLE_TEMPLATE_V1_W,
Security: ?*RPC_BINDING_HANDLE_SECURITY_V1_W,
Options: ?*RPC_BINDING_HANDLE_OPTIONS_V1,
Binding: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "RPCRT4" fn RpcServerInqBindingHandle(
Binding: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcImpersonateClient(
BindingHandle: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn RpcImpersonateClient2(
BindingHandle: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcRevertToSelfEx(
BindingHandle: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcRevertToSelf(
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "RPCRT4" fn RpcImpersonateClientContainer(
BindingHandle: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "RPCRT4" fn RpcRevertContainerImpersonation(
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcBindingInqAuthClientA(
ClientBinding: ?*c_void,
Privs: ?*?*c_void,
ServerPrincName: ?*?*u8,
AuthnLevel: ?*u32,
AuthnSvc: ?*u32,
AuthzSvc: ?*u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcBindingInqAuthClientW(
ClientBinding: ?*c_void,
Privs: ?*?*c_void,
ServerPrincName: ?*?*u16,
AuthnLevel: ?*u32,
AuthnSvc: ?*u32,
AuthzSvc: ?*u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcBindingInqAuthClientExA(
ClientBinding: ?*c_void,
Privs: ?*?*c_void,
ServerPrincName: ?*?*u8,
AuthnLevel: ?*u32,
AuthnSvc: ?*u32,
AuthzSvc: ?*u32,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcBindingInqAuthClientExW(
ClientBinding: ?*c_void,
Privs: ?*?*c_void,
ServerPrincName: ?*?*u16,
AuthnLevel: ?*u32,
AuthnSvc: ?*u32,
AuthzSvc: ?*u32,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcBindingInqAuthInfoA(
Binding: ?*c_void,
ServerPrincName: ?*?*u8,
AuthnLevel: ?*u32,
AuthnSvc: ?*u32,
AuthIdentity: ?*?*c_void,
AuthzSvc: ?*u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcBindingInqAuthInfoW(
Binding: ?*c_void,
ServerPrincName: ?*?*u16,
AuthnLevel: ?*u32,
AuthnSvc: ?*u32,
AuthIdentity: ?*?*c_void,
AuthzSvc: ?*u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcBindingSetAuthInfoA(
Binding: ?*c_void,
ServerPrincName: ?*u8,
AuthnLevel: u32,
AuthnSvc: u32,
AuthIdentity: ?*c_void,
AuthzSvc: u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcBindingSetAuthInfoExA(
Binding: ?*c_void,
ServerPrincName: ?*u8,
AuthnLevel: u32,
AuthnSvc: u32,
AuthIdentity: ?*c_void,
AuthzSvc: u32,
SecurityQos: ?*RPC_SECURITY_QOS,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcBindingSetAuthInfoW(
Binding: ?*c_void,
ServerPrincName: ?*u16,
AuthnLevel: u32,
AuthnSvc: u32,
AuthIdentity: ?*c_void,
AuthzSvc: u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcBindingSetAuthInfoExW(
Binding: ?*c_void,
ServerPrincName: ?*u16,
AuthnLevel: u32,
AuthnSvc: u32,
AuthIdentity: ?*c_void,
AuthzSvc: u32,
SecurityQOS: ?*RPC_SECURITY_QOS,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcBindingInqAuthInfoExA(
Binding: ?*c_void,
ServerPrincName: ?*?*u8,
AuthnLevel: ?*u32,
AuthnSvc: ?*u32,
AuthIdentity: ?*?*c_void,
AuthzSvc: ?*u32,
RpcQosVersion: u32,
SecurityQOS: ?*RPC_SECURITY_QOS,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcBindingInqAuthInfoExW(
Binding: ?*c_void,
ServerPrincName: ?*?*u16,
AuthnLevel: ?*u32,
AuthnSvc: ?*u32,
AuthIdentity: ?*?*c_void,
AuthzSvc: ?*u32,
RpcQosVersion: u32,
SecurityQOS: ?*RPC_SECURITY_QOS,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcServerCompleteSecurityCallback(
BindingHandle: ?*c_void,
Status: RPC_STATUS,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcServerRegisterAuthInfoA(
ServerPrincName: ?*u8,
AuthnSvc: u32,
GetKeyFn: ?RPC_AUTH_KEY_RETRIEVAL_FN,
Arg: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcServerRegisterAuthInfoW(
ServerPrincName: ?*u16,
AuthnSvc: u32,
GetKeyFn: ?RPC_AUTH_KEY_RETRIEVAL_FN,
Arg: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcBindingServerFromClient(
ClientBinding: ?*c_void,
ServerBinding: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcRaiseException(
exception: RPC_STATUS,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcTestCancel(
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcServerTestCancel(
BindingHandle: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcCancelThread(
Thread: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcCancelThreadEx(
Thread: ?*c_void,
Timeout: i32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn UuidCreate(
Uuid: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn UuidCreateSequential(
Uuid: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn UuidToStringA(
Uuid: ?*const Guid,
StringUuid: ?*?*u8,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn UuidFromStringA(
StringUuid: ?*u8,
Uuid: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn UuidToStringW(
Uuid: ?*const Guid,
StringUuid: ?*?*u16,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn UuidFromStringW(
StringUuid: ?*u16,
Uuid: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn UuidCompare(
Uuid1: ?*Guid,
Uuid2: ?*Guid,
Status: ?*RPC_STATUS,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn UuidCreateNil(
NilUuid: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn UuidEqual(
Uuid1: ?*Guid,
Uuid2: ?*Guid,
Status: ?*RPC_STATUS,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn UuidHash(
Uuid: ?*Guid,
Status: ?*RPC_STATUS,
) callconv(@import("std").os.windows.WINAPI) u16;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn UuidIsNil(
Uuid: ?*Guid,
Status: ?*RPC_STATUS,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcEpRegisterNoReplaceA(
IfSpec: ?*c_void,
BindingVector: ?*RPC_BINDING_VECTOR,
UuidVector: ?*UUID_VECTOR,
Annotation: ?*u8,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcEpRegisterNoReplaceW(
IfSpec: ?*c_void,
BindingVector: ?*RPC_BINDING_VECTOR,
UuidVector: ?*UUID_VECTOR,
Annotation: ?*u16,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcEpRegisterA(
IfSpec: ?*c_void,
BindingVector: ?*RPC_BINDING_VECTOR,
UuidVector: ?*UUID_VECTOR,
Annotation: ?*u8,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcEpRegisterW(
IfSpec: ?*c_void,
BindingVector: ?*RPC_BINDING_VECTOR,
UuidVector: ?*UUID_VECTOR,
Annotation: ?*u16,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcEpUnregister(
IfSpec: ?*c_void,
BindingVector: ?*RPC_BINDING_VECTOR,
UuidVector: ?*UUID_VECTOR,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn DceErrorInqTextA(
RpcStatus: RPC_STATUS,
ErrorText: *[256]u8,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn DceErrorInqTextW(
RpcStatus: RPC_STATUS,
ErrorText: *[256]u16,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcMgmtEpEltInqBegin(
EpBinding: ?*c_void,
InquiryType: u32,
IfId: ?*RPC_IF_ID,
VersOption: u32,
ObjectUuid: ?*Guid,
InquiryContext: ?*?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcMgmtEpEltInqDone(
InquiryContext: ?*?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcMgmtEpEltInqNextA(
InquiryContext: ?*?*c_void,
IfId: ?*RPC_IF_ID,
Binding: ?*?*c_void,
ObjectUuid: ?*Guid,
Annotation: ?*?*u8,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcMgmtEpEltInqNextW(
InquiryContext: ?*?*c_void,
IfId: ?*RPC_IF_ID,
Binding: ?*?*c_void,
ObjectUuid: ?*Guid,
Annotation: ?*?*u16,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn RpcMgmtEpUnregister(
EpBinding: ?*c_void,
IfId: ?*RPC_IF_ID,
Binding: ?*c_void,
ObjectUuid: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcMgmtSetAuthorizationFn(
AuthorizationFn: ?RPC_MGMT_AUTHORIZATION_FN,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "RPCRT4" fn RpcExceptionFilter(
ExceptionCode: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "RPCRT4" fn RpcServerInterfaceGroupCreateW(
Interfaces: [*]RPC_INTERFACE_TEMPLATEW,
NumIfs: u32,
Endpoints: [*]RPC_ENDPOINT_TEMPLATEW,
NumEndpoints: u32,
IdlePeriod: u32,
IdleCallbackFn: ?RPC_INTERFACE_GROUP_IDLE_CALLBACK_FN,
IdleCallbackContext: ?*c_void,
IfGroup: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows8.0'
pub extern "RPCRT4" fn RpcServerInterfaceGroupCreateA(
Interfaces: [*]RPC_INTERFACE_TEMPLATEA,
NumIfs: u32,
Endpoints: [*]RPC_ENDPOINT_TEMPLATEA,
NumEndpoints: u32,
IdlePeriod: u32,
IdleCallbackFn: ?RPC_INTERFACE_GROUP_IDLE_CALLBACK_FN,
IdleCallbackContext: ?*c_void,
IfGroup: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows8.0'
pub extern "RPCRT4" fn RpcServerInterfaceGroupClose(
IfGroup: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows8.0'
pub extern "RPCRT4" fn RpcServerInterfaceGroupActivate(
IfGroup: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows8.0'
pub extern "RPCRT4" fn RpcServerInterfaceGroupDeactivate(
IfGroup: ?*c_void,
ForceDeactivation: u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows8.0'
pub extern "RPCRT4" fn RpcServerInterfaceGroupInqBindings(
IfGroup: ?*c_void,
BindingVector: ?*?*RPC_BINDING_VECTOR,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcNegotiateTransferSyntax(
Message: ?*RPC_MESSAGE,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcGetBuffer(
Message: ?*RPC_MESSAGE,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcGetBufferWithObject(
Message: ?*RPC_MESSAGE,
ObjectUuid: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcSendReceive(
Message: ?*RPC_MESSAGE,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcFreeBuffer(
Message: ?*RPC_MESSAGE,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcSend(
Message: ?*RPC_MESSAGE,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcReceive(
Message: ?*RPC_MESSAGE,
Size: u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcFreePipeBuffer(
Message: ?*RPC_MESSAGE,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcReallocPipeBuffer(
Message: ?*RPC_MESSAGE,
NewSize: u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcRequestMutex(
Mutex: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn I_RpcClearMutex(
Mutex: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn I_RpcDeleteMutex(
Mutex: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn I_RpcAllocate(
Size: u32,
) callconv(@import("std").os.windows.WINAPI) ?*c_void;
pub extern "RPCRT4" fn I_RpcFree(
Object: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn I_RpcPauseExecution(
Milliseconds: u32,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn I_RpcGetExtendedError(
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcSystemHandleTypeSpecificWork(
Handle: ?*c_void,
ActualType: u8,
IdlType: u8,
MarshalDirection: LRPC_SYSTEM_HANDLE_MARSHAL_DIRECTION,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcGetCurrentCallHandle(
) callconv(@import("std").os.windows.WINAPI) ?*c_void;
pub extern "RPCRT4" fn I_RpcNsInterfaceExported(
EntryNameSyntax: u32,
EntryName: ?*u16,
RpcInterfaceInformation: ?*RPC_SERVER_INTERFACE,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcNsInterfaceUnexported(
EntryNameSyntax: u32,
EntryName: ?*u16,
RpcInterfaceInformation: ?*RPC_SERVER_INTERFACE,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcBindingToStaticStringBindingW(
Binding: ?*c_void,
StringBinding: ?*?*u16,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcBindingInqSecurityContext(
Binding: ?*c_void,
SecurityContextHandle: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcBindingInqSecurityContextKeyInfo(
Binding: ?*c_void,
KeyInfo: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcBindingInqWireIdForSnego(
Binding: ?*c_void,
WireId: ?*u8,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcBindingInqMarshalledTargetInfo(
Binding: ?*c_void,
MarshalledTargetInfoSize: ?*u32,
MarshalledTargetInfo: ?*?*u8,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "RPCRT4" fn I_RpcBindingInqLocalClientPID(
Binding: ?*c_void,
Pid: ?*u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcBindingHandleToAsyncHandle(
Binding: ?*c_void,
AsyncHandle: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcNsBindingSetEntryNameW(
Binding: ?*c_void,
EntryNameSyntax: u32,
EntryName: ?*u16,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcNsBindingSetEntryNameA(
Binding: ?*c_void,
EntryNameSyntax: u32,
EntryName: ?*u8,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcServerUseProtseqEp2A(
NetworkAddress: ?*u8,
Protseq: ?*u8,
MaxCalls: u32,
Endpoint: ?*u8,
SecurityDescriptor: ?*c_void,
Policy: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcServerUseProtseqEp2W(
NetworkAddress: ?*u16,
Protseq: ?*u16,
MaxCalls: u32,
Endpoint: ?*u16,
SecurityDescriptor: ?*c_void,
Policy: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcServerUseProtseq2W(
NetworkAddress: ?*u16,
Protseq: ?*u16,
MaxCalls: u32,
SecurityDescriptor: ?*c_void,
Policy: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcServerUseProtseq2A(
NetworkAddress: ?*u8,
Protseq: ?*u8,
MaxCalls: u32,
SecurityDescriptor: ?*c_void,
Policy: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcServerStartService(
Protseq: ?*u16,
Endpoint: ?*u16,
IfSpec: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcBindingInqDynamicEndpointW(
Binding: ?*c_void,
DynamicEndpoint: ?*?*u16,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcBindingInqDynamicEndpointA(
Binding: ?*c_void,
DynamicEndpoint: ?*?*u8,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcServerCheckClientRestriction(
Context: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcBindingInqTransportType(
Binding: ?*c_void,
Type: ?*u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcIfInqTransferSyntaxes(
RpcIfHandle: ?*c_void,
TransferSyntaxes: ?*RPC_TRANSFER_SYNTAX,
TransferSyntaxSize: u32,
TransferSyntaxCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_UuidCreate(
Uuid: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcBindingCopy(
SourceBinding: ?*c_void,
DestinationBinding: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcBindingIsClientLocal(
BindingHandle: ?*c_void,
ClientLocalFlag: ?*u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcBindingCreateNP(
ServerName: ?*u16,
ServiceName: ?*u16,
NetworkOptions: ?*u16,
Binding: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcSsDontSerializeContext(
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn I_RpcServerRegisterForwardFunction(
pForwardFunction: ?*?RPC_FORWARD_FUNCTION,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcServerInqAddressChangeFn(
) callconv(@import("std").os.windows.WINAPI) ?*?RPC_ADDRESS_CHANGE_FN;
pub extern "RPCRT4" fn I_RpcServerSetAddressChangeFn(
pAddressChangeFn: ?*?RPC_ADDRESS_CHANGE_FN,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcServerInqLocalConnAddress(
Binding: ?*c_void,
Buffer: ?*c_void,
BufferSize: ?*u32,
AddressFormat: ?*u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcServerInqRemoteConnAddress(
Binding: ?*c_void,
Buffer: ?*c_void,
BufferSize: ?*u32,
AddressFormat: ?*u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcSessionStrictContextHandle(
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn I_RpcTurnOnEEInfoPropagation(
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcServerInqTransportType(
Type: ?*u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcMapWin32Status(
Status: RPC_STATUS,
) callconv(@import("std").os.windows.WINAPI) i32;
pub extern "RPCRT4" fn I_RpcRecordCalloutFailure(
RpcStatus: RPC_STATUS,
CallOutState: ?*RDR_CALLOUT_STATE,
DllName: ?*u16,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn I_RpcMgmtEnableDedicatedThreadPool(
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcGetDefaultSD(
ppSecurityDescriptor: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcOpenClientProcess(
Binding: ?*c_void,
DesiredAccess: u32,
ClientProcess: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcBindingIsServerLocal(
Binding: ?*c_void,
ServerLocalFlag: ?*u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcBindingSetPrivateOption(
hBinding: ?*c_void,
option: u32,
optionValue: usize,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcServerSubscribeForDisconnectNotification(
Binding: ?*c_void,
hEvent: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcServerGetAssociationID(
Binding: ?*c_void,
AssociationID: ?*u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcServerDisableExceptionFilter(
) callconv(@import("std").os.windows.WINAPI) i32;
pub extern "RPCRT4" fn I_RpcServerSubscribeForDisconnectNotification2(
Binding: ?*c_void,
hEvent: ?*c_void,
SubscriptionId: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcServerUnsubscribeForDisconnectNotification(
Binding: ?*c_void,
SubscriptionId: Guid,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsBindingExportA(
EntryNameSyntax: u32,
EntryName: ?*u8,
IfSpec: ?*c_void,
BindingVec: ?*RPC_BINDING_VECTOR,
ObjectUuidVec: ?*UUID_VECTOR,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsBindingUnexportA(
EntryNameSyntax: u32,
EntryName: ?*u8,
IfSpec: ?*c_void,
ObjectUuidVec: ?*UUID_VECTOR,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsBindingExportW(
EntryNameSyntax: u32,
EntryName: ?*u16,
IfSpec: ?*c_void,
BindingVec: ?*RPC_BINDING_VECTOR,
ObjectUuidVec: ?*UUID_VECTOR,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsBindingUnexportW(
EntryNameSyntax: u32,
EntryName: ?*u16,
IfSpec: ?*c_void,
ObjectUuidVec: ?*UUID_VECTOR,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsBindingExportPnPA(
EntryNameSyntax: u32,
EntryName: ?*u8,
IfSpec: ?*c_void,
ObjectVector: ?*UUID_VECTOR,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsBindingUnexportPnPA(
EntryNameSyntax: u32,
EntryName: ?*u8,
IfSpec: ?*c_void,
ObjectVector: ?*UUID_VECTOR,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsBindingExportPnPW(
EntryNameSyntax: u32,
EntryName: ?*u16,
IfSpec: ?*c_void,
ObjectVector: ?*UUID_VECTOR,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsBindingUnexportPnPW(
EntryNameSyntax: u32,
EntryName: ?*u16,
IfSpec: ?*c_void,
ObjectVector: ?*UUID_VECTOR,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsBindingLookupBeginA(
EntryNameSyntax: u32,
EntryName: ?*u8,
IfSpec: ?*c_void,
ObjUuid: ?*Guid,
BindingMaxCount: u32,
LookupContext: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsBindingLookupBeginW(
EntryNameSyntax: u32,
EntryName: ?*u16,
IfSpec: ?*c_void,
ObjUuid: ?*Guid,
BindingMaxCount: u32,
LookupContext: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsBindingLookupNext(
LookupContext: ?*c_void,
BindingVec: ?*?*RPC_BINDING_VECTOR,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsBindingLookupDone(
LookupContext: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsGroupDeleteA(
GroupNameSyntax: GROUP_NAME_SYNTAX,
GroupName: ?*u8,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsGroupMbrAddA(
GroupNameSyntax: u32,
GroupName: ?*u8,
MemberNameSyntax: u32,
MemberName: ?*u8,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsGroupMbrRemoveA(
GroupNameSyntax: u32,
GroupName: ?*u8,
MemberNameSyntax: u32,
MemberName: ?*u8,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsGroupMbrInqBeginA(
GroupNameSyntax: u32,
GroupName: ?*u8,
MemberNameSyntax: u32,
InquiryContext: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsGroupMbrInqNextA(
InquiryContext: ?*c_void,
MemberName: ?*?*u8,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsGroupDeleteW(
GroupNameSyntax: GROUP_NAME_SYNTAX,
GroupName: ?*u16,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsGroupMbrAddW(
GroupNameSyntax: u32,
GroupName: ?*u16,
MemberNameSyntax: u32,
MemberName: ?*u16,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsGroupMbrRemoveW(
GroupNameSyntax: u32,
GroupName: ?*u16,
MemberNameSyntax: u32,
MemberName: ?*u16,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsGroupMbrInqBeginW(
GroupNameSyntax: u32,
GroupName: ?*u16,
MemberNameSyntax: u32,
InquiryContext: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsGroupMbrInqNextW(
InquiryContext: ?*c_void,
MemberName: ?*?*u16,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsGroupMbrInqDone(
InquiryContext: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsProfileDeleteA(
ProfileNameSyntax: u32,
ProfileName: ?*u8,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsProfileEltAddA(
ProfileNameSyntax: u32,
ProfileName: ?*u8,
IfId: ?*RPC_IF_ID,
MemberNameSyntax: u32,
MemberName: ?*u8,
Priority: u32,
Annotation: ?*u8,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsProfileEltRemoveA(
ProfileNameSyntax: u32,
ProfileName: ?*u8,
IfId: ?*RPC_IF_ID,
MemberNameSyntax: u32,
MemberName: ?*u8,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsProfileEltInqBeginA(
ProfileNameSyntax: u32,
ProfileName: ?*u8,
InquiryType: u32,
IfId: ?*RPC_IF_ID,
VersOption: u32,
MemberNameSyntax: u32,
MemberName: ?*u8,
InquiryContext: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsProfileEltInqNextA(
InquiryContext: ?*c_void,
IfId: ?*RPC_IF_ID,
MemberName: ?*?*u8,
Priority: ?*u32,
Annotation: ?*?*u8,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsProfileDeleteW(
ProfileNameSyntax: u32,
ProfileName: ?*u16,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsProfileEltAddW(
ProfileNameSyntax: u32,
ProfileName: ?*u16,
IfId: ?*RPC_IF_ID,
MemberNameSyntax: u32,
MemberName: ?*u16,
Priority: u32,
Annotation: ?*u16,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsProfileEltRemoveW(
ProfileNameSyntax: u32,
ProfileName: ?*u16,
IfId: ?*RPC_IF_ID,
MemberNameSyntax: u32,
MemberName: ?*u16,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsProfileEltInqBeginW(
ProfileNameSyntax: u32,
ProfileName: ?*u16,
InquiryType: u32,
IfId: ?*RPC_IF_ID,
VersOption: u32,
MemberNameSyntax: u32,
MemberName: ?*u16,
InquiryContext: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsProfileEltInqNextW(
InquiryContext: ?*c_void,
IfId: ?*RPC_IF_ID,
MemberName: ?*?*u16,
Priority: ?*u32,
Annotation: ?*?*u16,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsProfileEltInqDone(
InquiryContext: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsEntryObjectInqBeginA(
EntryNameSyntax: u32,
EntryName: ?*u8,
InquiryContext: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsEntryObjectInqBeginW(
EntryNameSyntax: u32,
EntryName: ?*u16,
InquiryContext: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsEntryObjectInqNext(
InquiryContext: ?*c_void,
ObjUuid: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsEntryObjectInqDone(
InquiryContext: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsEntryExpandNameA(
EntryNameSyntax: u32,
EntryName: ?*u8,
ExpandedName: ?*?*u8,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsMgmtBindingUnexportA(
EntryNameSyntax: u32,
EntryName: ?*u8,
IfId: ?*RPC_IF_ID,
VersOption: u32,
ObjectUuidVec: ?*UUID_VECTOR,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsMgmtEntryCreateA(
EntryNameSyntax: u32,
EntryName: ?*u8,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsMgmtEntryDeleteA(
EntryNameSyntax: u32,
EntryName: ?*u8,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsMgmtEntryInqIfIdsA(
EntryNameSyntax: u32,
EntryName: ?*u8,
IfIdVec: ?*?*RPC_IF_ID_VECTOR,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsMgmtHandleSetExpAge(
NsHandle: ?*c_void,
ExpirationAge: u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsMgmtInqExpAge(
ExpirationAge: ?*u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsMgmtSetExpAge(
ExpirationAge: u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsEntryExpandNameW(
EntryNameSyntax: u32,
EntryName: ?*u16,
ExpandedName: ?*?*u16,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsMgmtBindingUnexportW(
EntryNameSyntax: u32,
EntryName: ?*u16,
IfId: ?*RPC_IF_ID,
VersOption: u32,
ObjectUuidVec: ?*UUID_VECTOR,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsMgmtEntryCreateW(
EntryNameSyntax: u32,
EntryName: ?*u16,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsMgmtEntryDeleteW(
EntryNameSyntax: u32,
EntryName: ?*u16,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsMgmtEntryInqIfIdsW(
EntryNameSyntax: u32,
EntryName: ?*u16,
IfIdVec: ?*?*RPC_IF_ID_VECTOR,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsBindingImportBeginA(
EntryNameSyntax: u32,
EntryName: ?*u8,
IfSpec: ?*c_void,
ObjUuid: ?*Guid,
ImportContext: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsBindingImportBeginW(
EntryNameSyntax: u32,
EntryName: ?*u16,
IfSpec: ?*c_void,
ObjUuid: ?*Guid,
ImportContext: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsBindingImportNext(
ImportContext: ?*c_void,
Binding: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsBindingImportDone(
ImportContext: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCNS4" fn RpcNsBindingSelect(
BindingVec: ?*RPC_BINDING_VECTOR,
Binding: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcAsyncRegisterInfo(
pAsync: ?*RPC_ASYNC_STATE,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcAsyncInitializeHandle(
// TODO: what to do with BytesParamIndex 1?
pAsync: ?*RPC_ASYNC_STATE,
Size: u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcAsyncGetCallStatus(
pAsync: ?*RPC_ASYNC_STATE,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcAsyncCompleteCall(
pAsync: ?*RPC_ASYNC_STATE,
Reply: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcAsyncAbortCall(
pAsync: ?*RPC_ASYNC_STATE,
ExceptionCode: u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcAsyncCancelCall(
pAsync: ?*RPC_ASYNC_STATE,
fAbort: BOOL,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "RPCRT4" fn RpcErrorStartEnumeration(
EnumHandle: ?*RPC_ERROR_ENUM_HANDLE,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "RPCRT4" fn RpcErrorGetNextRecord(
EnumHandle: ?*RPC_ERROR_ENUM_HANDLE,
CopyStrings: BOOL,
ErrorInfo: ?*RPC_EXTENDED_ERROR_INFO,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "RPCRT4" fn RpcErrorEndEnumeration(
EnumHandle: ?*RPC_ERROR_ENUM_HANDLE,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "RPCRT4" fn RpcErrorResetEnumeration(
EnumHandle: ?*RPC_ERROR_ENUM_HANDLE,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "RPCRT4" fn RpcErrorGetNumberOfRecords(
EnumHandle: ?*RPC_ERROR_ENUM_HANDLE,
Records: ?*i32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "RPCRT4" fn RpcErrorSaveErrorInfo(
EnumHandle: ?*RPC_ERROR_ENUM_HANDLE,
ErrorBlob: ?*?*c_void,
BlobSize: ?*usize,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "RPCRT4" fn RpcErrorLoadErrorInfo(
// TODO: what to do with BytesParamIndex 1?
ErrorBlob: ?*c_void,
BlobSize: usize,
EnumHandle: ?*RPC_ERROR_ENUM_HANDLE,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "RPCRT4" fn RpcErrorAddRecord(
ErrorInfo: ?*RPC_EXTENDED_ERROR_INFO,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "RPCRT4" fn RpcErrorClearInformation(
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "RPCRT4" fn RpcGetAuthorizationContextForClient(
ClientBinding: ?*c_void,
ImpersonateOnReturn: BOOL,
Reserved1: ?*c_void,
pExpirationTime: ?*LARGE_INTEGER,
Reserved2: LUID,
Reserved3: u32,
Reserved4: ?*c_void,
pAuthzClientContext: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "RPCRT4" fn RpcFreeAuthorizationContext(
pAuthzClientContext: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "RPCRT4" fn RpcSsContextLockExclusive(
ServerBindingHandle: ?*c_void,
UserContext: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "RPCRT4" fn RpcSsContextLockShared(
ServerBindingHandle: ?*c_void,
UserContext: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "RPCRT4" fn RpcServerInqCallAttributesW(
ClientBinding: ?*c_void,
RpcCallAttributes: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "RPCRT4" fn RpcServerInqCallAttributesA(
ClientBinding: ?*c_void,
RpcCallAttributes: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "RPCRT4" fn RpcServerSubscribeForNotification(
Binding: ?*c_void,
Notification: RPC_NOTIFICATIONS,
NotificationType: RPC_NOTIFICATION_TYPES,
NotificationInfo: ?*RPC_ASYNC_NOTIFICATION_INFO,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "RPCRT4" fn RpcServerUnsubscribeForNotification(
Binding: ?*c_void,
Notification: RPC_NOTIFICATIONS,
NotificationsQueued: ?*u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "RPCRT4" fn RpcBindingBind(
pAsync: ?*RPC_ASYNC_STATE,
Binding: ?*c_void,
IfSpec: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "RPCRT4" fn RpcBindingUnbind(
Binding: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcAsyncSetHandle(
Message: ?*RPC_MESSAGE,
pAsync: ?*RPC_ASYNC_STATE,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcAsyncAbortCall(
pAsync: ?*RPC_ASYNC_STATE,
ExceptionCode: u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn I_RpcExceptionFilter(
ExceptionCode: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub extern "RPCRT4" fn I_RpcBindingInqClientTokenAttributes(
Binding: ?*c_void,
TokenId: ?*LUID,
AuthenticationId: ?*LUID,
ModifiedId: ?*LUID,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn NDRCContextBinding(
CContext: isize,
) callconv(@import("std").os.windows.WINAPI) ?*c_void;
pub extern "RPCRT4" fn NDRCContextMarshall(
CContext: isize,
pBuff: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NDRCContextUnmarshall(
pCContext: ?*isize,
hBinding: ?*c_void,
pBuff: ?*c_void,
DataRepresentation: u32,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NDRSContextMarshall(
CContext: ?*NDR_SCONTEXT_1,
pBuff: ?*c_void,
userRunDownIn: ?NDR_RUNDOWN,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NDRSContextUnmarshall(
pBuff: ?*c_void,
DataRepresentation: u32,
) callconv(@import("std").os.windows.WINAPI) ?*NDR_SCONTEXT_1;
pub extern "RPCRT4" fn NDRSContextMarshallEx(
BindingHandle: ?*c_void,
CContext: ?*NDR_SCONTEXT_1,
pBuff: ?*c_void,
userRunDownIn: ?NDR_RUNDOWN,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NDRSContextMarshall2(
BindingHandle: ?*c_void,
CContext: ?*NDR_SCONTEXT_1,
pBuff: ?*c_void,
userRunDownIn: ?NDR_RUNDOWN,
CtxGuard: ?*c_void,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NDRSContextUnmarshallEx(
BindingHandle: ?*c_void,
pBuff: ?*c_void,
DataRepresentation: u32,
) callconv(@import("std").os.windows.WINAPI) ?*NDR_SCONTEXT_1;
pub extern "RPCRT4" fn NDRSContextUnmarshall2(
BindingHandle: ?*c_void,
pBuff: ?*c_void,
DataRepresentation: u32,
CtxGuard: ?*c_void,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) ?*NDR_SCONTEXT_1;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcSsDestroyClientContext(
ContextHandle: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrSimpleTypeMarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
FormatChar: u8,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrPointerMarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrSimpleStructMarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrConformantStructMarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrConformantVaryingStructMarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrComplexStructMarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrFixedArrayMarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrConformantArrayMarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrConformantVaryingArrayMarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrVaryingArrayMarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrComplexArrayMarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrNonConformantStringMarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrConformantStringMarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrEncapsulatedUnionMarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrNonEncapsulatedUnionMarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrByteCountPointerMarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrXmitOrRepAsMarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrUserMarshalMarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrInterfacePointerMarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrClientContextMarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
ContextHandle: isize,
fCheck: i32,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrServerContextMarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
ContextHandle: ?*NDR_SCONTEXT_1,
RundownRoutine: ?NDR_RUNDOWN,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrServerContextNewMarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
ContextHandle: ?*NDR_SCONTEXT_1,
RundownRoutine: ?NDR_RUNDOWN,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrSimpleTypeUnmarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
FormatChar: u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrRangeUnmarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
ppMemory: ?*?*u8,
pFormat: ?*u8,
fMustAlloc: u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrCorrelationInitialize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*c_void,
CacheSize: u32,
flags: u32,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrCorrelationPass(
pStubMsg: ?*MIDL_STUB_MESSAGE,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrCorrelationFree(
pStubMsg: ?*MIDL_STUB_MESSAGE,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrPointerUnmarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
ppMemory: ?*?*u8,
pFormat: ?*u8,
fMustAlloc: u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrSimpleStructUnmarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
ppMemory: ?*?*u8,
pFormat: ?*u8,
fMustAlloc: u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrConformantStructUnmarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
ppMemory: ?*?*u8,
pFormat: ?*u8,
fMustAlloc: u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrConformantVaryingStructUnmarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
ppMemory: ?*?*u8,
pFormat: ?*u8,
fMustAlloc: u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrComplexStructUnmarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
ppMemory: ?*?*u8,
pFormat: ?*u8,
fMustAlloc: u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrFixedArrayUnmarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
ppMemory: ?*?*u8,
pFormat: ?*u8,
fMustAlloc: u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrConformantArrayUnmarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
ppMemory: ?*?*u8,
pFormat: ?*u8,
fMustAlloc: u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrConformantVaryingArrayUnmarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
ppMemory: ?*?*u8,
pFormat: ?*u8,
fMustAlloc: u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrVaryingArrayUnmarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
ppMemory: ?*?*u8,
pFormat: ?*u8,
fMustAlloc: u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrComplexArrayUnmarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
ppMemory: ?*?*u8,
pFormat: ?*u8,
fMustAlloc: u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrNonConformantStringUnmarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
ppMemory: ?*?*u8,
pFormat: ?*u8,
fMustAlloc: u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrConformantStringUnmarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
ppMemory: ?*?*u8,
pFormat: ?*u8,
fMustAlloc: u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrEncapsulatedUnionUnmarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
ppMemory: ?*?*u8,
pFormat: ?*u8,
fMustAlloc: u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrNonEncapsulatedUnionUnmarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
ppMemory: ?*?*u8,
pFormat: ?*u8,
fMustAlloc: u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrByteCountPointerUnmarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
ppMemory: ?*?*u8,
pFormat: ?*u8,
fMustAlloc: u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrXmitOrRepAsUnmarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
ppMemory: ?*?*u8,
pFormat: ?*u8,
fMustAlloc: u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrUserMarshalUnmarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
ppMemory: ?*?*u8,
pFormat: ?*u8,
fMustAlloc: u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrInterfacePointerUnmarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
ppMemory: ?*?*u8,
pFormat: ?*u8,
fMustAlloc: u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrClientContextUnmarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pContextHandle: ?*isize,
BindHandle: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrServerContextUnmarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
) callconv(@import("std").os.windows.WINAPI) ?*NDR_SCONTEXT_1;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "RPCRT4" fn NdrContextHandleInitialize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) ?*NDR_SCONTEXT_1;
pub extern "RPCRT4" fn NdrServerContextNewUnmarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) ?*NDR_SCONTEXT_1;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrPointerBufferSize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrSimpleStructBufferSize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrConformantStructBufferSize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrConformantVaryingStructBufferSize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrComplexStructBufferSize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrFixedArrayBufferSize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrConformantArrayBufferSize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrConformantVaryingArrayBufferSize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrVaryingArrayBufferSize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrComplexArrayBufferSize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrConformantStringBufferSize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrNonConformantStringBufferSize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrEncapsulatedUnionBufferSize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrNonEncapsulatedUnionBufferSize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrByteCountPointerBufferSize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrXmitOrRepAsBufferSize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrUserMarshalBufferSize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrInterfacePointerBufferSize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "RPCRT4" fn NdrContextHandleSize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrPointerMemorySize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "RPCRT4" fn NdrSimpleStructMemorySize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "RPCRT4" fn NdrConformantStructMemorySize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "RPCRT4" fn NdrConformantVaryingStructMemorySize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "RPCRT4" fn NdrComplexStructMemorySize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "RPCRT4" fn NdrFixedArrayMemorySize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "RPCRT4" fn NdrConformantArrayMemorySize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "RPCRT4" fn NdrConformantVaryingArrayMemorySize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "RPCRT4" fn NdrVaryingArrayMemorySize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "RPCRT4" fn NdrComplexArrayMemorySize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "RPCRT4" fn NdrConformantStringMemorySize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "RPCRT4" fn NdrNonConformantStringMemorySize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "RPCRT4" fn NdrEncapsulatedUnionMemorySize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "RPCRT4" fn NdrNonEncapsulatedUnionMemorySize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "RPCRT4" fn NdrXmitOrRepAsMemorySize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "RPCRT4" fn NdrUserMarshalMemorySize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "RPCRT4" fn NdrInterfacePointerMemorySize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrPointerFree(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrSimpleStructFree(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrConformantStructFree(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrConformantVaryingStructFree(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrComplexStructFree(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrFixedArrayFree(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrConformantArrayFree(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrConformantVaryingArrayFree(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrVaryingArrayFree(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrComplexArrayFree(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrEncapsulatedUnionFree(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrNonEncapsulatedUnionFree(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrByteCountPointerFree(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrXmitOrRepAsFree(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrUserMarshalFree(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrInterfacePointerFree(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*u8,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrConvert2(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pFormat: ?*u8,
NumberParams: i32,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrConvert(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrUserMarshalSimpleTypeConvert(
pFlags: ?*u32,
pBuffer: ?*u8,
FormatChar: u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrClientInitializeNew(
pRpcMsg: ?*RPC_MESSAGE,
pStubMsg: ?*MIDL_STUB_MESSAGE,
pStubDescriptor: ?*MIDL_STUB_DESC,
ProcNum: u32,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrServerInitializeNew(
pRpcMsg: ?*RPC_MESSAGE,
pStubMsg: ?*MIDL_STUB_MESSAGE,
pStubDescriptor: ?*MIDL_STUB_DESC,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrServerInitializePartial(
pRpcMsg: ?*RPC_MESSAGE,
pStubMsg: ?*MIDL_STUB_MESSAGE,
pStubDescriptor: ?*MIDL_STUB_DESC,
RequestedBufferSize: u32,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrClientInitialize(
pRpcMsg: ?*RPC_MESSAGE,
pStubMsg: ?*MIDL_STUB_MESSAGE,
pStubDescriptor: ?*MIDL_STUB_DESC,
ProcNum: u32,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrServerInitialize(
pRpcMsg: ?*RPC_MESSAGE,
pStubMsg: ?*MIDL_STUB_MESSAGE,
pStubDescriptor: ?*MIDL_STUB_DESC,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrServerInitializeUnmarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pStubDescriptor: ?*MIDL_STUB_DESC,
pRpcMsg: ?*RPC_MESSAGE,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrServerInitializeMarshall(
pRpcMsg: ?*RPC_MESSAGE,
pStubMsg: ?*MIDL_STUB_MESSAGE,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrGetBuffer(
pStubMsg: ?*MIDL_STUB_MESSAGE,
BufferLength: u32,
Handle: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrNsGetBuffer(
pStubMsg: ?*MIDL_STUB_MESSAGE,
BufferLength: u32,
Handle: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrSendReceive(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pBufferEnd: ?*u8,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrNsSendReceive(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pBufferEnd: ?*u8,
pAutoHandle: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) ?*u8;
pub extern "RPCRT4" fn NdrFreeBuffer(
pStubMsg: ?*MIDL_STUB_MESSAGE,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrGetDcomProtocolVersion(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pVersion: ?*RPC_VERSION,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrClientCall2(
pStubDescriptor: ?*MIDL_STUB_DESC,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) CLIENT_CALL_RETURN;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrAsyncClientCall(
pStubDescriptor: ?*MIDL_STUB_DESC,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) CLIENT_CALL_RETURN;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrDcomAsyncClientCall(
pStubDescriptor: ?*MIDL_STUB_DESC,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) CLIENT_CALL_RETURN;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrAsyncServerCall(
pRpcMsg: ?*RPC_MESSAGE,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrDcomAsyncStubCall(
pThis: ?*IRpcStubBuffer,
pChannel: ?*IRpcChannelBuffer,
pRpcMsg: ?*RPC_MESSAGE,
pdwStubPhase: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrStubCall2(
pThis: ?*c_void,
pChannel: ?*c_void,
pRpcMsg: ?*RPC_MESSAGE,
pdwStubPhase: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrServerCall2(
pRpcMsg: ?*RPC_MESSAGE,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrMapCommAndFaultStatus(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pCommStatus: ?*u32,
pFaultStatus: ?*u32,
Status: RPC_STATUS,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcSsAllocate(
Size: usize,
) callconv(@import("std").os.windows.WINAPI) ?*c_void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcSsDisableAllocate(
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcSsEnableAllocate(
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcSsFree(
NodeToFree: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcSsGetThreadHandle(
) callconv(@import("std").os.windows.WINAPI) ?*c_void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcSsSetClientAllocFree(
ClientAlloc: ?RPC_CLIENT_ALLOC,
ClientFree: ?RPC_CLIENT_FREE,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcSsSetThreadHandle(
Id: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcSsSwapClientAllocFree(
ClientAlloc: ?RPC_CLIENT_ALLOC,
ClientFree: ?RPC_CLIENT_FREE,
OldClientAlloc: ?*?RPC_CLIENT_ALLOC,
OldClientFree: ?*?RPC_CLIENT_FREE,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcSmAllocate(
Size: usize,
pStatus: ?*RPC_STATUS,
) callconv(@import("std").os.windows.WINAPI) ?*c_void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcSmClientFree(
pNodeToFree: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcSmDestroyClientContext(
ContextHandle: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcSmDisableAllocate(
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcSmEnableAllocate(
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcSmFree(
NodeToFree: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcSmGetThreadHandle(
pStatus: ?*RPC_STATUS,
) callconv(@import("std").os.windows.WINAPI) ?*c_void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcSmSetClientAllocFree(
ClientAlloc: ?RPC_CLIENT_ALLOC,
ClientFree: ?RPC_CLIENT_FREE,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcSmSetThreadHandle(
Id: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcSmSwapClientAllocFree(
ClientAlloc: ?RPC_CLIENT_ALLOC,
ClientFree: ?RPC_CLIENT_FREE,
OldClientAlloc: ?*?RPC_CLIENT_ALLOC,
OldClientFree: ?*?RPC_CLIENT_FREE,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn NdrRpcSsEnableAllocate(
pMessage: ?*MIDL_STUB_MESSAGE,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrRpcSsDisableAllocate(
pMessage: ?*MIDL_STUB_MESSAGE,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrRpcSmSetClientToOsf(
pMessage: ?*MIDL_STUB_MESSAGE,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrRpcSmClientAllocate(
Size: usize,
) callconv(@import("std").os.windows.WINAPI) ?*c_void;
pub extern "RPCRT4" fn NdrRpcSmClientFree(
NodeToFree: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrRpcSsDefaultAllocate(
Size: usize,
) callconv(@import("std").os.windows.WINAPI) ?*c_void;
pub extern "RPCRT4" fn NdrRpcSsDefaultFree(
NodeToFree: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrFullPointerXlatInit(
NumberOfPointers: u32,
XlatSide: XLAT_SIDE,
) callconv(@import("std").os.windows.WINAPI) ?*FULL_PTR_XLAT_TABLES;
pub extern "RPCRT4" fn NdrFullPointerXlatFree(
pXlatTables: ?*FULL_PTR_XLAT_TABLES,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrAllocate(
pStubMsg: ?*MIDL_STUB_MESSAGE,
Len: usize,
) callconv(@import("std").os.windows.WINAPI) ?*c_void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrClearOutParameters(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pFormat: ?*u8,
ArgAddr: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrOleAllocate(
Size: usize,
) callconv(@import("std").os.windows.WINAPI) ?*c_void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrOleFree(
NodeToFree: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrGetUserMarshalInfo(
pFlags: ?*u32,
InformationLevel: u32,
pMarshalInfo: ?*NDR_USER_MARSHAL_INFO,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn NdrCreateServerInterfaceFromStub(
pStub: ?*IRpcStubBuffer,
pServerIf: ?*RPC_SERVER_INTERFACE,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrClientCall3(
pProxyInfo: ?*MIDL_STUBLESS_PROXY_INFO,
nProcNum: u32,
pReturnValue: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) CLIENT_CALL_RETURN;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "RPCRT4" fn Ndr64AsyncClientCall(
pProxyInfo: ?*MIDL_STUBLESS_PROXY_INFO,
nProcNum: u32,
pReturnValue: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) CLIENT_CALL_RETURN;
pub extern "RPCRT4" fn Ndr64DcomAsyncClientCall(
pProxyInfo: ?*MIDL_STUBLESS_PROXY_INFO,
nProcNum: u32,
pReturnValue: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) CLIENT_CALL_RETURN;
pub extern "RPCRT4" fn Ndr64AsyncServerCall64(
pRpcMsg: ?*RPC_MESSAGE,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "RPCRT4" fn Ndr64AsyncServerCallAll(
pRpcMsg: ?*RPC_MESSAGE,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn Ndr64DcomAsyncStubCall(
pThis: ?*IRpcStubBuffer,
pChannel: ?*IRpcChannelBuffer,
pRpcMsg: ?*RPC_MESSAGE,
pdwStubPhase: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "RPCRT4" fn NdrStubCall3(
pThis: ?*c_void,
pChannel: ?*c_void,
pRpcMsg: ?*RPC_MESSAGE,
pdwStubPhase: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "RPCRT4" fn NdrServerCallAll(
pRpcMsg: ?*RPC_MESSAGE,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrServerCallNdr64(
pRpcMsg: ?*RPC_MESSAGE,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrPartialIgnoreClientMarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrPartialIgnoreServerUnmarshall(
pStubMsg: ?*MIDL_STUB_MESSAGE,
ppMemory: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrPartialIgnoreClientBufferSize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
pMemory: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrPartialIgnoreServerInitialize(
pStubMsg: ?*MIDL_STUB_MESSAGE,
ppMemory: ?*?*c_void,
pFormat: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "RPCRT4" fn RpcUserFree(
AsyncHandle: ?*c_void,
pBuffer: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn MesEncodeIncrementalHandleCreate(
UserState: ?*c_void,
AllocFn: ?MIDL_ES_ALLOC,
WriteFn: ?MIDL_ES_WRITE,
pHandle: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn MesDecodeIncrementalHandleCreate(
UserState: ?*c_void,
ReadFn: ?MIDL_ES_READ,
pHandle: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn MesIncrementalHandleReset(
Handle: ?*c_void,
UserState: ?*c_void,
AllocFn: ?MIDL_ES_ALLOC,
WriteFn: ?MIDL_ES_WRITE,
ReadFn: ?MIDL_ES_READ,
Operation: MIDL_ES_CODE,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn MesEncodeFixedBufferHandleCreate(
// TODO: what to do with BytesParamIndex 1?
pBuffer: ?PSTR,
BufferSize: u32,
pEncodedSize: ?*u32,
pHandle: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn MesEncodeDynBufferHandleCreate(
pBuffer: ?*?*i8,
pEncodedSize: ?*u32,
pHandle: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn MesDecodeBufferHandleCreate(
// TODO: what to do with BytesParamIndex 1?
Buffer: ?PSTR,
BufferSize: u32,
pHandle: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn MesBufferHandleReset(
Handle: ?*c_void,
HandleStyle: u32,
Operation: MIDL_ES_CODE,
// TODO: what to do with BytesParamIndex 4?
pBuffer: ?*?*i8,
BufferSize: u32,
pEncodedSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn MesHandleFree(
Handle: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn MesInqProcEncodingId(
Handle: ?*c_void,
pInterfaceId: ?*RPC_SYNTAX_IDENTIFIER,
pProcNum: ?*u32,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
pub extern "RPCRT4" fn NdrMesSimpleTypeAlignSize(
param0: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) usize;
pub extern "RPCRT4" fn NdrMesSimpleTypeDecode(
Handle: ?*c_void,
pObject: ?*c_void,
Size: i16,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrMesSimpleTypeEncode(
Handle: ?*c_void,
pStubDesc: ?*const MIDL_STUB_DESC,
pObject: ?*const c_void,
Size: i16,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrMesTypeAlignSize(
Handle: ?*c_void,
pStubDesc: ?*const MIDL_STUB_DESC,
pFormatString: ?*u8,
pObject: ?*const c_void,
) callconv(@import("std").os.windows.WINAPI) usize;
pub extern "RPCRT4" fn NdrMesTypeEncode(
Handle: ?*c_void,
pStubDesc: ?*const MIDL_STUB_DESC,
pFormatString: ?*u8,
pObject: ?*const c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrMesTypeDecode(
Handle: ?*c_void,
pStubDesc: ?*const MIDL_STUB_DESC,
pFormatString: ?*u8,
pObject: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrMesTypeAlignSize2(
Handle: ?*c_void,
pPicklingInfo: ?*const MIDL_TYPE_PICKLING_INFO,
pStubDesc: ?*const MIDL_STUB_DESC,
pFormatString: ?*u8,
pObject: ?*const c_void,
) callconv(@import("std").os.windows.WINAPI) usize;
pub extern "RPCRT4" fn NdrMesTypeEncode2(
Handle: ?*c_void,
pPicklingInfo: ?*const MIDL_TYPE_PICKLING_INFO,
pStubDesc: ?*const MIDL_STUB_DESC,
pFormatString: ?*u8,
pObject: ?*const c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrMesTypeDecode2(
Handle: ?*c_void,
pPicklingInfo: ?*const MIDL_TYPE_PICKLING_INFO,
pStubDesc: ?*const MIDL_STUB_DESC,
pFormatString: ?*u8,
pObject: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrMesTypeFree2(
Handle: ?*c_void,
pPicklingInfo: ?*const MIDL_TYPE_PICKLING_INFO,
pStubDesc: ?*const MIDL_STUB_DESC,
pFormatString: ?*u8,
pObject: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrMesProcEncodeDecode(
Handle: ?*c_void,
pStubDesc: ?*const MIDL_STUB_DESC,
pFormatString: ?*u8,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn NdrMesProcEncodeDecode2(
Handle: ?*c_void,
pStubDesc: ?*const MIDL_STUB_DESC,
pFormatString: ?*u8,
) callconv(@import("std").os.windows.WINAPI) CLIENT_CALL_RETURN;
pub extern "RPCRT4" fn NdrMesTypeAlignSize3(
Handle: ?*c_void,
pPicklingInfo: ?*const MIDL_TYPE_PICKLING_INFO,
pProxyInfo: ?*const MIDL_STUBLESS_PROXY_INFO,
ArrTypeOffset: ?*const ?*u32,
nTypeIndex: u32,
pObject: ?*const c_void,
) callconv(@import("std").os.windows.WINAPI) usize;
pub extern "RPCRT4" fn NdrMesTypeEncode3(
Handle: ?*c_void,
pPicklingInfo: ?*const MIDL_TYPE_PICKLING_INFO,
pProxyInfo: ?*const MIDL_STUBLESS_PROXY_INFO,
ArrTypeOffset: ?*const ?*u32,
nTypeIndex: u32,
pObject: ?*const c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrMesTypeDecode3(
Handle: ?*c_void,
pPicklingInfo: ?*const MIDL_TYPE_PICKLING_INFO,
pProxyInfo: ?*const MIDL_STUBLESS_PROXY_INFO,
ArrTypeOffset: ?*const ?*u32,
nTypeIndex: u32,
pObject: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrMesTypeFree3(
Handle: ?*c_void,
pPicklingInfo: ?*const MIDL_TYPE_PICKLING_INFO,
pProxyInfo: ?*const MIDL_STUBLESS_PROXY_INFO,
ArrTypeOffset: ?*const ?*u32,
nTypeIndex: u32,
pObject: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrMesProcEncodeDecode3(
Handle: ?*c_void,
pProxyInfo: ?*const MIDL_STUBLESS_PROXY_INFO,
nProcNum: u32,
pReturnValue: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) CLIENT_CALL_RETURN;
pub extern "RPCRT4" fn NdrMesSimpleTypeDecodeAll(
Handle: ?*c_void,
pProxyInfo: ?*const MIDL_STUBLESS_PROXY_INFO,
pObject: ?*c_void,
Size: i16,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrMesSimpleTypeEncodeAll(
Handle: ?*c_void,
pProxyInfo: ?*const MIDL_STUBLESS_PROXY_INFO,
pObject: ?*const c_void,
Size: i16,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "RPCRT4" fn NdrMesSimpleTypeAlignSizeAll(
Handle: ?*c_void,
pProxyInfo: ?*const MIDL_STUBLESS_PROXY_INFO,
) callconv(@import("std").os.windows.WINAPI) usize;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcCertGeneratePrincipalNameW(
Context: ?*const CERT_CONTEXT,
Flags: u32,
pBuffer: ?*?*u16,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
// TODO: this type is limited to platform 'windows5.0'
pub extern "RPCRT4" fn RpcCertGeneratePrincipalNameA(
Context: ?*const CERT_CONTEXT,
Flags: u32,
pBuffer: ?*?*u8,
) callconv(@import("std").os.windows.WINAPI) RPC_STATUS;
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (76)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../zig.zig").unicode_mode) {
.ansi => struct {
pub const RPC_PROTSEQ_VECTOR = thismodule.RPC_PROTSEQ_VECTORA;
pub const SEC_WINNT_AUTH_IDENTITY_ = thismodule.SEC_WINNT_AUTH_IDENTITY_A;
pub const RPC_HTTP_TRANSPORT_CREDENTIALS_ = thismodule.RPC_HTTP_TRANSPORT_CREDENTIALS_A;
pub const RPC_HTTP_TRANSPORT_CREDENTIALS_V2_ = thismodule.RPC_HTTP_TRANSPORT_CREDENTIALS_V2_A;
pub const RPC_HTTP_TRANSPORT_CREDENTIALS_V3_ = thismodule.RPC_HTTP_TRANSPORT_CREDENTIALS_V3_A;
pub const RPC_SECURITY_QOS_V2_ = thismodule.RPC_SECURITY_QOS_V2_A;
pub const RPC_SECURITY_QOS_V3_ = thismodule.RPC_SECURITY_QOS_V3_A;
pub const RPC_SECURITY_QOS_V4_ = thismodule.RPC_SECURITY_QOS_V4_A;
pub const RPC_SECURITY_QOS_V5_ = thismodule.RPC_SECURITY_QOS_V5_A;
pub const RPC_BINDING_HANDLE_TEMPLATE_V1_ = thismodule.RPC_BINDING_HANDLE_TEMPLATE_V1_A;
pub const RPC_BINDING_HANDLE_SECURITY_V1_ = thismodule.RPC_BINDING_HANDLE_SECURITY_V1_A;
pub const RPC_ENDPOINT_TEMPLATE = thismodule.RPC_ENDPOINT_TEMPLATEA;
pub const RPC_INTERFACE_TEMPLATE = thismodule.RPC_INTERFACE_TEMPLATEA;
pub const RPC_CALL_ATTRIBUTES_V1_ = thismodule.RPC_CALL_ATTRIBUTES_V1_A;
pub const RPC_CALL_ATTRIBUTES_V2_ = thismodule.RPC_CALL_ATTRIBUTES_V2_A;
pub const RPC_CALL_ATTRIBUTES_V3_ = thismodule.RPC_CALL_ATTRIBUTES_V3_A;
pub const RpcBindingFromStringBinding = thismodule.RpcBindingFromStringBindingA;
pub const RpcBindingToStringBinding = thismodule.RpcBindingToStringBindingA;
pub const RpcStringBindingCompose = thismodule.RpcStringBindingComposeA;
pub const RpcStringBindingParse = thismodule.RpcStringBindingParseA;
pub const RpcStringFree = thismodule.RpcStringFreeA;
pub const RpcNetworkIsProtseqValid = thismodule.RpcNetworkIsProtseqValidA;
pub const RpcNetworkInqProtseqs = thismodule.RpcNetworkInqProtseqsA;
pub const RpcProtseqVectorFree = thismodule.RpcProtseqVectorFreeA;
pub const RpcServerUseProtseq = thismodule.RpcServerUseProtseqA;
pub const RpcServerUseProtseqEx = thismodule.RpcServerUseProtseqExA;
pub const RpcServerUseProtseqEp = thismodule.RpcServerUseProtseqEpA;
pub const RpcServerUseProtseqEpEx = thismodule.RpcServerUseProtseqEpExA;
pub const RpcServerUseProtseqIf = thismodule.RpcServerUseProtseqIfA;
pub const RpcServerUseProtseqIfEx = thismodule.RpcServerUseProtseqIfExA;
pub const RpcMgmtInqServerPrincName = thismodule.RpcMgmtInqServerPrincNameA;
pub const RpcServerInqDefaultPrincName = thismodule.RpcServerInqDefaultPrincNameA;
pub const RpcNsBindingInqEntryName = thismodule.RpcNsBindingInqEntryNameA;
pub const RpcBindingCreate = thismodule.RpcBindingCreateA;
pub const RpcBindingInqAuthClient = thismodule.RpcBindingInqAuthClientA;
pub const RpcBindingInqAuthClientEx = thismodule.RpcBindingInqAuthClientExA;
pub const RpcBindingInqAuthInfo = thismodule.RpcBindingInqAuthInfoA;
pub const RpcBindingSetAuthInfo = thismodule.RpcBindingSetAuthInfoA;
pub const RpcBindingSetAuthInfoEx = thismodule.RpcBindingSetAuthInfoExA;
pub const RpcBindingInqAuthInfoEx = thismodule.RpcBindingInqAuthInfoExA;
pub const RpcServerRegisterAuthInfo = thismodule.RpcServerRegisterAuthInfoA;
pub const UuidToString = thismodule.UuidToStringA;
pub const UuidFromString = thismodule.UuidFromStringA;
pub const RpcEpRegisterNoReplace = thismodule.RpcEpRegisterNoReplaceA;
pub const RpcEpRegister = thismodule.RpcEpRegisterA;
pub const DceErrorInqText = thismodule.DceErrorInqTextA;
pub const RpcMgmtEpEltInqNext = thismodule.RpcMgmtEpEltInqNextA;
pub const RpcServerInterfaceGroupCreate = thismodule.RpcServerInterfaceGroupCreateA;
pub const I_RpcNsBindingSetEntryName = thismodule.I_RpcNsBindingSetEntryNameA;
pub const I_RpcServerUseProtseqEp2 = thismodule.I_RpcServerUseProtseqEp2A;
pub const I_RpcServerUseProtseq2 = thismodule.I_RpcServerUseProtseq2A;
pub const I_RpcBindingInqDynamicEndpoint = thismodule.I_RpcBindingInqDynamicEndpointA;
pub const RpcNsBindingExport = thismodule.RpcNsBindingExportA;
pub const RpcNsBindingUnexport = thismodule.RpcNsBindingUnexportA;
pub const RpcNsBindingExportPnP = thismodule.RpcNsBindingExportPnPA;
pub const RpcNsBindingUnexportPnP = thismodule.RpcNsBindingUnexportPnPA;
pub const RpcNsBindingLookupBegin = thismodule.RpcNsBindingLookupBeginA;
pub const RpcNsGroupDelete = thismodule.RpcNsGroupDeleteA;
pub const RpcNsGroupMbrAdd = thismodule.RpcNsGroupMbrAddA;
pub const RpcNsGroupMbrRemove = thismodule.RpcNsGroupMbrRemoveA;
pub const RpcNsGroupMbrInqBegin = thismodule.RpcNsGroupMbrInqBeginA;
pub const RpcNsGroupMbrInqNext = thismodule.RpcNsGroupMbrInqNextA;
pub const RpcNsProfileDelete = thismodule.RpcNsProfileDeleteA;
pub const RpcNsProfileEltAdd = thismodule.RpcNsProfileEltAddA;
pub const RpcNsProfileEltRemove = thismodule.RpcNsProfileEltRemoveA;
pub const RpcNsProfileEltInqBegin = thismodule.RpcNsProfileEltInqBeginA;
pub const RpcNsProfileEltInqNext = thismodule.RpcNsProfileEltInqNextA;
pub const RpcNsEntryObjectInqBegin = thismodule.RpcNsEntryObjectInqBeginA;
pub const RpcNsEntryExpandName = thismodule.RpcNsEntryExpandNameA;
pub const RpcNsMgmtBindingUnexport = thismodule.RpcNsMgmtBindingUnexportA;
pub const RpcNsMgmtEntryCreate = thismodule.RpcNsMgmtEntryCreateA;
pub const RpcNsMgmtEntryDelete = thismodule.RpcNsMgmtEntryDeleteA;
pub const RpcNsMgmtEntryInqIfIds = thismodule.RpcNsMgmtEntryInqIfIdsA;
pub const RpcNsBindingImportBegin = thismodule.RpcNsBindingImportBeginA;
pub const RpcServerInqCallAttributes = thismodule.RpcServerInqCallAttributesA;
pub const RpcCertGeneratePrincipalName = thismodule.RpcCertGeneratePrincipalNameA;
},
.wide => struct {
pub const RPC_PROTSEQ_VECTOR = thismodule.RPC_PROTSEQ_VECTORW;
pub const SEC_WINNT_AUTH_IDENTITY_ = thismodule.SEC_WINNT_AUTH_IDENTITY_W;
pub const RPC_HTTP_TRANSPORT_CREDENTIALS_ = thismodule.RPC_HTTP_TRANSPORT_CREDENTIALS_W;
pub const RPC_HTTP_TRANSPORT_CREDENTIALS_V2_ = thismodule.RPC_HTTP_TRANSPORT_CREDENTIALS_V2_W;
pub const RPC_HTTP_TRANSPORT_CREDENTIALS_V3_ = thismodule.RPC_HTTP_TRANSPORT_CREDENTIALS_V3_W;
pub const RPC_SECURITY_QOS_V2_ = thismodule.RPC_SECURITY_QOS_V2_W;
pub const RPC_SECURITY_QOS_V3_ = thismodule.RPC_SECURITY_QOS_V3_W;
pub const RPC_SECURITY_QOS_V4_ = thismodule.RPC_SECURITY_QOS_V4_W;
pub const RPC_SECURITY_QOS_V5_ = thismodule.RPC_SECURITY_QOS_V5_W;
pub const RPC_BINDING_HANDLE_TEMPLATE_V1_ = thismodule.RPC_BINDING_HANDLE_TEMPLATE_V1_W;
pub const RPC_BINDING_HANDLE_SECURITY_V1_ = thismodule.RPC_BINDING_HANDLE_SECURITY_V1_W;
pub const RPC_ENDPOINT_TEMPLATE = thismodule.RPC_ENDPOINT_TEMPLATEW;
pub const RPC_INTERFACE_TEMPLATE = thismodule.RPC_INTERFACE_TEMPLATEW;
pub const RPC_CALL_ATTRIBUTES_V1_ = thismodule.RPC_CALL_ATTRIBUTES_V1_W;
pub const RPC_CALL_ATTRIBUTES_V2_ = thismodule.RPC_CALL_ATTRIBUTES_V2_W;
pub const RPC_CALL_ATTRIBUTES_V3_ = thismodule.RPC_CALL_ATTRIBUTES_V3_W;
pub const RpcBindingFromStringBinding = thismodule.RpcBindingFromStringBindingW;
pub const RpcBindingToStringBinding = thismodule.RpcBindingToStringBindingW;
pub const RpcStringBindingCompose = thismodule.RpcStringBindingComposeW;
pub const RpcStringBindingParse = thismodule.RpcStringBindingParseW;
pub const RpcStringFree = thismodule.RpcStringFreeW;
pub const RpcNetworkIsProtseqValid = thismodule.RpcNetworkIsProtseqValidW;
pub const RpcNetworkInqProtseqs = thismodule.RpcNetworkInqProtseqsW;
pub const RpcProtseqVectorFree = thismodule.RpcProtseqVectorFreeW;
pub const RpcServerUseProtseq = thismodule.RpcServerUseProtseqW;
pub const RpcServerUseProtseqEx = thismodule.RpcServerUseProtseqExW;
pub const RpcServerUseProtseqEp = thismodule.RpcServerUseProtseqEpW;
pub const RpcServerUseProtseqEpEx = thismodule.RpcServerUseProtseqEpExW;
pub const RpcServerUseProtseqIf = thismodule.RpcServerUseProtseqIfW;
pub const RpcServerUseProtseqIfEx = thismodule.RpcServerUseProtseqIfExW;
pub const RpcMgmtInqServerPrincName = thismodule.RpcMgmtInqServerPrincNameW;
pub const RpcServerInqDefaultPrincName = thismodule.RpcServerInqDefaultPrincNameW;
pub const RpcNsBindingInqEntryName = thismodule.RpcNsBindingInqEntryNameW;
pub const RpcBindingCreate = thismodule.RpcBindingCreateW;
pub const RpcBindingInqAuthClient = thismodule.RpcBindingInqAuthClientW;
pub const RpcBindingInqAuthClientEx = thismodule.RpcBindingInqAuthClientExW;
pub const RpcBindingInqAuthInfo = thismodule.RpcBindingInqAuthInfoW;
pub const RpcBindingSetAuthInfo = thismodule.RpcBindingSetAuthInfoW;
pub const RpcBindingSetAuthInfoEx = thismodule.RpcBindingSetAuthInfoExW;
pub const RpcBindingInqAuthInfoEx = thismodule.RpcBindingInqAuthInfoExW;
pub const RpcServerRegisterAuthInfo = thismodule.RpcServerRegisterAuthInfoW;
pub const UuidToString = thismodule.UuidToStringW;
pub const UuidFromString = thismodule.UuidFromStringW;
pub const RpcEpRegisterNoReplace = thismodule.RpcEpRegisterNoReplaceW;
pub const RpcEpRegister = thismodule.RpcEpRegisterW;
pub const DceErrorInqText = thismodule.DceErrorInqTextW;
pub const RpcMgmtEpEltInqNext = thismodule.RpcMgmtEpEltInqNextW;
pub const RpcServerInterfaceGroupCreate = thismodule.RpcServerInterfaceGroupCreateW;
pub const I_RpcNsBindingSetEntryName = thismodule.I_RpcNsBindingSetEntryNameW;
pub const I_RpcServerUseProtseqEp2 = thismodule.I_RpcServerUseProtseqEp2W;
pub const I_RpcServerUseProtseq2 = thismodule.I_RpcServerUseProtseq2W;
pub const I_RpcBindingInqDynamicEndpoint = thismodule.I_RpcBindingInqDynamicEndpointW;
pub const RpcNsBindingExport = thismodule.RpcNsBindingExportW;
pub const RpcNsBindingUnexport = thismodule.RpcNsBindingUnexportW;
pub const RpcNsBindingExportPnP = thismodule.RpcNsBindingExportPnPW;
pub const RpcNsBindingUnexportPnP = thismodule.RpcNsBindingUnexportPnPW;
pub const RpcNsBindingLookupBegin = thismodule.RpcNsBindingLookupBeginW;
pub const RpcNsGroupDelete = thismodule.RpcNsGroupDeleteW;
pub const RpcNsGroupMbrAdd = thismodule.RpcNsGroupMbrAddW;
pub const RpcNsGroupMbrRemove = thismodule.RpcNsGroupMbrRemoveW;
pub const RpcNsGroupMbrInqBegin = thismodule.RpcNsGroupMbrInqBeginW;
pub const RpcNsGroupMbrInqNext = thismodule.RpcNsGroupMbrInqNextW;
pub const RpcNsProfileDelete = thismodule.RpcNsProfileDeleteW;
pub const RpcNsProfileEltAdd = thismodule.RpcNsProfileEltAddW;
pub const RpcNsProfileEltRemove = thismodule.RpcNsProfileEltRemoveW;
pub const RpcNsProfileEltInqBegin = thismodule.RpcNsProfileEltInqBeginW;
pub const RpcNsProfileEltInqNext = thismodule.RpcNsProfileEltInqNextW;
pub const RpcNsEntryObjectInqBegin = thismodule.RpcNsEntryObjectInqBeginW;
pub const RpcNsEntryExpandName = thismodule.RpcNsEntryExpandNameW;
pub const RpcNsMgmtBindingUnexport = thismodule.RpcNsMgmtBindingUnexportW;
pub const RpcNsMgmtEntryCreate = thismodule.RpcNsMgmtEntryCreateW;
pub const RpcNsMgmtEntryDelete = thismodule.RpcNsMgmtEntryDeleteW;
pub const RpcNsMgmtEntryInqIfIds = thismodule.RpcNsMgmtEntryInqIfIdsW;
pub const RpcNsBindingImportBegin = thismodule.RpcNsBindingImportBeginW;
pub const RpcServerInqCallAttributes = thismodule.RpcServerInqCallAttributesW;
pub const RpcCertGeneratePrincipalName = thismodule.RpcCertGeneratePrincipalNameW;
},
.unspecified => if (@import("builtin").is_test) struct {
pub const RPC_PROTSEQ_VECTOR = *opaque{};
pub const SEC_WINNT_AUTH_IDENTITY_ = *opaque{};
pub const RPC_HTTP_TRANSPORT_CREDENTIALS_ = *opaque{};
pub const RPC_HTTP_TRANSPORT_CREDENTIALS_V2_ = *opaque{};
pub const RPC_HTTP_TRANSPORT_CREDENTIALS_V3_ = *opaque{};
pub const RPC_SECURITY_QOS_V2_ = *opaque{};
pub const RPC_SECURITY_QOS_V3_ = *opaque{};
pub const RPC_SECURITY_QOS_V4_ = *opaque{};
pub const RPC_SECURITY_QOS_V5_ = *opaque{};
pub const RPC_BINDING_HANDLE_TEMPLATE_V1_ = *opaque{};
pub const RPC_BINDING_HANDLE_SECURITY_V1_ = *opaque{};
pub const RPC_ENDPOINT_TEMPLATE = *opaque{};
pub const RPC_INTERFACE_TEMPLATE = *opaque{};
pub const RPC_CALL_ATTRIBUTES_V1_ = *opaque{};
pub const RPC_CALL_ATTRIBUTES_V2_ = *opaque{};
pub const RPC_CALL_ATTRIBUTES_V3_ = *opaque{};
pub const RpcBindingFromStringBinding = *opaque{};
pub const RpcBindingToStringBinding = *opaque{};
pub const RpcStringBindingCompose = *opaque{};
pub const RpcStringBindingParse = *opaque{};
pub const RpcStringFree = *opaque{};
pub const RpcNetworkIsProtseqValid = *opaque{};
pub const RpcNetworkInqProtseqs = *opaque{};
pub const RpcProtseqVectorFree = *opaque{};
pub const RpcServerUseProtseq = *opaque{};
pub const RpcServerUseProtseqEx = *opaque{};
pub const RpcServerUseProtseqEp = *opaque{};
pub const RpcServerUseProtseqEpEx = *opaque{};
pub const RpcServerUseProtseqIf = *opaque{};
pub const RpcServerUseProtseqIfEx = *opaque{};
pub const RpcMgmtInqServerPrincName = *opaque{};
pub const RpcServerInqDefaultPrincName = *opaque{};
pub const RpcNsBindingInqEntryName = *opaque{};
pub const RpcBindingCreate = *opaque{};
pub const RpcBindingInqAuthClient = *opaque{};
pub const RpcBindingInqAuthClientEx = *opaque{};
pub const RpcBindingInqAuthInfo = *opaque{};
pub const RpcBindingSetAuthInfo = *opaque{};
pub const RpcBindingSetAuthInfoEx = *opaque{};
pub const RpcBindingInqAuthInfoEx = *opaque{};
pub const RpcServerRegisterAuthInfo = *opaque{};
pub const UuidToString = *opaque{};
pub const UuidFromString = *opaque{};
pub const RpcEpRegisterNoReplace = *opaque{};
pub const RpcEpRegister = *opaque{};
pub const DceErrorInqText = *opaque{};
pub const RpcMgmtEpEltInqNext = *opaque{};
pub const RpcServerInterfaceGroupCreate = *opaque{};
pub const I_RpcNsBindingSetEntryName = *opaque{};
pub const I_RpcServerUseProtseqEp2 = *opaque{};
pub const I_RpcServerUseProtseq2 = *opaque{};
pub const I_RpcBindingInqDynamicEndpoint = *opaque{};
pub const RpcNsBindingExport = *opaque{};
pub const RpcNsBindingUnexport = *opaque{};
pub const RpcNsBindingExportPnP = *opaque{};
pub const RpcNsBindingUnexportPnP = *opaque{};
pub const RpcNsBindingLookupBegin = *opaque{};
pub const RpcNsGroupDelete = *opaque{};
pub const RpcNsGroupMbrAdd = *opaque{};
pub const RpcNsGroupMbrRemove = *opaque{};
pub const RpcNsGroupMbrInqBegin = *opaque{};
pub const RpcNsGroupMbrInqNext = *opaque{};
pub const RpcNsProfileDelete = *opaque{};
pub const RpcNsProfileEltAdd = *opaque{};
pub const RpcNsProfileEltRemove = *opaque{};
pub const RpcNsProfileEltInqBegin = *opaque{};
pub const RpcNsProfileEltInqNext = *opaque{};
pub const RpcNsEntryObjectInqBegin = *opaque{};
pub const RpcNsEntryExpandName = *opaque{};
pub const RpcNsMgmtBindingUnexport = *opaque{};
pub const RpcNsMgmtEntryCreate = *opaque{};
pub const RpcNsMgmtEntryDelete = *opaque{};
pub const RpcNsMgmtEntryInqIfIds = *opaque{};
pub const RpcNsBindingImportBegin = *opaque{};
pub const RpcServerInqCallAttributes = *opaque{};
pub const RpcCertGeneratePrincipalName = *opaque{};
} else struct {
pub const RPC_PROTSEQ_VECTOR = @compileError("'RPC_PROTSEQ_VECTOR' requires that UNICODE be set to true or false in the root module");
pub const SEC_WINNT_AUTH_IDENTITY_ = @compileError("'SEC_WINNT_AUTH_IDENTITY_' requires that UNICODE be set to true or false in the root module");
pub const RPC_HTTP_TRANSPORT_CREDENTIALS_ = @compileError("'RPC_HTTP_TRANSPORT_CREDENTIALS_' requires that UNICODE be set to true or false in the root module");
pub const RPC_HTTP_TRANSPORT_CREDENTIALS_V2_ = @compileError("'RPC_HTTP_TRANSPORT_CREDENTIALS_V2_' requires that UNICODE be set to true or false in the root module");
pub const RPC_HTTP_TRANSPORT_CREDENTIALS_V3_ = @compileError("'RPC_HTTP_TRANSPORT_CREDENTIALS_V3_' requires that UNICODE be set to true or false in the root module");
pub const RPC_SECURITY_QOS_V2_ = @compileError("'RPC_SECURITY_QOS_V2_' requires that UNICODE be set to true or false in the root module");
pub const RPC_SECURITY_QOS_V3_ = @compileError("'RPC_SECURITY_QOS_V3_' requires that UNICODE be set to true or false in the root module");
pub const RPC_SECURITY_QOS_V4_ = @compileError("'RPC_SECURITY_QOS_V4_' requires that UNICODE be set to true or false in the root module");
pub const RPC_SECURITY_QOS_V5_ = @compileError("'RPC_SECURITY_QOS_V5_' requires that UNICODE be set to true or false in the root module");
pub const RPC_BINDING_HANDLE_TEMPLATE_V1_ = @compileError("'RPC_BINDING_HANDLE_TEMPLATE_V1_' requires that UNICODE be set to true or false in the root module");
pub const RPC_BINDING_HANDLE_SECURITY_V1_ = @compileError("'RPC_BINDING_HANDLE_SECURITY_V1_' requires that UNICODE be set to true or false in the root module");
pub const RPC_ENDPOINT_TEMPLATE = @compileError("'RPC_ENDPOINT_TEMPLATE' requires that UNICODE be set to true or false in the root module");
pub const RPC_INTERFACE_TEMPLATE = @compileError("'RPC_INTERFACE_TEMPLATE' requires that UNICODE be set to true or false in the root module");
pub const RPC_CALL_ATTRIBUTES_V1_ = @compileError("'RPC_CALL_ATTRIBUTES_V1_' requires that UNICODE be set to true or false in the root module");
pub const RPC_CALL_ATTRIBUTES_V2_ = @compileError("'RPC_CALL_ATTRIBUTES_V2_' requires that UNICODE be set to true or false in the root module");
pub const RPC_CALL_ATTRIBUTES_V3_ = @compileError("'RPC_CALL_ATTRIBUTES_V3_' requires that UNICODE be set to true or false in the root module");
pub const RpcBindingFromStringBinding = @compileError("'RpcBindingFromStringBinding' requires that UNICODE be set to true or false in the root module");
pub const RpcBindingToStringBinding = @compileError("'RpcBindingToStringBinding' requires that UNICODE be set to true or false in the root module");
pub const RpcStringBindingCompose = @compileError("'RpcStringBindingCompose' requires that UNICODE be set to true or false in the root module");
pub const RpcStringBindingParse = @compileError("'RpcStringBindingParse' requires that UNICODE be set to true or false in the root module");
pub const RpcStringFree = @compileError("'RpcStringFree' requires that UNICODE be set to true or false in the root module");
pub const RpcNetworkIsProtseqValid = @compileError("'RpcNetworkIsProtseqValid' requires that UNICODE be set to true or false in the root module");
pub const RpcNetworkInqProtseqs = @compileError("'RpcNetworkInqProtseqs' requires that UNICODE be set to true or false in the root module");
pub const RpcProtseqVectorFree = @compileError("'RpcProtseqVectorFree' requires that UNICODE be set to true or false in the root module");
pub const RpcServerUseProtseq = @compileError("'RpcServerUseProtseq' requires that UNICODE be set to true or false in the root module");
pub const RpcServerUseProtseqEx = @compileError("'RpcServerUseProtseqEx' requires that UNICODE be set to true or false in the root module");
pub const RpcServerUseProtseqEp = @compileError("'RpcServerUseProtseqEp' requires that UNICODE be set to true or false in the root module");
pub const RpcServerUseProtseqEpEx = @compileError("'RpcServerUseProtseqEpEx' requires that UNICODE be set to true or false in the root module");
pub const RpcServerUseProtseqIf = @compileError("'RpcServerUseProtseqIf' requires that UNICODE be set to true or false in the root module");
pub const RpcServerUseProtseqIfEx = @compileError("'RpcServerUseProtseqIfEx' requires that UNICODE be set to true or false in the root module");
pub const RpcMgmtInqServerPrincName = @compileError("'RpcMgmtInqServerPrincName' requires that UNICODE be set to true or false in the root module");
pub const RpcServerInqDefaultPrincName = @compileError("'RpcServerInqDefaultPrincName' requires that UNICODE be set to true or false in the root module");
pub const RpcNsBindingInqEntryName = @compileError("'RpcNsBindingInqEntryName' requires that UNICODE be set to true or false in the root module");
pub const RpcBindingCreate = @compileError("'RpcBindingCreate' requires that UNICODE be set to true or false in the root module");
pub const RpcBindingInqAuthClient = @compileError("'RpcBindingInqAuthClient' requires that UNICODE be set to true or false in the root module");
pub const RpcBindingInqAuthClientEx = @compileError("'RpcBindingInqAuthClientEx' requires that UNICODE be set to true or false in the root module");
pub const RpcBindingInqAuthInfo = @compileError("'RpcBindingInqAuthInfo' requires that UNICODE be set to true or false in the root module");
pub const RpcBindingSetAuthInfo = @compileError("'RpcBindingSetAuthInfo' requires that UNICODE be set to true or false in the root module");
pub const RpcBindingSetAuthInfoEx = @compileError("'RpcBindingSetAuthInfoEx' requires that UNICODE be set to true or false in the root module");
pub const RpcBindingInqAuthInfoEx = @compileError("'RpcBindingInqAuthInfoEx' requires that UNICODE be set to true or false in the root module");
pub const RpcServerRegisterAuthInfo = @compileError("'RpcServerRegisterAuthInfo' requires that UNICODE be set to true or false in the root module");
pub const UuidToString = @compileError("'UuidToString' requires that UNICODE be set to true or false in the root module");
pub const UuidFromString = @compileError("'UuidFromString' requires that UNICODE be set to true or false in the root module");
pub const RpcEpRegisterNoReplace = @compileError("'RpcEpRegisterNoReplace' requires that UNICODE be set to true or false in the root module");
pub const RpcEpRegister = @compileError("'RpcEpRegister' requires that UNICODE be set to true or false in the root module");
pub const DceErrorInqText = @compileError("'DceErrorInqText' requires that UNICODE be set to true or false in the root module");
pub const RpcMgmtEpEltInqNext = @compileError("'RpcMgmtEpEltInqNext' requires that UNICODE be set to true or false in the root module");
pub const RpcServerInterfaceGroupCreate = @compileError("'RpcServerInterfaceGroupCreate' requires that UNICODE be set to true or false in the root module");
pub const I_RpcNsBindingSetEntryName = @compileError("'I_RpcNsBindingSetEntryName' requires that UNICODE be set to true or false in the root module");
pub const I_RpcServerUseProtseqEp2 = @compileError("'I_RpcServerUseProtseqEp2' requires that UNICODE be set to true or false in the root module");
pub const I_RpcServerUseProtseq2 = @compileError("'I_RpcServerUseProtseq2' requires that UNICODE be set to true or false in the root module");
pub const I_RpcBindingInqDynamicEndpoint = @compileError("'I_RpcBindingInqDynamicEndpoint' requires that UNICODE be set to true or false in the root module");
pub const RpcNsBindingExport = @compileError("'RpcNsBindingExport' requires that UNICODE be set to true or false in the root module");
pub const RpcNsBindingUnexport = @compileError("'RpcNsBindingUnexport' requires that UNICODE be set to true or false in the root module");
pub const RpcNsBindingExportPnP = @compileError("'RpcNsBindingExportPnP' requires that UNICODE be set to true or false in the root module");
pub const RpcNsBindingUnexportPnP = @compileError("'RpcNsBindingUnexportPnP' requires that UNICODE be set to true or false in the root module");
pub const RpcNsBindingLookupBegin = @compileError("'RpcNsBindingLookupBegin' requires that UNICODE be set to true or false in the root module");
pub const RpcNsGroupDelete = @compileError("'RpcNsGroupDelete' requires that UNICODE be set to true or false in the root module");
pub const RpcNsGroupMbrAdd = @compileError("'RpcNsGroupMbrAdd' requires that UNICODE be set to true or false in the root module");
pub const RpcNsGroupMbrRemove = @compileError("'RpcNsGroupMbrRemove' requires that UNICODE be set to true or false in the root module");
pub const RpcNsGroupMbrInqBegin = @compileError("'RpcNsGroupMbrInqBegin' requires that UNICODE be set to true or false in the root module");
pub const RpcNsGroupMbrInqNext = @compileError("'RpcNsGroupMbrInqNext' requires that UNICODE be set to true or false in the root module");
pub const RpcNsProfileDelete = @compileError("'RpcNsProfileDelete' requires that UNICODE be set to true or false in the root module");
pub const RpcNsProfileEltAdd = @compileError("'RpcNsProfileEltAdd' requires that UNICODE be set to true or false in the root module");
pub const RpcNsProfileEltRemove = @compileError("'RpcNsProfileEltRemove' requires that UNICODE be set to true or false in the root module");
pub const RpcNsProfileEltInqBegin = @compileError("'RpcNsProfileEltInqBegin' requires that UNICODE be set to true or false in the root module");
pub const RpcNsProfileEltInqNext = @compileError("'RpcNsProfileEltInqNext' requires that UNICODE be set to true or false in the root module");
pub const RpcNsEntryObjectInqBegin = @compileError("'RpcNsEntryObjectInqBegin' requires that UNICODE be set to true or false in the root module");
pub const RpcNsEntryExpandName = @compileError("'RpcNsEntryExpandName' requires that UNICODE be set to true or false in the root module");
pub const RpcNsMgmtBindingUnexport = @compileError("'RpcNsMgmtBindingUnexport' requires that UNICODE be set to true or false in the root module");
pub const RpcNsMgmtEntryCreate = @compileError("'RpcNsMgmtEntryCreate' requires that UNICODE be set to true or false in the root module");
pub const RpcNsMgmtEntryDelete = @compileError("'RpcNsMgmtEntryDelete' requires that UNICODE be set to true or false in the root module");
pub const RpcNsMgmtEntryInqIfIds = @compileError("'RpcNsMgmtEntryInqIfIds' requires that UNICODE be set to true or false in the root module");
pub const RpcNsBindingImportBegin = @compileError("'RpcNsBindingImportBegin' requires that UNICODE be set to true or false in the root module");
pub const RpcServerInqCallAttributes = @compileError("'RpcServerInqCallAttributes' requires that UNICODE be set to true or false in the root module");
pub const RpcCertGeneratePrincipalName = @compileError("'RpcCertGeneratePrincipalName' requires that UNICODE be set to true or false in the root module");
},
};
//--------------------------------------------------------------------------------
// Section: Imports (17)
//--------------------------------------------------------------------------------
const Guid = @import("../zig.zig").Guid;
const BOOL = @import("../foundation.zig").BOOL;
const CERT_CONTEXT = @import("../security/cryptography/core.zig").CERT_CONTEXT;
const FILETIME = @import("../foundation.zig").FILETIME;
const HANDLE = @import("../foundation.zig").HANDLE;
const HRESULT = @import("../foundation.zig").HRESULT;
const HWND = @import("../foundation.zig").HWND;
const IRpcChannelBuffer = @import("../system/com.zig").IRpcChannelBuffer;
const IRpcStubBuffer = @import("../system/com.zig").IRpcStubBuffer;
const IUnknown = @import("../system/com.zig").IUnknown;
const LARGE_INTEGER = @import("../system/system_services.zig").LARGE_INTEGER;
const LUID = @import("../system/system_services.zig").LUID;
const OVERLAPPED = @import("../system/system_services.zig").OVERLAPPED;
const PSTR = @import("../foundation.zig").PSTR;
const PWSTR = @import("../foundation.zig").PWSTR;
const RPC_C_IMP_LEVEL = @import("../system/com.zig").RPC_C_IMP_LEVEL;
const SYSTEMTIME = @import("../foundation.zig").SYSTEMTIME;
test {
// The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476
if (@hasDecl(@This(), "RPC_OBJECT_INQ_FN")) { _ = RPC_OBJECT_INQ_FN; }
if (@hasDecl(@This(), "RPC_IF_CALLBACK_FN")) { _ = RPC_IF_CALLBACK_FN; }
if (@hasDecl(@This(), "RPC_SECURITY_CALLBACK_FN")) { _ = RPC_SECURITY_CALLBACK_FN; }
if (@hasDecl(@This(), "RPC_NEW_HTTP_PROXY_CHANNEL")) { _ = RPC_NEW_HTTP_PROXY_CHANNEL; }
if (@hasDecl(@This(), "RPC_HTTP_PROXY_FREE_STRING")) { _ = RPC_HTTP_PROXY_FREE_STRING; }
if (@hasDecl(@This(), "RPC_AUTH_KEY_RETRIEVAL_FN")) { _ = RPC_AUTH_KEY_RETRIEVAL_FN; }
if (@hasDecl(@This(), "RPC_MGMT_AUTHORIZATION_FN")) { _ = RPC_MGMT_AUTHORIZATION_FN; }
if (@hasDecl(@This(), "RPC_INTERFACE_GROUP_IDLE_CALLBACK_FN")) { _ = RPC_INTERFACE_GROUP_IDLE_CALLBACK_FN; }
if (@hasDecl(@This(), "RPC_FORWARD_FUNCTION")) { _ = RPC_FORWARD_FUNCTION; }
if (@hasDecl(@This(), "RPC_ADDRESS_CHANGE_FN")) { _ = RPC_ADDRESS_CHANGE_FN; }
if (@hasDecl(@This(), "RPC_DISPATCH_FUNCTION")) { _ = RPC_DISPATCH_FUNCTION; }
if (@hasDecl(@This(), "PRPC_RUNDOWN")) { _ = PRPC_RUNDOWN; }
if (@hasDecl(@This(), "RPCLT_PDU_FILTER_FUNC")) { _ = RPCLT_PDU_FILTER_FUNC; }
if (@hasDecl(@This(), "RPC_SETFILTER_FUNC")) { _ = RPC_SETFILTER_FUNC; }
if (@hasDecl(@This(), "RPC_BLOCKING_FN")) { _ = RPC_BLOCKING_FN; }
if (@hasDecl(@This(), "I_RpcProxyIsValidMachineFn")) { _ = I_RpcProxyIsValidMachineFn; }
if (@hasDecl(@This(), "I_RpcProxyGetClientAddressFn")) { _ = I_RpcProxyGetClientAddressFn; }
if (@hasDecl(@This(), "I_RpcProxyGetConnectionTimeoutFn")) { _ = I_RpcProxyGetConnectionTimeoutFn; }
if (@hasDecl(@This(), "I_RpcPerformCalloutFn")) { _ = I_RpcPerformCalloutFn; }
if (@hasDecl(@This(), "I_RpcFreeCalloutStateFn")) { _ = I_RpcFreeCalloutStateFn; }
if (@hasDecl(@This(), "I_RpcProxyGetClientSessionAndResourceUUID")) { _ = I_RpcProxyGetClientSessionAndResourceUUID; }
if (@hasDecl(@This(), "I_RpcProxyFilterIfFn")) { _ = I_RpcProxyFilterIfFn; }
if (@hasDecl(@This(), "I_RpcProxyUpdatePerfCounterFn")) { _ = I_RpcProxyUpdatePerfCounterFn; }
if (@hasDecl(@This(), "I_RpcProxyUpdatePerfCounterBackendServerFn")) { _ = I_RpcProxyUpdatePerfCounterBackendServerFn; }
if (@hasDecl(@This(), "PFN_RPCNOTIFICATION_ROUTINE")) { _ = PFN_RPCNOTIFICATION_ROUTINE; }
if (@hasDecl(@This(), "NDR_RUNDOWN")) { _ = NDR_RUNDOWN; }
if (@hasDecl(@This(), "NDR_NOTIFY_ROUTINE")) { _ = NDR_NOTIFY_ROUTINE; }
if (@hasDecl(@This(), "NDR_NOTIFY2_ROUTINE")) { _ = NDR_NOTIFY2_ROUTINE; }
if (@hasDecl(@This(), "EXPR_EVAL")) { _ = EXPR_EVAL; }
if (@hasDecl(@This(), "GENERIC_BINDING_ROUTINE")) { _ = GENERIC_BINDING_ROUTINE; }
if (@hasDecl(@This(), "GENERIC_UNBIND_ROUTINE")) { _ = GENERIC_UNBIND_ROUTINE; }
if (@hasDecl(@This(), "XMIT_HELPER_ROUTINE")) { _ = XMIT_HELPER_ROUTINE; }
if (@hasDecl(@This(), "USER_MARSHAL_SIZING_ROUTINE")) { _ = USER_MARSHAL_SIZING_ROUTINE; }
if (@hasDecl(@This(), "USER_MARSHAL_MARSHALLING_ROUTINE")) { _ = USER_MARSHAL_MARSHALLING_ROUTINE; }
if (@hasDecl(@This(), "USER_MARSHAL_UNMARSHALLING_ROUTINE")) { _ = USER_MARSHAL_UNMARSHALLING_ROUTINE; }
if (@hasDecl(@This(), "USER_MARSHAL_FREEING_ROUTINE")) { _ = USER_MARSHAL_FREEING_ROUTINE; }
if (@hasDecl(@This(), "CS_TYPE_NET_SIZE_ROUTINE")) { _ = CS_TYPE_NET_SIZE_ROUTINE; }
if (@hasDecl(@This(), "CS_TYPE_LOCAL_SIZE_ROUTINE")) { _ = CS_TYPE_LOCAL_SIZE_ROUTINE; }
if (@hasDecl(@This(), "CS_TYPE_TO_NETCS_ROUTINE")) { _ = CS_TYPE_TO_NETCS_ROUTINE; }
if (@hasDecl(@This(), "CS_TYPE_FROM_NETCS_ROUTINE")) { _ = CS_TYPE_FROM_NETCS_ROUTINE; }
if (@hasDecl(@This(), "CS_TAG_GETTING_ROUTINE")) { _ = CS_TAG_GETTING_ROUTINE; }
if (@hasDecl(@This(), "STUB_THUNK")) { _ = STUB_THUNK; }
if (@hasDecl(@This(), "SERVER_ROUTINE")) { _ = SERVER_ROUTINE; }
if (@hasDecl(@This(), "RPC_CLIENT_ALLOC")) { _ = RPC_CLIENT_ALLOC; }
if (@hasDecl(@This(), "RPC_CLIENT_FREE")) { _ = RPC_CLIENT_FREE; }
if (@hasDecl(@This(), "MIDL_ES_ALLOC")) { _ = MIDL_ES_ALLOC; }
if (@hasDecl(@This(), "MIDL_ES_WRITE")) { _ = MIDL_ES_WRITE; }
if (@hasDecl(@This(), "MIDL_ES_READ")) { _ = MIDL_ES_READ; }
@setEvalBranchQuota(
@import("std").meta.declarations(@This()).len * 3
);
// reference all the pub declarations
if (!@import("builtin").is_test) return;
inline for (@import("std").meta.declarations(@This())) |decl| {
if (decl.is_pub) {
_ = decl;
}
}
} | deps/zigwin32/win32/system/rpc.zig |
const tty = @import("tty.zig");
const cstr = @import("std").cstr;
const Process = @import("process.zig").Process;
// This should be in EAX.
pub const MULTIBOOT_BOOTLOADER_MAGIC = 0x2BADB002;
// Is there basic lower/upper memory information?
pub const MULTIBOOT_INFO_MEMORY = 0x00000001;
// Is there a full memory map?
pub const MULTIBOOT_INFO_MEM_MAP = 0x00000040;
// System information structure passed by the bootloader.
pub const MultibootInfo = packed struct {
// Multiboot info version number.
flags: u32,
// Available memory from BIOS.
mem_lower: u32,
mem_upper: u32,
// "root" partition.
boot_device: u32,
// Kernel command line.
cmdline: u32,
// Boot-Module list.
mods_count: u32,
mods_addr: u32,
// TODO: use the real types here.
u: u128,
// Memory Mapping buffer.
mmap_length: u32,
mmap_addr: u32,
// Drive Info buffer.
drives_length: u32,
drives_addr: u32,
// ROM configuration table.
config_table: u32,
// Boot Loader Name.
boot_loader_name: u32,
// APM table.
apm_table: u32,
// Video.
vbe_control_info: u32,
vbe_mode_info: u32,
vbe_mode: u16,
vbe_interface_seg: u16,
vbe_interface_off: u16,
vbe_interface_len: u16,
////
// Return the ending address of the last module.
//
pub fn lastModuleEnd(self: *const MultibootInfo) usize {
const mods = @intToPtr([*]MultibootModule, self.mods_addr);
return mods[self.mods_count - 1].mod_end;
}
////
// Load all the modules passed by the bootloader.
//
pub fn loadModules(self: *const MultibootInfo) void {
const mods = @intToPtr([*]MultibootModule, self.mods_addr)[0..self.mods_count];
for (mods) |mod| {
const cmdline = cstr.toSlice(@intToPtr([*]u8, mod.cmdline));
tty.step("Loading \"{}\"", cmdline);
_ = Process.create(mod.mod_start, null);
// TODO: deallocate the original memory.
tty.stepOK();
}
}
};
// Types of memory map entries.
pub const MULTIBOOT_MEMORY_AVAILABLE = 1;
pub const MULTIBOOT_MEMORY_RESERVED = 2;
// Entries in the memory map.
pub const MultibootMMapEntry = packed struct {
size: u32,
addr: u64,
len: u64,
type: u32,
};
pub const MultibootModule = packed struct {
// The memory used goes from bytes 'mod_start' to 'mod_end-1' inclusive.
mod_start: u32,
mod_end: u32,
cmdline: u32, // Module command line.
pad: u32, // Padding to take it to 16 bytes (must be zero).
};
// Multiboot structure to be read by the bootloader.
const MultibootHeader = packed struct {
magic: u32, // Must be equal to header magic number.
flags: u32, // Feature flags.
checksum: u32, // Above fields plus this one must equal 0 mod 2^32.
};
// NOTE: this structure is incomplete.
// Place the header at the very beginning of the binary.
export const multiboot_header align(4) linksection(".multiboot") = multiboot: {
const MAGIC = u32(0x1BADB002); // Magic number for validation.
const ALIGN = u32(1 << 0); // Align loaded modules.
const MEMINFO = u32(1 << 1); // Receive a memory map from the bootloader.
const FLAGS = ALIGN | MEMINFO; // Combine the flags.
break :multiboot MultibootHeader {
.magic = MAGIC,
.flags = FLAGS,
.checksum = ~(MAGIC +% FLAGS) +% 1,
};
}; | kernel/multiboot.zig |
const std = @import("std");
const getty = @import("../../../lib.zig");
pub fn Visitor(comptime Tuple: type) type {
return struct {
allocator: ?std.mem.Allocator = null,
const Self = @This();
const impl = @"impl Visitor"(Tuple);
pub usingnamespace getty.de.Visitor(
Self,
impl.visitor.Value,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
impl.visitor.visitSequence,
undefined,
undefined,
undefined,
);
};
}
fn @"impl Visitor"(comptime Tuple: type) type {
const Self = Visitor(Tuple);
return struct {
pub const visitor = struct {
pub const Value = Tuple;
pub fn visitSequence(self: Self, sequenceAccess: anytype) @TypeOf(sequenceAccess).Error!Value {
_ = self;
var seq: Value = undefined;
//var seen: usize = 0;
//errdefer {
//comptime var i: usize = 0;
//if (self.allocator) |allocator| {
//if (length > 0) {
//inline while (i < seen) : (i += 1) {
//getty.de.free(allocator, seq[i]);
//}
//}
//}
//}
switch (length) {
0 => seq = .{},
else => {
comptime var i: usize = 0;
inline while (i < length) : (i += 1) {
// NOTE: Using an if to unwrap `value` runs into a
// compiler bug, so this is a workaround.
const value = try sequenceAccess.nextElement(fields[i].field_type);
if (value == null) return error.InvalidLength;
seq[i] = value.?;
}
},
}
// Expected end of sequence, but found an element.
if ((try sequenceAccess.nextElement(void)) != null) {
return error.InvalidLength;
}
return seq;
}
};
const fields = std.meta.fields(Tuple);
const length = std.meta.fields(Tuple).len;
};
} | src/de/impl/visitor/tuple.zig |
const std = @import("std");
const Context = @import("Context.zig");
const Lexer = @import("Lexer.zig");
const Location = @import("Location.zig");
const Node = @import("Node.zig");
const Token = @import("Token.zig");
allocator: std.mem.Allocator,
can_break: bool = false, // Parsing a loop?
ctx: Context,
range_id: u8 = 0,
token_index: ?u16 = null,
tokens: std.MultiArrayList(Token),
const Parser = @This();
pub const Program = struct {
inits: []Node,
files: []Node,
recs: []Node,
rules: []Node,
exits: []Node,
};
pub fn parse(self: *Parser) !Program {
var inits = std.ArrayList(Node).init(self.allocator);
var files = std.ArrayList(Node).init(self.allocator);
var recs = std.ArrayList(Node).init(self.allocator);
var rules = std.ArrayList(Node).init(self.allocator);
var exits = std.ArrayList(Node).init(self.allocator);
while (try self.next()) |node| {
if (node.ty == .event) {
switch (node.ty.event.ty) {
.init => for (node.ty.event.nodes) |n| {
try inits.append(n);
try inits.append(Node.new(.stmt_end, 0)); // Stack clean up.
},
.file => for (node.ty.event.nodes) |n| {
try files.append(n);
try files.append(Node.new(.stmt_end, 0)); // Stack clean up.
},
.rec => for (node.ty.event.nodes) |n| {
try recs.append(n);
try recs.append(Node.new(.stmt_end, 0)); // Stack clean up.
},
.exit => for (node.ty.event.nodes) |n| {
try exits.append(n);
try exits.append(Node.new(.stmt_end, 0)); // Stack clean up.
},
}
} else {
try rules.append(node);
try rules.append(Node.new(.stmt_end, 0)); // Stack clean up.
}
}
return Program{
.inits = inits.items,
.files = files.items,
.recs = recs.items,
.rules = rules.items,
.exits = exits.items,
};
}
fn next(self: *Parser) anyerror!?Node {
return if (self.advance()) switch (self.currentTag()) {
.punct_semicolon => try self.next(),
else => try self.parseExpression(.lowest),
} else null;
}
// Pratt Parser
const Precedence = enum {
lowest,
redir,
print,
assign,
elvis,
ternary,
logic_or,
logic_and,
compare,
range,
sum,
product,
subscript,
mselect,
call,
prefix,
fn demote(self: *Precedence) void {
self.* = @intToEnum(Precedence, @enumToInt(self.*) - 1);
}
fn forTag(tag: Token.Tag) Precedence {
return switch (tag) {
.op_redir_append, .op_redir_clobber => .redir,
.op_add_eq,
.op_sub_eq,
.op_mul_eq,
.op_div_eq,
.op_mod_eq,
.punct_equals,
.op_define,
.op_elvis_eq,
=> .assign,
.op_elvis => .elvis,
.punct_question => .ternary,
.kw_or => .logic_or,
.kw_and => .logic_and,
.punct_lt,
.punct_gt,
.punct_tilde,
.op_match,
.op_matcher,
.op_nomatch,
.op_lte,
.op_gte,
.op_eq,
.op_neq,
=> .compare,
.op_range_ex, .op_range_in => .range,
.punct_plus,
.punct_minus,
.op_concat,
=> .sum,
.punct_star,
.punct_slash,
.punct_percent,
.op_repeat,
=> .product,
.punct_dot => .mselect,
.punct_lparen => .call,
.punct_lbracket => .subscript,
else => .lowest,
};
}
fn lessThan(self: Precedence, other: Precedence) bool {
return @enumToInt(self) < @enumToInt(other);
}
fn isRightAssociative(tag: Token.Tag) bool {
return switch (tag) {
.op_add_eq,
.op_sub_eq,
.op_mul_eq,
.op_div_eq,
.op_mod_eq,
.punct_equals,
.op_define,
.op_redir_append,
.op_redir_clobber,
=> true,
else => false,
};
}
};
const PrefixFn = fn (*Parser) anyerror!Node;
const InfixFn = fn (*Parser, Node) anyerror!Node;
fn prefixFn(tag: Token.Tag) ?PrefixFn {
return switch (tag) {
.float => Parser.parseFloat,
.ident => Parser.parseIdent,
.int => Parser.parseInt,
.raw_str => Parser.parseRawStr,
.string => Parser.parseString,
.uint => Parser.parseUint,
.kw_break => Parser.parseBreak,
.kw_continue => Parser.parseContinue,
.kw_do => Parser.parseDoWhile,
.kw_if => Parser.parseIf,
.kw_return => Parser.parseReturn,
.kw_select => Parser.parseRecRange,
.kw_while => Parser.parseWhile,
.at_cols,
.at_file,
.at_frnum,
.at_head,
.at_headers,
.at_ics,
.at_irs,
.at_ocs,
.at_ors,
.at_rec,
.at_rnum,
=> Parser.parseGlobal,
.op_neg, .punct_bang => Parser.parsePrefix,
.pd_false, .pd_true => Parser.parseBoolean,
.pd_nil => Parser.parseNil,
.pd_assert,
.pd_atan2,
.pd_capture,
.pd_chars,
.pd_col,
.pd_contains,
.pd_cos,
.pd_each,
.pd_endsWith,
.pd_exp,
.pd_filter,
.pd_int,
.pd_indexOf,
.pd_join,
.pd_keys,
.pd_keysByValueAsc,
.pd_keysByValueDesc,
.pd_lastIndexOf,
.pd_len,
.pd_log,
.pd_map,
.pd_max,
.pd_mean,
.pd_median,
.pd_memo,
.pd_min,
.pd_mode,
.pd_next,
.pd_print,
.pd_pop,
.pd_push,
.pd_rand,
.pd_reduce,
.pd_replace,
.pd_reset,
.pd_reverse,
.pd_sin,
.pd_sortAsc,
.pd_sortDesc,
.pd_split,
.pd_sqrt,
.pd_startsWith,
.pd_stdev,
.pd_toLower,
.pd_toUpper,
.pd_unique,
.pd_values,
=> Parser.parseBuiltin,
.pd_onInit,
.pd_onFile,
.pd_onRec,
.pd_onExit,
=> Parser.parseEvent,
.punct_lbrace => Parser.parseFunc,
.punct_lbracket => Parser.parseList,
.punct_lparen => Parser.parseGrouped,
else => null,
};
}
fn infixFn(self: Parser) InfixFn {
return switch (self.currentTag()) {
.punct_plus,
.punct_minus,
.punct_star,
.punct_slash,
.punct_percent,
.punct_lt,
.op_lte,
.punct_gt,
.op_gte,
.op_eq,
.op_neq,
.kw_and,
.kw_or,
.op_concat,
.op_repeat,
.op_match,
.op_matcher,
.op_nomatch,
=> Parser.parseInfix,
.punct_equals,
.op_add_eq,
.op_sub_eq,
.op_mul_eq,
.op_div_eq,
.op_mod_eq,
=> Parser.parseAssign,
.op_define => Parser.parseDefine,
.op_elvis => Parser.parseElvis,
.op_elvis_eq => Parser.parseElvisAssign,
.op_range_ex, .op_range_in => Parser.parseRange,
.op_redir_append, .op_redir_clobber => Parser.parseRedir,
.punct_dot => Parser.parseBuiltinMethod,
.punct_lbracket => Parser.parseSubscript,
.punct_lparen => Parser.parseCall,
.punct_question => Parser.parseTernary,
else => unreachable,
};
}
fn parseExpression(self: *Parser, precedence: Precedence) anyerror!Node {
const tag = self.currentTag();
const pfn = prefixFn(tag) orelse return self.ctx.err(
"No parse function for {}.",
.{tag},
error.NoParseFn,
self.currentOffset(),
);
var left = try pfn(self);
while (self.peekPrecedence()) |peek_prec| {
if (!precedence.lessThan(peek_prec)) break;
_ = self.advance();
const ifn = self.infixFn();
left = try ifn(self, left);
}
return left;
}
// Parse functions.
fn parseAssign(self: *Parser, lvalue: Node) anyerror!Node {
if (lvalue.ty != .ident and
lvalue.ty != .subscript and
lvalue.ty != .global) return self.ctx.err(
"{s} = ?",
.{@tagName(lvalue.ty)},
error.InvalidAssignment,
lvalue.offset,
);
const combo: Node.Combo = switch (self.currentTag()) {
.punct_equals => .none,
.op_add_eq => .add,
.op_sub_eq => .sub,
.op_mul_eq => .mul,
.op_div_eq => .div,
.op_mod_eq => .mod,
else => unreachable,
};
var node = Node.new(
.{ .assign = .{
.combo = combo,
.lvalue = try self.allocator.create(Node),
.rvalue = try self.allocator.create(Node),
} },
self.currentOffset(),
);
node.ty.assign.lvalue.* = lvalue;
try self.expectNext();
node.ty.assign.rvalue.* = try self.parseExpression(.lowest);
return node;
}
fn parseBoolean(self: *Parser) anyerror!Node {
return Node.new(.{ .boolean = self.currentIs(.pd_true) }, self.currentOffset());
}
fn parseBreak(self: *Parser) anyerror!Node {
if (!self.can_break) return self.ctx.err(
"Invalid break.",
.{},
error.InvalidBreak,
self.currentOffset(),
);
return Node.new(.loop_break, self.currentOffset());
}
fn parseBuiltin(self: *Parser) anyerror!Node {
return Node.new(.{ .builtin = self.currentTag() }, self.currentOffset());
}
pub fn isBuiltinMethod(tag: Token.Tag) bool {
return switch (tag) {
.pd_capture,
.pd_chars,
.pd_contains,
.pd_each,
.pd_endsWith,
.pd_filter,
.pd_indexOf,
.pd_join,
.pd_keys,
.pd_keysByValueAsc,
.pd_keysByValueDesc,
.pd_lastIndexOf,
.pd_len,
.pd_map,
.pd_max,
.pd_mean,
.pd_median,
.pd_min,
.pd_mode,
.pd_next,
.pd_pop,
.pd_push,
.pd_reduce,
.pd_replace,
.pd_reset,
.pd_reverse,
.pd_sortAsc,
.pd_sortDesc,
.pd_split,
.pd_startsWith,
.pd_stdev,
.pd_toLower,
.pd_toUpper,
.pd_unique,
.pd_values,
=> true,
else => false,
};
}
fn parseBuiltinMethod(self: *Parser, object: Node) anyerror!Node {
try self.expectNext();
if (!isBuiltinMethod(self.currentTag())) return self.ctx.err(
"{s} is not a builtin method.",
.{@tagName(self.currentTag())},
error.InvalidBuiltinMethod,
self.currentOffset(),
);
const builtin = try self.parseBuiltin();
try self.expectTag(.punct_lparen);
var call = try self.parseCall(builtin);
var new_args = try self.allocator.alloc(Node, call.ty.call.args.len + 1);
new_args[0] = object;
std.mem.copy(Node, new_args[1..], call.ty.call.args);
call.ty.call.args = new_args;
return call;
}
fn parseCall(self: *Parser, callee: Node) anyerror!Node {
var node = Node.new(
.{ .call = .{ .args = &[_]Node{}, .callee = try self.allocator.create(Node) } },
self.currentOffset(),
);
node.ty.call.callee.* = callee;
var args_list = std.ArrayList(Node).init(self.allocator);
while (!self.skipTag(.punct_rparen)) {
try self.expectNext();
const arg_node = try self.parseExpression(.lowest);
try args_list.append(arg_node);
_ = self.skipTag(.punct_comma);
}
// Check for predicate.
if (self.skipTag(.punct_lbrace)) {
const pred_node = try self.parseFunc();
try args_list.append(pred_node);
}
node.ty.call.args = args_list.items;
return node;
}
fn parseContinue(self: *Parser) anyerror!Node {
if (!self.can_break) return self.ctx.err(
"Invalid continue.",
.{},
error.InvalidContinue,
self.currentOffset(),
);
return Node.new(.loop_continue, self.currentOffset());
}
fn parseDefine(self: *Parser, name: Node) anyerror!Node {
if (name.ty != .ident) return self.ctx.err(
"{s} := ?",
.{@tagName(name.ty)},
error.InvalidDefine,
name.offset,
);
var node = Node.new(
.{ .define = .{ .lvalue = try self.allocator.create(Node), .rvalue = try self.allocator.create(Node) } },
self.currentOffset(),
);
node.ty.define.lvalue.* = name;
try self.expectNext();
node.ty.define.rvalue.* = try self.parseExpression(.lowest);
// Self-references
if (node.ty.define.rvalue.ty == .func) node.ty.define.rvalue.ty.func.name = name.ty.ident;
return node;
}
fn parseElvis(self: *Parser, condition: Node) anyerror!Node {
const offset = self.currentOffset();
// Condition
var conditon_ptr = try self.allocator.create(Node);
conditon_ptr.* = condition;
// Then branch
var then_slice = try self.allocator.alloc(Node, 1);
then_slice[0] = condition;
// Else branch
var else_slice = try self.allocator.alloc(Node, 1);
try self.expectNext();
else_slice[0] = try self.parseExpression(.ternary);
return Node.new(.{ .conditional = .{
.condition = conditon_ptr,
.then_branch = then_slice,
.else_branch = else_slice,
} }, offset);
}
fn parseElvisAssign(self: *Parser, condition: Node) anyerror!Node {
const offset = self.currentOffset();
// Condition
var conditon_ptr = try self.allocator.create(Node);
conditon_ptr.* = condition;
// Then branch
var then_slice = try self.allocator.alloc(Node, 1);
then_slice[0] = condition;
// Else branch
const assign_node = Node.new(.{ .assign = .{
.lvalue = conditon_ptr,
.rvalue = try self.allocator.create(Node),
} }, offset);
try self.expectNext();
assign_node.ty.assign.rvalue.* = try self.parseExpression(.ternary);
var else_slice = try self.allocator.alloc(Node, 1);
else_slice[0] = assign_node;
return Node.new(.{ .conditional = .{
.condition = conditon_ptr,
.then_branch = then_slice,
.else_branch = else_slice,
} }, offset);
}
fn parseEvent(self: *Parser) anyerror!Node {
var node = Node.new(.{ .event = .{
.nodes = undefined,
.ty = undefined,
} }, self.currentOffset());
node.ty.event.ty = switch (self.currentTag()) {
.pd_onInit => .init,
.pd_onFile => .file,
.pd_onRec => .rec,
.pd_onExit => .exit,
else => unreachable,
};
try self.expectTag(.punct_lbrace);
var list = std.ArrayList(Node).init(self.allocator);
while (!self.skipTag(.punct_rbrace)) {
try self.expectNext();
const next_node = try self.parseExpression(.lowest);
try list.append(next_node);
_ = self.skipTag(.punct_semicolon);
}
node.ty.event.nodes = list.items;
return node;
}
fn parseFloat(self: *Parser) anyerror!Node {
const start = self.currentOffset();
const end = self.currentOffset() + self.currentLen();
const float = try std.fmt.parseFloat(f64, self.ctx.src[start..end]);
return Node.new(.{ .float = float }, self.currentOffset());
}
fn parseFunc(self: *Parser) anyerror!Node {
var node = Node.new(
.{ .func = .{ .body = undefined, .params = &[_][]const u8{} } },
self.currentOffset(),
);
if (self.peekIs(.ident) and (self.peekNIs(2, .punct_comma) or self.peekNIs(2, .punct_fat_rarrow))) {
var params_list = std.ArrayList([]const u8).init(self.allocator);
while (!self.skipTag(.punct_fat_rarrow)) {
try self.expectNext();
if (!self.currentIs(.ident)) return self.ctx.err(
"Non-identifier function param.",
.{},
error.InvalidParam,
self.currentOffset(),
);
const param_node = try self.parseIdent();
try params_list.append(param_node.ty.ident);
_ = self.skipTag(.punct_comma);
}
node.ty.func.params = params_list.items;
} else {
_ = self.skipTag(.punct_fat_rarrow); // Optional =>
}
var body_list = std.ArrayList(Node).init(self.allocator);
try self.parseNodes(&body_list, .punct_rbrace, .punct_semicolon);
// Implicit return
if (body_list.items.len == 0 or body_list.items[body_list.items.len - 1].ty != .func_return) {
var synth_return = Node.new(
.{ .func_return = try self.allocator.create(Node) },
self.currentOffset(),
);
synth_return.ty.func_return.* = if (body_list.items.len == 0) Node.new(.nil, self.currentOffset()) else body_list.pop();
try body_list.append(synth_return);
}
node.ty.func.body = body_list.items;
return node;
}
fn parseGlobal(self: *Parser) anyerror!Node {
return Node.new(.{ .global = self.currentTag() }, self.currentOffset());
}
fn parseGrouped(self: *Parser) anyerror!Node {
try self.expectNext();
const node = try self.parseExpression(.lowest);
try self.expectTag(.punct_rparen);
return node;
}
fn parseIdent(self: *Parser) anyerror!Node {
const start = self.currentOffset();
const end = self.currentOffset() + self.currentLen();
return Node.new(.{ .ident = self.ctx.src[start..end] }, start);
}
fn parseIf(self: *Parser) anyerror!Node {
try self.expectTag(.punct_lparen);
try self.expectNext();
const condition_ptr = try self.allocator.create(Node);
condition_ptr.* = try self.parseExpression(.lowest);
try self.expectTag(.punct_rparen);
var then_branch_list = std.ArrayList(Node).init(self.allocator);
if (self.skipTag(.punct_lbrace)) {
try self.parseNodes(&then_branch_list, .punct_rbrace, .punct_semicolon);
} else {
try self.expectNext();
const then_node = try self.parseExpression(.lowest);
try then_branch_list.append(then_node);
}
var else_branch_list = std.ArrayList(Node).init(self.allocator);
if (self.skipTag(.kw_else)) {
if (self.skipTag(.punct_lbrace)) {
try self.parseNodes(&else_branch_list, .punct_rbrace, .punct_semicolon);
} else {
try self.expectNext();
const else_node = try self.parseExpression(.lowest);
try else_branch_list.append(else_node);
}
} else {
// Synthetic nil if no else branch provided.
try else_branch_list.append(Node.new(.nil, self.currentOffset()));
}
return Node.new(.{ .conditional = .{
.condition = condition_ptr,
.then_branch = then_branch_list.items,
.else_branch = else_branch_list.items,
} }, self.currentOffset());
}
fn parseInfix(self: *Parser, left: Node) anyerror!Node {
const left_ptr = try self.allocator.create(Node);
left_ptr.* = left;
var node = Node.new(
.{ .infix = .{
.left = left_ptr,
.op = self.currentTag(),
.right = undefined,
} },
self.currentOffset(),
);
node.ty.infix.right = try self.allocator.create(Node);
var precedence = Precedence.forTag(node.ty.infix.op);
try self.expectNext();
if (Precedence.isRightAssociative(node.ty.infix.op)) precedence.demote();
node.ty.infix.right.* = try self.parseExpression(precedence);
return node;
}
fn parseInt(self: *Parser) anyerror!Node {
const start = self.currentOffset();
const end = self.currentOffset() + self.currentLen();
const int = try std.fmt.parseInt(i32, self.ctx.src[start..end], 0);
return Node.new(.{ .int = int }, self.currentOffset());
}
fn parseList(self: *Parser) anyerror!Node {
var node = Node.new(.{ .list = &[_]Node{} }, self.currentOffset());
if (self.skipTag(.punct_rbracket)) return node; // Empty list.
if (self.skipTag(.punct_colon)) {
// Empty map.
try self.expectTag(.punct_rbracket);
node.ty = .{ .map = &[_]Node.Entry{} };
return node;
}
try self.expectNext();
var next_node = try self.parseExpression(.lowest);
if (self.skipTag(.punct_colon)) return self.parseMap(node, next_node);
var node_list = std.ArrayList(Node).init(self.allocator);
try node_list.append(next_node);
_ = self.skipTag(.punct_comma);
while (!self.skipTag(.punct_rbracket)) {
try self.expectNext();
next_node = try self.parseExpression(.lowest);
try node_list.append(next_node);
_ = self.skipTag(.punct_comma);
}
node.ty.list = node_list.items;
return node;
}
fn parseMap(self: *Parser, info_node: Node, first_key: Node) anyerror!Node {
// Have to complete the first entry.
try self.expectNext();
var value_node = try self.parseExpression(.lowest);
var entry = Node.Entry{ .key = first_key, .value = value_node };
var entry_list = std.ArrayList(Node.Entry).init(self.allocator);
try entry_list.append(entry);
_ = self.skipTag(.punct_comma);
while (!self.skipTag(.punct_rbracket)) {
// Key
try self.expectNext();
const key_node = try self.parseExpression(.lowest);
try self.expectTag(.punct_colon);
// Value
try self.expectNext();
value_node = try self.parseExpression(.lowest);
// Entry
entry = Node.Entry{ .key = key_node, .value = value_node };
try entry_list.append(entry);
_ = self.skipTag(.punct_comma);
}
return Node.new(.{ .map = entry_list.items }, info_node.offset);
}
fn parseNil(self: *Parser) anyerror!Node {
return Node.new(.nil, self.currentOffset());
}
fn parsePrefix(self: *Parser) anyerror!Node {
var node = Node.new(.{ .prefix = .{ .op = self.currentTag(), .operand = undefined } }, self.currentOffset());
try self.expectNext();
node.ty.prefix.operand = try self.allocator.create(Node);
node.ty.prefix.operand.* = try self.parseExpression(.prefix);
return node;
}
fn parseRange(self: *Parser, from: Node) anyerror!Node {
var from_ptr = try self.allocator.create(Node);
from_ptr.* = from;
var node = Node.new(
.{ .range = .{
.inclusive = self.currentIs(.op_range_in),
.from = from_ptr,
.to = undefined,
} },
self.currentOffset(),
);
try self.expectNext();
node.ty.range.to = try self.allocator.create(Node);
node.ty.range.to.* = try self.parseExpression(.range);
return node;
}
fn parseRecRange(self: *Parser) anyerror!Node {
// Ranges must be unique.
self.range_id += 1;
var node = Node.new(.{ .rec_range = .{
.from = null,
.to = null,
.action = &[0]Node{},
.id = self.range_id,
.exclusive = false,
} }, self.currentOffset());
try self.expectNext();
if (self.currentIs(.punct_lparen)) {
// From
try self.expectNext();
node.ty.rec_range.from = try self.allocator.create(Node);
node.ty.rec_range.from.?.* = try self.parseExpression(.lowest);
try self.expectTag(.punct_rparen);
// No range end expression with default action.
if (self.atEnd() or self.peekIs(.punct_semicolon)) return node;
_ = self.advance();
}
// Range with end expression.
if (self.currentIs(.op_range_ex) or self.currentIs(.op_range_in)) {
node.ty.rec_range.exclusive = self.currentIs(.op_range_ex);
try self.expectTag(.punct_lparen);
try self.expectNext();
node.ty.rec_range.to = try self.allocator.create(Node);
node.ty.rec_range.to.?.* = try self.parseExpression(.lowest);
try self.expectTag(.punct_rparen);
// Default action.
if (self.atEnd() or self.peekIs(.punct_semicolon)) return node;
_ = self.advance();
}
if (self.currentIs(.punct_lbrace)) {
var list = std.ArrayList(Node).init(self.allocator);
try self.parseNodes(&list, .punct_rbrace, .punct_semicolon);
node.ty.rec_range.action = list.items;
} else {
node.ty.rec_range.action = try self.allocator.alloc(Node, 1);
node.ty.rec_range.action[0] = try self.parseExpression(.lowest);
}
return node;
}
fn parseRedir(self: *Parser, expr: Node) anyerror!Node {
const expr_ptr = try self.allocator.create(Node);
expr_ptr.* = expr;
const current_tag = self.currentTag();
var node = Node.new(
.{ .redir = .{
.expr = expr_ptr,
.file = undefined,
.clobber = current_tag == .op_redir_clobber,
} },
self.currentOffset(),
);
var precedence = Precedence.forTag(current_tag);
if (Precedence.isRightAssociative(current_tag)) precedence.demote();
try self.expectNext();
node.ty.redir.file = try self.allocator.create(Node);
node.ty.redir.file.* = try self.parseExpression(precedence);
return node;
}
fn parseReturn(self: *Parser) anyerror!Node {
var node = Node.new(.{ .func_return = try self.allocator.create(Node) }, self.currentOffset());
if (!self.peekIs(.punct_semicolon) and
!self.peekIs(.punct_rbrace) and
!self.atEnd())
{
_ = self.advance();
node.ty.func_return.* = try self.parseExpression(.lowest);
} else {
node.ty.func_return.* = Node.new(.nil, self.currentOffset());
}
return node;
}
fn parseSubscript(self: *Parser, container: Node) anyerror!Node {
var node = Node.new(.{ .subscript = .{
.container = try self.allocator.create(Node),
.index = undefined,
} }, self.currentOffset());
node.ty.subscript.container.* = container;
try self.expectNext();
node.ty.subscript.index = try self.allocator.create(Node);
node.ty.subscript.index.* = try self.parseExpression(.lowest);
_ = try self.expectTag(.punct_rbracket);
return node;
}
// Strings
fn processEscapes(self: *Parser, str: []const u8) anyerror![]const u8 {
if (!std.mem.containsAtLeast(u8, str, 1, "\\")) return str;
var copy = std.ArrayList(u8).init(self.allocator);
var i: usize = 0;
while (i < str.len) : (i += 1) {
const byte = str[i];
if ('\\' == byte) {
if (i + 1 < str.len) {
const peek_byte = str[i + 1];
switch (peek_byte) {
'"' => {
i += 1;
try copy.append('"');
},
'n' => {
i += 1;
try copy.append('\n');
},
'r' => {
i += 1;
try copy.append('\r');
},
't' => {
i += 1;
try copy.append('\t');
},
'u' => {
i += 1;
const ustart = i + 1; // 1 past u
var j: usize = ustart;
while (j < str.len) : (j += 1) {
const ubyte = str[j];
switch (ubyte) {
'0'...'9',
'a'...'f',
'A'...'F',
=> i += 1,
else => break,
}
}
const code = try std.fmt.parseInt(u21, str[ustart..j], 16);
var ubuf: [4]u8 = undefined;
if (std.unicode.utf8Encode(code, &ubuf)) |ulen| {
try copy.appendSlice(ubuf[0..ulen]);
} else |_| {
const ulen = std.unicode.utf8Encode(0xFFFD, &ubuf) catch unreachable;
try copy.appendSlice(ubuf[0..ulen]);
}
},
else => continue,
}
}
} else try copy.append(byte);
}
return copy.items;
}
fn parseIpol(self: *Parser, src: []const u8, offset: u16) anyerror!Node.Ipol {
var parsable = src;
var format: ?[]const u8 = null;
var end: usize = 1;
if ('#' == src[0]) {
var reached_eof = true;
while (end < src.len) : (end += 1) {
if ('#' == src[end]) {
reached_eof = false;
break;
}
}
if (reached_eof) return self.ctx.err(
"Unterminated format spec.",
.{},
error.InvalidFormat,
offset,
);
format = src[1..end];
parsable = src[end + 1 ..];
}
// Need this for proper offsets in error messages.
const spec_len = if (format) |f| @intCast(u16, f.len) + 4 else 1;
// NOTE: Made this mistake more than once; using the same input as the main parser here will cause an infinite loop,
// subsequent stack overfflow, and NO error message, which will drive you crazy!
var sub_lexer = Lexer{ .allocator = self.allocator, .ctx = Context{ .filename = self.ctx.filename, .src = parsable } };
const sub_tokens = sub_lexer.lex() catch |err| return self.ctx.err(
"Error lexing sting interpolation `{s}`.",
.{parsable},
err,
offset + spec_len,
);
var sub_parser = Parser{
.allocator = self.allocator,
.ctx = Context{ .filename = self.ctx.filename, .src = parsable },
.tokens = sub_tokens,
};
const sub_program = sub_parser.parse() catch |err| return self.ctx.err(
"Error parsing sting interpolation `{s}`.",
.{parsable},
err,
offset + spec_len,
);
const sub_nodes = sub_program.rules;
// Avoid format of stmt_end bug.
end = sub_nodes.len;
if (sub_nodes[end - 1].ty == .stmt_end) end = end - 1;
// Adjust offsets for error messages.
for (sub_nodes) |*n| {
if (spec_len != 1) {
n.offset = offset + spec_len + n.offset - 1;
} else {
n.offset = offset + spec_len + n.offset;
}
}
return Node.Ipol{
.spec = format,
.nodes = sub_nodes[0..end],
.offset = offset,
};
}
fn parseString(self: *Parser) anyerror!Node {
const offset = self.currentOffset();
const src = try self.processEscapes(self.ctx.src[self.currentOffset() + 1 .. self.currentOffset() + self.currentLen() - 1]);
const src_len = src.len;
var start: usize = 0;
var i: usize = 0;
var segments = std.ArrayList(Node.Segment).init(self.allocator);
while (i < src_len) {
const byte = src[i];
if ('{' == byte and i + 1 < src_len and '{' == src[i + 1]) {
i += 2;
continue;
}
if ('}' == byte and i + 1 < src_len and '}' == src[i + 1]) {
i += 2;
continue;
}
if ('{' == byte) {
if (i > start) {
const str_segment = Node.Segment{ .plain = src[start..i] };
try segments.append(str_segment);
}
start = i + 1;
var end: usize = i + 1;
var nest_level: usize = 0;
var reached_eof = false;
while (end < src_len) {
const ibyte = src[end];
if ('{' == ibyte and end + 1 < src_len and '{' == src[end + 1]) {
end += 2;
continue;
}
if ('}' == ibyte and end + 1 < src_len and '}' == src[end + 1]) {
end += 2;
continue;
}
if ('{' == ibyte) nest_level += 1;
if ('}' == ibyte) {
if (nest_level > 0) {
nest_level -= 1;
} else {
reached_eof = false;
break;
}
}
end += 1;
}
if (reached_eof) return self.ctx.err(
"Unterminated string interpolation.",
.{},
error.InvalidIpol,
offset,
);
const ipol_segment = Node.Segment{ .ipol = try self.parseIpol(src[start..end], offset + @intCast(u16, start)) };
try segments.append(ipol_segment);
i = end + 1;
start = i;
continue;
}
i += 1;
}
if (start < src_len) {
const str_segment = Node.Segment{ .plain = src[start..src_len] };
try segments.append(str_segment);
}
return Node.new(.{ .string = segments.items }, offset);
}
fn parseRawStr(self: *Parser) anyerror!Node {
const start = self.currentOffset();
const end = self.currentOffset() + self.currentLen();
return Node.new(.{ .raw_str = self.ctx.src[start + 1 .. end - 1] }, start);
}
// End Strings
fn parseTernary(self: *Parser, condition: Node) anyerror!Node {
const offset = self.currentOffset();
// Condition
var conditon_ptr = try self.allocator.create(Node);
conditon_ptr.* = condition;
// Then branch
try self.expectNext();
var then_slice = try self.allocator.alloc(Node, 1);
then_slice[0] = try self.parseExpression(.ternary);
// Else branch
try self.expectTag(.punct_colon);
var else_slice = try self.allocator.alloc(Node, 1);
try self.expectNext();
else_slice[0] = try self.parseExpression(.ternary);
return Node.new(.{ .conditional = .{
.condition = conditon_ptr,
.then_branch = then_slice,
.else_branch = else_slice,
} }, offset);
}
fn parseUint(self: *Parser) anyerror!Node {
const start = self.currentOffset();
const end = self.currentOffset() + self.currentLen();
const uint = try std.fmt.parseUnsigned(u32, self.ctx.src[start..end], 0);
return Node.new(.{ .uint = uint }, self.currentOffset());
}
fn parseDoWhile(self: *Parser) anyerror!Node {
self.can_break = true;
defer self.can_break = false;
var node = Node.new(.{ .loop = .{
.condition = undefined,
.body = undefined,
.is_do = true,
} }, self.currentOffset());
// Body
var body_list = std.ArrayList(Node).init(self.allocator);
if (self.skipTag(.punct_lbrace)) {
try self.parseNodes(&body_list, .punct_rbrace, .punct_semicolon);
} else {
try self.expectNext();
const body_node = try self.parseExpression(.lowest);
try body_list.append(body_node);
}
// while loops need to clean up the stack after every iteration.
try body_list.append(Node.new(.stmt_end, 0));
node.ty.loop.body = body_list.items;
try self.expectTag(.kw_while);
// Condition
try self.expectTag(.punct_lparen);
try self.expectNext();
node.ty.loop.condition = try self.allocator.create(Node);
node.ty.loop.condition.* = try self.parseExpression(.lowest);
try self.expectTag(.punct_rparen);
return node;
}
fn parseWhile(self: *Parser) anyerror!Node {
self.can_break = true;
defer self.can_break = false;
var node = Node.new(.{ .loop = .{
.condition = undefined,
.body = undefined,
.is_do = false,
} }, self.currentOffset());
// Condition
try self.expectTag(.punct_lparen);
try self.expectNext();
node.ty.loop.condition = try self.allocator.create(Node);
node.ty.loop.condition.* = try self.parseExpression(.lowest);
try self.expectTag(.punct_rparen);
// Body
var body_list = std.ArrayList(Node).init(self.allocator);
if (self.skipTag(.punct_lbrace)) {
try self.parseNodes(&body_list, .punct_rbrace, .punct_semicolon);
} else {
try self.expectNext();
const body_node = try self.parseExpression(.lowest);
try body_list.append(body_node);
}
// while loops need to clean up the stack after every iteration.
try body_list.append(Node.new(.stmt_end, 0));
node.ty.loop.body = body_list.items;
return node;
}
// Parser movement.
fn len(self: Parser) u16 {
return @intCast(u16, self.tokens.items(.tag).len);
}
fn currentLen(self: Parser) u16 {
return self.tokens.items(.len)[self.token_index.?];
}
fn currentOffset(self: Parser) u16 {
return self.tokens.items(.offset)[self.token_index.?];
}
fn currentTag(self: Parser) Token.Tag {
return self.tokens.items(.tag)[self.token_index.?];
}
fn currentIs(self: Parser, tag: Token.Tag) bool {
return self.tokens.items(.tag)[self.token_index.?] == tag;
}
fn advance(self: *Parser) bool {
if (self.token_index) |*index| index.* += 1 else self.token_index = 0;
return self.token_index.? < self.len();
}
fn peekNIs(self: Parser, n: usize, tag: Token.Tag) bool {
if (self.token_index) |index| {
return if (index + n < self.len()) self.tokens.items(.tag)[index + n] == tag else false;
} else {
return if (n - 1 < self.len()) self.tokens.items(.tag)[n - 1] == tag else false;
}
}
fn peekIs(self: Parser, tag: Token.Tag) bool {
return self.peekNIs(1, tag);
}
fn peekPrecedence(self: Parser) ?Precedence {
if (self.token_index) |index| {
return if (index + 1 < self.len()) Precedence.forTag(self.tokens.items(.tag)[index + 1]) else null;
} else {
return Precedence.forTag(self.tokens.items(.tag)[0]);
}
}
fn skipTag(self: *Parser, tag: Token.Tag) bool {
return if (self.peekIs(tag)) self.advance() else false;
}
fn expectNext(self: *Parser) !void {
if (!self.advance()) return self.ctx.err(
"Unexpected end of tokens.",
.{},
error.ExpectNext,
@intCast(u16, self.ctx.src.len - 1),
);
}
fn expectTag(self: *Parser, tag: Token.Tag) !void {
try self.expectNext();
if (!self.currentIs(tag)) return self.ctx.err(
"Expected {s}, got {s}.",
.{ @tagName(tag), @tagName(self.currentTag()) },
error.expectTag,
self.currentOffset(),
);
}
// Helpers
fn atEnd(self: Parser) bool {
return self.token_index.? + 1 >= self.tokens.items(.tag).len;
}
fn parseNodes(self: *Parser, list: *std.ArrayList(Node), stop: Token.Tag, skip: Token.Tag) anyerror!void {
while (!self.skipTag(stop)) {
try self.expectNext();
const node = try self.parseExpression(.lowest);
try list.append(node);
try list.append(Node.new(.stmt_end, 0)); // Stack clean up.
_ = self.skipTag(skip);
}
if (list.items.len > 0) _ = list.pop(); // Remove last stmt_end to leave only last value on the stack.
}
// Tests
test "Parser booleans" {
const allocator = std.testing.allocator;
var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit();
const ctx = Context{ .filename = "inline", .src = "false true" };
var lexer = Lexer{ .allocator = arena.allocator(), .ctx = ctx };
var tokens = try lexer.lex();
var parser = Parser{
.allocator = arena.allocator(),
.ctx = ctx,
.tokens = tokens,
};
const program = try parser.parse();
try std.testing.expectEqual(@as(usize, 4), program.rules.len);
try std.testing.expectEqual(Node.Type.boolean, program.rules[0].ty);
try std.testing.expectEqual(false, program.rules[0].ty.boolean);
try std.testing.expectEqual(@as(u16, 0), program.rules[0].offset);
try std.testing.expectEqual(Node.Type.boolean, program.rules[2].ty);
try std.testing.expectEqual(true, program.rules[2].ty.boolean);
try std.testing.expectEqual(@as(u16, 6), program.rules[2].offset);
}
//test "Parser print function" {
// const allocator = std.testing.allocator;
// var arena = std.heap.ArenaAllocator.init(allocator);
// defer arena.deinit();
// const ctx = Context{ .filename = "inline", .src = "foo := { a, b => z := 1; a + z - b !> \"foo.txt\" }" };
// var lexer = Lexer{ .allocator = arena.allocator(), .ctx = ctx };
// var tokens = try lexer.lex();
// var parser = Parser{
// .allocator = arena.allocator(),
// .ctx = ctx,
// .tokens = tokens,
// };
// const program = try parser.parse();
//
// std.debug.print("\n--> {} <--\n", .{program.rules[0]});
//} | src/Parser.zig |
const std = @import("std");
pub const Pattern = struct {
start: usize,
states: []const State,
const State = union(enum) {
accept: void, // Accept the string and finish the match
split: [2]usize, // Split off to two different nodes
lit: struct { // Consume one literal byte
ch: u8,
next: usize,
},
set: struct { // Consume one byte in set
set: std.StaticBitSet(1 << 8),
next: usize,
},
// for debugging
pub fn format(self: State, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = fmt;
_ = options;
try writer.print("{s: >6}", .{@tagName(self)});
switch (self) {
.accept => {},
.split => |next| try writer.print(" -> {} {}", .{ next[0], next[1] }),
.lit => |lit| try writer.print(" '{}' -> {}", .{ std.fmt.fmtSliceEscapeLower(&.{lit.ch}), lit.next }),
.set => |set| try writer.print(" #set -> {}", .{set.next}), // TODO
}
}
};
const Fragment = struct {
start: usize,
out: []const *usize,
fn patch(self: Fragment, out: usize) void {
for (self.out) |p| {
p.* = out;
}
}
};
pub fn init(comptime pattern: []const u8, comptime flags: PatternFlags) Pattern {
const toks = comptime parse(pattern);
comptime var stack: []const Fragment = &.{};
comptime var states: [toks.len + 1]State = undefined; // +1 because accept state is not represented in the tokens
comptime var statei: usize = 0;
comptime for (toks) |tok| switch (tok) {
.ch => |ch| {
// Push literal match
states[statei] = .{ .lit = .{
.ch = ch,
.next = undefined,
} };
stack = stack ++ [_]Fragment{.{
.start = statei,
.out = &.{&states[statei].lit.next},
}};
statei += 1;
},
.class => |set| {
// Push set match
states[statei] = .{ .set = .{
.set = set,
.next = undefined,
} };
stack = stack ++ [_]Fragment{.{
.start = statei,
.out = &.{&states[statei].set.next},
}};
statei += 1;
},
.dot => {
// Create char set
var set = std.StaticBitSet(1 << 8).initFull();
if (!flags.oneline) {
set.unset('\r');
set.unset('\n');
}
// Push set match
states[statei] = .{ .set = .{
.set = set,
.next = undefined,
} };
stack = stack ++ [_]Fragment{.{
.start = statei,
.out = &.{&states[statei].set.next},
}};
statei += 1;
},
// TODO: greedy vs. ungreedy
.repeat => |repeat| {
// Pop repeated fragment
const frag = stack[stack.len - 1];
stack.len -= 1;
// Create split node
states[statei] = .{ .split = .{
frag.start,
undefined,
} };
const split_out = [_]*usize{&states[statei].split[1]};
switch (repeat.kind) {
.star => {
// Patch repeated fragment
frag.patch(statei);
// Push fragment starting with split node
stack = stack ++ [_]Fragment{.{
.start = statei,
.out = &split_out,
}};
},
.plus => {
// Patch repeated fragment
frag.patch(statei);
// Push fragment starting with repeated fragment
stack = stack ++ [_]Fragment{.{
.start = frag.start,
.out = &split_out,
}};
},
.question => {
// Push fragment starting with split node
stack = stack ++ [_]Fragment{.{
.start = statei,
.out = frag.out ++ split_out,
}};
},
}
statei += 1;
},
// TODO: capture groups
.group => |group| if (group.n > 0) {
// Store out array of top fragment for later
const out = stack[stack.len - 1].out;
// Concat grouped fragments
var i = 1;
while (i < group.n) : (i += 1) {
const frag = stack[stack.len - 1];
stack.len -= 1;
stack[stack.len - 1].patch(frag.start);
}
// Patch in the new out array
var frag = stack[stack.len - 1];
frag.out = out;
stack.len -= 1;
stack = stack ++ [_]Fragment{frag};
},
};
comptime {
// Push accept
states[statei] = .accept;
var state = statei;
statei += 1;
// Concat all fragments
var i = stack.len;
while (i > 0) {
i -= 1;
stack[i].patch(state);
state = stack[i].start;
}
}
const state_slice: []const State = states[0..statei];
return .{
.start = stack[0].start,
// Concatenating with an empty array copies the slice, ensuring any unused entries are discarded
.states = state_slice ++ [_]State{},
};
}
pub fn matchStr(comptime self: Pattern, str: []const u8) bool {
var stream = std.io.fixedBufferStream(str);
return self.match(stream.reader()) catch |err| switch (err) {};
}
pub fn match(comptime self: Pattern, r: anytype) !bool {
const Set = std.StaticBitSet(self.states.len);
const EvalState = if (@sizeOf(Set) <= @sizeOf(usize))
struct {
front: Set = Set.initEmpty(),
back: Set = undefined,
fn init(_: @This()) void {}
fn swap(st: *@This()) void {
std.mem.swap(Set, &st.front, &st.back);
st.front = Set.initEmpty();
}
}
else
struct {
sets: [2]Set = [_]Set{Set.initEmpty()} ** 2,
front: *Set = undefined,
back: *Set = undefined,
fn init(st: *@This()) void {
st.front = &st.sets[0];
st.back = &st.sets[1];
st.front.* = Set.initEmpty();
}
fn swap(st: *@This()) void {
std.mem.swap(*Set, &st.front, &st.back);
st.front.* = Set.initEmpty();
}
};
var state = EvalState{};
state.init();
state.front.set(self.start);
var ch: ?u8 = undefined;
var get_next = true;
while (true) {
if (get_next) {
// We've consumed a byte, get the next one
ch = r.readByte() catch |err| switch (err) {
error.EndOfStream => null,
else => |e| return e,
};
get_next = false;
} else if (state.front.findFirstSet() == null) {
// All routes have failed
return false;
}
state.swap();
var it = state.back.iterator(.{});
while (it.next()) |i| switch (self.states[i]) {
.accept => return true, // A route has succeded
.split => |next| {
state.front.set(next[0]);
state.front.set(next[1]);
},
.lit => |lit| if (ch) |c| if (lit.ch == c) {
state.front.set(lit.next);
get_next = true;
},
.set => |set| if (ch) |c| if (set.set.isSet(c)) {
state.front.set(set.next);
get_next = true;
},
};
}
}
const StateList = std.ArrayListUnmanaged(usize);
};
pub const PatternFlags = struct {
multiline: bool = false, // ^ and $ match start/end of line
insensitive: bool = false, // Matches are performed case-insensitively
oneline: bool = false, // Dot matches newline
ungreedy: bool = false, // Quantifiers are lazy
};
test "literal pattern" {
const pat = comptime Pattern.init("Hello, world!", .{});
try std.testing.expect(pat.matchStr("Hello, world!"));
try std.testing.expect(pat.matchStr("Hello, world! foobar"));
try std.testing.expect(!pat.matchStr("Hello, world"));
try std.testing.expect(!pat.matchStr("Hello, world !"));
try std.testing.expect(!pat.matchStr("Hello, world foobar"));
try std.testing.expect(!pat.matchStr("Hello"));
}
test "character class" {
const pat = comptime Pattern.init("a[bcd]e[f-i]j", .{});
try std.testing.expect(pat.matchStr("abefj"));
try std.testing.expect(pat.matchStr("acegj"));
try std.testing.expect(pat.matchStr("adehj"));
try std.testing.expect(pat.matchStr("abeij"));
try std.testing.expect(!pat.matchStr("aeefj"));
try std.testing.expect(!pat.matchStr("abejj"));
try std.testing.expect(!pat.matchStr("ace-j"));
try std.testing.expect(!pat.matchStr("adeej"));
}
test "dot" {
const pat = comptime Pattern.init(
\\a.b\.c
, .{});
try std.testing.expect(pat.matchStr("a*b.c"));
try std.testing.expect(pat.matchStr("axb.c"));
try std.testing.expect(pat.matchStr("a1b.c"));
try std.testing.expect(pat.matchStr("a-b.c"));
try std.testing.expect(pat.matchStr("a.b.c"));
try std.testing.expect(!pat.matchStr("a\nb.c"));
try std.testing.expect(!pat.matchStr("a\rb.c"));
try std.testing.expect(!pat.matchStr("a*b*c"));
try std.testing.expect(!pat.matchStr("axbxc"));
try std.testing.expect(!pat.matchStr("a1b1c"));
try std.testing.expect(!pat.matchStr("a-b-c"));
try std.testing.expect(!pat.matchStr("a.b,c"));
}
test "dot oneline" {
const pat = comptime Pattern.init(
\\a.b\.c
, .{ .oneline = true });
try std.testing.expect(pat.matchStr("a*b.c"));
try std.testing.expect(pat.matchStr("axb.c"));
try std.testing.expect(pat.matchStr("a1b.c"));
try std.testing.expect(pat.matchStr("a-b.c"));
try std.testing.expect(pat.matchStr("a.b.c"));
try std.testing.expect(pat.matchStr("a\nb.c"));
try std.testing.expect(pat.matchStr("a\rb.c"));
try std.testing.expect(!pat.matchStr("a*b*c"));
try std.testing.expect(!pat.matchStr("axbxc"));
try std.testing.expect(!pat.matchStr("a1b1c"));
try std.testing.expect(!pat.matchStr("a-b-c"));
try std.testing.expect(!pat.matchStr("a.b,c"));
try std.testing.expect(!pat.matchStr("a\nb\nc"));
try std.testing.expect(!pat.matchStr("a\rb\rc"));
}
test "capture group" {
const pat = comptime Pattern.init("(ab)(cd)ef", .{});
try std.testing.expect(pat.matchStr("abcdef"));
try std.testing.expect(!pat.matchStr("(ab)(cd)ef"));
}
test "repetition" {
const pat = comptime Pattern.init("a*b", .{});
try std.testing.expect(pat.matchStr("b"));
try std.testing.expect(pat.matchStr("ab"));
try std.testing.expect(pat.matchStr("abc"));
try std.testing.expect(pat.matchStr("aaaaaaab"));
try std.testing.expect(pat.matchStr("aaaaaaabaa"));
try std.testing.expect(!pat.matchStr("c"));
try std.testing.expect(!pat.matchStr("acb"));
try std.testing.expect(!pat.matchStr("aaaacb"));
}
test "complex pattern" {
const pat = comptime Pattern.init("Hello, (hello, )*wo+rld!?", .{});
try std.testing.expect(pat.matchStr("Hello, world!"));
try std.testing.expect(pat.matchStr("Hello, world"));
try std.testing.expect(pat.matchStr("Hello, wooooorld"));
try std.testing.expect(pat.matchStr("Hello, wooooorld!"));
try std.testing.expect(pat.matchStr("Hello, hello, hello, world!"));
try std.testing.expect(pat.matchStr("Hello, hello, hello, woooooorld!"));
try std.testing.expect(pat.matchStr("Hello, hello, wooorld"));
try std.testing.expect(!pat.matchStr("hello, hello, wooorld"));
try std.testing.expect(!pat.matchStr("Hello, hello, wrld"));
try std.testing.expect(!pat.matchStr("Hello, Hello, world!"));
}
/// Parses a regex pattern into a sequence of tokens
fn parse(comptime pattern: []const u8) []const Token {
comptime {
var stream = std.io.fixedBufferStream(pattern);
const r = stream.reader();
const err = struct {
fn unexpected(sym: []const u8) noreturn {
@compileError(std.fmt.comptimePrint(
"Unexpected '{}' at index {}",
.{ std.fmt.fmtSliceEscapeLower(sym), stream.pos },
));
}
fn unclosed(thing: []const u8, start: usize) noreturn {
@compileError(std.fmt.comptimePrint(
"Unclosed {s} starting at index {}",
.{ thing, start },
));
}
};
var groups: usize = 0;
var stack: []const usize = &.{}; // Group stack - stores start indices into toks
var toks: []const Token = &.{}; // Output token stream
var escape = false;
while (r.readByte()) |ch| {
var tok: ?Token = null;
if (escape) {
escape = false;
tok = .{ .ch = ch };
} else switch (ch) {
'\\' => escape = true,
'[' => {
const start = stream.pos;
var set = std.StaticBitSet(1 << 8).initEmpty();
var invert = false;
var prev: ?u8 = null;
while (r.readByte()) |ch2| {
const at_start = stream.pos == start + 1;
if (escape) {
escape = false;
} else switch (ch2) {
'\\' => { // Escape char
escape = true;
continue;
},
'^' => if (at_start) { // Invert set
invert = true;
continue;
},
'-' => if (prev) |sc| {
var ec = r.readByte() catch continue;
if (ec == ']') { // Trailing -, add it to the set and finish
set.set(ch2);
break;
}
while (ec > sc) : (ec -= 1) {
set.set(ec);
}
continue;
},
']' => break, // End of set
else => {},
}
set.set(ch2);
prev = ch2;
} else |e| switch (e) {
error.EndOfStream => err.unclosed("character class", start),
}
if (invert) {
set.toggleAll();
}
tok = .{ .class = set };
},
'.' => tok = .dot,
'*' => tok = .{ .repeat = .{ .kind = .star } },
'+' => tok = .{ .repeat = .{ .kind = .plus } },
'{' => unreachable,
'?' => {
if (toks.len > 0 and toks[toks.len - 1] == .repeat) {
// If we succeed another repetition, make that one lazy
var prev = toks[toks.len - 1];
if (prev.repeat.greedy) {
prev.repeat.greedy = false;
toks.len -= 1;
toks = toks ++ [_]Token{prev};
} else {
err.unexpected("?");
}
} else {
tok = .{ .repeat = .{ .kind = .question } };
}
},
// TODO: named groups
// TODO: non-capturing groups
'(' => stack = stack ++ [_]usize{toks.len},
')' => {
const start = stack[stack.len - 1];
stack.len -= 1;
const name = std.fmt.comptimePrint("{}", .{groups});
groups += 1;
tok = .{ .group = .{
.n = toks.len - start,
.name = name,
} };
},
else => tok = .{ .ch = ch },
}
if (tok) |t| {
toks = toks ++ [_]Token{t};
}
} else |e| switch (e) {
error.EndOfStream => {},
}
if (stack.len > 0) {
err.unclosed("group", stack[stack.len - 1]);
}
return toks;
}
}
const Token = union(enum) {
ch: u8, // Literal character (TODO: unicode support)
class: std.StaticBitSet(1 << 8), // Character class (TODO: unicode support)
dot: void, // Dot (any char, or [^\r\n] depending on oneline flag)
repeat: struct { // Repetition: *, + or ?
kind: enum { star, plus, question },
greedy: bool = true, // Inverse if ungreedy flag is set
},
group: struct { // Group the previous n items
n: usize,
name: ?[]const u8, // null if non-capturing
},
};
test "parse" {
try expectParse(&.{
.{ .ch = 'a' },
.{ .ch = 'b' },
.{ .ch = 'c' },
}, "abc");
try expectParse(&.{
.{ .ch = 'a' },
.{ .group = .{
.n = 1,
.name = "0",
} },
.{ .ch = 'b' },
.{ .ch = 'c' },
.{ .group = .{
.n = 2,
.name = "1",
} },
.{ .repeat = .{ .kind = .star } },
.{ .ch = 'd' },
.{ .ch = 'e' },
.{ .repeat = .{ .kind = .question } },
}, "(a)(bc)*de?");
try expectParse(&.{
.{ .ch = 'a' },
.{ .repeat = .{
.kind = .star,
.greedy = false,
} },
.{ .ch = 'b' },
.{ .repeat = .{
.kind = .plus,
.greedy = false,
} },
.dot,
.{ .repeat = .{
.kind = .question,
.greedy = false,
} },
}, "a*?b+?.??");
try expectParse(&.{
.{ .ch = ' ' },
.{ .ch = '.' },
.{ .ch = '*' },
.{ .ch = '+' },
.{ .ch = '{' },
.{ .ch = '(' },
},
\\ \.\*\+\{\(
);
try expectParse(&.{
.{ .ch = ' ' },
.{ .class = comptime blk: {
var set = std.StaticBitSet(1 << 8).initEmpty();
var i: u8 = 'a';
while (i <= 'z') : (i += 1) {
set.set(i);
}
set.set(']');
set.set('\\');
break :blk set;
} },
.{ .repeat = .{ .kind = .plus } },
.{ .class = comptime blk: {
var set = std.StaticBitSet(1 << 8).initEmpty();
set.set('-');
set.set('a');
break :blk set;
} },
.{ .class = comptime blk: {
var set = std.StaticBitSet(1 << 8).initFull();
set.unset('a');
set.unset('b');
set.unset('c');
break :blk set;
} },
.{ .class = comptime blk: {
var set = std.StaticBitSet(1 << 8).initFull();
var i: u8 = 'a';
while (i <= 'z') : (i += 1) {
set.unset(i);
}
set.unset('A');
set.unset('-');
break :blk set;
} },
},
\\ [a-z\]\\]+[-a][^abc][^a-zA-]
);
}
fn expectParse(expected: []const Token, comptime pattern: []const u8) !void {
const actual = parse(pattern);
if (expected.len != actual.len) {
std.debug.print("slice lengths differ. expected {}, found {}\n", .{ expected.len, actual.len });
return error.TestExpectedEqual;
}
for (expected) |e, i| {
const a = actual[i];
if (!std.meta.eql(e, a)) {
std.debug.print("index {} incorrect. expected {}, found {}\n", .{ i, e, a });
return error.TestExpectedEqual;
}
}
} | rez.zig |
const kernel = @import("../kernel/kernel.zig");
const log = kernel.log.scoped(.NVMe);
const TODO = kernel.TODO;
const PCI = @import("pci.zig");
const x86_64 = @import("../kernel/arch/x86_64.zig");
const NVMe = @This();
pub var controller: NVMe = undefined;
device: *PCI.Device,
capabilities: CAP,
version: u32,
doorbell_stride: u64,
ready_transition_timeout: u64,
maximum_data_transfer_bytes: u64,
rtd3_entry_latency_us: u32,
maximum_data_outstanding_commands: u16,
model: [40]u8,
admin_submission_queue: [*]u8,
admin_completion_queue: [*]u8,
admin_completion_queue_head: u32,
admin_submission_queue_tail: u32,
admin_completion_queue_phase: bool,
admin_completion_queue_last_result: u32,
admin_completion_queue_last_status: u16,
io_submission_queue: ?[*]u8,
io_completion_queue: ?[*]u8,
io_completion_queue_head: u32,
io_submission_queue_tail: u32,
io_submission_queue_head: u32,
io_completion_queue_phase: bool,
prp_list_pages: [io_queue_entry_count]kernel.Physical.Address,
prp_list_virtual: kernel.Virtual.Address,
const general_timeout = 5000;
const admin_queue_entry_count = 2;
const io_queue_entry_count = 256;
const submission_queue_entry_bytes = 64;
const completion_queue_entry_bytes = 16;
const Command = [16]u32;
pub fn new(device: *PCI.Device) NVMe {
return NVMe{
.device = device,
.capabilities = @bitCast(CAP, @as(u64, 0)),
.version = 0,
.doorbell_stride = 0,
.ready_transition_timeout = 0,
.maximum_data_transfer_bytes = 0,
.rtd3_entry_latency_us = 0,
.maximum_data_outstanding_commands = 0,
.model = undefined,
.admin_submission_queue = undefined,
.admin_completion_queue = undefined,
.admin_submission_queue_tail = 0,
.admin_completion_queue_head = 0,
.admin_completion_queue_phase = false,
.admin_completion_queue_last_result = 0,
.admin_completion_queue_last_status = 0,
.io_submission_queue = null,
.io_completion_queue = null,
.io_submission_queue_tail = 0,
.io_completion_queue_head = 0,
.io_submission_queue_head = 0,
.io_completion_queue_phase = false,
.prp_list_pages = undefined,
.prp_list_virtual = undefined,
};
}
pub fn find(pci: *PCI) ?*PCI.Device {
return pci.find_device(0x1, 0x8);
}
const Error = error{
not_found,
};
pub fn find_and_init(pci: *PCI) Error!void {
const nvme_device = find(pci) orelse return Error.not_found;
log.debug("Found NVMe drive", .{});
controller = NVMe.new(nvme_device);
const result = controller.device.enable_features(PCI.Device.Features.from_flags(&.{ .interrupts, .busmastering_dma, .memory_space_access, .bar0 }));
kernel.assert(@src(), result);
log.debug("Device features enabled", .{});
controller.init();
}
inline fn read(nvme: *NVMe, comptime register: Property) register.type {
log.debug("Reading {} bytes from BAR register #{} at offset 0x{x})", .{ @sizeOf(register.type), 0, register.offset });
return nvme.device.read_bar(register.type, 0, register.offset);
}
inline fn write(nvme: *NVMe, comptime register: Property, value: register.type) void {
log.debug("Writing {} bytes (0x{x}) to BAR register #{} at offset 0x{x})", .{ @sizeOf(register.type), value, 0, register.offset });
nvme.device.write_bar(register.type, 0, register.offset, value);
}
inline fn read_sqtdbl(nvme: *NVMe, index: u32) u32 {
return nvme.device.read_bar(u32, 0, 0x1000 + nvme.doorbell_stride * (2 * index + 0));
}
inline fn read_cqhdbl(nvme: *NVMe, index: u32) u32 {
return nvme.device.read_bar(u32, 0, 0x1000 + nvme.doorbell_stride * (2 * index + 1));
}
inline fn write_sqtdbl(nvme: *NVMe, index: u32, value: u32) void {
nvme.device.write_bar(u32, 0, 0x1000 + nvme.doorbell_stride * (2 * index + 0), value);
}
inline fn write_cqhdbl(nvme: *NVMe, index: u32, value: u32) void {
nvme.device.write_bar(u32, 0, 0x1000 + nvme.doorbell_stride * (2 * index + 1), value);
}
pub fn issue_admin_command(nvme: *NVMe, command: *Command, result: ?*u32) bool {
_ = result;
@ptrCast(*Command, @alignCast(@alignOf(Command), &nvme.admin_submission_queue[nvme.admin_submission_queue_tail * @sizeOf(Command)])).* = command.*;
nvme.admin_submission_queue_tail = (nvme.admin_submission_queue_tail + 1) % admin_queue_entry_count;
// TODO: reset event
@fence(.SeqCst); // best memory barrier?
kernel.assert(@src(), kernel.arch.are_interrupts_enabled());
log.debug("Entering in a wait state", .{});
nvme.write_sqtdbl(0, nvme.admin_submission_queue_tail);
asm volatile ("hlt");
// TODO: wait for event
//
if (nvme.admin_completion_queue_last_status != 0) {
const do_not_retry = nvme.admin_completion_queue_last_status & 0x8000 != 0;
const more = nvme.admin_completion_queue_last_status & 0x4000 != 0;
const command_retry_delay = @truncate(u8, nvme.admin_completion_queue_last_status >> 12) & 0x03;
const status_code_type = @truncate(u8, nvme.admin_completion_queue_last_status >> 9) & 0x07;
const status_code = @truncate(u8, nvme.admin_completion_queue_last_status >> 1);
_ = do_not_retry;
_ = more;
_ = command_retry_delay;
_ = status_code_type;
_ = status_code;
log.debug("Admin command failed", .{});
return false;
}
if (result) |p_result| p_result.* = nvme.admin_completion_queue_last_status;
return true;
}
const sector_size = 0x200;
const Operation = enum {
read,
write,
};
pub fn access(nvme: *NVMe, byte_offset: u64, byte_count: u64, operation: Operation) bool {
// TODO: @Lock
const new_tail = (nvme.io_submission_queue_tail + 1) % io_queue_entry_count;
const submission_queue_full = new_tail == nvme.io_submission_queue_head;
if (!submission_queue_full) {
const sector_offset = byte_offset / sector_size;
const sector_count = byte_count / sector_size;
_ = sector_offset;
_ = sector_count;
const prp1_physical_address = kernel.Physical.Memory.allocate_pages(1) orelse @panic("ph");
const prp1_virtual_address = prp1_physical_address.to_higher_half_virtual_address();
kernel.address_space.map(prp1_physical_address, prp1_virtual_address, kernel.Virtual.AddressSpace.Flags.from_flag(.read_write));
// if (!prp2)
// TODO: @Hack
var prp2_physical_address: kernel.Physical.Address = undefined;
if (true) {
prp2_physical_address = nvme.prp_list_pages[nvme.io_submission_queue_tail];
kernel.address_space.map(prp2_physical_address, nvme.prp_list_virtual, kernel.Virtual.AddressSpace.Flags.from_flags(&.{.read_write}));
const index = 0;
nvme.prp_list_virtual.access([*]kernel.Virtual.Address)[index] = kernel.address_space.allocate(0x1000) orelse @panic("asdjkajsdk");
}
var command = @ptrCast(*Command, @alignCast(@alignOf(Command), &nvme.io_submission_queue.?[nvme.io_submission_queue_tail * submission_queue_entry_bytes]));
command[0] = (nvme.io_submission_queue_tail << 16) | @as(u32, if (operation == .write) 0x01 else 0x02);
// TODO:
command[1] = device_nsid;
command[2] = 0;
command[3] = 0;
command[4] = 0;
command[5] = 0;
command[6] = @truncate(u32, prp1_physical_address.value);
command[7] = @truncate(u32, prp1_physical_address.value >> 32);
command[8] = @truncate(u32, prp2_physical_address.value);
command[9] = @truncate(u32, prp2_physical_address.value >> 32);
command[10] = @truncate(u32, sector_offset);
command[11] = @truncate(u32, sector_offset >> 32);
command[12] = @truncate(u16, sector_count);
command[13] = 0;
command[14] = 0;
command[15] = 0;
nvme.io_submission_queue_tail = new_tail;
log.debug("Sending the command", .{});
@fence(.SeqCst);
nvme.write_sqtdbl(1, new_tail);
asm volatile ("hlt");
for (prp1_virtual_address.access([*]u8)[0..0x1000]) |byte, i| {
if (byte != 0) {
log.debug("[{}]: 0x{x}", .{ i, byte });
}
}
for (prp2_physical_address.to_higher_half_virtual_address().access([*]u8)[0..0x1000]) |byte, i| {
if (byte != 0) {
log.debug("[{}]: 0x{x}", .{ i, byte });
}
}
TODO(@src());
} else @panic("queue full");
if (submission_queue_full) {
@panic("queue full wait");
}
return true;
}
pub var device_nsid: u32 = 0;
pub fn init(nvme: *NVMe) void {
nvme.capabilities = nvme.read(cap);
nvme.version = nvme.read(vs);
log.debug("Capabilities = 0x{x}. Version = {}", .{ nvme.capabilities, nvme.version });
if ((nvme.version >> 16) < 1) @panic("f1");
if ((nvme.version >> 16) == 1 and @truncate(u8, nvme.version >> 8) < 1) @panic("f2");
if (nvme.capabilities.mqes == 0) @panic("f3");
kernel.assert_unsafe(@bitOffsetOf(CAP, "nssrs") == 36);
if (!nvme.capabilities.css.nvm_command_set) @panic("f4");
if (nvme.capabilities.mpsmin < kernel.arch.page_shifter - 12) @panic("f5");
if (nvme.capabilities.mpsmax < kernel.arch.page_shifter - 12) @panic("f6");
nvme.doorbell_stride = @as(u64, 4) << nvme.capabilities.doorbell_stride;
log.debug("NVMe doorbell stride: 0x{x}", .{nvme.doorbell_stride});
nvme.ready_transition_timeout = nvme.capabilities.timeout * @as(u64, 500);
log.debug("NVMe ready transition timeout: 0x{x}", .{nvme.ready_transition_timeout});
const previous_configuration = nvme.read(cc);
log.debug("Previous configuration: 0x{x}", .{previous_configuration});
log.debug("we are here", .{});
if (previous_configuration.enable) {
log.debug("branch", .{});
// TODO. HACK we should use a timeout here
// TODO: PRobably buggy
while (!nvme.read(csts).ready) {
log.debug("busy waiting", .{});
}
var config = nvme.read(cc);
config.enable = false;
nvme.write(cc, config);
}
{
// TODO. HACK we should use a timeout here
while (nvme.read(csts).ready) {}
log.debug("past the timeout", .{});
}
nvme.write(cc, blk: {
var cc_value = nvme.read(cc);
cc_value.css = .nvm_command_set;
cc_value.mps = kernel.arch.page_shifter - 12;
cc_value.ams = .round_robin;
cc_value.shn = .no_notification;
cc_value.iosqes = 6;
cc_value.iocqes = 4;
break :blk cc_value;
});
nvme.write(aqa, blk: {
var aqa_value = nvme.read(aqa);
aqa_value.asqs = admin_queue_entry_count - 1;
aqa_value.acqs = admin_queue_entry_count - 1;
break :blk aqa_value;
});
const admin_submission_queue_size = admin_queue_entry_count * submission_queue_entry_bytes;
const admin_completion_queue_size = admin_queue_entry_count * completion_queue_entry_bytes;
const admin_queue_page_count = kernel.align_forward(admin_submission_queue_size, kernel.arch.page_size) + kernel.align_forward(admin_completion_queue_size, kernel.arch.page_size);
const admin_queue_physical_address = kernel.Physical.Memory.allocate_pages(admin_queue_page_count) orelse @panic("admin queue");
const admin_submission_queue_physical_address = admin_queue_physical_address;
const admin_completion_queue_physical_address = admin_queue_physical_address.offset(kernel.align_forward(admin_submission_queue_size, kernel.arch.page_size));
nvme.write(asq, ASQ{
.reserved = 0,
.asqb = @truncate(u52, admin_submission_queue_physical_address.value >> 12),
});
nvme.write(acq, ACQ{
.reserved = 0,
.acqb = @truncate(u52, admin_completion_queue_physical_address.value >> 12),
});
const admin_submission_queue_virtual_address = admin_submission_queue_physical_address.to_higher_half_virtual_address();
const admin_completion_queue_virtual_address = admin_completion_queue_physical_address.to_higher_half_virtual_address();
kernel.address_space.map(admin_submission_queue_physical_address, admin_submission_queue_virtual_address, kernel.Virtual.AddressSpace.Flags.from_flags(&.{.read_write}));
kernel.address_space.map(admin_completion_queue_physical_address, admin_completion_queue_virtual_address, kernel.Virtual.AddressSpace.Flags.from_flags(&.{.read_write}));
nvme.admin_submission_queue = admin_submission_queue_virtual_address.access([*]u8);
nvme.admin_completion_queue = admin_completion_queue_virtual_address.access([*]u8);
nvme.write(cc, blk: {
var new_cc = nvme.read(cc);
new_cc.enable = true;
break :blk new_cc;
});
{
// TODO: HACK use a timeout
while (true) {
const status = nvme.read(csts);
if (status.cfs) {
@panic("cfs");
} else if (status.ready) {
break;
}
}
}
if (!nvme.device.enable_single_interrupt(x86_64.interrupts.HandlerInfo.new(nvme, handle_irq))) {
@panic("f hanlder");
}
nvme.write(intmc, 1 << 0);
// TODO: @Hack remove that 3 for a proper value
const identify_data_physical_address = kernel.Physical.Memory.allocate_pages(3) orelse @panic("identify");
const identify_data_virtual_address = identify_data_physical_address.to_higher_half_virtual_address();
kernel.address_space.map(identify_data_physical_address, identify_data_virtual_address, kernel.Virtual.AddressSpace.Flags.from_flag(.read_write));
const identify_data = identify_data_virtual_address.access([*]u8);
{
var command = kernel.zeroes(Command);
command[0] = 0x06;
command[6] = @truncate(u32, identify_data_physical_address.value);
command[7] = @truncate(u32, identify_data_physical_address.value >> 32);
command[10] = 0x01;
if (!nvme.issue_admin_command(&command, null)) @panic("issue identify");
nvme.maximum_data_transfer_bytes = blk: {
if (identify_data[77] != 0) {
// TODO: mpsmin? shouldnt this be mpsmax?
break :blk @as(u64, 1) << (12 + @intCast(u6, identify_data[77]) + nvme.capabilities.mpsmin);
} else {
break :blk 0;
}
};
nvme.rtd3_entry_latency_us = @ptrCast(*u32, @alignCast(@alignOf(u32), &identify_data[88])).*;
nvme.maximum_data_outstanding_commands = @ptrCast(*u16, @alignCast(@alignOf(u16), &identify_data[514])).*;
kernel.copy(u8, &nvme.model, identify_data[24 .. 24 + @sizeOf(@TypeOf(nvme.model))]);
log.debug("NVMe model: {s}", .{nvme.model});
if (nvme.rtd3_entry_latency_us > 250 * 1000) {
nvme.rtd3_entry_latency_us = 250 * 1000;
}
if (identify_data[111] > 0x01) @panic("unsupported");
if (nvme.maximum_data_transfer_bytes == 0 or nvme.maximum_data_transfer_bytes == 2097152) {
nvme.maximum_data_transfer_bytes = 2097152;
}
}
{
var command = kernel.zeroes(Command);
command[0] = 0x09;
command[10] = 0x80;
command[11] = 0;
_ = nvme.issue_admin_command(&command, null);
}
{
const size = kernel.align_forward(io_queue_entry_count * completion_queue_entry_bytes, kernel.arch.page_size);
const page_count = kernel.bytes_to_pages(size, true);
const queue_physical_address = kernel.Physical.Memory.allocate_pages(page_count) orelse @panic("ph comp");
const physical_region = kernel.Physical.Memory.Region.new(queue_physical_address, size);
physical_region.map(&kernel.address_space, queue_physical_address.to_higher_half_virtual_address(), kernel.Virtual.AddressSpace.Flags.from_flag(.read_write));
nvme.io_completion_queue = queue_physical_address.to_higher_half_virtual_address().access([*]u8);
var command = kernel.zeroes(Command);
command[0] = 0x05;
command[6] = @truncate(u32, queue_physical_address.value);
command[7] = @truncate(u32, queue_physical_address.value >> 32);
command[10] = 1 | ((io_queue_entry_count - 1) << 16);
command[11] = (1 << 0) | (1 << 1);
if (!nvme.issue_admin_command(&command, null)) @panic("create queue");
}
{
const size = kernel.align_forward(io_queue_entry_count * submission_queue_entry_bytes, kernel.arch.page_size);
const page_count = kernel.bytes_to_pages(size, true);
const queue_physical_address = kernel.Physical.Memory.allocate_pages(page_count) orelse @panic("ph comp");
const physical_region = kernel.Physical.Memory.Region.new(queue_physical_address, size);
physical_region.map(&kernel.address_space, queue_physical_address.to_higher_half_virtual_address(), kernel.Virtual.AddressSpace.Flags.from_flag(.read_write));
nvme.io_submission_queue = queue_physical_address.to_higher_half_virtual_address().access([*]u8);
var command = kernel.zeroes(Command);
command[0] = 0x01;
command[6] = @truncate(u32, queue_physical_address.value);
command[7] = @truncate(u32, queue_physical_address.value >> 32);
command[10] = 1 | ((io_queue_entry_count - 1) << 16);
command[11] = (1 << 0) | (1 << 16);
if (!nvme.issue_admin_command(&command, null)) @panic("create queue");
}
{
for (nvme.prp_list_pages) |*prp_list_page| {
prp_list_page.* = kernel.Physical.Memory.allocate_pages(1) orelse @panic("prp physical");
}
kernel.address_space.map(nvme.prp_list_pages[0], nvme.prp_list_pages[0].to_higher_half_virtual_address(), kernel.Virtual.AddressSpace.Flags.from_flag(.read_write));
nvme.prp_list_virtual = nvme.prp_list_pages[0].to_higher_half_virtual_address();
}
var nsid: u32 = 0;
var device_count: u64 = 0;
namespace: while (true) {
{
var command = kernel.zeroes(Command);
command[0] = 0x06;
command[1] = nsid;
command[6] = @truncate(u32, identify_data_physical_address.value);
command[7] = @truncate(u32, identify_data_physical_address.value >> 32);
command[10] = 0x02;
if (!nvme.issue_admin_command(&command, null)) @panic("identify");
}
var i: u64 = 0;
while (i < 1024) : (i += 1) {
nsid = @ptrCast(*align(1) u32, &identify_data[i]).*;
if (nsid == 0) break :namespace;
log.debug("nsid", .{});
{
var command = kernel.zeroes(Command);
command[0] = 0x06;
command[1] = nsid;
command[6] = @truncate(u32, identify_data_physical_address.value + 0x1000);
command[7] = @truncate(u32, (identify_data_physical_address.value + 0x1000) >> 32);
command[10] = 0x00;
if (!nvme.issue_admin_command(&command, null)) @panic("identify");
}
const formatted_lba_size = identify_data[0x1000 + 26];
const lba_format = @ptrCast(*u32, @alignCast(@alignOf(u32), &identify_data[@as(u16, 0x1000) + 128 + 4 * @truncate(u4, formatted_lba_size)])).*;
if (@truncate(u16, lba_format) != 0) continue;
log.debug("lba_format", .{});
const sector_bytes_exponent = @truncate(u5, lba_format >> 16);
if (sector_bytes_exponent < 9 or sector_bytes_exponent > 16) continue;
const sector_bytes = @as(u64, 1) << sector_bytes_exponent;
log.debug("sector bytes: {}", .{sector_bytes});
device_nsid = nsid;
device_count += 1;
log.debug("Device NSID: {}", .{nsid});
}
}
kernel.assert(@src(), device_count == 1);
}
pub const Callback = fn (nvme: *NVMe, line: u64) bool;
pub fn handle_irq(nvme: *NVMe, line: u64) bool {
_ = line;
var from_admin = false;
var from_io = false;
if ((nvme.admin_completion_queue[nvme.admin_completion_queue_head * completion_queue_entry_bytes + 14] & (1 << 0) != 0) != nvme.admin_completion_queue_phase) {
from_admin = true;
nvme.admin_completion_queue_last_result = @ptrCast(*u32, @alignCast(@alignOf(u32), &nvme.admin_completion_queue[nvme.admin_completion_queue_head * completion_queue_entry_bytes + 0])).*;
nvme.admin_completion_queue_last_status = (@ptrCast(*u16, @alignCast(@alignOf(u16), &nvme.admin_completion_queue[nvme.admin_completion_queue_head * completion_queue_entry_bytes + 14])).*) & 0xfffe;
nvme.admin_completion_queue_head += 1;
if (nvme.admin_completion_queue_head == admin_queue_entry_count) {
nvme.admin_completion_queue_phase = !nvme.admin_completion_queue_phase;
nvme.admin_completion_queue_head = 0;
}
nvme.write_cqhdbl(0, nvme.admin_completion_queue_head);
// TODO: set event
}
while (nvme.io_completion_queue != null and ((nvme.io_completion_queue.?[nvme.io_completion_queue_head * completion_queue_entry_bytes + 14] & (1 << 0) != 0) != nvme.io_completion_queue_phase)) {
from_io = true;
const index = @ptrCast(*u16, @alignCast(@alignOf(u16), &nvme.io_completion_queue.?[nvme.io_completion_queue_head * completion_queue_entry_bytes + 12])).*;
const status = (@ptrCast(*u16, @alignCast(@alignOf(u16), &nvme.io_completion_queue.?[nvme.io_completion_queue_head * completion_queue_entry_bytes + 14])).*) & 0xfffe;
if (index < io_queue_entry_count) {
log.debug("Success: {}", .{status == 0});
if (status != 0) {
@panic("failed");
}
// TODO: abstraction stuff
} else @panic("wtf");
@fence(.SeqCst);
nvme.io_submission_queue_head = @ptrCast(*u16, @alignCast(@alignOf(u16), &nvme.io_completion_queue.?[nvme.io_completion_queue_head * completion_queue_entry_bytes + 8])).*;
// TODO: event set
nvme.io_completion_queue_head += 1;
if (nvme.io_completion_queue_head == io_queue_entry_count) {
nvme.io_completion_queue_phase = !nvme.io_completion_queue_phase;
nvme.io_completion_queue_head = 0;
}
nvme.write_cqhdbl(1, nvme.io_completion_queue_head);
}
return from_admin or from_io;
}
const Admin = struct {
const Command = struct {
const DataTransfer = enum(u2) {
no_data_transfer = 0,
host_to_controller = 1,
controller_to_host = 2,
bidirectional = 3,
};
const Opcode = enum(u8) {
delete_io_submission_queue = 0x00,
create_io_submission_queue = 0x01,
get_log_page = 0x02,
delete_io_completion_queue = 0x04,
create_io_completion_queue = 0x05,
identify = 0x06,
abort = 0x08,
set_features = 0x09,
get_features = 0x0a,
asynchronous_event_request = 0x0c,
namespace_management = 0x0d,
firmware_commit = 0x10,
firmware_image_download = 0x11,
device_self_test = 0x14,
namespace_attachment = 0x15,
keep_alive = 0x18,
directive_send = 0x19,
directive_receive = 0x1a,
virtualization_management = 0x1c,
nvme_mi_send = 0x1d,
nvme_mi_receive = 0x1e,
capacity_management = 0x20,
lockdown = 0x24,
doorbell_buffer_config = 0x7c,
fabrics_commands = 0x7f,
format_nvm = 0x80,
security_send = 0x81,
security_receive = 0x82,
sanitize = 0x84,
get_lba_status = 0x86,
pub inline fn is_generic_command(opcode: Opcode) bool {
return opcode & 0b10000000 != 0;
}
pub inline fn get_data_transfer(opcode: Opcode) DataTransfer {
return @intToEnum(DataTransfer, @truncate(u2, @enumToInt(opcode)));
}
pub inline fn get_function(opcode: Opcode) u5 {
return @truncate(u5, (@enumToInt(opcode) & 0b01111100) >> 2);
}
};
};
};
const SubmissionQueueEntry = struct {
command_dword0: CommandDword0,
};
const CommandDword0 = packed struct {
opcode: u8,
fuse: FUSE,
reserved: u4,
psdt: PSDT,
cid: u16,
const FUSE = enum(u2) {
normal = 0,
fuse_first_command = 1,
fuse_second_command = 2,
reserved = 3,
};
const PSDT = enum(u2) {
prps_used = 0,
sgls_buffer = 1,
sgls_segment = 2,
reserved = 3,
};
comptime {
kernel.assert_unsafe(@sizeOf(CommandDword0) == @sizeOf(u32));
}
};
const CommonCommandFormat = packed struct {
command_dword0: u4,
nsid: u4,
command_dword2: u4,
command_dword3: u4,
mptr: u8,
dptr: u16,
command_dword10: u4,
command_dword11: u4,
command_dword12: u4,
command_dword13: u4,
command_dword14: u4,
command_dword15: u4,
comptime {
kernel.assert_unsafe(@sizeOf(CommonCommandFormat) == @sizeOf(u64));
}
};
const AdminCommonCommandFormat = packed struct {
command_dword0: u4,
nsid: u4,
reserved: u8,
// == Same as Common ==
mptr: u8,
dptr: u16,
// == Same as Common ==
ndt: u4,
ndm: u4,
command_dword12: u4,
command_dword13: u4,
command_dword14: u4,
command_dword15: u4,
comptime {
kernel.assert_unsafe(@sizeOf(AdminCommonCommandFormat) == @sizeOf(u64));
}
};
const CommonCompletionQueueEntry = packed struct {
dw0: u32,
dw1: u32,
dw2: DW2,
const DW2 = packed struct {
sqhp: u16,
sqid: u16,
comptime {
kernel.assert_unsafe(@sizeOf(DW2) == @sizeOf(u32));
}
};
const DW3 = packed struct {
cid: u16,
phase_tag: bool,
status_field: StatusField,
comptime {
kernel.assert_unsafe(@sizeOf(DW3) == @sizeOf(u32));
}
};
const StatusField = packed struct {
sc: u8,
sct: u3,
crd: u2,
more: bool,
dnr: bool,
};
const GenericCommandStatus = enum(u8) {
successful_completion = 0x00,
invalid_command_opcode = 0x01,
invalid_field_in_command = 0x02,
command_id_conflict = 0x03,
data_transfer_error = 0x04,
commmands_aborted_due_to_power_loss_notification = 0x05,
internal_error = 0x06,
command_abort_requested = 0x07,
command_aborted_due_to_sq_deletion = 0x08,
command_aborted_due_to_failed_fused_command = 0x09,
command_aborted_due_to_missing_fused_command = 0x0a,
invalid_namespace_or_format = 0x0b,
command_sequence_error = 0x0c,
invalid_sgl_segment_descriptor = 0x0d,
invalid_number_of_sgl_descriptors = 0x0e,
data_sgl_length_invalid = 0x0f,
metadata_sgl_length_invalid = 0x10,
sgl_descriptor_type_invalid = 0x11,
invalid_use_of_controller_memory_buffer = 0x12,
prp_offset_invalid = 0x13,
atomic_write_unit_exceeded = 0x14,
operation_denied = 0x15,
sgl_offset_invalid = 0x16,
reserved = 0x17,
host_identifier_inconsistent_format = 0x18,
keep_alive_timer_expired = 0x19,
keep_alive_timeout_invalid = 0x1a,
command_aborted_due_to_preempt_and_abort = 0x1b,
sanitize_failed = 0x1c,
sanitize_in_progress = 0x1d,
sgl_data_block_glanularity_invalid = 0x1e,
command_not_supported_for_queue_in_cmb = 0x1f,
namespace_is_write_protected = 0x20,
command_interrupted = 0x21,
transient_transport_error = 0x22,
command_prohibited_by_command_and_feature_lockdown = 0x23,
admin_command_media_not_ready = 0x24,
lba_out_of_range = 0x80,
capacity_exceeded = 0x81,
namespace_not_ready = 0x82,
reservation_conflict = 0x83,
format_in_progress = 0x84,
invalid_value_size = 0x85,
invalid_key_size = 0x86,
kv_key_does_not_exist = 0x87,
unrecovered_error = 0x88,
key_exists = 0x89,
_,
};
const CommandSpecificStatus = enum(u8) {
completion_queue_invalid = 0x00,
invalid_queue_identifier = 0x01,
invalid_queue_size = 0x02,
abort_command_limit_exceeded = 0x03,
reserved = 0x04,
asynchronous_event_request_limi_exceeded = 0x05,
invalid_firmware_slot = 0x06,
invalid_firmware_image = 0x07,
invalid_interrupt_vector = 0x08,
invalid_log_page = 0x09,
invalid_format = 0x0a,
firmware_activation_requires_conventional_reset = 0x0b,
invalid_queue_deletion = 0x0c,
feature_identifier_not_saveable = 0x0d,
feature_not_changeable = 0x0e,
feature_not_namespace_specific = 0x0f,
firmware_activation_requires_nvm_subsystem_reset = 0x10,
firmware_activation_requires_controller_level_reset = 0x11,
firmware_activation_requires_maximum_time_violation = 0x12,
firmware_activation_prohibited = 0x13,
overlapping_range = 0x14,
namespace_insufficient_capacity = 0x15,
namespace_identifier_unavailable = 0x16,
reserved = 0x17,
namespace_already_attached = 0x18,
namespace_is_private = 0x19,
namespace_not_attached = 0x1a,
thin_provisioning_not_supported = 0x1b,
controller_list_invalid = 0x1c,
device_self_test_in_progress = 0x1d,
boot_partition_write_prohibited = 0x1e,
invalid_controller_identifier = 0x1f,
invalid_secondary_controller_state = 0x20,
invalid_number_of_controller_resources = 0x21,
invalid_resource_identifier = 0x22,
sanitize_prohibited_while_persistent_memory_region_is_enabled = 0x23,
ana_group_identifier_invalid = 0x24,
ana_attach_failed = 0x25,
insufficient_capacity = 0x26,
namespace_attachment_limit_exceeded = 0x27,
prohibition_of_command_execution_not_supported = 0x28,
io_command_set_not_supported = 0x29,
io_command_set_not_enabled = 0x2a,
io_command_set_combination_rejected = 0x2b,
invalid_io_command_set = 0x2c,
identifier_unavailable = 0x2d,
_,
};
const IOCommandSpecificStatus = enum(u8) {
conflicting_attributes = 0x80,
invalid_protection_information = 0x81,
attempted_write_to_read_only_range = 0x82,
command_size_limit_exceeded = 0x83,
_,
zoned_boundary_error = 0xb8,
zone_is_full = 0xb9,
zone_is_read_only = 0xba,
zone_is_offline = 0xbb,
zone_invalid_write = 0xbc,
too_many_active_zones = 0xbd,
too_many_open_zones = 0xbe,
invalid_zone_state_transition = 0xbf,
};
const FabricsCommandSpecificStatus = enum(u8) {
incompatible_format = 0x80,
controller_busy = 0x81,
connect_invalid_parameters = 0x82,
connected_restar_discovery = 0x83,
connect_invalid_host = 0x84,
invalid_queue_type = 0x85,
discover_restart = 0x90,
authentication_required = 0x91,
};
const MediaAndDataIntegrityError = enum(u8) {
write_fault = 0x80,
unrecovered_read_error = 0x81,
end_to_end_guard_check_error = 0x82,
end_to_end_application_tag_check_error = 0x83,
end_to_end_reference_tag_check_error = 0x84,
compare_failure = 0x85,
access_denied = 0x86,
deallocated_or_unwritten_logical_block = 0x87,
end_to_end_storage_tag_check_error = 0x88,
};
const PathRelatedStatus = enum(u8) {
internal_path_error = 0x00,
asymmetric_access_persistent_loss = 0x01,
asymmetric_access_inaccessible = 0x02,
asymmetric_access_transition = 0x03,
controller_pathing_error = 0x60,
host_pathing_error = 0x70,
command_aborted_by_host = 0x71,
};
};
const Property = struct {
offset: u64,
type: type,
};
const cap = Property{ .offset = 0, .type = CAP };
const vs = Property{ .offset = 0x08, .type = u32 };
const intms = Property{ .offset = 0xc, .type = u32 };
const intmc = Property{ .offset = 0x10, .type = u32 };
const cc = Property{ .offset = 0x14, .type = CC };
const csts = Property{ .offset = 0x1c, .type = CSTS };
const nssr = Property{ .offset = 0x20, .type = u32 };
const aqa = Property{ .offset = 0x24, .type = AQA };
const asq = Property{ .offset = 0x28, .type = ASQ };
const acq = Property{ .offset = 0x30, .type = ACQ };
const cmbloc = Property{ .offset = 0x38, .type = CMBLOC };
const cmbsz = Property{ .offset = 0x3c, .type = CMBSZ };
const bpinfo = Property{ .offset = 0x40, .type = BPINFO };
const bprsel = Property{ .offset = 0x44, .type = BPRSEL };
const bpmbl = Property{ .offset = 0x48, .type = BPMBL };
const cmbmsc = Property{ .offset = 0x50, .type = CMBMSC };
const cmbsts = Property{ .offset = 0x58, .type = CMBSTS };
const cmbebs = Property{ .offset = 0x5c, .type = CMBEBS };
const cmbswtp = Property{ .offset = 0x60, .type = CMBSWTP };
const nssd = Property{ .offset = 0x64, .type = u32 };
const crto = Property{ .offset = 0x68, .type = CRTO };
const pmrcap = Property{ .offset = 0xe00, .type = PMRCAP };
const pmrctl = Property{ .offset = 0xe04, .type = PMRCTL };
const pmrsts = Property{ .offset = 0xe08, .type = PMRSTS };
const pmrebs = Property{ .offset = 0xe0c, .type = PMREBS };
const pmrswtp = Property{ .offset = 0xe10, .type = PMRSWTP };
const pmrmscl = Property{ .offset = 0xe14, .type = PMRMSCL };
const pmrmscu = Property{ .offset = 0xe18, .type = u32 };
const CAP = packed struct {
mqes: u16,
cqr: bool,
ams: u2,
reserved: u5,
timeout: u8,
doorbell_stride: u4,
nssrs: bool,
css: CSS,
bps: bool,
cps: u2,
mpsmin: u4,
mpsmax: u4,
pmrs: bool,
cmbs: bool,
nsss: bool,
crwms: bool,
crims: bool,
reserved2: u3,
const CSS = packed struct {
nvm_command_set: bool,
reserved: u5,
io_command_sets: bool,
no_io_command_set: bool,
};
comptime {
kernel.assert_unsafe(@sizeOf(CAP) == @sizeOf(u64));
}
};
const CC = packed struct {
enable: bool,
reserved: u3,
css: CSS,
mps: u4,
ams: AMS,
shn: SHN,
iosqes: u4,
iocqes: u4,
crime: bool,
reserved2: u7,
const CSS = enum(u3) {
nvm_command_set = 0b000,
all_supported_io_command_sets = 0b110,
admin_command_set_only = 0b111,
_,
};
const AMS = enum(u3) {
round_robin = 0b000,
weighted_round_robin_with_urgent_priority_class = 0b001,
vendor_specific = 0b111,
_,
};
const SHN = enum(u2) {
no_notification = 0b00,
normal_shutdown_notification = 0b01,
abrupt_shutdown_notification = 0b10,
reserved = 0b11,
};
comptime {
kernel.assert_unsafe(@sizeOf(CC) == @sizeOf(u32));
}
};
const CSTS = packed struct {
ready: bool,
cfs: bool,
shst: SHST,
nssro: bool,
pp: bool,
st: bool,
reserved: u25,
const SHST = enum(u2) {
norma_operation = 0,
shutdown_processing_occurring = 1,
shutdown_processing_complete = 2,
};
comptime {
kernel.assert_unsafe(@sizeOf(CSTS) == @sizeOf(u32));
}
};
const AQA = packed struct {
asqs: u12,
reserved: u4,
acqs: u12,
reserved2: u4,
comptime {
kernel.assert_unsafe(@sizeOf(AQA) == @sizeOf(u32));
}
};
const ASQ = packed struct {
reserved: u12,
asqb: u52,
comptime {
kernel.assert_unsafe(@sizeOf(ASQ) == @sizeOf(u64));
}
};
const ACQ = packed struct {
reserved: u12,
acqb: u52,
comptime {
kernel.assert_unsafe(@sizeOf(ACQ) == @sizeOf(u64));
}
};
const CMBLOC = packed struct {
bir: u3,
cqmms: bool,
cqpds: bool,
cdpmls: bool,
cdpcils: bool,
cdmmms: bool,
cqda: bool,
reserved: u3,
offset: u20,
comptime {
kernel.assert_unsafe(@sizeOf(CMBLOC) == @sizeOf(u32));
}
};
const CMBSZ = packed struct {
sqs: bool,
cqs: bool,
lists: bool,
rds: bool,
wds: bool,
reserved: u3,
szu: SZU,
size: u20,
const SZU = enum(u4) {
kib_4 = 0,
kib_64 = 1,
mib_1 = 2,
mib_16 = 3,
mib_256 = 4,
gib_4 = 5,
gib_64 = 6,
_,
};
comptime {
kernel.assert_unsafe(@sizeOf(CMBSZ) == @sizeOf(u32));
}
};
const BPINFO = packed struct {
bpsz: u15,
reserved: u9,
brs: BRS,
reserved: u5,
abpid: bool,
const BRS = enum(u2) {
no_bpr = 0,
bpr_in_progress = 1,
bpr_completed = 2,
bpr_error = 3,
};
comptime {
kernel.assert_unsafe(@sizeOf(BPINFO) == @sizeOf(u32));
}
};
const BPRSEL = packed struct {
bprsz: u10,
bprof: u20,
reserved: bool,
bpid: bool,
comptime {
kernel.assert_unsafe(@sizeOf(BPRSEL) == @sizeOf(u32));
}
};
const BPMBL = packed struct {
reserved: u12,
bmbba: u52,
comptime {
kernel.assert_unsafe(@sizeOf(BPMBL) == @sizeOf(u64));
}
};
const CMBMSC = packed struct {
cre: bool,
cmse: bool,
reserved: u10,
cba: u52,
comptime {
kernel.assert_unsafe(@sizeOf(CMBMSC) == @sizeOf(u64));
}
};
const CMBSTS = packed struct {
cbai: bool,
reserved: u31,
comptime {
kernel.assert_unsafe(@sizeOf(CMBSTS) == @sizeOf(u32));
}
};
const CMBEBS = packed struct {
cmbszu: CMBSZU,
read_bypass_behavior: bool,
reserved: u3,
cmbwbz: u24,
const CMBSZU = enum(u4) {
bytes = 0,
kib = 1,
mib = 2,
gib = 3,
_,
};
comptime {
kernel.assert_unsafe(@sizeOf(CMBEBS) == @sizeOf(u32));
}
};
const CMBSWTP = packed struct {
cmbswtu: CMBSWTU,
reserved: u4,
cmbswtv: u24,
const CMBSWTU = enum(u4) {
bytes_s = 0,
kibs_s = 1,
mibs_s = 2,
gibs_s = 3,
_,
};
comptime {
kernel.assert_unsafe(@sizeOf(CMBSWTP) == @sizeOf(u32));
}
};
const CRTO = packed struct {
crwmt: u16,
crimt: u16,
comptime {
kernel.assert_unsafe(@sizeOf(CRTO) == @sizeOf(u32));
}
};
const PMRCAP = packed struct {
reserved: u3,
rds: bool,
wds: bool,
bir: u3,
pmrtu: PMRTU,
pmrwbm: u4,
reserved: u2,
pmrto: u8,
cmss: bool,
reserved: u7,
const PMRTU = enum(u2) {
ms_500 = 0,
minutes = 1,
_,
};
comptime {
kernel.assert_unsafe(@sizeOf(PMRCAP) == @sizeOf(u32));
}
};
const PMRCTL = packed struct {
enable: bool,
reserved: u31,
comptime {
kernel.assert_unsafe(@sizeOf(PMRCTL) == @sizeOf(u32));
}
};
const PMRSTS = packed struct {
err: u8,
nrdy: bool,
hsts: HSTS,
cbai: bool,
reserved: u20,
const HSTS = enum(u2) {
normal = 0,
restore_error = 1,
read_only = 2,
unreliable = 3,
};
comptime {
kernel.assert_unsafe(@sizeOf(PMRSTS) == @sizeOf(u32));
}
};
const PMREBS = packed struct {
pmrszu: PMRSZU,
read_bypass_behavior: bool,
reserved: u3,
pmrwbz: u24,
const PMRSZU = enum(u4) {
bytes = 0,
kib = 1,
mib = 2,
gib = 3,
_,
};
comptime {
kernel.assert_unsafe(@sizeOf(PMREBS) == @sizeOf(u32));
}
};
const PMRSWTP = packed struct {
pmrswtu: PMRSWTU,
reserved: u4,
pmrswtv: u24,
const PMRSWTU = enum(u4) {
bytes_s = 0,
kib_s = 1,
mib_s = 2,
gib_s,
_,
};
comptime {
kernel.assert_unsafe(@sizeOf(PMRSWTP) == @sizeOf(u32));
}
};
const PMRMSCL = packed struct {
reserved: bool,
cmse: bool,
reserved2: u10,
cba: u20,
comptime {
kernel.assert_unsafe(@sizeOf(PMRMSCL) == @sizeOf(u32));
}
}; | src/drivers/nvme.zig |
const std = @import("std");
const Str = []const u8;
const Bytecode = std.ArrayList(u8);
const Locations = std.ArrayList(Loc);
const Value = @import("value.zig").Value;
const Constants = std.ArrayList(Value);
pub const Op = enum {
Return,
Constant,
True,
False,
Nil,
Add,
Sub,
Mul,
Div,
Neg,
Not,
And,
Or,
Xor,
Equal,
NotEqual,
Greater,
GreaterEqual,
Less,
LessEqual,
DefineGlobal,
SetGlobal,
GetGlobal,
Print, // FIXME: Temporary
Pop,
};
pub const Loc = struct {
line: usize,
col: usize,
};
const Words = packed struct {
low: u8,
high: u8,
};
const ConstantIndex = packed union {
index: u16,
words: Words,
};
pub const Chunk = struct {
code: Bytecode,
constants: Constants,
const Self = @This();
pub fn init(allocator: std.mem.Allocator) Chunk {
return Chunk{
.code = Bytecode.init(allocator),
.constants = Constants.init(allocator),
};
}
pub fn deinit(self: *Self) void {
self.constants.deinit();
self.code.deinit();
}
fn addConstant(self: *Self, value: Value) ConstantIndex {
const id = @intCast(u16, self.constants.items.len);
self.constants.append(value) catch unreachable;
return ConstantIndex{ .index = id };
}
pub fn pushConstant(self: *Self, value: Value) void {
const id = self.addConstant(value);
self.code.append(id.words.low) catch unreachable;
self.code.append(id.words.high) catch unreachable;
}
pub fn push(self: *Self, op: Op) void {
const op_index = @enumToInt(op);
self.code.append(op_index) catch unreachable;
}
pub fn getConstant(self: Self, ip: usize) Value {
const index = ConstantIndex{
.words = Words{
.low = self.code.items[ip],
.high = self.code.items[ip + 1],
},
};
return self.constants.items[@intCast(usize, index.index)];
}
}; | src/bytecode.zig |
const std = @import("std");
const mem = std.mem;
const LV = @This();
allocator: *mem.Allocator,
array: []bool,
lo: u21 = 44032,
hi: u21 = 55176,
pub fn init(allocator: *mem.Allocator) !LV {
var instance = LV{
.allocator = allocator,
.array = try allocator.alloc(bool, 11145),
};
mem.set(bool, instance.array, false);
var index: u21 = 0;
instance.array[0] = true;
instance.array[28] = true;
instance.array[56] = true;
instance.array[84] = true;
instance.array[112] = true;
instance.array[140] = true;
instance.array[168] = true;
instance.array[196] = true;
instance.array[224] = true;
instance.array[252] = true;
instance.array[280] = true;
instance.array[308] = true;
instance.array[336] = true;
instance.array[364] = true;
instance.array[392] = true;
instance.array[420] = true;
instance.array[448] = true;
instance.array[476] = true;
instance.array[504] = true;
instance.array[532] = true;
instance.array[560] = true;
instance.array[588] = true;
instance.array[616] = true;
instance.array[644] = true;
instance.array[672] = true;
instance.array[700] = true;
instance.array[728] = true;
instance.array[756] = true;
instance.array[784] = true;
instance.array[812] = true;
instance.array[840] = true;
instance.array[868] = true;
instance.array[896] = true;
instance.array[924] = true;
instance.array[952] = true;
instance.array[980] = true;
instance.array[1008] = true;
instance.array[1036] = true;
instance.array[1064] = true;
instance.array[1092] = true;
instance.array[1120] = true;
instance.array[1148] = true;
instance.array[1176] = true;
instance.array[1204] = true;
instance.array[1232] = true;
instance.array[1260] = true;
instance.array[1288] = true;
instance.array[1316] = true;
instance.array[1344] = true;
instance.array[1372] = true;
instance.array[1400] = true;
instance.array[1428] = true;
instance.array[1456] = true;
instance.array[1484] = true;
instance.array[1512] = true;
instance.array[1540] = true;
instance.array[1568] = true;
instance.array[1596] = true;
instance.array[1624] = true;
instance.array[1652] = true;
instance.array[1680] = true;
instance.array[1708] = true;
instance.array[1736] = true;
instance.array[1764] = true;
instance.array[1792] = true;
instance.array[1820] = true;
instance.array[1848] = true;
instance.array[1876] = true;
instance.array[1904] = true;
instance.array[1932] = true;
instance.array[1960] = true;
instance.array[1988] = true;
instance.array[2016] = true;
instance.array[2044] = true;
instance.array[2072] = true;
instance.array[2100] = true;
instance.array[2128] = true;
instance.array[2156] = true;
instance.array[2184] = true;
instance.array[2212] = true;
instance.array[2240] = true;
instance.array[2268] = true;
instance.array[2296] = true;
instance.array[2324] = true;
instance.array[2352] = true;
instance.array[2380] = true;
instance.array[2408] = true;
instance.array[2436] = true;
instance.array[2464] = true;
instance.array[2492] = true;
instance.array[2520] = true;
instance.array[2548] = true;
instance.array[2576] = true;
instance.array[2604] = true;
instance.array[2632] = true;
instance.array[2660] = true;
instance.array[2688] = true;
instance.array[2716] = true;
instance.array[2744] = true;
instance.array[2772] = true;
instance.array[2800] = true;
instance.array[2828] = true;
instance.array[2856] = true;
instance.array[2884] = true;
instance.array[2912] = true;
instance.array[2940] = true;
instance.array[2968] = true;
instance.array[2996] = true;
instance.array[3024] = true;
instance.array[3052] = true;
instance.array[3080] = true;
instance.array[3108] = true;
instance.array[3136] = true;
instance.array[3164] = true;
instance.array[3192] = true;
instance.array[3220] = true;
instance.array[3248] = true;
instance.array[3276] = true;
instance.array[3304] = true;
instance.array[3332] = true;
instance.array[3360] = true;
instance.array[3388] = true;
instance.array[3416] = true;
instance.array[3444] = true;
instance.array[3472] = true;
instance.array[3500] = true;
instance.array[3528] = true;
instance.array[3556] = true;
instance.array[3584] = true;
instance.array[3612] = true;
instance.array[3640] = true;
instance.array[3668] = true;
instance.array[3696] = true;
instance.array[3724] = true;
instance.array[3752] = true;
instance.array[3780] = true;
instance.array[3808] = true;
instance.array[3836] = true;
instance.array[3864] = true;
instance.array[3892] = true;
instance.array[3920] = true;
instance.array[3948] = true;
instance.array[3976] = true;
instance.array[4004] = true;
instance.array[4032] = true;
instance.array[4060] = true;
instance.array[4088] = true;
instance.array[4116] = true;
instance.array[4144] = true;
instance.array[4172] = true;
instance.array[4200] = true;
instance.array[4228] = true;
instance.array[4256] = true;
instance.array[4284] = true;
instance.array[4312] = true;
instance.array[4340] = true;
instance.array[4368] = true;
instance.array[4396] = true;
instance.array[4424] = true;
instance.array[4452] = true;
instance.array[4480] = true;
instance.array[4508] = true;
instance.array[4536] = true;
instance.array[4564] = true;
instance.array[4592] = true;
instance.array[4620] = true;
instance.array[4648] = true;
instance.array[4676] = true;
instance.array[4704] = true;
instance.array[4732] = true;
instance.array[4760] = true;
instance.array[4788] = true;
instance.array[4816] = true;
instance.array[4844] = true;
instance.array[4872] = true;
instance.array[4900] = true;
instance.array[4928] = true;
instance.array[4956] = true;
instance.array[4984] = true;
instance.array[5012] = true;
instance.array[5040] = true;
instance.array[5068] = true;
instance.array[5096] = true;
instance.array[5124] = true;
instance.array[5152] = true;
instance.array[5180] = true;
instance.array[5208] = true;
instance.array[5236] = true;
instance.array[5264] = true;
instance.array[5292] = true;
instance.array[5320] = true;
instance.array[5348] = true;
instance.array[5376] = true;
instance.array[5404] = true;
instance.array[5432] = true;
instance.array[5460] = true;
instance.array[5488] = true;
instance.array[5516] = true;
instance.array[5544] = true;
instance.array[5572] = true;
instance.array[5600] = true;
instance.array[5628] = true;
instance.array[5656] = true;
instance.array[5684] = true;
instance.array[5712] = true;
instance.array[5740] = true;
instance.array[5768] = true;
instance.array[5796] = true;
instance.array[5824] = true;
instance.array[5852] = true;
instance.array[5880] = true;
instance.array[5908] = true;
instance.array[5936] = true;
instance.array[5964] = true;
instance.array[5992] = true;
instance.array[6020] = true;
instance.array[6048] = true;
instance.array[6076] = true;
instance.array[6104] = true;
instance.array[6132] = true;
instance.array[6160] = true;
instance.array[6188] = true;
instance.array[6216] = true;
instance.array[6244] = true;
instance.array[6272] = true;
instance.array[6300] = true;
instance.array[6328] = true;
instance.array[6356] = true;
instance.array[6384] = true;
instance.array[6412] = true;
instance.array[6440] = true;
instance.array[6468] = true;
instance.array[6496] = true;
instance.array[6524] = true;
instance.array[6552] = true;
instance.array[6580] = true;
instance.array[6608] = true;
instance.array[6636] = true;
instance.array[6664] = true;
instance.array[6692] = true;
instance.array[6720] = true;
instance.array[6748] = true;
instance.array[6776] = true;
instance.array[6804] = true;
instance.array[6832] = true;
instance.array[6860] = true;
instance.array[6888] = true;
instance.array[6916] = true;
instance.array[6944] = true;
instance.array[6972] = true;
instance.array[7000] = true;
instance.array[7028] = true;
instance.array[7056] = true;
instance.array[7084] = true;
instance.array[7112] = true;
instance.array[7140] = true;
instance.array[7168] = true;
instance.array[7196] = true;
instance.array[7224] = true;
instance.array[7252] = true;
instance.array[7280] = true;
instance.array[7308] = true;
instance.array[7336] = true;
instance.array[7364] = true;
instance.array[7392] = true;
instance.array[7420] = true;
instance.array[7448] = true;
instance.array[7476] = true;
instance.array[7504] = true;
instance.array[7532] = true;
instance.array[7560] = true;
instance.array[7588] = true;
instance.array[7616] = true;
instance.array[7644] = true;
instance.array[7672] = true;
instance.array[7700] = true;
instance.array[7728] = true;
instance.array[7756] = true;
instance.array[7784] = true;
instance.array[7812] = true;
instance.array[7840] = true;
instance.array[7868] = true;
instance.array[7896] = true;
instance.array[7924] = true;
instance.array[7952] = true;
instance.array[7980] = true;
instance.array[8008] = true;
instance.array[8036] = true;
instance.array[8064] = true;
instance.array[8092] = true;
instance.array[8120] = true;
instance.array[8148] = true;
instance.array[8176] = true;
instance.array[8204] = true;
instance.array[8232] = true;
instance.array[8260] = true;
instance.array[8288] = true;
instance.array[8316] = true;
instance.array[8344] = true;
instance.array[8372] = true;
instance.array[8400] = true;
instance.array[8428] = true;
instance.array[8456] = true;
instance.array[8484] = true;
instance.array[8512] = true;
instance.array[8540] = true;
instance.array[8568] = true;
instance.array[8596] = true;
instance.array[8624] = true;
instance.array[8652] = true;
instance.array[8680] = true;
instance.array[8708] = true;
instance.array[8736] = true;
instance.array[8764] = true;
instance.array[8792] = true;
instance.array[8820] = true;
instance.array[8848] = true;
instance.array[8876] = true;
instance.array[8904] = true;
instance.array[8932] = true;
instance.array[8960] = true;
instance.array[8988] = true;
instance.array[9016] = true;
instance.array[9044] = true;
instance.array[9072] = true;
instance.array[9100] = true;
instance.array[9128] = true;
instance.array[9156] = true;
instance.array[9184] = true;
instance.array[9212] = true;
instance.array[9240] = true;
instance.array[9268] = true;
instance.array[9296] = true;
instance.array[9324] = true;
instance.array[9352] = true;
instance.array[9380] = true;
instance.array[9408] = true;
instance.array[9436] = true;
instance.array[9464] = true;
instance.array[9492] = true;
instance.array[9520] = true;
instance.array[9548] = true;
instance.array[9576] = true;
instance.array[9604] = true;
instance.array[9632] = true;
instance.array[9660] = true;
instance.array[9688] = true;
instance.array[9716] = true;
instance.array[9744] = true;
instance.array[9772] = true;
instance.array[9800] = true;
instance.array[9828] = true;
instance.array[9856] = true;
instance.array[9884] = true;
instance.array[9912] = true;
instance.array[9940] = true;
instance.array[9968] = true;
instance.array[9996] = true;
instance.array[10024] = true;
instance.array[10052] = true;
instance.array[10080] = true;
instance.array[10108] = true;
instance.array[10136] = true;
instance.array[10164] = true;
instance.array[10192] = true;
instance.array[10220] = true;
instance.array[10248] = true;
instance.array[10276] = true;
instance.array[10304] = true;
instance.array[10332] = true;
instance.array[10360] = true;
instance.array[10388] = true;
instance.array[10416] = true;
instance.array[10444] = true;
instance.array[10472] = true;
instance.array[10500] = true;
instance.array[10528] = true;
instance.array[10556] = true;
instance.array[10584] = true;
instance.array[10612] = true;
instance.array[10640] = true;
instance.array[10668] = true;
instance.array[10696] = true;
instance.array[10724] = true;
instance.array[10752] = true;
instance.array[10780] = true;
instance.array[10808] = true;
instance.array[10836] = true;
instance.array[10864] = true;
instance.array[10892] = true;
instance.array[10920] = true;
instance.array[10948] = true;
instance.array[10976] = true;
instance.array[11004] = true;
instance.array[11032] = true;
instance.array[11060] = true;
instance.array[11088] = true;
instance.array[11116] = true;
instance.array[11144] = true;
// Placeholder: 0. Struct name, 1. Code point kind
return instance;
}
pub fn deinit(self: *LV) void {
self.allocator.free(self.array);
}
// isLV checks if cp is of the kind LV.
pub fn isLV(self: LV, cp: u21) bool {
if (cp < self.lo or cp > self.hi) return false;
const index = cp - self.lo;
return if (index >= self.array.len) false else self.array[index];
} | src/components/autogen/GraphemeBreakProperty/LV.zig |
const std = @import("std");
const Builder = std.build.Builder;
const glfw = @import("libs/mach-glfw/build.zig");
const system_sdk = @import("libs/mach-glfw/system_sdk.zig");
pub const LinuxWindowManager = enum {
X11,
Wayland,
};
pub const Options = struct {
/// Defaults to X11 on Linux.
linux_window_manager: ?LinuxWindowManager = null,
/// Defaults to true on Windows
d3d12: ?bool = null,
/// Defaults to true on Darwin
metal: ?bool = null,
/// Defaults to true on Linux, Fuchsia
// TODO(build-system): enable on Windows if we can cross compile Vulkan
vulkan: ?bool = null,
/// Defaults to true on Windows, Linux
// TODO(build-system): not respected at all currently
desktop_gl: ?bool = null,
/// Defaults to true on Android, Linux, Windows, Emscripten
// TODO(build-system): not respected at all currently
opengl_es: ?bool = null,
/// Whether or not minimal debug symbols should be emitted. This is -g1 in most cases, enough to
/// produce stack traces but omitting debug symbols for locals. For spirv-tools and tint in
/// specific, -g0 will be used (no debug symbols at all) to save an additional ~39M.
///
/// When enabled, a debug build of the static library goes from ~947M to just ~53M.
minimal_debug_symbols: bool = true,
/// Detects the default options to use for the given target.
pub fn detectDefaults(self: Options, target: std.Target) Options {
const tag = target.os.tag;
const linux_desktop_like = isLinuxDesktopLike(target);
var options = self;
if (options.linux_window_manager == null and linux_desktop_like) options.linux_window_manager = .X11;
if (options.d3d12 == null) options.d3d12 = tag == .windows;
if (options.metal == null) options.metal = tag.isDarwin();
if (options.vulkan == null) options.vulkan = tag == .fuchsia or linux_desktop_like;
// TODO(build-system): respect these options / defaults
if (options.desktop_gl == null) options.desktop_gl = linux_desktop_like; // TODO(build-system): add windows
options.opengl_es = false;
// if (options.opengl_es == null) options.opengl_es = tag == .windows or tag == .emscripten or target.isAndroid() or linux_desktop_like;
return options;
}
pub fn appendFlags(self: Options, flags: *std.ArrayList([]const u8), zero_debug_symbols: bool) !void {
if (self.minimal_debug_symbols) {
if (zero_debug_symbols) try flags.append("-g0") else try flags.append("-g1");
}
}
};
pub fn link(b: *Builder, step: *std.build.LibExeObjStep, options: Options) void {
const target = (std.zig.system.NativeTargetInfo.detect(b.allocator, step.target) catch unreachable).target;
const opt = options.detectDefaults(target);
const lib_mach_dawn_native = buildLibMachDawnNative(b, step, opt);
step.linkLibrary(lib_mach_dawn_native);
const lib_dawn_common = buildLibDawnCommon(b, step, opt);
step.linkLibrary(lib_dawn_common);
const lib_dawn_platform = buildLibDawnPlatform(b, step, opt);
step.linkLibrary(lib_dawn_platform);
// dawn-native
const lib_abseil_cpp = buildLibAbseilCpp(b, step, opt);
step.linkLibrary(lib_abseil_cpp);
const lib_dawn_native = buildLibDawnNative(b, step, opt);
step.linkLibrary(lib_dawn_native);
const lib_dawn_wire = buildLibDawnWire(b, step, opt);
step.linkLibrary(lib_dawn_wire);
const lib_dawn_utils = buildLibDawnUtils(b, step, opt);
step.linkLibrary(lib_dawn_utils);
const lib_spirv_tools = buildLibSPIRVTools(b, step, opt);
step.linkLibrary(lib_spirv_tools);
const lib_tint = buildLibTint(b, step, opt);
step.linkLibrary(lib_tint);
}
fn isLinuxDesktopLike(target: std.Target) bool {
const tag = target.os.tag;
return !tag.isDarwin() and tag != .windows and tag != .fuchsia and tag != .emscripten and !target.isAndroid();
}
fn buildLibMachDawnNative(b: *Builder, step: *std.build.LibExeObjStep, options: Options) *std.build.LibExeObjStep {
var main_abs = std.fs.path.join(b.allocator, &.{ thisDir(), "src/dawn/dummy.zig" }) catch unreachable;
const lib = b.addStaticLibrary("dawn-native-mach", main_abs);
lib.install();
lib.setBuildMode(step.build_mode);
lib.setTarget(step.target);
lib.linkLibCpp();
// TODO(build-system): pass system SDK options through
glfw.link(b, lib, .{ .system_sdk = .{ .set_sysroot = false } });
var flags = std.ArrayList([]const u8).init(b.allocator);
options.appendFlags(&flags, false) catch unreachable;
appendDawnEnableBackendTypeFlags(&flags, options) catch unreachable;
flags.appendSlice(&.{
include("libs/mach-glfw/upstream/glfw/include"),
include("libs/dawn/out/Debug/gen/src/include"),
include("libs/dawn/out/Debug/gen/src"),
include("libs/dawn/src/include"),
include("libs/dawn/src"),
}) catch unreachable;
lib.addCSourceFile("src/dawn/dawn_native_mach.cpp", flags.items);
return lib;
}
// Builds common sources; derived from src/common/BUILD.gn
fn buildLibDawnCommon(b: *Builder, step: *std.build.LibExeObjStep, options: Options) *std.build.LibExeObjStep {
var main_abs = std.fs.path.join(b.allocator, &.{ thisDir(), "src/dawn/dummy.zig" }) catch unreachable;
const lib = b.addStaticLibrary("dawn-common", main_abs);
lib.setBuildMode(step.build_mode);
lib.setTarget(step.target);
lib.linkLibCpp();
var flags = std.ArrayList([]const u8).init(b.allocator);
options.appendFlags(&flags, false) catch unreachable;
flags.append(include("libs/dawn/src")) catch unreachable;
var sources = std.ArrayList([]const u8).init(b.allocator);
for ([_][]const u8{
"src/common/Assert.cpp",
"src/common/DynamicLib.cpp",
"src/common/GPUInfo.cpp",
"src/common/Log.cpp",
"src/common/Math.cpp",
"src/common/RefCounted.cpp",
"src/common/Result.cpp",
"src/common/SlabAllocator.cpp",
"src/common/SystemUtils.cpp",
}) |path| {
var abs_path = std.fs.path.join(b.allocator, &.{ thisDir(), "libs/dawn", path }) catch unreachable;
sources.append(abs_path) catch unreachable;
}
const target = (std.zig.system.NativeTargetInfo.detect(b.allocator, step.target) catch unreachable).target;
if (target.os.tag == .macos) {
// TODO(build-system): pass system SDK options through
system_sdk.include(b, lib, .{});
lib.linkFramework("Foundation");
var abs_path = std.fs.path.join(b.allocator, &.{ thisDir(), "libs/dawn/src/common/SystemUtils_mac.mm" }) catch unreachable;
sources.append(abs_path) catch unreachable;
}
lib.addCSourceFiles(sources.items, flags.items);
return lib;
}
// Build dawn platform sources; derived from src/dawn_platform/BUILD.gn
fn buildLibDawnPlatform(b: *Builder, step: *std.build.LibExeObjStep, options: Options) *std.build.LibExeObjStep {
var main_abs = std.fs.path.join(b.allocator, &.{ thisDir(), "src/dawn/dummy.zig" }) catch unreachable;
const lib = b.addStaticLibrary("dawn-platform", main_abs);
lib.install();
lib.setBuildMode(step.build_mode);
lib.setTarget(step.target);
lib.linkLibCpp();
var flags = std.ArrayList([]const u8).init(b.allocator);
options.appendFlags(&flags, false) catch unreachable;
flags.appendSlice(&.{
include("libs/dawn/src"),
include("libs/dawn/src/include"),
include("libs/dawn/out/Debug/gen/src/include"),
}) catch unreachable;
var sources = std.ArrayList([]const u8).init(b.allocator);
for ([_][]const u8{
"src/dawn_platform/DawnPlatform.cpp",
"src/dawn_platform/WorkerThread.cpp",
"src/dawn_platform/tracing/EventTracer.cpp",
}) |path| {
var abs_path = std.fs.path.join(b.allocator, &.{ thisDir(), "libs/dawn", path }) catch unreachable;
sources.append(abs_path) catch unreachable;
}
lib.addCSourceFiles(sources.items, flags.items);
return lib;
}
fn appendDawnEnableBackendTypeFlags(flags: *std.ArrayList([]const u8), options: Options) !void {
const d3d12 = "-DDAWN_ENABLE_BACKEND_D3D12";
const metal = "-DDAWN_ENABLE_BACKEND_METAL";
const vulkan = "-DDAWN_ENABLE_BACKEND_VULKAN";
const opengl = "-DDAWN_ENABLE_BACKEND_OPENGL";
const desktop_gl = "-DDAWN_ENABLE_BACKEND_DESKTOP_GL";
const opengl_es = "-DDAWN_ENABLE_BACKEND_OPENGLES";
const backend_null = "-DDAWN_ENABLE_BACKEND_NULL";
try flags.append(backend_null);
if (options.d3d12.?) try flags.append(d3d12);
if (options.metal.?) try flags.append(metal);
if (options.vulkan.?) try flags.append(vulkan);
if (options.desktop_gl.?) try flags.appendSlice(&.{ opengl, desktop_gl });
if (options.opengl_es.?) try flags.appendSlice(&.{ opengl, opengl_es });
}
// Builds dawn native sources; derived from src/dawn_native/BUILD.gn
fn buildLibDawnNative(b: *Builder, step: *std.build.LibExeObjStep, options: Options) *std.build.LibExeObjStep {
var main_abs = std.fs.path.join(b.allocator, &.{ thisDir(), "src/dawn/dummy.zig" }) catch unreachable;
const lib = b.addStaticLibrary("dawn-native", main_abs);
lib.install();
lib.setBuildMode(step.build_mode);
lib.setTarget(step.target);
lib.linkLibCpp();
system_sdk.include(b, lib, .{});
var flags = std.ArrayList([]const u8).init(b.allocator);
options.appendFlags(&flags, false) catch unreachable;
appendDawnEnableBackendTypeFlags(&flags, options) catch unreachable;
if (options.desktop_gl.?) {
// OpenGL requires spriv-cross until Dawn moves OpenGL shader generation to Tint.
flags.append(include("libs/dawn/third_party/vulkan-deps/spirv-cross/src")) catch unreachable;
const lib_spirv_cross = buildLibSPIRVCross(b, step, options);
step.linkLibrary(lib_spirv_cross);
}
flags.appendSlice(&.{
include("libs/dawn"),
include("libs/dawn/src"),
include("libs/dawn/src/include"),
include("libs/dawn/third_party/vulkan-deps/spirv-tools/src/include"),
include("libs/dawn/third_party/abseil-cpp"),
include("libs/dawn/third_party/khronos"),
// TODO(build-system): make these optional
"-DTINT_BUILD_SPV_READER=1",
"-DTINT_BUILD_SPV_WRITER=1",
"-DTINT_BUILD_WGSL_READER=1",
"-DTINT_BUILD_WGSL_WRITER=1",
"-DTINT_BUILD_MSL_WRITER=1",
"-DTINT_BUILD_HLSL_WRITER=1",
include("libs/dawn/third_party/tint"),
include("libs/dawn/third_party/tint/include"),
include("libs/dawn/out/Debug/gen/src/include"),
include("libs/dawn/out/Debug/gen/src"),
}) catch unreachable;
var sources = std.ArrayList([]const u8).init(b.allocator);
sources.appendSlice(&.{
thisDir() ++ "/src/dawn/sources/dawn_native.cpp",
thisDir() ++ "/libs/dawn/out/Debug/gen/src/dawn/dawn_proc.c",
}) catch unreachable;
// dawn_native_utils_gen
sources.append(thisDir() ++ "/src/dawn/sources/dawn_native_utils_gen.cpp") catch unreachable;
// TODO(build-system): could allow enable_vulkan_validation_layers here. See src/dawn_native/BUILD.gn
// TODO(build-system): allow use_angle here. See src/dawn_native/BUILD.gn
// TODO(build-system): could allow use_swiftshader here. See src/dawn_native/BUILD.gn
if (options.d3d12.?) {
// TODO(build-system): windows
// libs += [ "dxguid.lib" ]
// TODO(build-system): reduce build units
for ([_][]const u8{
"src/dawn_native/d3d12/AdapterD3D12.cpp",
"src/dawn_native/d3d12/BackendD3D12.cpp",
"src/dawn_native/d3d12/BindGroupD3D12.cpp",
"src/dawn_native/d3d12/BindGroupLayoutD3D12.cpp",
"src/dawn_native/d3d12/BufferD3D12.cpp",
"src/dawn_native/d3d12/CPUDescriptorHeapAllocationD3D12.cpp",
"src/dawn_native/d3d12/CommandAllocatorManager.cpp",
"src/dawn_native/d3d12/CommandBufferD3D12.cpp",
"src/dawn_native/d3d12/CommandRecordingContext.cpp",
"src/dawn_native/d3d12/ComputePipelineD3D12.cpp",
"src/dawn_native/d3d12/D3D11on12Util.cpp",
"src/dawn_native/d3d12/D3D12Error.cpp",
"src/dawn_native/d3d12/D3D12Info.cpp",
"src/dawn_native/d3d12/DeviceD3D12.cpp",
"src/dawn_native/d3d12/GPUDescriptorHeapAllocationD3D12.cpp",
"src/dawn_native/d3d12/HeapAllocatorD3D12.cpp",
"src/dawn_native/d3d12/HeapD3D12.cpp",
"src/dawn_native/d3d12/NativeSwapChainImplD3D12.cpp",
"src/dawn_native/d3d12/PageableD3D12.cpp",
"src/dawn_native/d3d12/PipelineLayoutD3D12.cpp",
"src/dawn_native/d3d12/PlatformFunctions.cpp",
"src/dawn_native/d3d12/QuerySetD3D12.cpp",
"src/dawn_native/d3d12/QueueD3D12.cpp",
"src/dawn_native/d3d12/RenderPassBuilderD3D12.cpp",
"src/dawn_native/d3d12/RenderPipelineD3D12.cpp",
"src/dawn_native/d3d12/ResidencyManagerD3D12.cpp",
"src/dawn_native/d3d12/ResourceAllocatorManagerD3D12.cpp",
"src/dawn_native/d3d12/ResourceHeapAllocationD3D12.cpp",
"src/dawn_native/d3d12/SamplerD3D12.cpp",
"src/dawn_native/d3d12/SamplerHeapCacheD3D12.cpp",
"src/dawn_native/d3d12/ShaderModuleD3D12.cpp",
"src/dawn_native/d3d12/ShaderVisibleDescriptorAllocatorD3D12.cpp",
"src/dawn_native/d3d12/StagingBufferD3D12.cpp",
"src/dawn_native/d3d12/StagingDescriptorAllocatorD3D12.cpp",
"src/dawn_native/d3d12/SwapChainD3D12.cpp",
"src/dawn_native/d3d12/TextureCopySplitter.cpp",
"src/dawn_native/d3d12/TextureD3D12.cpp",
"src/dawn_native/d3d12/UtilsD3D12.cpp",
}) |path| {
var abs_path = std.fs.path.join(b.allocator, &.{ thisDir(), "libs/dawn", path }) catch unreachable;
lib.addCSourceFile(abs_path, flags.items);
sources.append(abs_path) catch unreachable;
}
}
if (options.metal.?) {
lib.linkFramework("Metal");
lib.linkFramework("CoreGraphics");
lib.linkFramework("Foundation");
lib.linkFramework("IOKit");
lib.linkFramework("IOSurface");
lib.linkFramework("QuartzCore");
sources.appendSlice(&.{
thisDir() ++ "/src/dawn/sources/dawn_native_metal.mm",
thisDir() ++ "/libs/dawn/src/dawn_native/metal/BackendMTL.mm",
}) catch unreachable;
}
if (options.linux_window_manager != null and options.linux_window_manager.? == .X11) {
lib.linkSystemLibrary("X11");
for ([_][]const u8{
"src/dawn_native/XlibXcbFunctions.cpp",
}) |path| {
var abs_path = std.fs.path.join(b.allocator, &.{ thisDir(), "libs/dawn", path }) catch unreachable;
sources.append(abs_path) catch unreachable;
}
}
for ([_][]const u8{
"src/dawn_native/null/DeviceNull.cpp",
}) |path| {
var abs_path = std.fs.path.join(b.allocator, &.{ thisDir(), "libs/dawn", path }) catch unreachable;
sources.append(abs_path) catch unreachable;
}
if (options.desktop_gl.? or options.vulkan.?) {
for ([_][]const u8{
"src/dawn_native/SpirvValidation.cpp",
}) |path| {
var abs_path = std.fs.path.join(b.allocator, &.{ thisDir(), "libs/dawn", path }) catch unreachable;
sources.append(abs_path) catch unreachable;
}
}
if (options.desktop_gl.?) {
for ([_][]const u8{
"out/Debug/gen/src/dawn_native/opengl/OpenGLFunctionsBase_autogen.cpp",
}) |path| {
var abs_path = std.fs.path.join(b.allocator, &.{ thisDir(), "libs/dawn", path }) catch unreachable;
sources.append(abs_path) catch unreachable;
}
// TODO(build-system): reduce build units
for ([_][]const u8{
"src/dawn_native/opengl/BackendGL.cpp",
"src/dawn_native/opengl/BindGroupGL.cpp",
"src/dawn_native/opengl/BindGroupLayoutGL.cpp",
"src/dawn_native/opengl/BufferGL.cpp",
"src/dawn_native/opengl/CommandBufferGL.cpp",
"src/dawn_native/opengl/ComputePipelineGL.cpp",
"src/dawn_native/opengl/DeviceGL.cpp",
"src/dawn_native/opengl/GLFormat.cpp",
"src/dawn_native/opengl/NativeSwapChainImplGL.cpp",
"src/dawn_native/opengl/OpenGLFunctions.cpp",
"src/dawn_native/opengl/OpenGLVersion.cpp",
"src/dawn_native/opengl/PersistentPipelineStateGL.cpp",
"src/dawn_native/opengl/PipelineGL.cpp",
"src/dawn_native/opengl/PipelineLayoutGL.cpp",
"src/dawn_native/opengl/QuerySetGL.cpp",
"src/dawn_native/opengl/QueueGL.cpp",
"src/dawn_native/opengl/RenderPipelineGL.cpp",
"src/dawn_native/opengl/SamplerGL.cpp",
"src/dawn_native/opengl/ShaderModuleGL.cpp",
"src/dawn_native/opengl/SpirvUtils.cpp",
"src/dawn_native/opengl/SwapChainGL.cpp",
"src/dawn_native/opengl/TextureGL.cpp",
"src/dawn_native/opengl/UtilsGL.cpp",
}) |path| {
var abs_path = std.fs.path.join(b.allocator, &.{ thisDir(), "libs/dawn", path }) catch unreachable;
sources.append(abs_path) catch unreachable;
}
}
const target = (std.zig.system.NativeTargetInfo.detect(b.allocator, step.target) catch unreachable).target;
if (options.vulkan.?) {
// TODO(build-system): reduce build units
for ([_][]const u8{
"src/dawn_native/vulkan/AdapterVk.cpp",
"src/dawn_native/vulkan/BackendVk.cpp",
"src/dawn_native/vulkan/BindGroupLayoutVk.cpp",
"src/dawn_native/vulkan/BindGroupVk.cpp",
"src/dawn_native/vulkan/BufferVk.cpp",
"src/dawn_native/vulkan/CommandBufferVk.cpp",
"src/dawn_native/vulkan/ComputePipelineVk.cpp",
"src/dawn_native/vulkan/DescriptorSetAllocator.cpp",
"src/dawn_native/vulkan/DeviceVk.cpp",
"src/dawn_native/vulkan/FencedDeleter.cpp",
"src/dawn_native/vulkan/NativeSwapChainImplVk.cpp",
"src/dawn_native/vulkan/PipelineLayoutVk.cpp",
"src/dawn_native/vulkan/QuerySetVk.cpp",
"src/dawn_native/vulkan/QueueVk.cpp",
"src/dawn_native/vulkan/RenderPassCache.cpp",
"src/dawn_native/vulkan/RenderPipelineVk.cpp",
"src/dawn_native/vulkan/ResourceHeapVk.cpp",
"src/dawn_native/vulkan/ResourceMemoryAllocatorVk.cpp",
"src/dawn_native/vulkan/SamplerVk.cpp",
"src/dawn_native/vulkan/ShaderModuleVk.cpp",
"src/dawn_native/vulkan/StagingBufferVk.cpp",
"src/dawn_native/vulkan/SwapChainVk.cpp",
"src/dawn_native/vulkan/TextureVk.cpp",
"src/dawn_native/vulkan/UtilsVulkan.cpp",
"src/dawn_native/vulkan/VulkanError.cpp",
"src/dawn_native/vulkan/VulkanExtensions.cpp",
"src/dawn_native/vulkan/VulkanFunctions.cpp",
"src/dawn_native/vulkan/VulkanInfo.cpp",
}) |path| {
var abs_path = std.fs.path.join(b.allocator, &.{ thisDir(), "libs/dawn", path }) catch unreachable;
sources.append(abs_path) catch unreachable;
}
if (isLinuxDesktopLike(target)) {
for ([_][]const u8{
"src/dawn_native/vulkan/external_memory/MemoryServiceOpaqueFD.cpp",
"src/dawn_native/vulkan/external_semaphore/SemaphoreServiceFD.cpp",
}) |path| {
var abs_path = std.fs.path.join(b.allocator, &.{ thisDir(), "libs/dawn", path }) catch unreachable;
lib.addCSourceFile(abs_path, flags.items);
sources.append(abs_path) catch unreachable;
}
} else if (target.os.tag == .fuchsia) {
for ([_][]const u8{
"src/dawn_native/vulkan/external_memory/MemoryServiceZirconHandle.cpp",
"src/dawn_native/vulkan/external_semaphore/SemaphoreServiceZirconHandle.cpp",
}) |path| {
var abs_path = std.fs.path.join(b.allocator, &.{ thisDir(), "libs/dawn", path }) catch unreachable;
sources.append(abs_path) catch unreachable;
}
} else {
for ([_][]const u8{
"src/dawn_native/vulkan/external_memory/MemoryServiceNull.cpp",
"src/dawn_native/vulkan/external_semaphore/SemaphoreServiceNull.cpp",
}) |path| {
var abs_path = std.fs.path.join(b.allocator, &.{ thisDir(), "libs/dawn", path }) catch unreachable;
sources.append(abs_path) catch unreachable;
}
}
}
// TODO(build-system): fuchsia: add is_fuchsia here from upstream source file
if (options.vulkan.?) {
// TODO(build-system): vulkan
// if (enable_vulkan_validation_layers) {
// defines += [
// "DAWN_ENABLE_VULKAN_VALIDATION_LAYERS",
// "DAWN_VK_DATA_DIR=\"$vulkan_data_subdir\"",
// ]
// }
// if (enable_vulkan_loader) {
// data_deps += [ "${dawn_vulkan_loader_dir}:libvulkan" ]
// defines += [ "DAWN_ENABLE_VULKAN_LOADER" ]
// }
}
// TODO(build-system): swiftshader
// if (use_swiftshader) {
// data_deps += [
// "${dawn_swiftshader_dir}/src/Vulkan:icd_file",
// "${dawn_swiftshader_dir}/src/Vulkan:swiftshader_libvulkan",
// ]
// defines += [
// "DAWN_ENABLE_SWIFTSHADER",
// "DAWN_SWIFTSHADER_VK_ICD_JSON=\"${swiftshader_icd_file_name}\"",
// ]
// }
// }
if (options.opengl_es.?) {
// TODO(build-system): gles
// if (use_angle) {
// data_deps += [
// "${dawn_angle_dir}:libEGL",
// "${dawn_angle_dir}:libGLESv2",
// ]
// }
// }
}
for ([_][]const u8{
"src/dawn_native/DawnNative.cpp",
"src/dawn_native/null/NullBackend.cpp",
}) |path| {
var abs_path = std.fs.path.join(b.allocator, &.{ thisDir(), "libs/dawn", path }) catch unreachable;
sources.append(abs_path) catch unreachable;
}
if (options.d3d12.?) {
for ([_][]const u8{
"src/dawn_native/d3d12/D3D12Backend.cpp",
}) |path| {
var abs_path = std.fs.path.join(b.allocator, &.{ thisDir(), "libs/dawn", path }) catch unreachable;
sources.append(abs_path) catch unreachable;
}
}
if (options.desktop_gl.?) {
for ([_][]const u8{
"src/dawn_native/opengl/OpenGLBackend.cpp",
}) |path| {
var abs_path = std.fs.path.join(b.allocator, &.{ thisDir(), "libs/dawn", path }) catch unreachable;
sources.append(abs_path) catch unreachable;
}
}
if (options.vulkan.?) {
for ([_][]const u8{
"src/dawn_native/vulkan/VulkanBackend.cpp",
}) |path| {
var abs_path = std.fs.path.join(b.allocator, &.{ thisDir(), "libs/dawn", path }) catch unreachable;
sources.append(abs_path) catch unreachable;
}
// TODO(build-system): vulkan
// if (enable_vulkan_validation_layers) {
// data_deps =
// [ "${dawn_vulkan_validation_layers_dir}:vulkan_validation_layers" ]
// if (!is_android) {
// data_deps +=
// [ "${dawn_vulkan_validation_layers_dir}:vulkan_gen_json_files" ]
// }
// }
}
lib.addCSourceFiles(sources.items, flags.items);
return lib;
}
// Builds third party tint sources; derived from third_party/tint/src/BUILD.gn
fn buildLibTint(b: *Builder, step: *std.build.LibExeObjStep, options: Options) *std.build.LibExeObjStep {
var main_abs = std.fs.path.join(b.allocator, &.{ thisDir(), "src/dawn/dummy.zig" }) catch unreachable;
const lib = b.addStaticLibrary("tint", main_abs);
lib.install();
lib.setBuildMode(step.build_mode);
lib.setTarget(step.target);
lib.linkLibCpp();
var flags = std.ArrayList([]const u8).init(b.allocator);
options.appendFlags(&flags, true) catch unreachable;
flags.appendSlice(&.{
// TODO(build-system): make these optional
"-DTINT_BUILD_SPV_READER=1",
"-DTINT_BUILD_SPV_WRITER=1",
"-DTINT_BUILD_WGSL_READER=1",
"-DTINT_BUILD_WGSL_WRITER=1",
"-DTINT_BUILD_MSL_WRITER=1",
"-DTINT_BUILD_HLSL_WRITER=1",
"-DTINT_BUILD_GLSL_WRITER=1",
include("libs/dawn"),
include("libs/dawn/third_party/tint"),
include("libs/dawn/third_party/tint/include"),
// Required for TINT_BUILD_SPV_READER=1 and TINT_BUILD_SPV_WRITER=1, if specified
include("libs/dawn/third_party/vulkan-deps"),
include("libs/dawn/third_party/vulkan-deps/spirv-tools/src"),
include("libs/dawn/third_party/vulkan-deps/spirv-tools/src/include"),
include("libs/dawn/third_party/vulkan-deps/spirv-headers/src/include"),
include("libs/dawn/out/Debug/gen/third_party/vulkan-deps/spirv-tools/src"),
include("libs/dawn/out/Debug/gen/third_party/vulkan-deps/spirv-tools/src/include"),
}) catch unreachable;
// libtint_core_all_src
var sources = std.ArrayList([]const u8).init(b.allocator);
sources.appendSlice(&.{
thisDir() ++ "/src/dawn/sources/tint_core_all_src.cc",
thisDir() ++ "/src/dawn/sources/tint_core_all_src_2.cc",
thisDir() ++ "/libs/dawn/third_party/tint/src/ast/node.cc",
thisDir() ++ "/libs/dawn/third_party/tint/src/ast/texture.cc",
}) catch unreachable;
const target = (std.zig.system.NativeTargetInfo.detect(b.allocator, step.target) catch unreachable).target;
switch (target.os.tag) {
.windows => sources.append(thisDir() ++ "/libs/dawn/third_party/tint/src/diagnostic/printer_windows.cc") catch unreachable,
.linux => sources.append(thisDir() ++ "/libs/dawn/third_party/tint/src/diagnostic/printer_linux.cc") catch unreachable,
else => sources.append(thisDir() ++ "/libs/dawn/third_party/tint/src/diagnostic/printer_other.cc") catch unreachable,
}
// libtint_sem_src
sources.appendSlice(&.{
thisDir() ++ "/src/dawn/sources/tint_sem_src.cc",
thisDir() ++ "/src/dawn/sources/tint_sem_src_2.cc",
thisDir() ++ "/libs/dawn/third_party/tint/src/sem/node.cc",
thisDir() ++ "/libs/dawn/third_party/tint/src/sem/texture_type.cc",
}) catch unreachable;
// libtint_spv_reader_src
sources.append(thisDir() ++ "/src/dawn/sources/tint_spv_reader_src.cc") catch unreachable;
// libtint_spv_writer_src
sources.append(thisDir() ++ "/src/dawn/sources/tint_spv_writer_src.cc") catch unreachable;
// TODO(build-system): make optional
// libtint_wgsl_reader_src
for ([_][]const u8{
"third_party/tint/src/reader/wgsl/lexer.cc",
"third_party/tint/src/reader/wgsl/parser.cc",
"third_party/tint/src/reader/wgsl/parser_impl.cc",
"third_party/tint/src/reader/wgsl/token.cc",
}) |path| {
var abs_path = std.fs.path.join(b.allocator, &.{ thisDir(), "libs/dawn", path }) catch unreachable;
sources.append(abs_path) catch unreachable;
}
// TODO(build-system): make optional
// libtint_wgsl_writer_src
for ([_][]const u8{
"third_party/tint/src/writer/wgsl/generator.cc",
"third_party/tint/src/writer/wgsl/generator_impl.cc",
}) |path| {
var abs_path = std.fs.path.join(b.allocator, &.{ thisDir(), "libs/dawn", path }) catch unreachable;
sources.append(abs_path) catch unreachable;
}
// TODO(build-system): make optional
// libtint_msl_writer_src
for ([_][]const u8{
"third_party/tint/src/writer/msl/generator.cc",
"third_party/tint/src/writer/msl/generator_impl.cc",
}) |path| {
var abs_path = std.fs.path.join(b.allocator, &.{ thisDir(), "libs/dawn", path }) catch unreachable;
sources.append(abs_path) catch unreachable;
}
// TODO(build-system): make optional
// libtint_hlsl_writer_src
for ([_][]const u8{
"third_party/tint/src/writer/hlsl/generator.cc",
"third_party/tint/src/writer/hlsl/generator_impl.cc",
}) |path| {
var abs_path = std.fs.path.join(b.allocator, &.{ thisDir(), "libs/dawn", path }) catch unreachable;
sources.append(abs_path) catch unreachable;
}
// TODO(build-system): make optional
// libtint_glsl_writer_src
for ([_][]const u8{
"third_party/tint/src/transform/glsl.cc",
"third_party/tint/src/writer/glsl/generator.cc",
"third_party/tint/src/writer/glsl/generator_impl.cc",
}) |path| {
var abs_path = std.fs.path.join(b.allocator, &.{ thisDir(), "libs/dawn", path }) catch unreachable;
sources.append(abs_path) catch unreachable;
}
lib.addCSourceFiles(sources.items, flags.items);
return lib;
}
// Builds third_party/vulkan-deps/spirv-tools sources; derived from third_party/vulkan-deps/spirv-tools/src/BUILD.gn
fn buildLibSPIRVTools(b: *Builder, step: *std.build.LibExeObjStep, options: Options) *std.build.LibExeObjStep {
var main_abs = std.fs.path.join(b.allocator, &.{ thisDir(), "src/dawn/dummy.zig" }) catch unreachable;
const lib = b.addStaticLibrary("spirv-tools", main_abs);
lib.install();
lib.setBuildMode(step.build_mode);
lib.setTarget(step.target);
lib.linkLibCpp();
var flags = std.ArrayList([]const u8).init(b.allocator);
options.appendFlags(&flags, true) catch unreachable;
flags.appendSlice(&.{
include("libs/dawn"),
include("libs/dawn/third_party/vulkan-deps/spirv-tools/src"),
include("libs/dawn/third_party/vulkan-deps/spirv-tools/src/include"),
include("libs/dawn/third_party/vulkan-deps/spirv-headers/src/include"),
include("libs/dawn/out/Debug/gen/third_party/vulkan-deps/spirv-tools/src"),
include("libs/dawn/out/Debug/gen/third_party/vulkan-deps/spirv-tools/src/include"),
}) catch unreachable;
// spvtools
var sources = std.ArrayList([]const u8).init(b.allocator);
sources.appendSlice(&.{
thisDir() ++ "/src/dawn/sources/spirv_tools.cpp",
thisDir() ++ "/libs/dawn/third_party/vulkan-deps/spirv-tools/src/source/operand.cpp",
thisDir() ++ "/libs/dawn/third_party/vulkan-deps/spirv-tools/src/source/spirv_reducer_options.cpp",
}) catch unreachable;
// spvtools_val
sources.append(thisDir() ++ "/src/dawn/sources/spirv_tools_val.cpp") catch unreachable;
// spvtools_opt
sources.appendSlice(&.{
thisDir() ++ "/src/dawn/sources/spirv_tools_opt.cpp",
thisDir() ++ "/src/dawn/sources/spirv_tools_opt_2.cpp",
thisDir() ++ "/libs/dawn/third_party/vulkan-deps/spirv-tools/src/source/opt/local_single_store_elim_pass.cpp",
thisDir() ++ "/libs/dawn/third_party/vulkan-deps/spirv-tools/src/source/opt/loop_unswitch_pass.cpp",
thisDir() ++ "/libs/dawn/third_party/vulkan-deps/spirv-tools/src/source/opt/mem_pass.cpp",
thisDir() ++ "/libs/dawn/third_party/vulkan-deps/spirv-tools/src/source/opt/ssa_rewrite_pass.cpp",
thisDir() ++ "/libs/dawn/third_party/vulkan-deps/spirv-tools/src/source/opt/vector_dce.cpp",
}) catch unreachable;
// spvtools_link
for ([_][]const u8{
"third_party/vulkan-deps/spirv-tools/src/source/link/linker.cpp",
}) |path| {
var abs_path = std.fs.path.join(b.allocator, &.{ thisDir(), "libs/dawn", path }) catch unreachable;
sources.append(abs_path) catch unreachable;
}
lib.addCSourceFiles(sources.items, flags.items);
return lib;
}
// Builds third_party/vulkan-deps/spirv-tools sources; derived from third_party/vulkan-deps/spirv-tools/src/BUILD.gn
fn buildLibSPIRVCross(b: *Builder, step: *std.build.LibExeObjStep, options: Options) *std.build.LibExeObjStep {
var main_abs = std.fs.path.join(b.allocator, &.{ thisDir(), "src/dawn/dummy.zig" }) catch unreachable;
const lib = b.addStaticLibrary("spirv-cross", main_abs);
lib.install();
lib.setBuildMode(step.build_mode);
lib.setTarget(step.target);
lib.linkLibCpp();
var flags = std.ArrayList([]const u8).init(b.allocator);
options.appendFlags(&flags, false) catch unreachable;
flags.appendSlice(&.{
"-DSPIRV_CROSS_EXCEPTIONS_TO_ASSERTIONS",
include("libs/dawn/third_party/vulkan-deps/spirv-cross/src"),
include("libs/dawn"),
"-Wno-extra-semi",
"-Wno-ignored-qualifiers",
"-Wno-implicit-fallthrough",
"-Wno-inconsistent-missing-override",
"-Wno-missing-field-initializers",
"-Wno-newline-eof",
"-Wno-sign-compare",
"-Wno-unused-variable",
}) catch unreachable;
const target = (std.zig.system.NativeTargetInfo.detect(b.allocator, step.target) catch unreachable).target;
if (target.os.tag != .windows) flags.append("-fno-exceptions") catch unreachable;
// spvtools_link
lib.addCSourceFile(thisDir() ++ "/src/dawn/sources/spirv_cross.cpp", flags.items);
return lib;
}
// Builds third_party/abseil sources; derived from:
//
// ```
// $ find third_party/abseil-cpp/absl | grep '\.cc' | grep -v 'test' | grep -v 'benchmark' | grep -v gaussian_distribution_gentables | grep -v print_hash_of | grep -v chi_square
// ```
//
fn buildLibAbseilCpp(b: *Builder, step: *std.build.LibExeObjStep, options: Options) *std.build.LibExeObjStep {
var main_abs = std.fs.path.join(b.allocator, &.{ thisDir(), "src/dawn/dummy.zig" }) catch unreachable;
const lib = b.addStaticLibrary("abseil-cpp", main_abs);
lib.install();
lib.setBuildMode(step.build_mode);
lib.setTarget(step.target);
lib.linkLibCpp();
system_sdk.include(b, lib, .{});
const target = (std.zig.system.NativeTargetInfo.detect(b.allocator, step.target) catch unreachable).target;
if (target.os.tag == .macos) lib.linkFramework("CoreFoundation");
var flags = std.ArrayList([]const u8).init(b.allocator);
options.appendFlags(&flags, false) catch unreachable;
flags.appendSlice(&.{
include("libs/dawn"),
include("libs/dawn/third_party/abseil-cpp"),
}) catch unreachable;
// absl
lib.addCSourceFiles(&.{
thisDir() ++ "/src/dawn/sources/abseil.cc",
thisDir() ++ "/libs/dawn/third_party/abseil-cpp/absl/strings/numbers.cc",
thisDir() ++ "/libs/dawn/third_party/abseil-cpp/absl/time/internal/cctz/src/time_zone_posix.cc",
thisDir() ++ "/libs/dawn/third_party/abseil-cpp/absl/time/format.cc",
thisDir() ++ "/libs/dawn/third_party/abseil-cpp/absl/random/internal/randen_hwaes.cc",
}, flags.items);
return lib;
}
// Buids dawn wire sources; derived from src/dawn_wire/BUILD.gn
fn buildLibDawnWire(b: *Builder, step: *std.build.LibExeObjStep, options: Options) *std.build.LibExeObjStep {
var main_abs = std.fs.path.join(b.allocator, &.{ thisDir(), "src/dawn/dummy.zig" }) catch unreachable;
const lib = b.addStaticLibrary("dawn-wire", main_abs);
lib.install();
lib.setBuildMode(step.build_mode);
lib.setTarget(step.target);
lib.linkLibCpp();
var flags = std.ArrayList([]const u8).init(b.allocator);
options.appendFlags(&flags, false) catch unreachable;
flags.appendSlice(&.{
include("libs/dawn"),
include("libs/dawn/src"),
include("libs/dawn/src/include"),
include("libs/dawn/out/Debug/gen/src/include"),
include("libs/dawn/out/Debug/gen/src"),
}) catch unreachable;
lib.addCSourceFile(thisDir() ++ "/src/dawn/sources/dawn_wire_gen.cpp", flags.items);
return lib;
}
// Builds dawn utils sources; derived from src/utils/BUILD.gn
fn buildLibDawnUtils(b: *Builder, step: *std.build.LibExeObjStep, options: Options) *std.build.LibExeObjStep {
var main_abs = std.fs.path.join(b.allocator, &.{ thisDir(), "src/dawn/dummy.zig" }) catch unreachable;
const lib = b.addStaticLibrary("dawn-utils", main_abs);
lib.install();
lib.setBuildMode(step.build_mode);
lib.setTarget(step.target);
lib.linkLibCpp();
glfw.link(b, lib, .{ .system_sdk = .{ .set_sysroot = false } });
var flags = std.ArrayList([]const u8).init(b.allocator);
options.appendFlags(&flags, false) catch unreachable;
appendDawnEnableBackendTypeFlags(&flags, options) catch unreachable;
flags.appendSlice(&.{
include("libs/mach-glfw/upstream/glfw/include"),
include("libs/dawn/src"),
include("libs/dawn/src/include"),
include("libs/dawn/out/Debug/gen/src/include"),
}) catch unreachable;
var sources = std.ArrayList([]const u8).init(b.allocator);
for ([_][]const u8{
"src/utils/BackendBinding.cpp",
"src/utils/NullBinding.cpp",
}) |path| {
var abs_path = std.fs.path.join(b.allocator, &.{ thisDir(), "libs/dawn", path }) catch unreachable;
sources.append(abs_path) catch unreachable;
}
if (options.d3d12.?) {
for ([_][]const u8{
"src/utils/D3D12Binding.cpp",
}) |path| {
var abs_path = std.fs.path.join(b.allocator, &.{ thisDir(), "libs/dawn", path }) catch unreachable;
sources.append(abs_path) catch unreachable;
}
}
if (options.metal.?) {
for ([_][]const u8{
"src/utils/MetalBinding.mm",
}) |path| {
var abs_path = std.fs.path.join(b.allocator, &.{ thisDir(), "libs/dawn", path }) catch unreachable;
sources.append(abs_path) catch unreachable;
}
}
if (options.desktop_gl.?) {
for ([_][]const u8{
"src/utils/OpenGLBinding.cpp",
}) |path| {
var abs_path = std.fs.path.join(b.allocator, &.{ thisDir(), "libs/dawn", path }) catch unreachable;
sources.append(abs_path) catch unreachable;
}
}
if (options.vulkan.?) {
for ([_][]const u8{
"src/utils/VulkanBinding.cpp",
}) |path| {
var abs_path = std.fs.path.join(b.allocator, &.{ thisDir(), "libs/dawn", path }) catch unreachable;
sources.append(abs_path) catch unreachable;
}
}
lib.addCSourceFiles(sources.items, flags.items);
return lib;
}
fn include(comptime rel: []const u8) []const u8 {
return "-I" ++ thisDir() ++ "/" ++ rel;
}
fn thisDir() []const u8 {
return std.fs.path.dirname(@src().file) orelse ".";
} | gpu/build_dawn.zig |
const fmath = @import("index.zig");
pub fn ilogb(x: var) -> i32 {
const T = @typeOf(x);
switch (T) {
f32 => @inlineCall(ilogb32, x),
f64 => @inlineCall(ilogb64, x),
else => @compileError("ilogb not implemented for " ++ @typeName(T)),
}
}
// NOTE: Should these be exposed publically?
const fp_ilogbnan = -1 - i32(@maxValue(u32) >> 1);
const fp_ilogb0 = fp_ilogbnan;
fn ilogb32(x: f32) -> i32 {
var u = @bitCast(u32, x);
var e = i32((u >> 23) & 0xFF);
if (e == 0) {
u <<= 9;
if (u == 0) {
fmath.raiseInvalid();
return fp_ilogb0;
}
// subnormal
e = -0x7F;
while (u >> 31 == 0) : (u <<= 1) {
e -= 1;
}
return e;
}
if (e == 0xFF) {
fmath.raiseInvalid();
if (u << 9 != 0) {
return fp_ilogbnan;
} else {
return @maxValue(i32);
}
}
e - 0x7F
}
fn ilogb64(x: f64) -> i32 {
var u = @bitCast(u64, x);
var e = i32((u >> 52) & 0x7FF);
if (e == 0) {
u <<= 12;
if (u == 0) {
fmath.raiseInvalid();
return fp_ilogb0;
}
// subnormal
e = -0x3FF;
while (u >> 63 == 0) : (u <<= 1) {
e -= 1;
}
return e;
}
if (e == 0x7FF) {
fmath.raiseInvalid();
if (u << 12 != 0) {
return fp_ilogbnan;
} else {
return @maxValue(i32);
}
}
e - 0x3FF
}
test "ilogb" {
fmath.assert(ilogb(f32(0.2)) == ilogb32(0.2));
fmath.assert(ilogb(f64(0.2)) == ilogb64(0.2));
}
test "ilogb32" {
fmath.assert(ilogb32(0.0) == fp_ilogb0);
fmath.assert(ilogb32(0.5) == -1);
fmath.assert(ilogb32(0.8923) == -1);
fmath.assert(ilogb32(10.0) == 3);
fmath.assert(ilogb32(-123984) == 16);
fmath.assert(ilogb32(2398.23) == 11);
}
test "ilogb64" {
fmath.assert(ilogb64(0.0) == fp_ilogb0);
fmath.assert(ilogb64(0.5) == -1);
fmath.assert(ilogb64(0.8923) == -1);
fmath.assert(ilogb64(10.0) == 3);
fmath.assert(ilogb64(-123984) == 16);
fmath.assert(ilogb64(2398.23) == 11);
} | src/ilogb.zig |
const std = @import("std");
const mem = std.mem;
const testing = std.testing;
const Allocator = mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const ArrayList = std.ArrayList;
pub const Attribute = struct {
name: []const u8,
value: []const u8,
};
pub const Content = union(enum) {
CharData: []const u8,
Comment: []const u8,
Element: *Element,
};
pub const Element = struct {
pub const AttributeList = ArrayList(*Attribute);
pub const ContentList = ArrayList(Content);
tag: []const u8,
attributes: AttributeList,
children: ContentList,
fn init(tag: []const u8, alloc: *Allocator) Element {
return .{
.tag = tag,
.attributes = AttributeList.init(alloc),
.children = ContentList.init(alloc),
};
}
pub fn getAttribute(self: *Element, attrib_name: []const u8) ?[]const u8 {
for (self.attributes.items) |child| {
if (mem.eql(u8, child.name, attrib_name)) {
return child.value;
}
}
return null;
}
pub fn getCharData(self: *Element, child_tag: []const u8) ?[]const u8 {
const child = self.findChildByTag(child_tag) orelse return null;
if (child.children.items.len != 1) {
return null;
}
return switch (child.children.items[0]) {
.CharData => |char_data| char_data,
else => null,
};
}
pub fn iterator(self: *Element) ChildIterator {
return .{
.items = self.children.items,
.i = 0,
};
}
pub fn elements(self: *Element) ChildElementIterator {
return .{
.inner = self.iterator(),
};
}
pub fn findChildByTag(self: *Element, tag: []const u8) ?*Element {
return self.findChildrenByTag(tag).next();
}
pub fn findChildrenByTag(self: *Element, tag: []const u8) FindChildrenByTagIterator {
return .{
.inner = self.elements(),
.tag = tag,
};
}
pub const ChildIterator = struct {
items: []Content,
i: usize,
pub fn next(self: *ChildIterator) ?*Content {
if (self.i < self.items.len) {
self.i += 1;
return &self.items[self.i - 1];
}
return null;
}
};
pub const ChildElementIterator = struct {
inner: ChildIterator,
pub fn next(self: *ChildElementIterator) ?*Element {
while (self.inner.next()) |child| {
if (child.* != .Element) {
continue;
}
return child.*.Element;
}
return null;
}
};
pub const FindChildrenByTagIterator = struct {
inner: ChildElementIterator,
tag: []const u8,
pub fn next(self: *FindChildrenByTagIterator) ?*Element {
while (self.inner.next()) |child| {
if (!mem.eql(u8, child.tag, self.tag)) {
continue;
}
return child;
}
return null;
}
};
};
pub const XmlDecl = struct {
version: []const u8,
encoding: ?[]const u8,
standalone: ?bool,
};
pub const Document = struct {
arena: ArenaAllocator,
xml_decl: ?*XmlDecl,
root: *Element,
pub fn deinit(self: Document) void {
var arena = self.arena; // Copy to stack so self can be taken by value.
arena.deinit();
}
};
const ParseContext = struct {
source: []const u8,
offset: usize,
line: usize,
column: usize,
fn init(source: []const u8) ParseContext {
return .{
.source = source,
.offset = 0,
.line = 0,
.column = 0,
};
}
fn peek(self: *ParseContext) ?u8 {
return if (self.offset < self.source.len) self.source[self.offset] else null;
}
fn consume(self: *ParseContext) !u8 {
if (self.offset < self.source.len) {
return self.consumeNoEof();
}
return error.UnexpectedEof;
}
fn consumeNoEof(self: *ParseContext) u8 {
std.debug.assert(self.offset < self.source.len);
const c = self.source[self.offset];
self.offset += 1;
if (c == '\n') {
self.line += 1;
self.column = 0;
} else {
self.column += 1;
}
return c;
}
fn eat(self: *ParseContext, char: u8) bool {
self.expect(char) catch return false;
return true;
}
fn expect(self: *ParseContext, expected: u8) !void {
if (self.peek()) |actual| {
if (expected != actual) {
return error.UnexpectedCharacter;
}
_ = self.consumeNoEof();
return;
}
return error.UnexpectedEof;
}
fn eatStr(self: *ParseContext, text: []const u8) bool {
self.expectStr(text) catch return false;
return true;
}
fn expectStr(self: *ParseContext, text: []const u8) !void {
if (self.source.len < self.offset + text.len) {
return error.UnexpectedEof;
} else if (std.mem.startsWith(u8, self.source[self.offset..], text)) {
var i: usize = 0;
while (i < text.len) : (i += 1) {
_ = self.consumeNoEof();
}
return;
}
return error.UnexpectedCharacter;
}
fn eatWs(self: *ParseContext) bool {
var ws = false;
while (self.peek()) |ch| {
switch (ch) {
' ', '\t', '\n', '\r' => {
ws = true;
_ = self.consumeNoEof();
},
else => break,
}
}
return ws;
}
fn expectWs(self: *ParseContext) !void {
if (!self.eatWs()) return error.UnexpectedCharacter;
}
fn currentLine(self: ParseContext) []const u8 {
var begin: usize = 0;
if (mem.lastIndexOfScalar(u8, self.source[0..self.offset], '\n')) |prev_nl| {
begin = prev_nl + 1;
}
var end = mem.indexOfScalarPos(u8, self.source, self.offset, '\n') orelse self.source.len;
return self.source[begin..end];
}
};
test "ParseContext" {
{
var ctx = ParseContext.init("I like pythons");
try testing.expectEqual(@as(?u8, 'I'), ctx.peek());
try testing.expectEqual(@as(u8, 'I'), ctx.consumeNoEof());
try testing.expectEqual(@as(?u8, ' '), ctx.peek());
try testing.expectEqual(@as(u8, ' '), try ctx.consume());
try testing.expect(ctx.eat('l'));
try testing.expectEqual(@as(?u8, 'i'), ctx.peek());
try testing.expectEqual(false, ctx.eat('a'));
try testing.expectEqual(@as(?u8, 'i'), ctx.peek());
try ctx.expect('i');
try testing.expectEqual(@as(?u8, 'k'), ctx.peek());
try testing.expectError(error.UnexpectedCharacter, ctx.expect('a'));
try testing.expectEqual(@as(?u8, 'k'), ctx.peek());
try testing.expect(ctx.eatStr("ke"));
try testing.expectEqual(@as(?u8, ' '), ctx.peek());
try testing.expect(ctx.eatWs());
try testing.expectEqual(@as(?u8, 'p'), ctx.peek());
try testing.expectEqual(false, ctx.eatWs());
try testing.expectEqual(@as(?u8, 'p'), ctx.peek());
try testing.expectEqual(false, ctx.eatStr("aaaaaaaaa"));
try testing.expectEqual(@as(?u8, 'p'), ctx.peek());
try testing.expectError(error.UnexpectedEof, ctx.expectStr("aaaaaaaaa"));
try testing.expectEqual(@as(?u8, 'p'), ctx.peek());
try testing.expectError(error.UnexpectedCharacter, ctx.expectStr("pytn"));
try testing.expectEqual(@as(?u8, 'p'), ctx.peek());
try ctx.expectStr("python");
try testing.expectEqual(@as(?u8, 's'), ctx.peek());
}
{
var ctx = ParseContext.init("");
try testing.expectEqual(ctx.peek(), null);
try testing.expectError(error.UnexpectedEof, ctx.consume());
try testing.expectEqual(ctx.eat('p'), false);
try testing.expectError(error.UnexpectedEof, ctx.expect('p'));
}
}
pub const ParseError = error{
IllegalCharacter,
UnexpectedEof,
UnexpectedCharacter,
UnclosedValue,
UnclosedComment,
InvalidName,
InvalidEntity,
InvalidStandaloneValue,
NonMatchingClosingTag,
InvalidDocument,
OutOfMemory,
};
pub fn parse(backing_allocator: *Allocator, source: []const u8) !Document {
var ctx = ParseContext.init(source);
return try parseDocument(&ctx, backing_allocator);
}
fn parseDocument(ctx: *ParseContext, backing_allocator: *Allocator) !Document {
var doc = Document{
.arena = ArenaAllocator.init(backing_allocator),
.xml_decl = null,
.root = undefined,
};
errdefer doc.deinit();
try trySkipComments(ctx, &doc.arena.allocator);
doc.xml_decl = try tryParseProlog(ctx, &doc.arena.allocator);
_ = ctx.eatWs();
try trySkipComments(ctx, &doc.arena.allocator);
doc.root = (try tryParseElement(ctx, &doc.arena.allocator)) orelse return error.InvalidDocument;
_ = ctx.eatWs();
try trySkipComments(ctx, &doc.arena.allocator);
if (ctx.peek() != null) return error.InvalidDocument;
return doc;
}
fn parseAttrValue(ctx: *ParseContext, alloc: *Allocator) ![]const u8 {
const quote = try ctx.consume();
if (quote != '"' and quote != '\'') return error.UnexpectedCharacter;
const begin = ctx.offset;
while (true) {
const c = ctx.consume() catch return error.UnclosedValue;
if (c == quote) break;
}
const end = ctx.offset - 1;
return try dupeAndUnescape(alloc, ctx.source[begin..end]);
}
fn parseEqAttrValue(ctx: *ParseContext, alloc: *Allocator) ![]const u8 {
_ = ctx.eatWs();
try ctx.expect('=');
_ = ctx.eatWs();
return try parseAttrValue(ctx, alloc);
}
fn parseNameNoDupe(ctx: *ParseContext) ![]const u8 {
// XML's spec on names is very long, so to make this easier
// we just take any character that is not special and not whitespace
const begin = ctx.offset;
while (ctx.peek()) |ch| {
switch (ch) {
' ', '\t', '\n', '\r' => break,
'&', '"', '\'', '<', '>', '?', '=', '/' => break,
else => _ = ctx.consumeNoEof(),
}
}
const end = ctx.offset;
if (begin == end) return error.InvalidName;
return ctx.source[begin..end];
}
fn tryParseCharData(ctx: *ParseContext, alloc: *Allocator) !?[]const u8 {
const begin = ctx.offset;
while (ctx.peek()) |ch| {
switch (ch) {
'<' => break,
else => _ = ctx.consumeNoEof(),
}
}
const end = ctx.offset;
if (begin == end) return null;
return try dupeAndUnescape(alloc, ctx.source[begin..end]);
}
fn parseContent(ctx: *ParseContext, alloc: *Allocator) ParseError!Content {
if (try tryParseCharData(ctx, alloc)) |cd| {
return Content{ .CharData = cd };
} else if (try tryParseComment(ctx, alloc)) |comment| {
return Content{ .Comment = comment };
} else if (try tryParseElement(ctx, alloc)) |elem| {
return Content{ .Element = elem };
} else {
return error.UnexpectedCharacter;
}
}
fn tryParseAttr(ctx: *ParseContext, alloc: *Allocator) !?*Attribute {
const name = parseNameNoDupe(ctx) catch return null;
_ = ctx.eatWs();
try ctx.expect('=');
_ = ctx.eatWs();
const value = try parseAttrValue(ctx, alloc);
const attr = try alloc.create(Attribute);
attr.name = try alloc.dupe(u8, name);
attr.value = value;
return attr;
}
fn tryParseElement(ctx: *ParseContext, alloc: *Allocator) !?*Element {
const start = ctx.offset;
if (!ctx.eat('<')) return null;
const tag = parseNameNoDupe(ctx) catch {
ctx.offset = start;
return null;
};
const element = try alloc.create(Element);
element.* = Element.init(try alloc.dupe(u8, tag), alloc);
while (ctx.eatWs()) {
const attr = (try tryParseAttr(ctx, alloc)) orelse break;
try element.attributes.append(attr);
}
if (ctx.eatStr("/>")) {
return element;
}
try ctx.expect('>');
while (true) {
if (ctx.peek() == null) {
return error.UnexpectedEof;
} else if (ctx.eatStr("</")) {
break;
}
const content = try parseContent(ctx, alloc);
try element.children.append(content);
}
const closing_tag = try parseNameNoDupe(ctx);
if (!std.mem.eql(u8, tag, closing_tag)) {
return error.NonMatchingClosingTag;
}
_ = ctx.eatWs();
try ctx.expect('>');
return element;
}
test "tryParseElement" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var alloc = &arena.allocator;
{
var ctx = ParseContext.init("<= a='b'/>");
try testing.expectEqual(@as(?*Element, null), try tryParseElement(&ctx, alloc));
try testing.expectEqual(@as(?u8, '<'), ctx.peek());
}
{
var ctx = ParseContext.init("<python size='15' color = \"green\"/>");
const elem = try tryParseElement(&ctx, alloc);
try testing.expectEqualSlices(u8, elem.?.tag, "python");
const size_attr = elem.?.attributes.items[0];
try testing.expectEqualSlices(u8, size_attr.name, "size");
try testing.expectEqualSlices(u8, size_attr.value, "15");
const color_attr = elem.?.attributes.items[1];
try testing.expectEqualSlices(u8, color_attr.name, "color");
try testing.expectEqualSlices(u8, color_attr.value, "green");
}
{
var ctx = ParseContext.init("<python>test</python>");
const elem = try tryParseElement(&ctx, alloc);
try testing.expectEqualSlices(u8, elem.?.tag, "python");
try testing.expectEqualSlices(u8, elem.?.children.items[0].CharData, "test");
}
{
var ctx = ParseContext.init("<a>b<c/>d<e/>f<!--g--></a>");
const elem = try tryParseElement(&ctx, alloc);
try testing.expectEqualSlices(u8, elem.?.tag, "a");
try testing.expectEqualSlices(u8, elem.?.children.items[0].CharData, "b");
try testing.expectEqualSlices(u8, elem.?.children.items[1].Element.tag, "c");
try testing.expectEqualSlices(u8, elem.?.children.items[2].CharData, "d");
try testing.expectEqualSlices(u8, elem.?.children.items[3].Element.tag, "e");
try testing.expectEqualSlices(u8, elem.?.children.items[4].CharData, "f");
try testing.expectEqualSlices(u8, elem.?.children.items[5].Comment, "g");
}
}
fn tryParseProlog(ctx: *ParseContext, alloc: *Allocator) !?*XmlDecl {
const start = ctx.offset;
if (!ctx.eatStr("<?") or !mem.eql(u8, try parseNameNoDupe(ctx), "xml")) {
ctx.offset = start;
return null;
}
const decl = try alloc.create(XmlDecl);
decl.encoding = null;
decl.standalone = null;
// Version info is mandatory
try ctx.expectWs();
try ctx.expectStr("version");
decl.version = try parseEqAttrValue(ctx, alloc);
if (ctx.eatWs()) {
// Optional encoding and standalone info
var require_ws = false;
if (ctx.eatStr("encoding")) {
decl.encoding = try parseEqAttrValue(ctx, alloc);
require_ws = true;
}
if (require_ws == ctx.eatWs() and ctx.eatStr("standalone")) {
const standalone = try parseEqAttrValue(ctx, alloc);
if (std.mem.eql(u8, standalone, "yes")) {
decl.standalone = true;
} else if (std.mem.eql(u8, standalone, "no")) {
decl.standalone = false;
} else {
return error.InvalidStandaloneValue;
}
}
_ = ctx.eatWs();
}
try ctx.expectStr("?>");
return decl;
}
test "tryParseProlog" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var alloc = &arena.allocator;
{
var ctx = ParseContext.init("<?xmla version='aa'?>");
try testing.expectEqual(@as(?*XmlDecl, null), try tryParseProlog(&ctx, alloc));
try testing.expectEqual(@as(?u8, '<'), ctx.peek());
}
{
var ctx = ParseContext.init("<?xml version='aa'?>");
const decl = try tryParseProlog(&ctx, alloc);
try testing.expectEqualSlices(u8, "aa", decl.?.version);
try testing.expectEqual(@as(?[]const u8, null), decl.?.encoding);
try testing.expectEqual(@as(?bool, null), decl.?.standalone);
}
{
var ctx = ParseContext.init("<?xml version=\"aa\" encoding = 'bbb' standalone \t = 'yes'?>");
const decl = try tryParseProlog(&ctx, alloc);
try testing.expectEqualSlices(u8, "aa", decl.?.version);
try testing.expectEqualSlices(u8, "bbb", decl.?.encoding.?);
try testing.expectEqual(@as(?bool, true), decl.?.standalone.?);
}
}
fn trySkipComments(ctx: *ParseContext, alloc: *Allocator) !void {
while (try tryParseComment(ctx, alloc)) |_| {
_ = ctx.eatWs();
}
}
fn tryParseComment(ctx: *ParseContext, alloc: *Allocator) !?[]const u8 {
if (!ctx.eatStr("<!--")) return null;
const begin = ctx.offset;
while (!ctx.eatStr("-->")) {
_ = ctx.consume() catch return error.UnclosedComment;
}
const end = ctx.offset - "-->".len;
return try alloc.dupe(u8, ctx.source[begin..end]);
}
fn unescapeEntity(text: []const u8) !u8 {
const EntitySubstition = struct { text: []const u8, replacement: u8 };
const entities = [_]EntitySubstition{
.{ .text = "<", .replacement = '<' },
.{ .text = ">", .replacement = '>' },
.{ .text = "&", .replacement = '&' },
.{ .text = "'", .replacement = '\'' },
.{ .text = """, .replacement = '"' },
};
for (entities) |entity| {
if (std.mem.eql(u8, text, entity.text)) return entity.replacement;
}
return error.InvalidEntity;
}
fn dupeAndUnescape(alloc: *Allocator, text: []const u8) ![]const u8 {
const str = try alloc.alloc(u8, text.len);
var j: usize = 0;
var i: usize = 0;
while (i < text.len) : (j += 1) {
if (text[i] == '&') {
const entity_end = 1 + (mem.indexOfScalarPos(u8, text, i, ';') orelse return error.InvalidEntity);
str[j] = try unescapeEntity(text[i..entity_end]);
i = entity_end;
} else {
str[j] = text[i];
i += 1;
}
}
return alloc.shrink(str, j);
}
test "dupeAndUnescape" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var alloc = &arena.allocator;
try testing.expectEqualSlices(u8, "test", try dupeAndUnescape(alloc, "test"));
try testing.expectEqualSlices(u8, "a<b&c>d\"e'f<", try dupeAndUnescape(alloc, "a<b&c>d"e'f<"));
try testing.expectError(error.InvalidEntity, dupeAndUnescape(alloc, "python&"));
try testing.expectError(error.InvalidEntity, dupeAndUnescape(alloc, "python&&"));
try testing.expectError(error.InvalidEntity, dupeAndUnescape(alloc, "python&test;"));
try testing.expectError(error.InvalidEntity, dupeAndUnescape(alloc, "python&boa"));
}
test "Top level comments" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var alloc = &arena.allocator;
const doc = try parse(alloc, "<?xml version='aa'?><!--comment--><python color='green'/><!--another comment-->");
try testing.expectEqualSlices(u8, "python", doc.root.tag);
} | generator/xml.zig |
const WasGo = @cImport({
@cInclude("errno.h");
@cInclude("stdio.h");
@cInclude("stdlib.h");
@cInclude("wasgo/wasgo.h");
@cInclude("Spatial.h");
@cInclude("Transform.h");
@cInclude("InputEventKey.h");
});
const print = @import("std").debug.print;
var velocity: f32 = 0;
var frame_counter: i32 = 0;
var thrust: f32 = 0;
var thrust_limit: f32 = 50;
var thrust_delta: f32 = 0;
var gravity_influence: f32 = 100;
var smooth: f32 = 0.9;
export fn _ready() void {
// thrust_limit = WasGo.get_property_float("thrust_limit");
// gravity_influence = WasGo.get_property_float("gravity_influence");
// smooth = WasGo.get_property_float("smoothness");
}
// export fn _unhandled_key_input(p_key_event: WasGo.InputEventKey) void {
// p_key_event.get_scancode();
// switch (p_key_event.get_scancode()) {
// KEY_W => {
// if (p_key_event.is_pressed()) {
// thrust_delta = 10;
// } else {
// thrust_delta = 0;
// }
// break;
// },
// KEY_S => {
// if (p_key_event.is_pressed()) {
// thrust_delta = -10;
// } else {
// thrust_delta = 0;
// }
// break;
// },
// else => break,
// }
// }
export fn _physics_process(delta: f32) void {
// var y_ang: f32 = 0;
// var plane: WasGo.Spatial = {};
// var direction: WasGo.Vector3 = {};
// var target_vector: WasGo.Vector3 = {};
// var t: WasGo.Transform = {};
// var target_speed: f32 = 0;
// var this_node: Node = WasGo.this_node();
// var path: Variant = WasGo.get_property_nodepath("other_node");
// plane = @ptrCast(Spatial, this_node.get_node(path));
// var b: Basis = plane.get_transform().get_basis();
// direction = b.get_axis(2);
// y_ang = direction.angle_to(Vector3(0, 1, 0));
// if ((thrust <= thrust_limit and thrust_delta > 0) || (thrust >= 0 and thrust_delta < 0)) {
// thrust += thrust_delta;
// }
// target_speed = thrust + (y_ang / Math_PI - 0.5) * gravity_influence; //we subtract 0.5 from the angle over pi because gravity's influence should be zero at 90 degrees or when the angle over pi is 0.5
// velocity = (velocity * smooth + target_speed * (1 - smooth)) / 2;
// target_vector = Vector3(0, 0, velocity);
// t = plane.get_transform();
// t.translate(target_vector * delta);
// plane.set_transform(t);
// frame_counter = @rem(frame_counter + 1, 120);
// if (frame_counter == 0) {
// WasGo.printf("thrust: %d\n", int(thrust * 1000));
// WasGo.printf("y_ang: %d\n", int(y_ang * 1000));
// WasGo.printf("velocity: %d\n", int(velocity * 1000));
// }
} | demo/thrust-zig/thrust.zig |
const std = @import("std");
const mkl_path = "C:\\Program Files (x86)\\Intel\\oneAPI\\mkl\\latest\\";
const tbb_path = "C:\\Program Files (x86)\\Intel\\oneAPI\\tbb\\latest\\";
fn linkMKL(exe : *std.build.LibExeObjStep) void {
exe.addIncludeDir(mkl_path ++ "include");
exe.addLibPath(mkl_path ++ "lib\\intel64");
exe.linkSystemLibrary("mkl_core");
exe.linkSystemLibrary("mkl_tbb_thread");
exe.linkSystemLibrary("mkl_intel_thread");
exe.linkSystemLibrary("mkl_intel_lp64");
exe.addLibPath(tbb_path ++ "lib\\intel64\\vc14");
// even after doing this, tbb12 still seems to be dynamically linked
// it looks like tbb does not support static linking on purpose
// https://stackoverflow.com/a/19684240
// exe.linkSystemLibrary("tbb12");
exe.linkLibC();
// adding this in manually like this means that failing to specify use-mkl will
// result in a compile error instead of a link error
exe.addPackagePath("mkl", "bindings\\mkl.zig");
}
pub fn build(b: *std.build.Builder) void {
const use_mkl = b.option(bool, "use-mkl", "Use the MKL library") orelse false;
// Standard target options allows the person running `zig build` to choose
// what target to build for. Here we do not override the defaults, which
// means any target is allowed, and the default is native. Other options
// for restricting supported target set are available.
const target = b.standardTargetOptions(.{});
// Standard release options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall.
const mode = b.standardReleaseOptions();
const exe = b.addExecutable("main", "src/main.zig");
exe.setTarget(target);
exe.setBuildMode(mode);
exe.addBuildOption(bool, "USE_MKL", use_mkl);
if (use_mkl) {
linkMKL(exe);
}
exe.install();
const run_cmd = exe.run();
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
const test_step = b.step("test", "Run library tests");
for ([_][]const u8{
"src/tensor.zig", // for some reason this also runs array.zig's tests
// "src/array.zig",
}) |test_file| {
const tests = b.addTest(test_file);
tests.setTarget(target);
tests.setBuildMode(mode);
tests.addBuildOption(bool, "USE_MKL", use_mkl);
if (use_mkl) {
linkMKL(tests);
}
test_step.dependOn(&tests.step);
}
} | build.zig |
const std = @import("std");
const mem = std.mem;
const net = std.net;
const os = std.os;
const IO = @import("tigerbeetle-io").IO;
const http = @import("http");
fn IoOpContext(comptime ResultType: type) type {
return struct {
frame: anyframe = undefined,
result: ResultType = undefined,
};
}
const Client = struct {
io: IO,
sock: os.socket_t,
address: std.net.Address,
send_buf: []u8,
recv_buf: []u8,
allocator: mem.Allocator,
done: bool = false,
fn init(allocator: mem.Allocator, address: std.net.Address) !Client {
const sock = try os.socket(address.any.family, os.SOCK_STREAM | os.SOCK_CLOEXEC, 0);
const send_buf = try allocator.alloc(u8, 8192);
const recv_buf = try allocator.alloc(u8, 8192);
return Client{
.io = try IO.init(256, 0),
.sock = sock,
.address = address,
.send_buf = send_buf,
.recv_buf = recv_buf,
.allocator = allocator,
};
}
pub fn deinit(self: *Client) void {
self.allocator.free(self.send_buf);
self.allocator.free(self.recv_buf);
self.io.deinit();
}
pub fn start(self: *Client) !void {
try connect(&self.io, self.sock, self.address);
var fbs = std.io.fixedBufferStream(self.send_buf);
var w = fbs.writer();
std.fmt.format(w, "Hello from client!\n", .{}) catch unreachable;
const sent = try send(&self.io, self.sock, fbs.getWritten());
std.debug.print("Sent: {s}", .{self.send_buf[0..sent]});
const received = try recv(&self.io, self.sock, self.recv_buf);
std.debug.print("Received: {s}", .{self.recv_buf[0..received]});
try close(&self.io, self.sock);
self.done = true;
}
pub fn run(self: *Client) !void {
while (!self.done) try self.io.tick();
}
const ConnectContext = IoOpContext(IO.ConnectError!void);
fn connect(io: *IO, sock: os.socket_t, address: std.net.Address) IO.ConnectError!void {
var ctx: ConnectContext = undefined;
var completion: IO.Completion = undefined;
io.connect(*ConnectContext, &ctx, connectCallback, &completion, sock, address);
suspend {
ctx.frame = @frame();
}
return ctx.result;
}
fn connectCallback(
ctx: *ConnectContext,
completion: *IO.Completion,
result: IO.ConnectError!void,
) void {
ctx.result = result;
resume ctx.frame;
}
const SendContext = IoOpContext(IO.SendError!usize);
fn send(io: *IO, sock: os.socket_t, buffer: []const u8) IO.SendError!usize {
var ctx: SendContext = undefined;
var completion: IO.Completion = undefined;
io.send(
*SendContext,
&ctx,
sendCallback,
&completion,
sock,
buffer,
if (std.Target.current.os.tag == .linux) os.MSG_NOSIGNAL else 0,
);
suspend {
ctx.frame = @frame();
}
return ctx.result;
}
fn sendCallback(
ctx: *SendContext,
completion: *IO.Completion,
result: IO.SendError!usize,
) void {
ctx.result = result;
resume ctx.frame;
}
const RecvContext = IoOpContext(IO.RecvError!usize);
fn recv(io: *IO, sock: os.socket_t, buffer: []u8) IO.RecvError!usize {
var ctx: RecvContext = undefined;
var completion: IO.Completion = undefined;
io.recv(
*RecvContext,
&ctx,
recvCallback,
&completion,
sock,
buffer,
if (std.Target.current.os.tag == .linux) os.MSG_NOSIGNAL else 0,
);
suspend {
ctx.frame = @frame();
}
return ctx.result;
}
fn recvCallback(
ctx: *RecvContext,
completion: *IO.Completion,
result: IO.RecvError!usize,
) void {
ctx.result = result;
resume ctx.frame;
}
const CloseContext = IoOpContext(IO.CloseError!void);
fn close(io: *IO, sock: os.socket_t) IO.CloseError!void {
var ctx: CloseContext = undefined;
var completion: IO.Completion = undefined;
io.close(
*CloseContext,
&ctx,
closeCallback,
&completion,
sock,
);
suspend {
ctx.frame = @frame();
}
return ctx.result;
}
fn closeCallback(
ctx: *CloseContext,
completion: *IO.Completion,
result: IO.CloseError!void,
) void {
ctx.result = result;
resume ctx.frame;
}
};
pub fn main() anyerror!void {
const allocator = std.heap.page_allocator;
const address = try std.net.Address.parseIp4("127.0.0.1", 3131);
var client = try Client.init(allocator, address);
defer client.deinit();
_ = async client.start();
try client.run();
} | examples/async_tcp_echo_client.zig |
const std = @import("std");
const fs = std.fs;
const io = std.io;
const mem = std.mem;
const process = std.process;
const assert = std.debug.assert;
const tmpDir = std.testing.tmpDir;
const Allocator = mem.Allocator;
const Blake3 = std.crypto.hash.Blake3;
const OsTag = std.Target.Os.Tag;
const Arch = enum {
any,
aarch64,
x86_64,
fn fromTargetCpuArch(comptime arch: std.Target.Cpu.Arch) Arch {
return switch (arch) {
.aarch64 => .aarch64,
.x86_64 => .x86_64,
else => @compileError("unsupported CPU architecture"),
};
}
};
const Abi = enum {
any,
gnu,
};
const Target = struct {
arch: Arch,
os: OsTag = .macos,
abi: Abi = .gnu,
fn hash(a: Target) u32 {
return @enumToInt(a.arch) +%
(@enumToInt(a.os) *% @as(u32, 4202347608)) +%
(@enumToInt(a.abi) *% @as(u32, 4082223418));
}
fn eql(a: Target, b: Target) bool {
return a.arch == b.arch and a.os == b.os and a.abi == b.abi;
}
fn name(self: Target, allocator: *Allocator) ![]const u8 {
return std.fmt.allocPrint(allocator, "{s}-{s}-{s}", .{
@tagName(self.arch),
@tagName(self.os),
@tagName(self.abi),
});
}
};
const targets = [_]Target{
Target{
.arch = .any,
.abi = .any,
},
Target{
.arch = .aarch64,
},
Target{
.arch = .x86_64,
},
};
const dest_target: Target = .{
.arch = Arch.fromTargetCpuArch(std.builtin.cpu.arch),
};
const headers_source_prefix: []const u8 = "libc/include";
const common_name = "any-macos-any";
const Contents = struct {
bytes: []const u8,
hit_count: usize,
hash: []const u8,
is_generic: bool,
fn hitCountLessThan(context: void, lhs: *const Contents, rhs: *const Contents) bool {
_ = context;
return lhs.hit_count < rhs.hit_count;
}
};
const TargetToHashContext = struct {
pub fn hash(self: @This(), target: Target) u32 {
_ = self;
return target.hash();
}
pub fn eql(self: @This(), a: Target, b: Target) bool {
_ = self;
return a.eql(b);
}
};
const TargetToHash = std.ArrayHashMap(Target, []const u8, TargetToHashContext, true);
const HashToContents = std.StringHashMap(Contents);
const PathTable = std.StringHashMap(*TargetToHash);
/// The don't-dedup-list contains file paths with known problematic headers
/// which while contain the same contents between architectures, should not be
/// deduped since they contain includes, etc. which are relative and thus cannot be separated
/// into a shared include dir such as `any-macos-any`.
const dont_dedup_list = &[_][]const u8{
"libkern/OSAtomic.h",
"libkern/OSAtomicDeprecated.h",
"libkern/OSSpinLockDeprecated.h",
"libkern/OSAtomicQueue.h",
};
fn generateDontDedupMap(allocator: *Allocator) !std.StringHashMap(void) {
var map = std.StringHashMap(void).init(allocator);
errdefer map.deinit();
try map.ensureCapacity(dont_dedup_list.len);
for (dont_dedup_list) |path| {
map.putAssumeCapacityNoClobber(path, {});
}
return map;
}
const usage =
\\Usage: fetch_them_macos_headers fetch [cflags]
\\ fetch_them_macos_headers generate <destination>
\\
\\Commands:
\\ fetch [cflags] Fetch libc headers into libc/include/<arch>-macos-gnu dir
\\ generate <destination> Generate deduplicated dirs { aarch64-macos-gnu, x86_64-macos-gnu, any-macos-any }
\\ into a given <destination> path
\\
\\General Options:
\\-h, --help Print this help and exit
;
const hint =
\\Try:
\\1. Add missing libc headers to src/headers.c
\\2. Fetch them:
\\ ./zig-cache/bin/fetch_them_macos_headers fetch
\\3. Generate deduplicated headers dirs in <destination> path:
\\ ./zig-cache/bin/fetch_them_macos_headers generate <destination>
\\
\\See -h/--help for more info.
;
fn mainArgs(allocator: *Allocator, all_args: []const []const u8) !void {
const args = all_args[1..];
if (args.len == 0) {
try io.getStdErr().writeAll("fatal: no command or option specified\n\n");
try io.getStdOut().writeAll(hint);
return;
}
const first_arg = args[0];
if (mem.eql(u8, first_arg, "--help") or mem.eql(u8, first_arg, "-h")) {
try io.getStdOut().writeAll(usage);
return;
} else if (mem.eql(u8, first_arg, "generate")) {
return generateDedupDirs(allocator, args[1..]);
} else if (mem.eql(u8, first_arg, "fetch")) {
return fetchHeaders(allocator, args[1..]);
} else {
const msg = try std.fmt.allocPrint(allocator, "fatal: unknown command or option: {s}", .{first_arg});
try io.getStdErr().writeAll(msg);
return;
}
}
fn fetchHeaders(allocator: *Allocator, args: []const []const u8) !void {
var tmp = tmpDir(.{});
defer tmp.cleanup();
const tmp_path = try tmp.dir.realpathAlloc(allocator, ".");
const tmp_filename = "headers";
const tmp_file_path = try fs.path.join(allocator, &[_][]const u8{ tmp_path, tmp_filename });
const headers_list_filename = "headers.o.d";
const headers_list_path = try fs.path.join(allocator, &[_][]const u8{ tmp_path, headers_list_filename });
var argv = std.ArrayList([]const u8).init(allocator);
try argv.appendSlice(&[_][]const u8{
"cc",
"-o",
tmp_file_path,
"src/headers.c",
"-MD",
"-MV",
"-MF",
headers_list_path,
});
try argv.appendSlice(args);
// TODO instead of calling `cc` as a child process here,
// hook in directly to `zig cc` API.
const res = try std.ChildProcess.exec(.{
.allocator = allocator,
.argv = argv.items,
});
if (res.stderr.len != 0) {
std.log.err("{s}", .{res.stderr});
}
// Read in the contents of `upgrade.o.d`
const headers_list_file = try tmp.dir.openFile(headers_list_filename, .{});
defer headers_list_file.close();
var headers_dir = fs.cwd().openDir(headers_source_prefix, .{}) catch |err| switch (err) {
error.FileNotFound, error.NotDir => {
const msg = try std.fmt.allocPrint(
allocator,
"fatal: path '{s}' not found or not a directory. Did you accidentally delete it?",
.{headers_source_prefix},
);
try io.getStdErr().writeAll(msg);
process.exit(1);
},
else => return err,
};
defer headers_dir.close();
const dest_path = try dest_target.name(allocator);
try headers_dir.deleteTree(dest_path);
var dest_dir = try headers_dir.makeOpenPath(dest_path, .{});
var dirs = std.StringHashMap(fs.Dir).init(allocator);
try dirs.putNoClobber(".", dest_dir);
const headers_list_str = try headers_list_file.reader().readAllAlloc(allocator, std.math.maxInt(usize));
const prefix = "/usr/include";
var it = mem.split(headers_list_str, "\n");
while (it.next()) |line| {
if (mem.lastIndexOf(u8, line, "clang") != null) continue;
if (mem.lastIndexOf(u8, line, prefix[0..])) |idx| {
const out_rel_path = line[idx + prefix.len + 1 ..];
const out_rel_path_stripped = mem.trim(u8, out_rel_path, " \\");
const dirname = fs.path.dirname(out_rel_path_stripped) orelse ".";
const maybe_dir = try dirs.getOrPut(dirname);
if (!maybe_dir.found_existing) {
maybe_dir.value_ptr.* = try dest_dir.makeOpenPath(dirname, .{});
}
const basename = fs.path.basename(out_rel_path_stripped);
const line_stripped = mem.trim(u8, line, " \\");
const abs_dirname = fs.path.dirname(line_stripped).?;
var orig_subdir = try fs.cwd().openDir(abs_dirname, .{});
defer orig_subdir.close();
try orig_subdir.copyFile(basename, maybe_dir.value_ptr.*, basename, .{});
}
}
var dir_it = dirs.iterator();
while (dir_it.next()) |entry| {
entry.value_ptr.close();
}
}
fn generateDedupDirs(allocator: *Allocator, args: []const []const u8) !void {
if (args.len < 1) {
try io.getStdErr().writeAll("fatal: no destination path specified");
process.exit(1);
}
const dest_path = args[0];
var dest_dir = fs.cwd().makeOpenPath(dest_path, .{}) catch |err| switch (err) {
error.NotDir => {
const msg = try std.fmt.allocPrint(allocator, "fatal: path '{s}' not a directory", .{dest_path});
try io.getStdErr().writeAll(msg);
process.exit(1);
},
else => return err,
};
defer dest_dir.close();
var path_table = PathTable.init(allocator);
var hash_to_contents = HashToContents.init(allocator);
var savings = FindResult{};
inline for (targets) |target| {
const res = try findDuplicates(target, allocator, headers_source_prefix, &path_table, &hash_to_contents);
savings.max_bytes_saved += res.max_bytes_saved;
savings.total_bytes += res.total_bytes;
}
std.log.warn("summary: {} could be reduced to {}", .{
std.fmt.fmtIntSizeBin(savings.total_bytes),
std.fmt.fmtIntSizeBin(savings.total_bytes - savings.max_bytes_saved),
});
var tmp = tmpDir(.{
.iterate = true,
});
defer tmp.cleanup();
var dont_dedup_map = try generateDontDedupMap(allocator);
defer dont_dedup_map.deinit();
var missed_opportunity_bytes: usize = 0;
// Iterate path_table. For each path, put all the hashes into a list. Sort by hit_count.
// The hash with the highest hit_count gets to be the "generic" one. Everybody else
// gets their header in a separate arch directory.
var path_it = path_table.iterator();
while (path_it.next()) |path_kv| {
if (!dont_dedup_map.contains(path_kv.key_ptr.*)) {
var contents_list = std.ArrayList(*Contents).init(allocator);
{
var hash_it = path_kv.value_ptr.*.iterator();
while (hash_it.next()) |hash_kv| {
const contents = &hash_to_contents.getEntry(hash_kv.value_ptr.*).?.value_ptr.*;
try contents_list.append(contents);
}
}
std.sort.sort(*Contents, contents_list.items, {}, Contents.hitCountLessThan);
const best_contents = contents_list.popOrNull().?;
if (best_contents.hit_count > 1) {
// Put it in `any-macos-gnu`.
const full_path = try fs.path.join(allocator, &[_][]const u8{ common_name, path_kv.key_ptr.* });
try tmp.dir.makePath(fs.path.dirname(full_path).?);
try tmp.dir.writeFile(full_path, best_contents.bytes);
best_contents.is_generic = true;
while (contents_list.popOrNull()) |contender| {
if (contender.hit_count > 1) {
const this_missed_bytes = contender.hit_count * contender.bytes.len;
missed_opportunity_bytes += this_missed_bytes;
std.log.warn("Missed opportunity ({}): {s}", .{
std.fmt.fmtIntSizeBin(this_missed_bytes),
path_kv.key_ptr.*,
});
} else break;
}
}
}
var hash_it = path_kv.value_ptr.*.iterator();
while (hash_it.next()) |hash_kv| {
const contents = &hash_to_contents.getEntry(hash_kv.value_ptr.*).?.value_ptr.*;
if (contents.is_generic) continue;
const target = hash_kv.key_ptr.*;
const target_name = try target.name(allocator);
const full_path = try fs.path.join(allocator, &[_][]const u8{ target_name, path_kv.key_ptr.* });
try tmp.dir.makePath(fs.path.dirname(full_path).?);
try tmp.dir.writeFile(full_path, contents.bytes);
}
}
inline for (targets) |target| {
const target_name = try target.name(allocator);
try dest_dir.deleteTree(target_name);
}
try dest_dir.deleteTree(common_name);
var tmp_it = tmp.dir.iterate();
while (try tmp_it.next()) |entry| {
switch (entry.kind) {
.Directory => {
const sub_dir = try tmp.dir.openDir(entry.name, .{
.iterate = true,
});
const dest_sub_dir = try dest_dir.makeOpenPath(entry.name, .{});
try copyDirAll(sub_dir, dest_sub_dir);
},
else => {
std.log.warn("unexpected file format: not a directory: '{s}'", .{entry.name});
},
}
}
}
const FindResult = struct {
max_bytes_saved: usize = 0,
total_bytes: usize = 0,
};
fn findDuplicates(
comptime target: Target,
allocator: *Allocator,
dest_path: []const u8,
path_table: *PathTable,
hash_to_contents: *HashToContents,
) !FindResult {
var result = FindResult{};
const target_name = try target.name(allocator);
const target_include_dir = try fs.path.join(allocator, &[_][]const u8{ dest_path, target_name });
var dir_stack = std.ArrayList([]const u8).init(allocator);
try dir_stack.append(target_include_dir);
while (dir_stack.popOrNull()) |full_dir_name| {
var dir = fs.cwd().openDir(full_dir_name, .{
.iterate = true,
}) catch |err| switch (err) {
error.FileNotFound => break,
error.AccessDenied => break,
else => return err,
};
defer dir.close();
var dir_it = dir.iterate();
while (try dir_it.next()) |entry| {
const full_path = try fs.path.join(allocator, &[_][]const u8{ full_dir_name, entry.name });
switch (entry.kind) {
.Directory => try dir_stack.append(full_path),
.File => {
const rel_path = try fs.path.relative(allocator, target_include_dir, full_path);
const max_size = 2 * 1024 * 1024 * 1024;
const raw_bytes = try fs.cwd().readFileAlloc(allocator, full_path, max_size);
const trimmed = mem.trim(u8, raw_bytes, " \r\n\t");
result.total_bytes += raw_bytes.len;
const hash = try allocator.alloc(u8, 32);
var hasher = Blake3.init(.{});
hasher.update(rel_path);
hasher.update(trimmed);
hasher.final(hash);
const gop = try hash_to_contents.getOrPut(hash);
if (gop.found_existing) {
result.max_bytes_saved += raw_bytes.len;
gop.value_ptr.hit_count += 1;
std.log.warn("duplicate: {s} {s} ({})", .{
target_name,
rel_path,
std.fmt.fmtIntSizeBin(raw_bytes.len),
});
} else {
gop.value_ptr.* = Contents{
.bytes = trimmed,
.hit_count = 1,
.hash = hash,
.is_generic = false,
};
}
const path_gop = try path_table.getOrPut(rel_path);
const target_to_hash = if (path_gop.found_existing) path_gop.value_ptr.* else blk: {
const ptr = try allocator.create(TargetToHash);
ptr.* = TargetToHash.init(allocator);
path_gop.value_ptr.* = ptr;
break :blk ptr;
};
try target_to_hash.putNoClobber(target, hash);
},
else => std.log.warn("unexpected file: {s}", .{full_path}),
}
}
}
return result;
}
fn copyDirAll(source: fs.Dir, dest: fs.Dir) anyerror!void {
var it = source.iterate();
while (try it.next()) |next| {
switch (next.kind) {
.Directory => {
var sub_dir = try dest.makeOpenPath(next.name, .{});
var sub_source = try source.openDir(next.name, .{
.iterate = true,
});
defer {
sub_dir.close();
sub_source.close();
}
try copyDirAll(sub_source, sub_dir);
},
.File => {
var source_file = try source.openFile(next.name, .{});
var dest_file = try dest.createFile(next.name, .{});
defer {
source_file.close();
dest_file.close();
}
const stat = try source_file.stat();
const ncopied = try source_file.copyRangeAll(0, dest_file, 0, stat.size);
assert(ncopied == stat.size);
},
else => |kind| {
std.log.warn("unexpected file kind '{s}' will be ignored", .{kind});
},
}
}
}
pub fn main() anyerror!void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = &arena.allocator;
const args = try std.process.argsAlloc(allocator);
return mainArgs(allocator, args);
} | src/main.zig |
pub fn Formatter(
comptime Context: type,
comptime Writer: type,
comptime nullFn: fn (Context, Writer) Writer.Error!void,
comptime boolFn: fn (Context, Writer, bool) Writer.Error!void,
comptime intFn: fn (Context, Writer, anytype) Writer.Error!void,
comptime floatFn: fn (Context, Writer, anytype) Writer.Error!void,
comptime numberStringFn: fn (Context, Writer, []const u8) Writer.Error!void,
comptime beginStringFn: fn (Context, Writer) Writer.Error!void,
comptime endStringFn: fn (Context, Writer) Writer.Error!void,
comptime stringFragmentFn: fn (Context, Writer, []const u8) Writer.Error!void,
comptime charEscapeFn: fn (Context, Writer, u21) Writer.Error!void,
comptime beginArrayFn: fn (Context, Writer) Writer.Error!void,
comptime endArrayFn: fn (Context, Writer) Writer.Error!void,
comptime beginArrayValueFn: fn (Context, Writer, bool) Writer.Error!void,
comptime endArrayValueFn: fn (Context, Writer) Writer.Error!void,
comptime beginObjectFn: fn (Context, Writer) Writer.Error!void,
comptime endObjectFn: fn (Context, Writer) Writer.Error!void,
comptime beginObjectKeyFn: fn (Context, Writer, bool) Writer.Error!void,
comptime endObjectKeyFn: fn (Context, Writer) Writer.Error!void,
comptime beginObjectValueFn: fn (Context, Writer) Writer.Error!void,
comptime endObjectValueFn: fn (Context, Writer) Writer.Error!void,
comptime rawFragmentFn: fn (Context, Writer, []const u8) Writer.Error!void,
) type {
const T = struct {
context: Context,
const Self = @This();
/// Writes a `null` value to the specified writer.
pub fn writeNull(self: Self, writer: Writer) Writer.Error!void {
try nullFn(self.context, writer);
}
/// Writes `true` or `false` to the specified writer.
pub fn writeBool(self: Self, writer: Writer, value: bool) Writer.Error!void {
try boolFn(self.context, writer, value);
}
/// Writes an integer value to the specified writer.
pub fn writeInt(self: Self, writer: Writer, value: anytype) Writer.Error!void {
switch (@typeInfo(@TypeOf(value))) {
.ComptimeInt, .Int => try intFn(self.context, writer, value),
else => @compileError("expected integer, found " ++ @typeName(@TypeOf(value))),
}
}
// Writes an floating point value to the specified writer.
pub fn writeFloat(self: Self, writer: Writer, value: anytype) Writer.Error!void {
switch (@typeInfo(@TypeOf(value))) {
.ComptimeFloat, .Float => try floatFn(self.context, writer, value),
else => @compileError("expected floating point, found " ++ @typeName(@TypeOf(value))),
}
}
/// Writes a number that has already been rendered into a string.
///
/// TODO: Check that the string is actually an integer when parsed.
pub fn writeNumberString(self: Self, writer: Writer, value: []const u8) Writer.Error!void {
try numberStringFn(self.context, writer, value);
}
/// Called before each series of `write_string_fragment` and
/// `write_char_escape`. Writes a `"` to the specified writer.
pub fn beginString(self: Self, writer: Writer) Writer.Error!void {
try beginStringFn(self.context, writer);
}
/// Called after each series of `write_string_fragment` and
/// `write_char_escape`. Writes a `"` to the specified writer.
pub fn endString(self: Self, writer: Writer) Writer.Error!void {
try endStringFn(self.context, writer);
}
/// Writes a string fragment that doesn't need any escaping to the
/// specified writer.
pub fn writeStringFragment(self: Self, writer: Writer, value: []const u8) Writer.Error!void {
try stringFragmentFn(self.context, writer, value);
}
pub fn writeCharEscape(self: Self, writer: Writer, value: u21) Writer.Error!void {
try charEscapeFn(self.context, writer, value);
}
pub fn beginArray(self: Self, writer: Writer) Writer.Error!void {
try beginArrayFn(self.context, writer);
}
pub fn endArray(self: Self, writer: Writer) Writer.Error!void {
try endArrayFn(self.context, writer);
}
pub fn beginArrayValue(self: Self, writer: Writer, first: bool) Writer.Error!void {
try beginArrayValueFn(self.context, writer, first);
}
pub fn endArrayValue(self: Self, writer: Writer) Writer.Error!void {
try endArrayValueFn(self.context, writer);
}
pub fn beginObject(self: Self, writer: Writer) Writer.Error!void {
try beginObjectFn(self.context, writer);
}
pub fn endObject(self: Self, writer: Writer) Writer.Error!void {
try endObjectFn(self.context, writer);
}
pub fn beginObjectKey(self: Self, writer: Writer, first: bool) Writer.Error!void {
try beginObjectKeyFn(self.context, writer, first);
}
pub fn endObjectKey(self: Self, writer: Writer) Writer.Error!void {
try endObjectKeyFn(self.context, writer);
}
pub fn beginObjectValue(self: Self, writer: Writer) Writer.Error!void {
try beginObjectValueFn(self.context, writer);
}
pub fn endObjectValue(self: Self, writer: Writer) Writer.Error!void {
try endObjectValueFn(self.context, writer);
}
pub fn writeRawFragment(self: Self, writer: Writer, value: []const u8) Writer.Error!void {
try rawFragmentFn(self.context, writer, value);
}
};
return struct {
pub fn formatter(self: Context) T {
return .{ .context = self };
}
};
} | src/ser/interface/formatter.zig |
const builtin = @import("builtin");
const std = @import("std");
const os = std.os;
const b64 = std.base64.standard.Encoder;
// const zfetch = @import("zfetch");
const hzzp = @import("hzzp");
const tls = @import("iguanaTLS");
const Emote = @import("../Chat.zig").Message.Emote;
const EmoteHashMap = std.StringHashMap(struct {
data: []const u8,
idx: u32,
});
allocator: std.mem.Allocator,
idx_counter: u32 = 1,
cache: EmoteHashMap,
const Self = @This();
// TODO: for people with 8k SUMQHD terminals, let them use bigger size emotes
// const path_fmt = "https://localhost:443/emoticons/v1/{s}/3.0";
const hostname = "static-cdn.jtvnw.net";
pub fn init(allocator: std.mem.Allocator) Self {
return Self{
.allocator = allocator,
.cache = EmoteHashMap.init(allocator),
};
}
// TODO: make this concurrent
// TODO: make so failing one emote doesn't fail the whole job!
pub fn fetch(self: *Self, emote_list: []Emote) !void {
for (emote_list) |*emote| {
std.log.debug("fetching {}", .{emote.*});
const result = try self.cache.getOrPut(emote.twitch_id);
errdefer _ = self.cache.remove(emote.twitch_id);
if (!result.found_existing) {
std.log.debug("need to download", .{});
// Need to download the image
var img = img: {
const TLSStream = tls.Client(std.net.Stream.Reader, std.net.Stream.Writer, tls.ciphersuites.all, true);
const HttpClient = hzzp.base.client.BaseClient(TLSStream.Reader, TLSStream.Writer);
var sock = try std.net.tcpConnectToHost(self.allocator, hostname, 443);
defer sock.close();
var defaultCsprng = blk: {
var seed: [std.rand.DefaultCsprng.secret_seed_length]u8 = undefined;
try std.os.getrandom(&seed);
break :blk &std.rand.DefaultCsprng.init(seed);
};
var rand = defaultCsprng.random();
var tls_sock = try tls.client_connect(.{
.rand = rand,
.temp_allocator = self.allocator,
.reader = sock.reader(),
.writer = sock.writer(),
.cert_verifier = .none,
.ciphersuites = tls.ciphersuites.all,
.protocols = &[_][]const u8{"http/1.1"},
}, hostname);
defer tls_sock.close_notify() catch {};
var buf: [1024]u8 = undefined;
var client = HttpClient.init(
&buf,
tls_sock.reader(),
tls_sock.writer(),
);
const path = try std.fmt.allocPrint(
self.allocator,
"/emoticons/v1/{s}/1.0",
.{emote.twitch_id},
);
defer self.allocator.free(path);
client.writeStatusLine("GET", path) catch {
return error.Error;
};
client.writeHeaderValue("Host", hostname) catch unreachable;
client.writeHeaderValue("User-Agent", "Zig") catch unreachable;
client.writeHeaderValue("Accept", "*/*") catch unreachable;
client.finishHeaders() catch unreachable;
// Consume headers
while (try client.next()) |event| {
switch (event) {
.status => |status| switch (status.code) {
200 => {},
else => |code| {
std.log.debug("http bad response code: {d}", .{code});
return error.HttpFailed;
},
},
.header => {},
.head_done => break,
else => |val| std.log.debug("got other: {}", .{val}),
}
}
break :img try client.reader().readAllAlloc(self.allocator, 1024 * 100);
};
// var img = img: {
// const path = try std.fmt.allocPrint(
// self.allocator,
// path_fmt,
// .{emote.twitch_id},
// );
// defer self.allocator.free(path);
// std.log.debug("emote url = ({s})", .{path});
// var headers = zfetch.Headers.init(self.allocator);
// defer headers.deinit();
// try headers.appendValue("Host", "static-cdn.jtvnw.net");
// try headers.appendValue("User-Agent", "Bork");
// try headers.appendValue("Accept", "*/*");
// var req = try zfetch.Request.init(self.allocator, path, null);
// defer req.deinit();
// try req.do(.GET, headers, null);
// if (req.status.code != 200) {
// std.log.err("emote request failed ({s})", .{path});
// return error.HttpError;
// }
// break :img try req.reader().readAllAlloc(self.allocator, 1024 * 100);
// };
var encode_buf = try self.allocator.alloc(u8, std.base64.standard.Encoder.calcSize(img.len));
result.value_ptr.* = .{
.data = b64.encode(encode_buf, img),
.idx = self.idx_counter,
};
self.idx_counter += 1;
}
emote.img_data = result.value_ptr.data;
emote.idx = result.value_ptr.idx;
}
} | src/network/EmoteCache.zig |
const std = @import("std");
const stdx = @import("../stdx.zig");
const ds = stdx.ds;
const t = stdx.testing;
const log = stdx.log.scoped(.document);
const MaxLineChunkSize = 50;
// When line chunk becomes full, the size is reduced to target threshold.
const LineChunkTargetThreshold = 40;
pub const LineChunkId = u32;
// Line chunk is a relative pointer into the buffer.
pub const LineChunk = struct {
// Offset from line chunk buffer.
id: LineChunkId,
size: u32,
};
const LineChunkArray = [MaxLineChunkSize]LineId;
pub const LineLocation = struct {
leaf_id: NodeId,
// Offset from the leaf's line chunk.
chunk_line_idx: u32,
};
const TreeBranchFactor = 3;
// Document is organized by lines. It has nice properties for most text editing tasks.
// A self balancing btree is used to group adjacent lines into chunks.
// This allows line ops to affect only relevant chunks and not the entire document while preserving line order.
// It's also capable of propagating up aggregate line info like line-height which should come in handy when we implement line wrapping.
//
// Notes:
// - Always has at least one leaf node. (TODO: Revisit this)
// - Once a chunk gets to size 0 it is removed. It won't be able to match any line position and it simplifies line iteration when we can assume each chunk is at least 1 line.
// TODO: Might want to keep newline characters in lines for scanning convenience.
pub const Document = struct {
const Self = @This();
alloc: std.mem.Allocator,
line_tree: ds.CompleteTreeArray(TreeBranchFactor, Node),
line_chunks: ds.CompactUnorderedList(LineChunkId, LineChunkArray),
lines: ds.CompactUnorderedList(LineId, Line),
// Temp vars.
node_buf: std.ArrayList(NodeId),
str_buf: std.ArrayList(u8),
pub fn init(self: *Self, alloc: std.mem.Allocator) void {
self.* = .{
.line_tree = ds.CompleteTreeArray(3, Node).init(alloc),
.alloc = alloc,
.line_chunks = ds.CompactUnorderedList(LineChunkId, LineChunkArray).init(alloc),
.lines = ds.CompactUnorderedList(LineId, Line).init(alloc),
.node_buf = std.ArrayList(NodeId).init(alloc),
.str_buf = std.ArrayList(u8).init(alloc),
};
self.setUpEmptyDoc();
}
fn setUpEmptyDoc(self: *Self) void {
const chunk_id = self.line_chunks.add(undefined) catch unreachable;
_ = self.line_tree.append(.{
.Branch = .{
.num_lines = 0,
},
}) catch unreachable;
_ = self.line_tree.append(.{
.Leaf = .{
.chunk = .{
.id = chunk_id,
.size = 0,
},
},
}) catch unreachable;
}
pub fn deinit(self: *Self) void {
self.line_tree.deinit();
self.line_chunks.deinit();
var iter = self.lines.iterator();
while (iter.next()) |line| {
line.buf.deinit();
}
self.lines.deinit();
self.node_buf.deinit();
self.str_buf.deinit();
}
// This is findLineLoc except if line_idx is at the end,
// it will return a LineLocation that points to existing leaf but chunk_lin_idx doesn't exist yet.
fn findInsertLineLoc(self: *Self, line_idx: u32) LineLocation {
const root = self.line_tree.getNodePtr(0);
if (line_idx < root.Branch.num_lines) {
return self.findLineLoc(line_idx);
} else if (line_idx == root.Branch.num_lines) {
// Shortcut for getting the last leaf.
const last = self.line_tree.getLastLeaf();
return .{
.leaf_id = last,
.chunk_line_idx = self.line_tree.getNode(last).Leaf.chunk.size,
};
} else {
unreachable;
}
}
// Assumes line idx is in bounds.
pub fn findLineLoc(self: *Self, line_idx: u32) LineLocation {
return self.findLineLoc2(0, 0, line_idx).?;
}
fn findLineLoc2(self: *Self, node_id: NodeId, start_line: u32, target_line: u32) ?LineLocation {
const node = self.line_tree.getNodePtr(node_id);
switch (node.*) {
.Branch => |br| {
if (target_line >= start_line and target_line < start_line + br.num_lines) {
var cur_line = start_line;
const range = self.line_tree.getChildrenRange(node_id);
var id = range.start;
while (id < range.end) : (id += 1) {
const cur_item = self.line_tree.getNode(id);
const res = self.findLineLoc2(id, cur_line, target_line);
if (res != null) {
return res;
}
switch (cur_item) {
.Branch => |child_br| {
cur_line += child_br.num_lines;
},
.Leaf => |child_leaf| {
cur_line += child_leaf.chunk.size;
},
}
}
}
},
.Leaf => |leaf| {
if (target_line >= start_line and target_line < start_line + leaf.chunk.size) {
return LineLocation{
.leaf_id = node_id,
.chunk_line_idx = target_line - start_line,
};
}
},
}
return null;
}
// Move lines from existing chunk to new if target threshold is exceeded.
// Caller must deal with rebalancing the tree and moving the new leaf to the right place.
fn reallocLeafLineChunk(self: *Self, loc: LineLocation) LineLocation {
const leaf = self.line_tree.getNodePtr(loc.leaf_id);
const num_lines = leaf.Leaf.chunk.size;
if (num_lines <= LineChunkTargetThreshold) {
unreachable;
}
const num_moved = num_lines - LineChunkTargetThreshold;
const new_chunk_id = self.line_chunks.add(undefined) catch unreachable;
const new_chunk_ptr = LineChunk{
.id = new_chunk_id,
.size = num_moved,
};
const new_leaf = self.line_tree.append(.{
.Leaf = .{
.chunk = new_chunk_ptr,
},
}) catch unreachable;
// log.warn("leaf: {}, {}", .{leaf, loc});
const chunk = self.getLineChunkSlice(leaf.Leaf.chunk);
const new_chunk = self.getLineChunkSlice(new_chunk_ptr);
var i: u32 = 0;
while (i < num_moved) : (i += 1) {
new_chunk[i] = chunk[LineChunkTargetThreshold + i];
}
leaf.Leaf.chunk.size -= num_moved;
self.updateParentNumLines(loc.leaf_id, -@intCast(i32, num_moved));
return .{
.leaf_id = new_leaf,
.chunk_line_idx = 0,
};
}
// Assumes already balanced line tree except new leaf node.
// Assumes new leaf was created to come after target leaf.
// If new leaf is after target, then we need to shift every node AFTER target downwards to the new node.
// Then new node is moved to the node AFTER target.
// If new leaf is before target, then we need to shift every node at target upwards to the new node.
// Then new node is moved to the target.
fn rebalanceWithNewLeaf(self: *Self, new_id: NodeId, after_target: NodeId) void {
self.node_buf.resize(self.line_tree.getMaxLeaves()) catch unreachable;
// TODO: Only get leaves from new to target.
const leaves = self.line_tree.getInOrderLeaves(self.node_buf.items);
if (self.line_tree.isLeafNodeBefore(new_id, after_target)) {
// Start from new node.
var i = std.mem.indexOfScalar(NodeId, leaves, new_id).?;
const temp = self.line_tree.getNode(new_id);
// First node that moves to the new node is special since all it's num lines is reported to parent.
var node = self.line_tree.getNodePtr(leaves[i]);
node.* = self.line_tree.getNode(leaves[i + 1]);
self.updateParentNumLines(leaves[i], @intCast(i32, node.Leaf.chunk.size));
i += 1;
// Shift the rest upwards.
while (leaves[i] != after_target) : (i += 1) {
// log.warn("i={} cur_node={} target={}", .{i, leaves[i], after_target});
node = self.line_tree.getNodePtr(leaves[i]);
const last_num_lines = node.Leaf.chunk.size;
node.* = self.line_tree.getNode(leaves[i + 1]);
self.updateParentNumLines(leaves[i], @intCast(i32, node.Leaf.chunk.size) - @intCast(i32, last_num_lines));
}
// Replace target with new.
node = self.line_tree.getNodePtr(leaves[i]);
const last_num_lines = node.Leaf.chunk.size;
node.* = temp;
self.updateParentNumLines(leaves[i], @intCast(i32, node.Leaf.chunk.size) - @intCast(i32, last_num_lines));
} else {
// Start from new node.
var i = std.mem.indexOfScalar(NodeId, leaves, new_id).?;
// First node that moves to the new node is special since all it's num lines is reported to parent.
if (leaves[i] != after_target + 1) {
var node = self.line_tree.getNodePtr(leaves[i]);
node.* = self.line_tree.getNode(leaves[i - 1]);
self.updateParentNumLines(leaves[i], @intCast(i32, node.Leaf.chunk.size));
i -= 1;
const temp = self.line_tree.getNode(new_id);
// Shift the rest downwards.
while (leaves[i] != after_target + 1) : (i -= 1) {
node = self.line_tree.getNodePtr(leaves[i]);
const last_num_lines = node.Leaf.chunk.size;
node.* = self.line_tree.getNode(leaves[i - 1]);
self.updateParentNumLines(leaves[i], @intCast(i32, node.Leaf.chunk.size) - @intCast(i32, last_num_lines));
}
// Replace node AFTER target with new.
node = self.line_tree.getNodePtr(leaves[i]);
const last_num_lines = node.Leaf.chunk.size;
node.* = temp;
self.updateParentNumLines(leaves[i], @intCast(i32, node.Leaf.chunk.size) - @intCast(i32, last_num_lines));
} else {
// New node is exactly where it should be already.
const node = self.line_tree.getNodePtr(leaves[i]);
self.updateParentNumLines(leaves[i], @intCast(i32, node.Leaf.chunk.size));
}
}
}
pub fn removeRangeInLine(self: *Self, line_idx: u32, start: u32, end: u32) void {
self.replaceRangeInLine(line_idx, start, end, "");
}
pub fn replaceRangeInLine(self: *Self, line_idx: u32, start: u32, end: u32, str: []const u8) void {
const line_id = self.getLineId(line_idx);
const buf = &self.lines.getPtrNoCheck(line_id).buf;
buf.replaceRange(start, end - start, str) catch unreachable;
}
// Performs insert in a line. Assumes no new lines.
pub fn insertIntoLine(self: *Self, line_idx: u32, ch_idx: u32, str: []const u8) void {
const line_id = self.getLineId(line_idx);
const buf = &self.lines.getPtrNoCheck(line_id).buf;
buf.insertSlice(ch_idx, str) catch unreachable;
}
pub fn insertLine(self: *Self, line_idx: u32, str: []const u8) void {
var line = Line{
.buf = std.ArrayList(u8).init(self.alloc),
};
line.buf.appendSlice(str) catch unreachable;
const line_id = self.lines.add(line) catch unreachable;
var loc = self.findInsertLineLoc(line_idx);
var leaf = self.line_tree.getNodePtr(loc.leaf_id);
if (leaf.Leaf.chunk.size == MaxLineChunkSize) {
// Reached chunk limit, allocate another leaf node line chunk.
const new_loc = self.reallocLeafLineChunk(loc);
if (self.line_tree.getParent(new_loc.leaf_id)) |parent_id| {
const parent = self.line_tree.getNode(parent_id);
if (parent == .Leaf) {
// If parent is a leaf node, we have to insert a branch.
const new_branch = self.line_tree.append(.{
.Branch = .{
.num_lines = parent.Leaf.chunk.size,
},
}) catch unreachable;
self.line_tree.swap(parent_id, new_branch);
// Update the target loc if we swapped it.
if (loc.leaf_id == parent_id) {
loc.leaf_id = new_branch;
}
}
}
// Rebalance line tree with new leaf node.
self.rebalanceWithNewLeaf(new_loc.leaf_id, loc.leaf_id);
// Find the target leaf again.
loc = self.findInsertLineLoc(line_idx);
leaf = self.line_tree.getNodePtr(loc.leaf_id);
}
// Copy existing lines down.
const offset = loc.chunk_line_idx;
leaf.Leaf.chunk.size += 1;
var chunk = self.getLineChunkSlice(leaf.Leaf.chunk);
var i = chunk.len - offset - 1;
while (i >= offset + 1) : (i -= 1) {
chunk[i] = chunk[i - 1];
}
chunk[offset] = line_id;
// log.warn("new line id: {}", .{line_id});
// log.warn("buf after: {any}", .{chunk.*});
// Propagate size change upwards.
self.updateParentNumLines(loc.leaf_id, 1);
}
fn updateParentNumLines(self: *Self, node_id: NodeId, lc_delta: i32) void {
const parent_id = self.line_tree.getParent(node_id);
if (parent_id == null) {
return;
}
const parent = self.line_tree.getNodePtr(parent_id.?);
if (lc_delta > 0) {
parent.Branch.num_lines += @intCast(u32, lc_delta);
} else {
parent.Branch.num_lines -= @intCast(u32, -lc_delta);
}
self.updateParentNumLines(parent_id.?, lc_delta);
}
// Clears the doc.
fn clearRetainingCapacity(self: *Self) void {
self.line_tree.clearRetainingCapacity();
self.line_chunks.clearRetainingCapacity();
var iter = self.lines.iterator();
while (iter.next()) |line| {
line.buf.deinit();
}
self.lines.clearRetainingCapacity();
self.setUpEmptyDoc();
}
pub fn loadSource(self: *Self, src: []const u8) void {
self.clearRetainingCapacity();
var iter = stdx.string.splitLines(src);
while (iter.next()) |line| {
self.insertLine(self.numLines(), line);
}
}
pub fn loadFromFile(self: *Self, path: []const u8) void {
_ = self;
_ = path;
// Load from stream.
@compileError("TODO");
}
pub fn getFirstLeaf(self: *Self) NodeId {
return self.line_tree.getFirstLeaf();
}
pub fn getLastLeaf(self: *Self) NodeId {
return self.line_tree.getLastLeaf();
}
pub fn numLines(self: *Self) u32 {
return self.line_tree.getNode(0).Branch.num_lines;
}
pub fn getLeafLineChunkSlice(self: *Self, leaf_id: NodeId) []LineId {
const leaf = self.getNode(leaf_id);
return self.getLineChunkSlice(leaf.Leaf.chunk);
}
pub fn getLineChunkSlice(self: *Self, chunk: LineChunk) []LineId {
return self.line_chunks.getPtrNoCheck(chunk.id)[0..chunk.size];
}
pub fn getLineId(self: *Self, line_idx: u32) LineId {
const loc = self.findLineLoc(line_idx);
return self.getLineIdByLoc(loc);
}
pub fn getLineIdByLoc(self: *Self, loc: LineLocation) LineId {
return self.getLeafLineChunkSlice(loc.leaf_id)[loc.chunk_line_idx];
}
pub fn getLine(self: *Self, line_idx: u32) []const u8 {
const line_id = self.getLineId(line_idx);
return self.lines.getNoCheck(line_id).buf.items;
}
pub fn getLineById(self: *Self, id: LineId) []const u8 {
return self.lines.getNoCheck(id).buf.items;
}
pub fn getNode(self: *Self, id: NodeId) Node {
return self.line_tree.getNode(id);
}
pub fn getNextLeafNode(self: *Self, id: NodeId) ?NodeId {
return self.line_tree.getNextLeaf(id);
}
pub fn getPrevLeafNode(self: *Self, id: NodeId) ?NodeId {
return self.line_tree.getPrevLeaf(id);
}
// Given a location to the line and char offsets from the line, get the string between the offsets.
pub fn getSubstringFromLineLoc(self: *Self, loc: LineLocation, start_ch: u32, end_ch: u32) []const u8 {
var cur_leaf_id = loc.leaf_id;
var chunk = self.getLeafLineChunkSlice(cur_leaf_id);
var chunk_line_idx = loc.chunk_line_idx;
var line = self.getLineById(chunk[chunk_line_idx]);
if (end_ch <= line.len) {
// It's a substring from the start line.
return line[start_ch..end_ch];
} else {
// Build multiline string.
self.str_buf.clearRetainingCapacity();
// Add first line substring.
self.str_buf.appendSlice(line[start_ch..]) catch unreachable;
self.str_buf.append('\n') catch unreachable;
var offset: u32 = @intCast(u32, self.str_buf.items.len);
// Add middle lines.
while (true) {
chunk_line_idx += 1;
if (chunk_line_idx == chunk.len) {
// Advance line chunk.
cur_leaf_id = self.getNextLeafNode(cur_leaf_id).?;
chunk = self.getLeafLineChunkSlice(cur_leaf_id);
chunk_line_idx = 0;
}
line = self.getLineById(chunk[chunk_line_idx]);
offset += @intCast(u32, line.len) + 1;
if (offset >= end_ch) {
break;
}
self.str_buf.appendSlice(line) catch unreachable;
self.str_buf.append('\n') catch unreachable;
}
// Add last line substring.
line = self.getLineById(chunk[chunk_line_idx]);
self.str_buf.appendSlice(line[0..end_ch]) catch unreachable;
return self.str_buf.items;
}
}
// end_chunk_line_idx is inclusive
// end_ch_idx is exclusive
pub fn getString(self: *Self, start: NodeId, start_chunk_line_idx: u32, start_ch_idx: u32, end: NodeId, end_chunk_line_idx: u32, end_ch_idx: u32) []const u8 {
if (start == end and start_chunk_line_idx == end_chunk_line_idx) {
const chunk = self.getLeafLineChunkSlice(start);
return self.getLineById(chunk[start_chunk_line_idx])[start_ch_idx..end_ch_idx];
} else {
// Build temp string.
self.str_buf.clearRetainingCapacity();
var cur_node = start;
var cur_chunk_line_idx = start_chunk_line_idx;
var cur_chunk = self.getLeafLineChunkSlice(cur_node);
var line = self.getLineById(cur_chunk[cur_chunk_line_idx]);
// Add first line substring.
self.str_buf.appendSlice(line[start_ch_idx..]) catch unreachable;
self.str_buf.append('\n') catch unreachable;
// Add middle lines.
while (true) {
if (cur_chunk_line_idx == cur_chunk.len) {
// Advance line chunk.
cur_node = self.getNextLeafNode(cur_node).?;
cur_chunk = self.getLeafLineChunkSlice(cur_node);
cur_chunk_line_idx = 0;
}
if (cur_node == end and cur_chunk_line_idx == end_chunk_line_idx) {
break;
}
line = self.getLineById(cur_chunk[cur_chunk_line_idx]);
self.str_buf.appendSlice(line) catch unreachable;
self.str_buf.append('\n') catch unreachable;
cur_chunk_line_idx += 1;
}
// Add last line substring.
line = self.getLineById(cur_chunk[cur_chunk_line_idx]);
self.str_buf.appendSlice(line[0..end_ch_idx]) catch unreachable;
return self.str_buf.items;
}
}
};
test "Document" {
const src =
\\This is a document.
\\This is the second line.
;
var doc: Document = undefined;
doc.init(t.alloc);
defer doc.deinit();
doc.loadSource(src);
try t.eq(doc.numLines(), 2);
try t.eqStr(doc.getLine(0), "This is a document.");
// Test insert op on line.
doc.insertIntoLine(0, 10, "cool ");
try t.eqStr(doc.getLine(0), "This is a cool document.");
}
test "Big document" {
const line = "This is a line.\n";
var src_buf = std.ArrayList(u8).init(t.alloc);
defer src_buf.deinit();
src_buf.resize(line.len * 1000) catch unreachable;
var i: u32 = 0;
while (i < 1000) : (i += 1) {
src_buf.appendSlice(line) catch unreachable;
}
var doc: Document = undefined;
doc.init(t.alloc);
defer doc.deinit();
doc.loadSource(src_buf.items);
try t.eq(doc.numLines(), 1001);
}
pub const NodeId = u32;
const Node = union(enum) {
Branch: struct {
num_lines: u32,
},
Leaf: struct {
chunk: LineChunk,
},
};
pub const LineId = u32;
const Line = struct {
buf: std.ArrayList(u8),
}; | stdx/textbuf/document.zig |
const std = @import("std");
const ast = std.zig.ast;
const Token = std.zig.Token;
use @import("clang.zig");
pub const Mode = enum {
import,
translate,
};
pub const ClangErrMsg = Stage2ErrorMsg;
pub fn translate(
backing_allocator: *std.mem.Allocator,
args_begin: [*]?[*]const u8,
args_end: [*]?[*]const u8,
mode: Mode,
errors: *[]ClangErrMsg,
resources_path: [*]const u8,
) !*ast.Tree {
const ast_unit = ZigClangLoadFromCommandLine(
args_begin,
args_end,
&errors.ptr,
&errors.len,
resources_path,
) orelse {
if (errors.len == 0) return error.OutOfMemory;
return error.SemanticAnalyzeFail;
};
defer ZigClangASTUnit_delete(ast_unit);
var tree_arena = std.heap.ArenaAllocator.init(backing_allocator);
errdefer tree_arena.deinit();
const arena = &tree_arena.allocator;
const root_node = try arena.create(ast.Node.Root);
root_node.* = ast.Node.Root{
.base = ast.Node{ .id = ast.Node.Id.Root },
.decls = ast.Node.Root.DeclList.init(arena),
.doc_comments = null,
// initialized with the eof token at the end
.eof_token = undefined,
};
const tree = try arena.create(ast.Tree);
tree.* = ast.Tree{
.source = undefined, // need to use Buffer.toOwnedSlice later
.root_node = root_node,
.arena_allocator = tree_arena,
.tokens = ast.Tree.TokenList.init(arena),
.errors = ast.Tree.ErrorList.init(arena),
};
var source_buffer = try std.Buffer.initSize(arena, 0);
try appendToken(tree, &source_buffer, "// TODO: implement more than just an empty source file", .LineComment);
try appendToken(tree, &source_buffer, "", .Eof);
tree.source = source_buffer.toOwnedSlice();
return tree;
}
fn appendToken(tree: *ast.Tree, source_buffer: *std.Buffer, src_text: []const u8, token_id: Token.Id) !void {
const start_index = source_buffer.len();
try source_buffer.append(src_text);
const end_index = source_buffer.len();
const new_token = try tree.tokens.addOne();
new_token.* = Token{
.id = token_id,
.start = start_index,
.end = end_index,
};
}
pub fn freeErrors(errors: []ClangErrMsg) void {
ZigClangErrorMsg_delete(errors.ptr, errors.len);
} | src-self-hosted/translate_c.zig |
const std = @import("std");
const print = std.debug.print;
usingnamespace @import("value.zig");
usingnamespace @import("chunk.zig");
usingnamespace @import("compiler.zig");
usingnamespace @import("heap.zig");
usingnamespace @import("vm.zig");
pub const GCLOG = std.log.scoped(.GC);
pub fn collectGarbage() !void {
GCLOG.info("-- gc begin", .{});
try markRoots();
try traceReferences();
//try sweep();
GCLOG.info("-- gc end", .{});
}
fn traceReferences() !void {
while (vm.grayStack.items.len > 0) {
try blackenObject(vm.grayStack.pop());
}
}
// A black object is any object whose isMarked field is set and that is no longer in the gray stack.
fn blackenObject(obj: *Obj) !void {
switch (obj.objType) {
.str => GCLOG.info("{} blacken {}", .{ @ptrToInt(obj), @ptrCast(*ObjString, obj).chars }),
.fun => {
const fun = @ptrCast(*ObjFunction, obj);
if (fun.name) |name| {
GCLOG.info("{} blacken <fn {}>", .{ @ptrToInt(obj), name.chars });
} else {
GCLOG.info("{} blacken <script>", .{@ptrToInt(obj)});
}
},
.closure => {
try printValue(objFunction2Value(@ptrCast(*ObjClosure, obj).fun));
},
.upvalue => GCLOG.info("{} blacken upvalue", .{@ptrToInt(obj)}),
}
switch (obj.objType) {
.str => return,
.upvalue => try markValue(&@ptrCast(*ObjUpvalue, obj).closed),
.fun => {
const fun = @ptrCast(*ObjFunction, obj);
if (fun.name) |name| {
try markObject(@ptrCast(*Obj, name));
}
try markArray(&fun.chunk.constants);
},
.closure => {
const closure = @ptrCast(*ObjClosure, obj);
try markObject(@ptrCast(*Obj, closure.fun));
for (closure.upvalues.items) |*item| {
try markObject(@ptrCast(*Obj, item));
}
}
}
}
fn markArray(array: *ArrayListOfValue) !void {
for (array.items) |*item| {
try markValue(item);
}
}
// ROOT分析
fn markRoots() !void {
// 1. 操作栈
for (vm.stack[0..vm.stackTop]) |*value| {
try markValue(value);
}
var i: usize = 0;
while (i < vm.frameCount) : (i += 1) {
try markObject(@ptrCast(*Obj, vm.frames[i].closure));
}
var upvalue = vm.openUpvalue;
while (upvalue) |uv| {
try markObject(@ptrCast(*Obj, uv));
upvalue = uv.next;
}
// 2. 全局变量
try markGlobals(&vm.globals);
// 编译状态
try markCompilerRoots();
}
fn markCompilerRoots() !void {
var compiler = current;
while (compiler) |c| {
if (c.function) |fun| {
try markObject(@ptrCast(*Obj, fun));
}
compiler = c.enclosing;
}
}
fn markValue(value: *Value) !void {
if (!isObj(value.*)) return;
try markObject(asObj(value.*));
}
fn markObject(obj: *Obj) !void {
if (obj.isMarked) return;
switch (obj.objType) {
.str => GCLOG.info("{} mark {}", .{ @ptrToInt(obj), @ptrCast(*ObjString, obj).chars }),
.fun => {
const fun = @ptrCast(*ObjFunction, obj);
if (fun.name) |name| {
GCLOG.info("{} mark <fn {}>", .{ @ptrToInt(obj), name.chars });
} else {
GCLOG.info("{} mark <script>", .{@ptrToInt(obj)});
}
},
.closure => {
try printValue(objFunction2Value(@ptrCast(*ObjClosure, obj).fun));
},
.upvalue => GCLOG.info("{} mark upvalue", .{@ptrToInt(obj)}),
}
obj.isMarked = true;
try vm.grayStack.append(obj);
}
fn markGlobals(globals: *ObjStringHashOfValue) !void {
var iterator = globals.iterator();
while (iterator.next()) |kv| {
try markObject(@ptrCast(*Obj, kv.key));
try markValue(&kv.value);
}
} | zvm/src/gc.zig |
const std = @import("std");
const string = []const u8;
const range = @import("range").range;
const input = @embedFile("../input/day11.txt");
// const input =
// \\5483143223
// \\2745854711
// \\5264556173
// \\6141336146
// \\6357385478
// \\4167524645
// \\2176841721
// \\6882881134
// \\4846848554
// \\5283751526
// ;
const L = 10;
pub fn main() !void {
//
// part 1
{
var grid: [L][L]u32 = undefined;
{
var iter = std.mem.split(u8, input, "\n");
var y: usize = 0;
while (iter.next()) |line| : (y += 1) {
for (line) |c, x| {
const num = try std.fmt.parseUnsigned(u32, &[_]u8{c}, 10);
grid[y][x] = num;
}
}
}
const steps = 100;
var total_flash_count: u32 = 0;
// commence steps
for (range(steps)) |_| {
// increment all spaces by 1
for (grid) |_, y| {
for (grid[y]) |_, x| {
grid[y][x] += 1;
}
}
// print(grid);
// check for flashes
var inner: u32 = 0;
while (true) {
defer inner += 1;
var flash_count: u32 = 0;
for (range(L)) |_, y| {
for (range(L)) |_, x| {
const n = grid[y][x];
if (n > 9 and n != 100) {
// increment neighbors
if (y > 0) inc(&grid, y - 1, x, 1); //up
inc(&grid, y + 1, x, 1); //down
if (x > 0) inc(&grid, y, x - 1, 1); //left
inc(&grid, y, x + 1, 1); //right
if (x > 0) if (y > 0) inc(&grid, y - 1, x - 1, 1); //up left
if (y > 0) inc(&grid, y - 1, x + 1, 1); //up right
if (x > 0) inc(&grid, y + 1, x - 1, 1); //down left
inc(&grid, y + 1, x + 1, 1); //down right
// this flashed
grid[y][x] = 100;
flash_count += 1;
total_flash_count += 1;
}
}
}
if (flash_count == 0) {
break;
}
}
// reset flashed elements to 0
for (grid) |line, y| {
for (line) |n, x| {
if (n == 100) {
grid[y][x] = 0;
}
}
}
}
std.debug.print("{d}\n", .{total_flash_count});
}
// part 2
{
var grid: [L][L]u32 = undefined;
{
var iter = std.mem.split(u8, input, "\n");
var y: usize = 0;
while (iter.next()) |line| : (y += 1) {
for (line) |c, x| {
const num = try std.fmt.parseUnsigned(u32, &[_]u8{c}, 10);
grid[y][x] = num;
}
}
}
var step: usize = 0;
var found: bool = false;
// commence steps
while (!found) {
step += 1;
// increment all spaces by 1
for (grid) |_, y| {
for (grid[y]) |_, x| {
grid[y][x] += 1;
}
}
// check for flashes
var inner: u32 = 0;
var step_flashes: u32 = 0;
while (true) {
defer inner += 1;
var flash_count: u32 = 0;
for (range(L)) |_, y| {
for (range(L)) |_, x| {
const n = grid[y][x];
if (n > 9 and n != 100) {
// increment neighbors
if (y > 0) inc(&grid, y - 1, x, 1); //up
inc(&grid, y + 1, x, 1); //down
if (x > 0) inc(&grid, y, x - 1, 1); //left
inc(&grid, y, x + 1, 1); //right
if (x > 0) if (y > 0) inc(&grid, y - 1, x - 1, 1); //up left
if (y > 0) inc(&grid, y - 1, x + 1, 1); //up right
if (x > 0) inc(&grid, y + 1, x - 1, 1); //down left
inc(&grid, y + 1, x + 1, 1); //down right
// this flashed
grid[y][x] = 100;
flash_count += 1;
step_flashes += 1;
}
}
}
// std.log.debug("step {d}: inner {d}: flashes {d}", .{ step, inner, flash_count });
if (flash_count == 0) {
break;
}
if (step_flashes == L * L) {
found = true;
break;
}
}
// reset flashed elements to 0
for (grid) |line, y| {
for (line) |n, x| {
if (n == 100) {
grid[y][x] = 0;
}
}
}
}
std.debug.print("{d}\n", .{step});
}
}
fn inc(grid: *[L][L]u32, y: usize, x: usize, n: u32) void {
if (y < 0) return;
if (x < 0) return;
if (y >= grid.len) return;
if (x >= grid[0].len) return;
if (grid[y][x] == 100) return;
grid[y][x] += n;
// std.log.info("inc'd {d},{d}", .{ x, y });
}
fn print(grid: [L][L]u32) void {
for (grid) |line| {
for (line) |nn| {
if (nn == 100) {
std.debug.print(" *", .{});
continue;
}
std.debug.print("{d:>2}", .{nn});
}
std.debug.print("\n", .{});
}
std.debug.print("\n", .{});
} | src/day11.zig |
const testing = @import("std").testing;
const math = @import("std").math;
pub const v3 = struct {
x: f32,
y: f32,
z: f32,
/// initializes a v3 with x, y and z
pub fn init(x: f32, y: f32, z: f32) v3 {
return v3 {
.x = x,
.y = y,
.z = z,
};
}
/// returns the component from an index
pub fn at(v: v3, i: u16) f32 {
return switch (i) {
0 => v.x,
1 => v.y,
2 => v.z,
else => @panic("invalid index value provided when accesing a v3 index"),
};
}
/// sets the component from an index
pub fn set(v: *v3, i: u16, val: f32) void {
switch (i) {
0 => v.x = val,
1 => v.y = val,
2 => v.z = val,
else => @panic("invalid index value provided when accessing a v3 index"),
}
}
/// returns the x, y and z of the v3 as a [3]f32 array.
/// to be used to pass to other stuff like opengl.
pub fn arr(v: v3) [3]f32 {
return .{v.x, v.y, v.z};
}
/// returns the length/magnitude of the vector
pub fn len(v: v3) f32 {
var sum: f32 = 0;
sum += v.x * v.x;
sum += v.y * v.y;
sum += v.z * v.z;
return math.sqrt(sum);
}
/// returns the normalized vector
pub fn normalized(v: v3) v3 {
const l = v.len();
if (l == 0) {
return v3.init(0, 0, 0);
}
return divs(v, l);
}
/// returns the dot product of two v3
pub fn dot(a: v3, b: v3) f32 {
var res: f32 = 0;
res += a.x * b.x;
res += a.y * b.y;
res += a.z * b.z;
return res;
}
/// returns the cross product of two v3
pub fn cross(a: v3, b: v3) v3 {
return v3.init(a.y * b.z - a.z * b.y,
a.z * b.x - a.x * b.z,
a.x * b.y - a.y * b.x);
}
/// returns the negated vector
pub fn neg(v: v3) v3 {
return v3.init(-v.x, -v.y, -v.z);
}
/// divides the v3 with a scalar
pub fn divs(v: v3, s: f32) v3 {
return v3.init(v.x / s, v.y / s, v.z / s);
}
/// multiplies the v3 with a scalar
pub fn muls(v: v3, s: f32) v3 {
return v3.init(v.x * s, v.y * s, v.z * s);
}
/// sums the v3 with a scalar
pub fn sums(v: v3, s: f32) v3 {
return v3.init(v.x + s, v.y + s, v.z + s);
}
/// subtracts the v3 from a scalar
pub fn subs(v: v3, s: f32) v3 {
return v3.init(v.x - s, v.y - s, v.z - s);
}
/// sums the v3 with another v3
pub fn sumv(a: v3, b: v3) v3 {
return v3.init(a.x + b.x, a.y + b.y, a.z + b.z);
}
/// subtracts the v3 from another v3
pub fn subv(a: v3, b: v3) v3 {
return v3.init(a.x - b.x, a.y - b.y, a.z - b.z);
}
};
test "creating a v3" {
const x = v3.init(4, 8, 2);
testing.expect(x.x == 4);
testing.expect(x.y == 8);
testing.expect(x.z == 2);
testing.expect(x.at(0) == 4);
testing.expect(x.at(1) == 8);
testing.expect(x.at(2) == 2);
testing.expect(x.arr()[0] == 4);
testing.expect(x.arr()[1] == 8);
testing.expect(x.arr()[2] == 2);
}
test "v3 length" {
const x = v3.init(4, 8, 2);
testing.expect(math.approxEq(f32, x.len(), 9.16515138991168, math.f32_epsilon));
}
test "v3 operation" {
const x = v3.init(4, 8, 2);
const y = v3.init(1, 3, 5);
var res = v3.divs(x, 2);
testing.expect(res.x == 2);
testing.expect(res.y == 4);
testing.expect(res.z == 1);
res = v3.muls(x, 2);
testing.expect(res.x == 8);
testing.expect(res.y == 16);
testing.expect(res.z == 4);
res = v3.neg(x);
testing.expect(res.x == -4);
testing.expect(res.y == -8);
testing.expect(res.z == -2);
res = v3.sums(x, 2);
testing.expect(res.x == 6);
testing.expect(res.y == 10);
testing.expect(res.z == 4);
res = v3.subs(x, 2);
testing.expect(res.x == 2);
testing.expect(res.y == 6);
testing.expect(res.z == 0);
res = v3.sumv(x, y);
testing.expect(res.x == 5);
testing.expect(res.y == 11);
testing.expect(res.z == 7);
res = v3.subv(x, y);
testing.expect(res.x == 3);
testing.expect(res.y == 5);
testing.expect(res.z == -3);
}
test "v3 normalized" {
const a = v3.init(4, 8, 2);
const x = v3.normalized(a);
testing.expect(math.approxEq(f32, x.x, 0.4364357804719848, math.f32_epsilon));
testing.expect(math.approxEq(f32, x.y, 0.8728715609439696, math.f32_epsilon));
testing.expect(math.approxEq(f32, x.z, 0.2182178902359924, math.f32_epsilon));
}
test "v3 dot" {
const x = v3.init(4, 8, 2);
const y = v3.init(1, 3, 5);
const res = v3.dot(x, y);
testing.expect(res == 38);
}
test "v3 cross" {
const x = v3.init(4, 8, 2);
const y = v3.init(1, 3, 5);
const res = v3.cross(x, y);
testing.expect(res.x == 34);
testing.expect(res.y == -18);
testing.expect(res.z == 4);
} | src/vector3.zig |
const base = @import("base.zig");
const std = @import("std");
pub fn monthMax(segments: []const ?base.Segment) u8 {
//Assumes same months for leap and non-leap years.
var month_max: u8 = 1;
for (segments) |raw_s| {
const s = raw_s orelse unreachable;
if (s.month > month_max) {
month_max = s.month;
}
}
return month_max;
}
pub fn dayCount(segments: []const ?base.Segment) u16 {
if (segments[segments.len - 1]) |final_segment| {
return final_segment.offset + final_segment.day_end;
}
unreachable;
}
pub fn leapDayCount(common: []const ?base.Segment, leap: []const ?base.Segment) u16 {
return dayCount(leap) - dayCount(common);
}
//For MJD converted by
//https://www.vcalc.com/equation/?uuid=e900a382-77a1-11e5-a3bb-bc764e2038f2
pub fn mjdFromVcalc(vcalc: f32) i32 {
return @floatToInt(i32, std.math.floor(vcalc));
}
pub fn validInEnum(comptime E: type, x: i32) bool {
inline for (std.meta.fields(E)) |field| {
if (field.value == x) {
return true;
}
}
return false;
}
pub fn lastOfEnum(comptime E: type) comptime_int {
var raw_res: ?comptime_int = null;
inline for (std.meta.fields(E)) |field| {
if (raw_res) |res| {
if (res < field.value) {
raw_res = field.value;
}
} else {
raw_res = field.value;
}
}
const final = raw_res orelse unreachable;
return final;
}
pub fn getDayOfYearFromSegment(month: u8, day: u8, s: base.Segment) ?u16 {
if (s.month == month and s.day_start <= day and s.day_end >= day) {
const day_of_month = day - s.day_start;
return s.offset + day_of_month + 1;
} else {
return null;
}
}
pub fn getDayOfYear(month: u8, day: u8, segments: []const ?base.Segment) u16 {
for (segments) |raw_s| {
const s = raw_s orelse unreachable;
if (getDayOfYearFromSegment(month, day, s)) |res| {
return res;
}
}
unreachable;
}
pub fn initIc(
ic: base.Intercalary,
COMMON: []const ?base.Segment,
LEAP: []const ?base.Segment,
) base.Intercalary {
var name_i = ic.name_i;
if (ic.month == 0 and ic.name_i == 0) {
name_i = ic.day - 1;
}
return base.Intercalary{
.month = ic.month,
.day = ic.day,
.day_of_year = getDayOfYear(ic.month, ic.day, COMMON[0..COMMON.len]),
.day_of_leap_year = getDayOfYear(ic.month, ic.day, LEAP[0..LEAP.len]),
.era_start_alt_name = ic.era_start_alt_name,
.name_i = name_i,
};
}
pub fn seekIc(month: u8, day: u8, cal: *const base.Cal) ?base.Intercalary {
if (cal.*.intercalary_list) |ic_list| {
var ici: u8 = 0;
while (ic_list[ici]) |res| : (ici += 1) {
if (res.month == month and res.day == day) {
return res;
}
}
}
return null;
}
pub fn yearLen(leap: bool, cal: *const base.Cal) u16 {
const lc = cal.*.leap_cycle;
if (leap) {
return lc.common_days + lc.leap_days;
} else {
return lc.common_days;
}
}
pub fn listLen(comptime T: type, list: [*:null]const ?T) usize {
//std.mem.len and std.mem.indexOfSentinel fail for base.Intercalary
var i: usize = 0;
while (list[i]) |_| : (i += 1) {}
return i;
} | src/gen.zig |
const std = @import("std");
const expect = std.testing.expect;
const warn = std.debug.warn;
const Cpu = @import("cpu.zig").Cpu;
const Opcode = @import("opcode.zig").Opcode;
const OpcodeEnum = @import("enum.zig").OpcodeEnum;
const AddressingModeEnum = @import("enum.zig").AddressingModeEnum;
test "should initialize correct internal registers and flags" {
const cpu = Cpu.init();
expect(cpu.program_counter == 0xC000);
expect(cpu.reg_a == 0x00);
expect(cpu.reg_x == 0x00);
expect(cpu.reg_y == 0x00);
expect(cpu.f_carry == 0x00);
expect(cpu.f_zero == 0x00);
expect(cpu.f_interrupt_disable == 0x01);
expect(cpu.f_interrupt_disable_temp == 0x01);
expect(cpu.f_decimal == 0x00);
expect(cpu.f_break == 0x00);
expect(cpu.f_break_temp == 0x00);
expect(cpu.f_unused == 0x01);
expect(cpu.f_overflow == 0x00);
expect(cpu.f_negative == 0x00);
}
test "should correctly update status flags from value" {
var cpu = Cpu.init();
cpu.set_status_flags(0x42);
expect(cpu.f_carry == 0);
expect(cpu.f_zero == 1);
expect(cpu.f_interrupt_disable == 0);
expect(cpu.f_decimal == 0);
expect(cpu.f_break == 0);
expect(cpu.f_unused == 1);
expect(cpu.f_overflow == 1);
expect(cpu.f_negative == 0);
cpu.set_status_flags(0x00);
expect(cpu.f_carry == 0);
expect(cpu.f_zero == 0);
expect(cpu.f_interrupt_disable == 0);
expect(cpu.f_decimal == 0);
expect(cpu.f_break == 0);
expect(cpu.f_unused == 1);
expect(cpu.f_overflow == 0);
expect(cpu.f_negative == 0);
cpu.set_status_flags(0xFF);
expect(cpu.f_carry == 1);
expect(cpu.f_zero == 1);
expect(cpu.f_interrupt_disable == 1);
expect(cpu.f_decimal == 1);
expect(cpu.f_break == 1);
expect(cpu.f_unused == 1);
expect(cpu.f_overflow == 1);
expect(cpu.f_negative == 1);
}
test "should correctly get status flag value" {
var cpu = Cpu.init();
cpu.set_status_flags(0x42);
expect(cpu.get_status_flags() == 0x62);
}
test "should correctly resolve Absolute address" {
var cpu = Cpu.init();
var address: u16 = undefined;
cpu.ram.write(cpu.program_counter, 0x34);
cpu.ram.write(cpu.program_counter + 1, 0x12);
address = cpu.resolve_address(AddressingModeEnum.Absolute);
expect(address == 0x1234);
expect(cpu.cycles == 0);
}
test "should correctly resolve AbsoluteX address" {
var cpu = Cpu.init();
var address: u16 = undefined;
cpu.program_counter = 0xC000;
cpu.cycles = 0;
cpu.ram.write(cpu.program_counter, 0x34);
cpu.ram.write(cpu.program_counter + 1, 0x12);
cpu.reg_x = 0x01;
address = cpu.resolve_address(AddressingModeEnum.AbsoluteX);
expect(address == 0x1235);
expect(cpu.cycles == 0);
cpu.program_counter = 0xC000;
cpu.cycles = 0;
cpu.ram.write(cpu.program_counter, 0xFF);
cpu.ram.write(cpu.program_counter + 1, 0x01);
cpu.reg_x = 0x01;
address = cpu.resolve_address(AddressingModeEnum.AbsoluteX);
expect(address == 0x0200);
expect(cpu.cycles == 1);
}
test "should correctly resolve AbsoluteY address" {
var cpu = Cpu.init();
var address: u16 = undefined;
cpu.program_counter = 0xC000;
cpu.cycles = 0;
cpu.ram.write(cpu.program_counter, 0x34);
cpu.ram.write(cpu.program_counter + 1, 0x12);
cpu.reg_y = 0x01;
address = cpu.resolve_address(AddressingModeEnum.AbsoluteY);
expect(address == 0x1235);
expect(cpu.cycles == 0);
cpu.program_counter = 0xC000;
cpu.cycles = 0;
cpu.ram.write(cpu.program_counter, 0xFF);
cpu.ram.write(cpu.program_counter + 1, 0x01);
cpu.reg_y = 0x01;
address = cpu.resolve_address(AddressingModeEnum.AbsoluteY);
expect(address == 0x0200);
expect(cpu.cycles == 1);
}
test "should correctly resolve Accumulator address" {
var cpu = Cpu.init();
var address: u16 = undefined;
cpu.reg_a = 0x42;
address = cpu.resolve_address(AddressingModeEnum.Accumulator);
expect(address == 0x0042);
expect(cpu.cycles == 0);
}
test "should correctly resolve Immediate address" {
var cpu = Cpu.init();
var address: u16 = undefined;
address = cpu.resolve_address(AddressingModeEnum.Immediate);
expect(address == 0xC000);
expect(cpu.cycles == 0);
}
test "should correctly resolve Indirect address" {
var cpu = Cpu.init();
var address: u16 = undefined;
cpu.program_counter = 0xC000;
cpu.cycles = 0;
cpu.ram.write(cpu.program_counter, 0x34);
cpu.ram.write(cpu.program_counter + 1, 0x12);
cpu.ram.write(0x1234, 0x78);
cpu.ram.write(0x1235, 0x56);
address = cpu.resolve_address(AddressingModeEnum.Indirect);
expect(address == 0x5678);
expect(cpu.cycles == 0);
cpu.program_counter = 0xC000;
cpu.cycles = 0;
cpu.ram.write(cpu.program_counter, 0xFF);
cpu.ram.write(cpu.program_counter + 1, 0x00);
address = cpu.resolve_address(AddressingModeEnum.Indirect);
expect(address == 0x0100);
expect(cpu.cycles == 0);
}
test "should correctly resolve IndirectX address" {
var cpu = Cpu.init();
var address: u16 = undefined;
cpu.program_counter = 0xC000;
cpu.cycles = 0;
cpu.ram.write(cpu.program_counter, 0x42);
cpu.reg_x = 0x01;
cpu.ram.write(0x0043, 0x78);
cpu.ram.write(0x0044, 0x56);
address = cpu.resolve_address(AddressingModeEnum.IndirectX);
expect(address == 0x5678);
expect(cpu.cycles == 0);
cpu.program_counter = 0xC000;
cpu.cycles = 0;
cpu.ram.write(cpu.program_counter, 0xFF);
cpu.reg_x = 0x00;
cpu.ram.write(0x00FF, 0x34);
cpu.ram.write(0x0000, 0x12);
address = cpu.resolve_address(AddressingModeEnum.IndirectX);
expect(address == 0x1234);
expect(cpu.cycles == 0);
}
test "should correctly resolve IndirectY address" {
var cpu = Cpu.init();
var address: u16 = undefined;
cpu.program_counter = 0xC000;
cpu.cycles = 0;
cpu.ram.write(cpu.program_counter, 0x42);
cpu.reg_y = 0x01;
cpu.ram.write(0x0042, 0x78);
cpu.ram.write(0x0043, 0x56);
address = cpu.resolve_address(AddressingModeEnum.IndirectY);
expect(address == 0x5679);
expect(cpu.cycles == 0);
cpu.program_counter = 0xC000;
cpu.cycles = 0;
cpu.ram.write(cpu.program_counter, 0xFF);
cpu.reg_y = 0x00;
cpu.ram.write(0x00FF, 0x34);
cpu.ram.write(0x0000, 0x12);
address = cpu.resolve_address(AddressingModeEnum.IndirectY);
expect(address == 0x1234);
expect(cpu.cycles == 0);
cpu.program_counter = 0xC000;
cpu.cycles = 0;
cpu.ram.write(cpu.program_counter, 0xFF);
cpu.reg_y = 0x01;
cpu.ram.write(0x00FF, 0xFF);
cpu.ram.write(0x0000, 0x12);
address = cpu.resolve_address(AddressingModeEnum.IndirectY);
expect(address == 0x1300);
expect(cpu.cycles == 1);
}
test "should correctly resolve Relative address" {
var cpu = Cpu.init();
var address: u16 = undefined;
cpu.program_counter = 0xC000;
cpu.ram.write(cpu.program_counter, 0x01);
address = cpu.resolve_address(AddressingModeEnum.Relative);
expect(address == 0xC001);
expect(cpu.cycles == 0);
cpu.program_counter = 0xC000;
cpu.ram.write(cpu.program_counter, 0x88);
address = cpu.resolve_address(AddressingModeEnum.Relative);
expect(address == 0xBF88);
expect(cpu.cycles == 0);
}
test "should correctly resolve ZeroPage address" {
var cpu = Cpu.init();
var address: u16 = undefined;
cpu.ram.write(cpu.program_counter, 0x42);
address = cpu.resolve_address(AddressingModeEnum.ZeroPage);
expect(address == 0x42);
expect(cpu.cycles == 0);
}
test "should correctly resolve ZeroPageX address" {
var cpu = Cpu.init();
var address: u16 = undefined;
cpu.program_counter = 0xC000;
cpu.ram.write(cpu.program_counter, 0x42);
cpu.reg_x = 0x01;
address = cpu.resolve_address(AddressingModeEnum.ZeroPageX);
expect(address == 0x43);
expect(cpu.cycles == 0);
cpu.program_counter = 0xC000;
cpu.ram.write(cpu.program_counter, 0xFF);
cpu.reg_x = 0x01;
address = cpu.resolve_address(AddressingModeEnum.ZeroPageX);
expect(address == 0x00);
expect(cpu.cycles == 0);
}
test "should correctly resolve ZeroPageY address" {
var cpu = Cpu.init();
var address: u16 = undefined;
cpu.program_counter = 0xC000;
cpu.ram.write(cpu.program_counter, 0x42);
cpu.reg_y = 0x01;
address = cpu.resolve_address(AddressingModeEnum.ZeroPageY);
expect(address == 0x43);
expect(cpu.cycles == 0);
cpu.program_counter = 0xC000;
cpu.ram.write(cpu.program_counter, 0xFF);
cpu.reg_y = 0x01;
address = cpu.resolve_address(AddressingModeEnum.ZeroPageY);
expect(address == 0x00);
expect(cpu.cycles == 0);
}
test "should correctly execute AAC opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.AAC, 0x0B, AddressingModeEnum.Immediate, 2, 2);
cpu.ram.write(0x0000, 0x88);
cpu.reg_a = 0xFF;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.f_negative == 0x01);
expect(cpu.f_zero == 0x00);
expect(cpu.f_carry == 0x01);
}
test "should correctly execute AAX opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.AAX, 0x83, AddressingModeEnum.IndirectX, 2, 6);
cpu.ram.write(0x0000, 0x00);
cpu.reg_a = 0x44;
cpu.reg_x = 0xFF;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.ram.read_8(0x0000) == 0x44);
}
test "should correctly execute ADC opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.ADC, 0x69, AddressingModeEnum.Immediate, 2, 2);
cpu.ram.write(0x0000, 0x00);
cpu.reg_a = 0xFF;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.reg_a == 0xFF);
expect(cpu.f_negative == 0x01);
expect(cpu.f_zero == 0x00);
expect(cpu.f_carry == 0x00);
cpu.ram.write(0x0000, 0x01);
cpu.reg_a = 0xFF;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.reg_a == 0x00);
expect(cpu.f_negative == 0x00);
expect(cpu.f_zero == 0x01);
expect(cpu.f_carry == 0x01);
cpu.ram.write(0x0000, 0x00);
cpu.reg_a = 0x42;
cpu.f_carry = 0x01;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.reg_a == 0x43);
expect(cpu.f_negative == 0x00);
expect(cpu.f_zero == 0x00);
expect(cpu.f_carry == 0x00);
cpu.ram.write(0x0000, 0x00);
cpu.reg_a = 0xFF;
cpu.f_carry = 0x01;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.reg_a == 0x00);
expect(cpu.f_negative == 0x00);
expect(cpu.f_zero == 0x01);
expect(cpu.f_carry == 0x01);
}
test "should correctly execute AND opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.AND, 0x29, AddressingModeEnum.Immediate, 2, 2);
cpu.ram.write(0x0000, 0xFF);
cpu.reg_a = 0x44;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.reg_a == 0x44);
expect(cpu.f_negative == 0x00);
expect(cpu.f_zero == 0x00);
expect(cpu.f_carry == 0x00);
}
test "should correctly execute ASL opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.ASL, 0x06, AddressingModeEnum.ZeroPage, 2, 5);
cpu.ram.write(0x0000, 0x42);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.ram.read_8(0x0000) == 0x84);
expect(cpu.f_negative == 0x01);
expect(cpu.f_zero == 0x00);
expect(cpu.f_carry == 0x00);
cpu.ram.write(0x0000, 0xFF);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.ram.read_8(0x0000) == 0xFE);
expect(cpu.f_negative == 0x01);
expect(cpu.f_zero == 0x00);
expect(cpu.f_carry == 0x01);
opcode = Opcode.init(OpcodeEnum.ASL, 0x06, AddressingModeEnum.Accumulator, 2, 5);
cpu.reg_a = 0x42;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.reg_a == 0x84);
expect(cpu.f_negative == 0x01);
expect(cpu.f_zero == 0x00);
expect(cpu.f_carry == 0x00);
}
test "should correctly execute ATX opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.ATX, 0xAB, AddressingModeEnum.Immediate, 2, 2);
cpu.ram.write(0x0000, 0x42);
cpu.reg_a = 0xDD;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.reg_a == 0x42);
expect(cpu.reg_x == 0x42);
expect(cpu.f_zero == 0x00);
expect(cpu.f_negative == 0x00);
}
test "should correctly execute BCC opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.BCC, 0x90, AddressingModeEnum.Relative, 2, 2);
cpu.program_counter = 0xFFFF;
cpu.f_carry = 0x00;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.program_counter == 0x0000);
cpu.program_counter = 0xFFFF;
cpu.f_carry = 0x01;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.program_counter == 0x0001);
}
test "should correctly execute BCS opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.BCS, 0xB0, AddressingModeEnum.Relative, 2, 2);
cpu.program_counter = 0xFFFF;
cpu.f_carry = 0x00;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.program_counter == 0x0001);
cpu.program_counter = 0xFFFF;
cpu.f_carry = 0x01;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.program_counter == 0x0000);
}
test "should correctly execute BEQ opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.BEQ, 0xF0, AddressingModeEnum.Relative, 2, 2);
cpu.program_counter = 0xFFFF;
cpu.f_zero = 0x00;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.program_counter == 0x0001);
cpu.program_counter = 0xFFFF;
cpu.f_zero = 0x01;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.program_counter == 0x0000);
}
test "should correctly execute BIT opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.BIT, 0x2C, AddressingModeEnum.Absolute, 3, 4);
cpu.ram.write(0x0000, 0x42);
cpu.reg_a = 0x42;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.f_zero == 0x00);
expect(cpu.f_overflow == 0x01);
expect(cpu.f_negative == 0x00);
}
test "should correctly execute BMI opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.BMI, 0x30, AddressingModeEnum.Relative, 2, 2);
cpu.program_counter = 0xFFFF;
cpu.f_negative = 0x00;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.program_counter == 0x0001);
cpu.program_counter = 0xFFFF;
cpu.f_negative = 0x01;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.program_counter == 0x0000);
}
test "should correctly execute BNE opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.BNE, 0xD0, AddressingModeEnum.Relative, 2, 2);
cpu.program_counter = 0xFFFF;
cpu.f_zero = 0x00;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.program_counter == 0x0000);
cpu.program_counter = 0xFFFF;
cpu.f_zero = 0x01;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.program_counter == 0x0001);
}
test "should correctly execute BPL opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.BPL, 0x10, AddressingModeEnum.Relative, 2, 2);
cpu.program_counter = 0xFFFF;
cpu.f_negative = 0x00;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.program_counter == 0x0000);
cpu.program_counter = 0xFFFF;
cpu.f_negative = 0x01;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.program_counter == 0x0001);
}
test "should correctly execute BVC opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.BVC, 0x50, AddressingModeEnum.Relative, 2, 2);
cpu.program_counter = 0xFFFF;
cpu.f_overflow = 0x00;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.program_counter == 0x0000);
cpu.program_counter = 0xFFFF;
cpu.f_overflow = 0x01;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.program_counter == 0x0001);
}
test "should correctly execute BVS opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.BVS, 0x70, AddressingModeEnum.Relative, 2, 2);
cpu.program_counter = 0xFFFF;
cpu.f_overflow = 0x00;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.program_counter == 0x0001);
cpu.program_counter = 0xFFFF;
cpu.f_overflow = 0x01;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.program_counter == 0x0000);
}
test "should correctly execute CLC opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.CLC, 0x18, AddressingModeEnum.Implicit, 1, 2);
cpu.f_carry = 0x01;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.f_carry == 0x00);
}
test "should correctly execute CLD opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.CLD, 0xD8, AddressingModeEnum.Implicit, 1, 2);
cpu.f_decimal = 0x01;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.f_decimal == 0x00);
}
test "should correctly execute CLI opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.CLI, 0x58, AddressingModeEnum.Implicit, 1, 2);
cpu.f_interrupt_disable = 0x01;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.f_interrupt_disable == 0x00);
}
test "should correctly execute CLV opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.CLV, 0xB8, AddressingModeEnum.Implicit, 1, 2);
cpu.f_overflow = 0x01;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.f_overflow == 0x00);
}
test "should correctly execute CMP opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.CMP, 0xC5, AddressingModeEnum.ZeroPage, 2, 3);
cpu.reg_a = 0x42;
cpu.ram.write(0x0000, 0x42);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.f_carry == 0x00);
cpu.reg_a = 0xFF;
cpu.ram.write(0x0000, 0x0F);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.f_carry == 0x01);
}
test "should correctly execute CPX opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.CPX, 0xE0, AddressingModeEnum.Immediate, 2, 2);
cpu.reg_x = 0x42;
cpu.ram.write(0x0000, 0x42);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.f_carry == 0x00);
cpu.reg_x = 0xFF;
cpu.ram.write(0x0000, 0x0F);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.f_carry == 0x01);
}
test "should correctly execute CPY opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.CPY, 0xC0, AddressingModeEnum.Immediate, 2, 2);
cpu.reg_y = 0x42;
cpu.ram.write(0x0000, 0x42);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.f_carry == 0x00);
cpu.reg_y = 0xFF;
cpu.ram.write(0x0000, 0x0F);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.f_carry == 0x01);
}
test "should correctly execute DCP opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.DCP, 0xC3, AddressingModeEnum.IndirectX, 2, 8);
cpu.reg_a = 0x42;
cpu.ram.write(0x0000, 0x42);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.f_carry == 0x00);
cpu.reg_a = 0xFF;
cpu.ram.write(0x0000, 0x0F);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.f_carry == 0x01);
}
test "should correctly execute DEC opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.DEC, 0xC6, AddressingModeEnum.ZeroPage, 2, 5);
cpu.ram.write(0x0000, 0x42);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.ram.read_8(0x0000) == 0x41);
}
test "should correctly execute DEX opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.DEX, 0xCA, AddressingModeEnum.Implicit, 1, 2);
cpu.reg_x = 0x42;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.reg_x == 0x41);
}
test "should correctly execute DEY opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.DEY, 0x88, AddressingModeEnum.Implicit, 1, 2);
cpu.reg_y = 0x42;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.reg_y == 0x41);
}
test "should correctly execute EOR opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.EOR, 0x41, AddressingModeEnum.IndirectX, 2, 6);
cpu.reg_a = 0x42;
cpu.ram.write(0x0000, 0x24);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.reg_a == 0x66);
}
test "should correctly execute INC opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.INC, 0xE6, AddressingModeEnum.ZeroPage, 2, 5);
cpu.ram.write(0x0000, 0x42);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.ram.read_8(0x0000) == 0x43);
}
test "should correctly execute INX opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.INX, 0xE8, AddressingModeEnum.Implicit, 1, 2);
cpu.reg_x = 0x42;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.reg_x == 0x43);
}
test "should correctly execute INY opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.INY, 0xC8, AddressingModeEnum.Implicit, 1, 2);
cpu.reg_y = 0x42;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.reg_y == 0x43);
}
test "should correctly execute JMP opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.JMP, 0x4C, AddressingModeEnum.Absolute, 3, 3);
cpu.ram.write(0x0000, 0x42);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.program_counter == 0x0000);
}
test "should correctly execute JSR opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.JSR, 0x20, AddressingModeEnum.Absolute, 3, 6);
cpu.program_counter = 0x1234;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.ram.pop_from_stack() == 0x37);
expect(cpu.ram.pop_from_stack() == 0x12);
expect(cpu.program_counter == 0x0000);
}
test "should correctly execute LAX opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.LAX, 0xA3, AddressingModeEnum.IndirectX, 2, 6);
cpu.ram.write(0x0000, 0x42);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.reg_a == 0x42);
expect(cpu.reg_x == 0x42);
}
test "should correctly execute LDA opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.LDA, 0xA1, AddressingModeEnum.IndirectX, 2, 6);
cpu.ram.write(0x0000, 0x42);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.reg_a == 0x42);
}
test "should correctly execute LDX opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.LDX, 0xA2, AddressingModeEnum.Immediate, 2, 2);
cpu.ram.write(0x0000, 0x42);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.reg_x == 0x42);
}
test "should correctly execute LDY opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.LDY, 0xA0, AddressingModeEnum.Immediate, 2, 2);
cpu.ram.write(0x0000, 0x42);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.reg_y == 0x42);
}
test "should correctly execute LSR opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.LSR, 0x46, AddressingModeEnum.ZeroPage, 2, 5);
cpu.ram.write(0x0000, 0x42);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.f_carry == 0x00);
expect(cpu.ram.read_8(0x0000) == 0x21);
cpu.ram.write(0x0000, 0x21);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.f_carry == 0x01);
expect(cpu.ram.read_8(0x0000) == 0x10);
}
test "should correctly execute ORA opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.ORA, 0x01, AddressingModeEnum.IndirectX, 2, 6);
cpu.ram.write(0x0000, 0xAA);
cpu.reg_a = 0x55;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.f_zero == 0x00);
cpu.ram.write(0x0000, 0x00);
cpu.reg_a = 0x00;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.f_zero == 0x01);
}
test "should correctly execute PHA opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.PHA, 0x48, AddressingModeEnum.Implicit, 1, 3);
cpu.reg_a = 0x42;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.ram.pop_from_stack() == 0x42);
}
test "should correctly execute PHP opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.PHP, 0x08, AddressingModeEnum.Implicit, 1, 3);
cpu.ram.push_to_stack(0x42);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.ram.pop_from_stack() == 0x52);
}
test "should correctly execute PLA opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.PLA, 0x68, AddressingModeEnum.Implicit, 1, 4);
cpu.ram.push_to_stack(0x42);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.reg_a == 0x42);
}
test "should correctly execute PLP opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.PLP, 0x28, AddressingModeEnum.Implicit, 1, 4);
cpu.ram.push_to_stack(0xAA);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.get_status_flags() == 0xAA);
}
test "should correctly execute RLA opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.RLA, 0x23, AddressingModeEnum.IndirectX, 2, 8);
cpu.ram.write(0x0000, 0xFF);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.f_carry == 0x01);
expect(cpu.reg_a == 0x00);
}
test "should correctly execute ROL opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.ROL, 0x26, AddressingModeEnum.ZeroPage, 2, 5);
cpu.ram.write(0x0000, 0xFF);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.f_carry == 0x01);
expect(cpu.reg_a == 0x00);
}
test "should correctly execute ROR opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.ROR, 0x66, AddressingModeEnum.ZeroPage, 2, 5);
cpu.ram.write(0x0000, 0xFF);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.f_carry == 0x01);
expect(cpu.reg_a == 0x00);
}
test "should correctly execute RTI opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.RTI, 0x40, AddressingModeEnum.Implicit, 1, 6);
cpu.ram.push_to_stack(0x12);
cpu.ram.push_to_stack(0x34);
cpu.ram.push_to_stack(0xAA);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.get_status_flags() == 0xAA);
expect(cpu.program_counter == 0x1234);
}
test "should correctly execute RTS opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.RTS, 0x60, AddressingModeEnum.Implicit, 1, 6);
cpu.ram.push_to_stack(0x12);
cpu.ram.push_to_stack(0x34);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.program_counter == 0x1234);
}
test "should correctly execute SBC opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.SBC, 0xE1, AddressingModeEnum.IndirectX, 2, 6);
cpu.ram.write(0x0000, 0x00);
cpu.reg_a = 0xFF;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.reg_a == 0xFF);
expect(cpu.f_negative == 0x01);
expect(cpu.f_zero == 0x00);
expect(cpu.f_carry == 0x00);
cpu.ram.write(0x0000, 0x01);
cpu.reg_a = 0xFF;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.reg_a == 0xFE);
expect(cpu.f_negative == 0x01);
expect(cpu.f_zero == 0x00);
expect(cpu.f_carry == 0x00);
cpu.ram.write(0x0000, 0x00);
cpu.reg_a = 0x42;
cpu.f_carry = 0x01;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.reg_a == 0x41);
expect(cpu.f_negative == 0x00);
expect(cpu.f_zero == 0x00);
expect(cpu.f_carry == 0x00);
cpu.ram.write(0x0000, 0x00);
cpu.reg_a = 0x01;
cpu.f_carry = 0x01;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.reg_a == 0x00);
expect(cpu.f_negative == 0x00);
expect(cpu.f_zero == 0x01);
expect(cpu.f_carry == 0x00);
cpu.ram.write(0x0000, 0x01);
cpu.reg_a = 0x00;
cpu.f_carry = 0x00;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.reg_a == 0xFF);
expect(cpu.f_negative == 0x01);
expect(cpu.f_zero == 0x00);
expect(cpu.f_carry == 0x01);
cpu.ram.write(0x0000, 0x01);
cpu.reg_a = 0x00;
cpu.f_carry = 0x01;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.reg_a == 0xFE);
expect(cpu.f_negative == 0x01);
expect(cpu.f_zero == 0x00);
expect(cpu.f_carry == 0x01);
}
test "should correctly execute SEC opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.SEC, 0x38, AddressingModeEnum.Implicit, 1, 2);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.f_carry == 0x01);
}
test "should correctly execute SED opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.SED, 0xF8, AddressingModeEnum.Implicit, 1, 2);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.f_decimal == 0x01);
}
test "should correctly execute SEI opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.SEI, 0x78, AddressingModeEnum.Implicit, 1, 2);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.f_interrupt_disable == 0x01);
}
test "should correctly execute SLO opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.SLO, 0x03, AddressingModeEnum.IndirectX, 2, 8);
cpu.ram.write(0x0000, 0xAA);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.reg_a == 0x54);
}
test "should correctly execute SRE opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.SRE, 0x43, AddressingModeEnum.IndirectX, 2, 8);
cpu.ram.write(0x0000, 0xAA);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.reg_a == 0x55);
}
test "should correctly execute STA opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.STA, 0x81, AddressingModeEnum.IndirectX, 2, 6);
cpu.reg_a = 0x42;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.ram.read_8(0x0000) == 0x42);
}
test "should correctly execute STX opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.STX, 0x86, AddressingModeEnum.ZeroPage, 2, 3);
cpu.reg_x = 0x42;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.ram.read_8(0x0000) == 0x42);
}
test "should correctly execute STY opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.STY, 0x84, AddressingModeEnum.ZeroPage, 2, 3);
cpu.reg_y = 0x42;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.ram.read_8(0x0000) == 0x42);
}
test "should correctly execute TAX opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.TAX, 0xAA, AddressingModeEnum.Implicit, 1, 2);
cpu.reg_a = 0x42;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.reg_x == 0x42);
}
test "should correctly execute TSX opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.TSX, 0xBA, AddressingModeEnum.Implicit, 1, 2);
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.reg_x == 0xFD);
}
test "should correctly execute TXA opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.TXA, 0x8A, AddressingModeEnum.Implicit, 1, 2);
cpu.reg_x = 0x42;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.reg_a == 0x42);
}
test "should correctly execute TXS opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.TXS, 0x9A, AddressingModeEnum.Implicit, 1, 2);
cpu.reg_x = 0x42;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.ram.stack_pointer == 0x42);
}
test "should correctly execute TYA opcode" {
var cpu = Cpu.init();
var opcode = Opcode.init(OpcodeEnum.TYA, 0x98, AddressingModeEnum.Implicit, 1, 2);
cpu.reg_y = 0x42;
cpu.execute_instruction(opcode, 0x0000);
expect(cpu.reg_a == 0x42);
} | src/test_cpu.zig |
const std = @import("std");
pub fn main() anyerror!void {
std.log.info("All your codebase are belong to us.", .{});
}
// Declare a struct.
// Zig gives no guarantees about the order of fields and the size of
// the struct but the fields are guaranteed to be ABI-aligned.
const Point = struct {
x: f32,
y: f32,
};
// Maybe we want to pass it to OpenGL so we want to be particular about
// how the bytes are arranged.
const Point2 = packed struct {
x: f32,
y: f32,
};
// Declare an instance of a struct.
const p = Point {
.x = 0.12,
.y = 0.34,
};
// Maybe we're not ready to fill out some of the fields.
var p2 = Point {
.x = 0.12,
.y = undefined,
};
// Structs can have methods
// Struct methods are not special, they are only namespaced
// functions that you can call with dot syntax.
const Vec3 = struct {
x: f32,
y: f32,
z: f32,
pub fn init(x: f32, y: f32, z: f32) Vec3 {
return Vec3 {
.x = x,
.y = y,
.z = z,
};
}
pub fn dot(self: Vec3, other: Vec3) f32 {
return self.x * other.x + self.y * other.y + self.z * other.z;
}
};
const expect = @import("std").testing.expect;
test "dot product" {
const v1 = Vec3.init(1.0, 0.0, 0.0);
const v2 = Vec3.init(0.0, 1.0, 0.0);
try expect(v1.dot(v2) == 0.0);
// Other than being available to call with dot syntax, struct methods are
// not special. You can reference them as any other declaration inside
// the struct:
try expect(Vec3.dot(v1, v2) == 0.0);
}
// Structs can have declarations.
// Structs can have 0 fields.
const Empty = struct {
pub const PI = 3.14;
};
test "struct namespaced variable" {
try expect(Empty.PI == 3.14);
try expect(@sizeOf(Empty) == 0);
// you can still instantiate an empty struct
//const does_nothing = Empty {};
}
// struct field order is determined by the compiler for optimal performance.
// however, you can still calculate a struct base pointer given a field pointer:
fn setYBasedOnX(x: *f32, y: f32) void {
const point = @fieldParentPtr(Point, "x", x);
point.y = y;
}
test "field parent pointer" {
var point = Point {
.x = 0.1234,
.y = 0.5678,
};
setYBasedOnX(&point.x, 0.9);
try expect(point.y == 0.9);
}
// You can return a struct from a function. This is how we do generics
// in Zig:
fn LinkedList(comptime T: type) type {
return struct {
pub const Node = struct {
prev: ?*Node,
next: ?*Node,
data: T,
};
first: ?*Node,
last: ?*Node,
len: usize,
};
}
test "linked list" {
// Functions called at compile-time are memoized. This means you can
// do this:
try expect(LinkedList(i32) == LinkedList(i32));
var list = LinkedList(i32) {
.first = null,
.last = null,
.len = 0,
};
try expect(list.len == 0);
// Since types are first class values you can instantiate the type
// by assigning it to a variable:
const ListOfInts = LinkedList(i32);
try expect(ListOfInts == LinkedList(i32));
var node = ListOfInts.Node {
.prev = null,
.next = null,
.data = 1234,
};
var list2 = LinkedList(i32) {
.first = &node,
.last = &node,
.len = 1,
};
try expect(list2.first.?.data == 1234);
} | structs/src/main.zig |
const diff = @import("diff.zig");
const std = @import("std");
const testing = std.testing;
const warn = std.debug.warn;
const TestCase = struct {
a: []const u8,
b: []const u8,
ops: []const diff.Op,
};
test "split lines" {
var a = std.debug.global_allocator;
var src = "A\nB\nC\n";
const lines = try diff.splitLines(a, src);
defer lines.deinit();
const want = [_][]const u8{
"A\n",
"B\n",
"C\n",
};
testing.expectEqual(lines.len, want.len);
for (lines.toSlice()) |v, i| {
testing.expectEqualSlices(u8, v, want[i]);
}
}
const file_a = "a/a.go";
const file_b = "b/b.go";
const unified_prefix = "--- " ++ file_a ++ "\n+++ " ++ file_b ++ "\n";
test "diff" {
var allocator = std.debug.global_allocator;
const cases = [_]TestCase{
TestCase{
.a = "A\nB\nC\n",
.b = "A\nB\nC\n",
.ops = [_]diff.Op{},
},
TestCase{
.a = "A\n",
.b = "B\n",
.ops = [_]diff.Op{
diff.Op{
.kind = .Delete,
.content = null,
.i_1 = 0,
.i_2 = 1,
.j_1 = 0,
},
diff.Op{
.kind = .Insert,
.content = [_][]const u8{"B\n"},
.i_1 = 1,
.i_2 = 1,
.j_1 = 0,
},
},
},
};
for (cases) |ts, i| {
if (i == 0) {
continue;
}
var arena = std.heap.ArenaAllocator.init(allocator);
var a = try diff.splitLines(&arena.allocator, ts.a);
var b = try diff.splitLines(&arena.allocator, ts.b);
var ls = try diff.applyEdits(&arena.allocator, a.toSlice(), ts.ops);
var u = try diff.Unified.init(
&arena.allocator,
file_a,
file_b,
a.toSlice(),
ts.ops,
);
warn("{}\n", u);
arena.deinit();
}
} | src/lsp/diff/diff_test.zig |
const std = @import("std");
usingnamespace @import("common.zig");
usingnamespace @import("string.zig");
const debug = std.debug;
const math = std.math;
const mem = std.mem;
const fmt = std.fmt;
fn valueRef() type {
return value;
}
const value = options([]type{
object,
array,
jstring,
number,
string("true"),
string("false"),
string("null"),
});
const object = options([]type{
sequence([]type{ char('{'), members, char('}') }),
sequence([]type{ char('{'), ws, char('}') }),
});
const members = options([]type{
sequence([]type{ member, char(','), members }),
member,
});
const member = sequence([]type{ ws, string, ws, char(':'), element });
const array = options([]type{
sequence([]type{ char('['), elements, char(']') }),
sequence([]type{ char('['), ws, char(']') }),
});
const elements = options([]type{
sequence([]type{ element, char(','), elements }),
element,
});
const element = sequence([]type{ ws, ref(void, valueRef), ws });
const jstring = sequence([]type{ char('"'), characters, char('"') });
const characters = options([]type{
sequence([]type{ character, characters }),
character,
});
// TODO: Unicode
const character = options([]type{
range(' ', '!'),
range('#', '['),
range(']', '~'),
sequence([]type{ char('\\'), escape }),
});
const escape = options([]type{
char('"'),
char('\\'),
char('/'),
char('b'),
char('n'),
char('r'),
char('t'),
sequence([]type{ char('u'), hex, hex, hex, hex }),
});
const hex = options([]type{
digit,
range('A', 'F'),
range('a', 'f'),
});
const number = sequence([]type{ int, frac, exp });
const int = options([]type{
sequence([]type{ char('-'), onenine, digits }),
sequence([]type{ char('-'), digit }),
sequence([]type{ onenine, digits }),
sequence([]type{digit}),
});
const digits = options([]type{
sequence([]type{ digit, digits }),
digit,
});
const digit = options([]type{
char('0'),
onenine,
});
const onenine = range('1', '9');
const frac = options([]type{
sequence([]type{ char('.'), digits }),
string(""),
});
const exp = options([]type{
sequence([]type{ char('E'), sign, digits }),
sequence([]type{ char('e'), sign, digits }),
string(""),
});
const sign = options([]type{
char('+'),
char('-'),
string(""),
});
fn wsRef() type {
return ws;
}
const ws0x09 = sequence([]type{ char(0x09), ref(u8, wsRef) });
const ws0x0a = sequence([]type{ char(0x0a), ref(u8, wsRef) });
const ws0x0d = sequence([]type{ char(0x0d), ref(u8, wsRef) });
const ws0x20 = sequence([]type{ char(0x20), ref(u8, wsRef) });
const ws = options([]type{
then(ws0x09, void, toVoid(ws0x09.Result)),
then(ws0x0a, void, toVoid(ws0x0a.Result)),
then(ws0x0d, void, toVoid(ws0x0d.Result)),
then(ws0x20, void, toVoid(ws0x20.Result)),
nothing,
});
//test "parser.json" {
// _ = element.parse(Input.init("{}")) orelse unreachable;
//} | src/parser/json.zig |
const mat4x4 = @import("mat4x4.zig");
/// Generic Vector3 Type
pub fn Generic(comptime T: type) type {
switch (T) {
i16, i32, i64, i128, f16, f32, f64, f128 => {
return struct {
const Self = @This();
/// X value
x: T = 0,
/// Y value
y: T = 0,
/// Z value
z: T = 0,
/// Adds two Vector3s and returns the result
pub fn add(self: Self, other: Self) Self {
return .{ .x = self.x + other.x, .y = self.y + other.y, .z = self.z + other.z };
}
/// Add values to the self and returns the result
pub fn addValues(self: Self, x: T, y: T, z: T) Self {
return .{ .x = self.x + x, .y = self.y + y, .z = self.z + z };
}
/// Subtracts two Vector3s and returns the result
pub fn sub(self: Self, other: Self) Self {
return .{ .x = self.x - other.x, .y = self.y - other.y, .z = self.z - other.z };
}
/// Subtract values to the self and returns the result
pub fn subValues(self: Self, x: T, y: T, z: T) Self {
return .{ .x = self.x - x, .y = self.y - y, .z = self.z - z };
}
/// Divides two Vector3s and returns the result
pub fn div(self: Self, other: Self) Self {
return .{ .x = self.x / other.x, .y = self.y / other.y, .z = self.z / other.z };
}
/// Divide values to the self and returns the result
pub fn divValues(self: Self, x: T, y: T, z: T) Self {
return .{ .x = self.x / x, .y = self.y / y, .z = self.z / z };
}
/// Multiplies two Vector3s and returns the result
pub fn mul(self: Self, other: Self) Self {
return .{ .x = self.x * other.x, .y = self.y * other.y, .z = self.z * other.z };
}
/// Multiply values to the self and returns the result
pub fn mulValues(self: Self, x: T, y: T, z: T) Self {
return .{ .x = self.x * x, .y = self.y * y, .z = self.z * z };
}
/// Transforms a Vector3 by a given 4x4 Matrix
pub fn transform(v1: Self, mat: mat4x4.Generic(T)) Self {
const x = v1.x;
const y = v1.y;
const z = v1.z;
return Self{
.x = mat.m0 * x + mat.m4 * y + mat.m8 * z + mat.m12,
.y = mat.m1 * x + mat.m5 * y + mat.m9 * z + mat.m13,
.z = mat.m2 * x + mat.m6 * y + mat.m10 * z + mat.m14,
};
}
};
},
else => @compileError("Vector3 not implemented for " ++ @typeName(T)),
}
} | src/kiragine/kira/math/vec3.zig |
const std = @import("std");
const util = @import("util.zig");
const data = @embedFile("../data/day17.txt");
pub const Rectangle = struct {
top_left: util.Point(i32),
bot_right: util.Point(i32),
};
pub const VelocityTimePair = struct {
velocity: util.Point(i32),
time: i32,
};
// Given the target area, a pair with an x inside the area and the corresponding t value, the function
// will add any applicable y-values for the pair to the pair_list. Returns whether the value immediately
// _overshoots_ the target area.
pub fn addPairsForX(target_area: Rectangle, x_pair: VelocityTimePair, pair_list: *util.List(VelocityTimePair)) !void {
var dy: i32 = -1000;
//util.print("Checking x-pair: {}\n", .{x_pair});
while (true) : (dy += 1) {
const y_val = util.geometricSummation(dy) - util.geometricSummation(x_pair.time - dy - 1);
// We're short of the target at the required t; so the starting y-velocity was too high.
if (y_val > target_area.top_left.y) break;
// Otherwise, if we're in range, count it. In either case, keep processing until we
// overshoot.
if (y_val >= target_area.bot_right.y) {
try pair_list.append(VelocityTimePair{ .velocity = .{ .x = x_pair.velocity.x, .y = dy }, .time = x_pair.time });
}
}
}
pub fn main() !void {
defer {
const leaks = util.gpa_impl.deinit();
std.debug.assert(!leaks);
}
// Parse out target area
var it = util.tokenize(u8, data, "targetarea :,");
// Parse actual data
const x_data = it.next() orelse return error.InvalidInput;
const y_data = it.next() orelse return error.InvalidInput;
// Get integers from the x and y groups
var x_it = util.tokenize(u8, x_data, "x=..");
const x_min = try util.parseInt(i32, x_it.next() orelse return error.InvalidInput, 10);
const x_max = try util.parseInt(i32, x_it.next() orelse return error.InvalidInput, 10);
var y_it = util.tokenize(u8, y_data, "y=..");
const y_max = try util.parseInt(i32, y_it.next() orelse return error.InvalidInput, 10);
const y_min = try util.parseInt(i32, y_it.next() orelse return error.InvalidInput, 10);
// Create rectangle
const target_area = Rectangle{
.top_left = util.Point(i32){ .x = x_min, .y = y_min },
.bot_right = util.Point(i32){ .x = x_max, .y = y_max },
};
// Any x velocity that can possibly land us in the box must be between 0 and x_max; so we can
// check all the values. We'll come up with a list of all t (time-step) values and their x-
// values that can land inside the box.
var x_pairs = util.List(VelocityTimePair).init(util.gpa);
defer x_pairs.deinit();
var dx: i32 = 1;
while (dx <= target_area.bot_right.x) : (dx += 1) {
// If this value can't possibly reach the box, then we can just skip it.
const sum_x = util.geometricSummation(dx);
if (sum_x < target_area.top_left.x) continue;
// For anything that _could_ reach the box at max, try all possible time values until we
// overshoot the max x. We can calculate the x value for a given t in constant time because
// the x value for a t is a geometric sum, which has a closed-form solution.
var t: i32 = 1;
while (t <= dx) : (t += 1) {
const x_at_time = sum_x - util.geometricSummation(dx - t);
if (x_at_time > target_area.bot_right.x) break;
if (x_at_time < target_area.top_left.x) continue;
// We've found some x-velocity that works.
try x_pairs.append(VelocityTimePair{
.velocity = .{ .x = dx, .y = 0 },
.time = t,
});
}
}
// Final pairs
var pairs = util.List(VelocityTimePair).init(util.gpa);
defer pairs.deinit();
// Now, for each x-velocity that _could_ reach the target, attempt to find some y-value
// that will get the probe to the box at that time-value.
for (x_pairs.items) |*pair| {
try addPairsForX(target_area, pair.*, &pairs);
// If the intial x-velocity is equal to the time-step where the x-intersect with the box
// happens, that means that by the time the probe has gotten to the target x-value, it is
// already falling straight down. In this case, _any_ timestep greater than the one we found
// will also satisfy the intersect; up until the point where the y-value is guaranteed to
// overshoot the box (eg. at 2 x area height). So, we'll check increasing t-values until
// that point.
if (pair.velocity.x == pair.time) {
// TODO: Better control of upper bound
var i: usize = 0;
while (i < 2000) : (i += 1) {
pair.time += 1;
try addPairsForX(target_area, pair.*, &pairs);
}
}
}
// Now, find the pair that reaches the maximum y value; which is just the geometric summation
// of the y-velocity (since we know the y-velocity is positive)
var max: i32 = std.math.minInt(i32);
var optimal_velocity: util.Point(i32) = undefined;
for (pairs.items) |pair| {
const highest_y = util.geometricSummation(pair.velocity.y);
if (highest_y > max) {
max = highest_y;
optimal_velocity = pair.velocity;
}
}
// Find unique velocities for part 2
var unique_velocities = util.Map(util.Point(i32), void).init(util.gpa);
defer unique_velocities.deinit();
for (pairs.items) |pair| {
try unique_velocities.put(pair.velocity, {});
}
util.print("Part 1: Optimal trajectory is {}, with a max y-value of {d}\n", .{ optimal_velocity, max });
util.print("Part 2: Number of unique pairs: {d}\n", .{unique_velocities.count()});
} | src/day17.zig |
const std = @import("std");
usingnamespace (@import("../machine.zig"));
usingnamespace (@import("../util.zig"));
const imm = Operand.immediate;
const mem = Operand.memory;
const memRm = Operand.memoryRm;
const reg = Operand.register;
test "cpuid features" {
debugPrint(false);
{
const cpu_features = [_]CpuFeature { ._8086, };
const m16 = Machine.init_with_features(.x86_16, cpu_features[0..]);
const m32 = Machine.init_with_features(.x86_32, cpu_features[0..]);
const m64 = Machine.init_with_features(.x64, cpu_features[0..]);
testOp2(m16, .MOV, reg(.AL), reg(.AL), "88 c0");
testOp2(m16, .MOV, reg(.AX), reg(.AX), "89 c0");
testOp2(m16, .MOV, reg(.EAX), reg(.EAX), AsmError.InvalidOperand);
testOp2(m16, .MOV, reg(.RAX), reg(.RAX), AsmError.InvalidOperand);
testOp2(m32, .MOV, reg(.AL), reg(.AL), "88 c0");
testOp2(m32, .MOV, reg(.AX), reg(.AX), "66 89 c0");
testOp2(m32, .MOV, reg(.EAX), reg(.EAX), AsmError.InvalidOperand);
testOp2(m32, .MOV, reg(.RAX), reg(.RAX), AsmError.InvalidOperand);
testOp2(m64, .MOV, reg(.AL), reg(.AL), "88 c0");
testOp2(m64, .MOV, reg(.AX), reg(.AX), "66 89 c0");
testOp2(m64, .MOV, reg(.EAX), reg(.EAX), AsmError.InvalidOperand);
testOp2(m64, .MOV, reg(.RAX), reg(.RAX), AsmError.InvalidOperand);
testOp2(m64, .FCMOVB, reg(.ST0), reg(.ST7), AsmError.InvalidOperand);
testOp0(m64, .EMMS, AsmError.InvalidOperand);
testOp0(m64, .VZEROALL, AsmError.InvalidOperand);
testOp0(m64, .SFENCE, AsmError.InvalidOperand);
}
{
const cpu_features = [_]CpuFeature { ._8086, ._386, .x86_64, .CMOV, .FPU };
const m16 = Machine.init_with_features(.x86_16, cpu_features[0..]);
const m32 = Machine.init_with_features(.x86_32, cpu_features[0..]);
const m64 = Machine.init_with_features(.x64, cpu_features[0..]);
testOp2(m64, .MOV, reg(.AL), reg(.AL), "88 c0");
testOp2(m64, .MOV, reg(.AX), reg(.AX), "66 89 c0");
testOp2(m64, .MOV, reg(.EAX), reg(.EAX), "89 c0");
testOp2(m64, .MOV, reg(.RAX), reg(.RAX), "48 89 c0");
testOp2(m64, .MOV, reg(.RAX), reg(.RAX), "48 89 c0");
testOp2(m64, .FCMOVB, reg(.ST0), reg(.ST7), "da c7");
testOp0(m64, .EMMS, AsmError.InvalidOperand);
testOp0(m64, .VZEROALL, AsmError.InvalidOperand);
testOp0(m64, .SFENCE, AsmError.InvalidOperand);
}
{
const cpu_features = [_]CpuFeature { .Intel, ._8086, .SYSCALL, .LAHF_SAHF };
const m32 = Machine.init_with_features(.x86_32, cpu_features[0..]);
const m64 = Machine.init_with_features(.x64, cpu_features[0..]);
testOp0(m32, .SYSCALL, AsmError.InvalidOperand);
testOp0(m32, .SYSCALL, AsmError.InvalidOperand);
testOp0(m32, .SYSRET, AsmError.InvalidOperand);
testOp0(m32, .SYSRET, AsmError.InvalidOperand);
testOp0(m64, .SYSCALL, "0F 05");
testOp0(m64, .SYSCALL, "0F 05");
testOp0(m64, .SYSRET, "0F 07");
testOp0(m64, .SYSRET, "0F 07");
testOp2(m32, .FCMOVB, reg(.ST0), reg(.ST7), AsmError.InvalidOperand);
testOp2(m64, .FCMOVB, reg(.ST0), reg(.ST7), AsmError.InvalidOperand);
testOp0(m32, .LAHF, "9F");
testOp0(m32, .SAHF, "9E");
testOp0(m64, .LAHF, "9F");
testOp0(m64, .SAHF, "9E");
}
{
const cpu_features = [_]CpuFeature { .Amd, ._8086, .SYSCALL };
const m32 = Machine.init_with_features(.x86_32, cpu_features[0..]);
const m64 = Machine.init_with_features(.x64, cpu_features[0..]);
testOp0(m32, .SYSCALL, "0F 05");
testOp0(m32, .SYSCALL, "0F 05");
testOp0(m32, .SYSRET, "0F 07");
testOp0(m32, .SYSRET, "0F 07");
testOp0(m64, .SYSCALL, "0F 05");
testOp0(m64, .SYSCALL, "0F 05");
testOp0(m64, .SYSRET, "0F 07");
testOp0(m64, .SYSRET, "0F 07");
testOp2(m32, .FCMOVB, reg(.ST0), reg(.ST7), AsmError.InvalidOperand);
testOp2(m64, .FCMOVB, reg(.ST0), reg(.ST7), AsmError.InvalidOperand);
testOp0(m32, .LAHF, "9F");
testOp0(m32, .SAHF, "9E");
testOp0(m64, .LAHF, AsmError.InvalidOperand);
testOp0(m64, .SAHF, AsmError.InvalidOperand);
}
} | src/x86/tests/cpuid.zig |
const std = @import("std");
const testing = std.testing;
/// Read a single unsigned LEB128 value from the given reader as type T,
/// or error.Overflow if the value cannot fit.
pub fn readULEB128(comptime T: type, reader: anytype) !T {
const U = if (@typeInfo(T).Int.bits < 8) u8 else T;
const ShiftT = std.math.Log2Int(U);
const max_group = (@typeInfo(U).Int.bits + 6) / 7;
var value = @as(U, 0);
var group = @as(ShiftT, 0);
while (group < max_group) : (group += 1) {
const byte = try reader.readByte();
var temp = @as(U, byte & 0x7f);
if (@shlWithOverflow(U, temp, group * 7, &temp)) return error.Overflow;
value |= temp;
if (byte & 0x80 == 0) break;
} else {
return error.Overflow;
}
// only applies in the case that we extended to u8
if (U != T) {
if (value > std.math.maxInt(T)) return error.Overflow;
}
return @truncate(T, value);
}
/// Write a single unsigned integer as unsigned LEB128 to the given writer.
pub fn writeULEB128(writer: anytype, uint_value: anytype) !void {
const T = @TypeOf(uint_value);
const U = if (@typeInfo(T).Int.bits < 8) u8 else T;
var value = @intCast(U, uint_value);
while (true) {
const byte = @truncate(u8, value & 0x7f);
value >>= 7;
if (value == 0) {
try writer.writeByte(byte);
break;
} else {
try writer.writeByte(byte | 0x80);
}
}
}
/// Read a single signed LEB128 value from the given reader as type T,
/// or error.Overflow if the value cannot fit.
pub fn readILEB128(comptime T: type, reader: anytype) !T {
const S = if (@typeInfo(T).Int.bits < 8) i8 else T;
const U = std.meta.Int(.unsigned, @typeInfo(S).Int.bits);
const ShiftU = std.math.Log2Int(U);
const max_group = (@typeInfo(U).Int.bits + 6) / 7;
var value = @as(U, 0);
var group = @as(ShiftU, 0);
while (group < max_group) : (group += 1) {
const byte = try reader.readByte();
var temp = @as(U, byte & 0x7f);
const shift = group * 7;
if (@shlWithOverflow(U, temp, shift, &temp)) {
// Overflow is ok so long as the sign bit is set and this is the last byte
if (byte & 0x80 != 0) return error.Overflow;
if (@bitCast(S, temp) >= 0) return error.Overflow;
// and all the overflowed bits are 1
const remaining_shift = @intCast(u3, @typeInfo(U).Int.bits - @as(u16, shift));
const remaining_bits = @bitCast(i8, byte | 0x80) >> remaining_shift;
if (remaining_bits != -1) return error.Overflow;
}
value |= temp;
if (byte & 0x80 == 0) {
const needs_sign_ext = group + 1 < max_group;
if (byte & 0x40 != 0 and needs_sign_ext) {
const ones = @as(S, -1);
value |= @bitCast(U, ones) << (shift + 7);
}
break;
}
} else {
return error.Overflow;
}
const result = @bitCast(S, value);
// Only applies if we extended to i8
if (S != T) {
if (result > std.math.maxInt(T) or result < std.math.minInt(T)) return error.Overflow;
}
return @truncate(T, result);
}
/// Write a single signed integer as signed LEB128 to the given writer.
pub fn writeILEB128(writer: anytype, int_value: anytype) !void {
const T = @TypeOf(int_value);
const S = if (@typeInfo(T).Int.bits < 8) i8 else T;
const U = std.meta.Int(.unsigned, @typeInfo(S).Int.bits);
var value = @intCast(S, int_value);
while (true) {
const uvalue = @bitCast(U, value);
const byte = @truncate(u8, uvalue);
value >>= 6;
if (value == -1 or value == 0) {
try writer.writeByte(byte & 0x7F);
break;
} else {
value >>= 1;
try writer.writeByte(byte | 0x80);
}
}
}
/// This is an "advanced" function. It allows one to use a fixed amount of memory to store a
/// ULEB128. This defeats the entire purpose of using this data encoding; it will no longer use
/// fewer bytes to store smaller numbers. The advantage of using a fixed width is that it makes
/// fields have a predictable size and so depending on the use case this tradeoff can be worthwhile.
/// An example use case of this is in emitting DWARF info where one wants to make a ULEB128 field
/// "relocatable", meaning that it becomes possible to later go back and patch the number to be a
/// different value without shifting all the following code.
pub fn writeUnsignedFixed(comptime l: usize, ptr: *[l]u8, int: std.meta.Int(.unsigned, l * 7)) void {
const T = @TypeOf(int);
const U = if (@typeInfo(T).Int.bits < 8) u8 else T;
var value = @intCast(U, int);
comptime var i = 0;
inline while (i < (l - 1)) : (i += 1) {
const byte = @truncate(u8, value) | 0b1000_0000;
value >>= 7;
ptr[i] = byte;
}
ptr[i] = @truncate(u8, value);
}
test "writeUnsignedFixed" {
{
var buf: [4]u8 = undefined;
writeUnsignedFixed(4, &buf, 0);
testing.expect((try test_read_uleb128(u64, &buf)) == 0);
}
{
var buf: [4]u8 = undefined;
writeUnsignedFixed(4, &buf, 1);
testing.expect((try test_read_uleb128(u64, &buf)) == 1);
}
{
var buf: [4]u8 = undefined;
writeUnsignedFixed(4, &buf, 1000);
testing.expect((try test_read_uleb128(u64, &buf)) == 1000);
}
{
var buf: [4]u8 = undefined;
writeUnsignedFixed(4, &buf, 10000000);
testing.expect((try test_read_uleb128(u64, &buf)) == 10000000);
}
}
// tests
fn test_read_stream_ileb128(comptime T: type, encoded: []const u8) !T {
var reader = std.io.fixedBufferStream(encoded);
return try readILEB128(T, reader.reader());
}
fn test_read_stream_uleb128(comptime T: type, encoded: []const u8) !T {
var reader = std.io.fixedBufferStream(encoded);
return try readULEB128(T, reader.reader());
}
fn test_read_ileb128(comptime T: type, encoded: []const u8) !T {
var reader = std.io.fixedBufferStream(encoded);
const v1 = try readILEB128(T, reader.reader());
return v1;
}
fn test_read_uleb128(comptime T: type, encoded: []const u8) !T {
var reader = std.io.fixedBufferStream(encoded);
const v1 = try readULEB128(T, reader.reader());
return v1;
}
fn test_read_ileb128_seq(comptime T: type, comptime N: usize, encoded: []const u8) !void {
var reader = std.io.fixedBufferStream(encoded);
var i: usize = 0;
while (i < N) : (i += 1) {
const v1 = try readILEB128(T, reader.reader());
}
}
fn test_read_uleb128_seq(comptime T: type, comptime N: usize, encoded: []const u8) !void {
var reader = std.io.fixedBufferStream(encoded);
var i: usize = 0;
while (i < N) : (i += 1) {
const v1 = try readULEB128(T, reader.reader());
}
}
test "deserialize signed LEB128" {
// Truncated
testing.expectError(error.EndOfStream, test_read_stream_ileb128(i64, "\x80"));
// Overflow
testing.expectError(error.Overflow, test_read_ileb128(i8, "\x80\x80\x40"));
testing.expectError(error.Overflow, test_read_ileb128(i16, "\x80\x80\x80\x40"));
testing.expectError(error.Overflow, test_read_ileb128(i32, "\x80\x80\x80\x80\x40"));
testing.expectError(error.Overflow, test_read_ileb128(i64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x40"));
testing.expectError(error.Overflow, test_read_ileb128(i8, "\xff\x7e"));
// Decode SLEB128
testing.expect((try test_read_ileb128(i64, "\x00")) == 0);
testing.expect((try test_read_ileb128(i64, "\x01")) == 1);
testing.expect((try test_read_ileb128(i64, "\x3f")) == 63);
testing.expect((try test_read_ileb128(i64, "\x40")) == -64);
testing.expect((try test_read_ileb128(i64, "\x41")) == -63);
testing.expect((try test_read_ileb128(i64, "\x7f")) == -1);
testing.expect((try test_read_ileb128(i64, "\x80\x01")) == 128);
testing.expect((try test_read_ileb128(i64, "\x81\x01")) == 129);
testing.expect((try test_read_ileb128(i64, "\xff\x7e")) == -129);
testing.expect((try test_read_ileb128(i64, "\x80\x7f")) == -128);
testing.expect((try test_read_ileb128(i64, "\x81\x7f")) == -127);
testing.expect((try test_read_ileb128(i64, "\xc0\x00")) == 64);
testing.expect((try test_read_ileb128(i64, "\xc7\x9f\x7f")) == -12345);
testing.expect((try test_read_ileb128(i8, "\xff\x7f")) == -1);
testing.expect((try test_read_ileb128(i16, "\xff\xff\x7f")) == -1);
testing.expect((try test_read_ileb128(i32, "\xff\xff\xff\xff\x7f")) == -1);
testing.expect((try test_read_ileb128(i32, "\x80\x80\x80\x80\x08")) == -0x80000000);
testing.expect((try test_read_ileb128(i64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x01")) == @bitCast(i64, @intCast(u64, 0x8000000000000000)));
testing.expect((try test_read_ileb128(i64, "\x80\x80\x80\x80\x80\x80\x80\x80\x40")) == -0x4000000000000000);
testing.expect((try test_read_ileb128(i64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x7f")) == -0x8000000000000000);
// Decode unnormalized SLEB128 with extra padding bytes.
testing.expect((try test_read_ileb128(i64, "\x80\x00")) == 0);
testing.expect((try test_read_ileb128(i64, "\x80\x80\x00")) == 0);
testing.expect((try test_read_ileb128(i64, "\xff\x00")) == 0x7f);
testing.expect((try test_read_ileb128(i64, "\xff\x80\x00")) == 0x7f);
testing.expect((try test_read_ileb128(i64, "\x80\x81\x00")) == 0x80);
testing.expect((try test_read_ileb128(i64, "\x80\x81\x80\x00")) == 0x80);
// Decode sequence of SLEB128 values
try test_read_ileb128_seq(i64, 4, "\x81\x01\x3f\x80\x7f\x80\x80\x80\x00");
}
test "deserialize unsigned LEB128" {
// Truncated
testing.expectError(error.EndOfStream, test_read_stream_uleb128(u64, "\x80"));
// Overflow
testing.expectError(error.Overflow, test_read_uleb128(u8, "\x80\x02"));
testing.expectError(error.Overflow, test_read_uleb128(u8, "\x80\x80\x40"));
testing.expectError(error.Overflow, test_read_uleb128(u16, "\x80\x80\x84"));
testing.expectError(error.Overflow, test_read_uleb128(u16, "\x80\x80\x80\x40"));
testing.expectError(error.Overflow, test_read_uleb128(u32, "\x80\x80\x80\x80\x90"));
testing.expectError(error.Overflow, test_read_uleb128(u32, "\x80\x80\x80\x80\x40"));
testing.expectError(error.Overflow, test_read_uleb128(u64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x40"));
// Decode ULEB128
testing.expect((try test_read_uleb128(u64, "\x00")) == 0);
testing.expect((try test_read_uleb128(u64, "\x01")) == 1);
testing.expect((try test_read_uleb128(u64, "\x3f")) == 63);
testing.expect((try test_read_uleb128(u64, "\x40")) == 64);
testing.expect((try test_read_uleb128(u64, "\x7f")) == 0x7f);
testing.expect((try test_read_uleb128(u64, "\x80\x01")) == 0x80);
testing.expect((try test_read_uleb128(u64, "\x81\x01")) == 0x81);
testing.expect((try test_read_uleb128(u64, "\x90\x01")) == 0x90);
testing.expect((try test_read_uleb128(u64, "\xff\x01")) == 0xff);
testing.expect((try test_read_uleb128(u64, "\x80\x02")) == 0x100);
testing.expect((try test_read_uleb128(u64, "\x81\x02")) == 0x101);
testing.expect((try test_read_uleb128(u64, "\x80\xc1\x80\x80\x10")) == 4294975616);
testing.expect((try test_read_uleb128(u64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x01")) == 0x8000000000000000);
// Decode ULEB128 with extra padding bytes
testing.expect((try test_read_uleb128(u64, "\x80\x00")) == 0);
testing.expect((try test_read_uleb128(u64, "\x80\x80\x00")) == 0);
testing.expect((try test_read_uleb128(u64, "\xff\x00")) == 0x7f);
testing.expect((try test_read_uleb128(u64, "\xff\x80\x00")) == 0x7f);
testing.expect((try test_read_uleb128(u64, "\x80\x81\x00")) == 0x80);
testing.expect((try test_read_uleb128(u64, "\x80\x81\x80\x00")) == 0x80);
// Decode sequence of ULEB128 values
try test_read_uleb128_seq(u64, 4, "\x81\x01\x3f\x80\x7f\x80\x80\x80\x00");
}
fn test_write_leb128(value: anytype) !void {
const T = @TypeOf(value);
const signedness = @typeInfo(T).Int.signedness;
const t_signed = signedness == .signed;
const writeStream = if (t_signed) writeILEB128 else writeULEB128;
const readStream = if (t_signed) readILEB128 else readULEB128;
// decode to a larger bit size too, to ensure sign extension
// is working as expected
const larger_type_bits = ((@typeInfo(T).Int.bits + 8) / 8) * 8;
const B = std.meta.Int(signedness, larger_type_bits);
const bytes_needed = bn: {
const S = std.meta.Int(signedness, @sizeOf(T) * 8);
if (@typeInfo(T).Int.bits <= 7) break :bn @as(u16, 1);
const unused_bits = if (value < 0) @clz(T, ~value) else @clz(T, value);
const used_bits: u16 = (@typeInfo(T).Int.bits - unused_bits) + @boolToInt(t_signed);
if (used_bits <= 7) break :bn @as(u16, 1);
break :bn ((used_bits + 6) / 7);
};
const max_groups = if (@typeInfo(T).Int.bits == 0) 1 else (@typeInfo(T).Int.bits + 6) / 7;
var buf: [max_groups]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buf);
// stream write
try writeStream(fbs.writer(), value);
const w1_pos = fbs.pos;
testing.expect(w1_pos == bytes_needed);
// stream read
fbs.pos = 0;
const sr = try readStream(T, fbs.reader());
testing.expect(fbs.pos == w1_pos);
testing.expect(sr == value);
// bigger type stream read
fbs.pos = 0;
const bsr = try readStream(B, fbs.reader());
testing.expect(fbs.pos == w1_pos);
testing.expect(bsr == value);
}
test "serialize unsigned LEB128" {
const max_bits = 18;
comptime var t = 0;
inline while (t <= max_bits) : (t += 1) {
const T = std.meta.Int(.unsigned, t);
const min = std.math.minInt(T);
const max = std.math.maxInt(T);
var i = @as(std.meta.Int(.unsigned, @typeInfo(T).Int.bits + 1), min);
while (i <= max) : (i += 1) try test_write_leb128(@intCast(T, i));
}
}
test "serialize signed LEB128" {
// explicitly test i0 because starting `t` at 0
// will break the while loop
try test_write_leb128(@as(i0, 0));
const max_bits = 18;
comptime var t = 1;
inline while (t <= max_bits) : (t += 1) {
const T = std.meta.Int(.signed, t);
const min = std.math.minInt(T);
const max = std.math.maxInt(T);
var i = @as(std.meta.Int(.signed, @typeInfo(T).Int.bits + 1), min);
while (i <= max) : (i += 1) try test_write_leb128(@intCast(T, i));
}
} | lib/std/leb128.zig |
const MachO = @This();
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const fmt = std.fmt;
const fs = std.fs;
const log = std.log.scoped(.link);
const macho = std.macho;
const codegen = @import("../codegen.zig");
const aarch64 = @import("../codegen/aarch64.zig");
const math = std.math;
const mem = std.mem;
const trace = @import("../tracy.zig").trace;
const build_options = @import("build_options");
const Module = @import("../Module.zig");
const Compilation = @import("../Compilation.zig");
const link = @import("../link.zig");
const File = link.File;
const Cache = @import("../Cache.zig");
const target_util = @import("../target.zig");
const DebugSymbols = @import("MachO/DebugSymbols.zig");
const Trie = @import("MachO/Trie.zig");
const CodeSignature = @import("MachO/CodeSignature.zig");
usingnamespace @import("MachO/commands.zig");
usingnamespace @import("MachO/imports.zig");
pub const base_tag: File.Tag = File.Tag.macho;
base: File,
/// Debug symbols bundle (or dSym).
d_sym: ?DebugSymbols = null,
/// Page size is dependent on the target cpu architecture.
/// For x86_64 that's 4KB, whereas for aarch64, that's 16KB.
page_size: u16,
/// Mach-O header
header: ?macho.mach_header_64 = null,
/// We commit 0x1000 = 4096 bytes of space to the header and
/// the table of load commands. This should be plenty for any
/// potential future extensions.
header_pad: u16 = 0x1000,
/// Table of all load commands
load_commands: std.ArrayListUnmanaged(LoadCommand) = .{},
/// __PAGEZERO segment
pagezero_segment_cmd_index: ?u16 = null,
/// __TEXT segment
text_segment_cmd_index: ?u16 = null,
/// __DATA_CONST segment
data_const_segment_cmd_index: ?u16 = null,
/// __DATA segment
data_segment_cmd_index: ?u16 = null,
/// __LINKEDIT segment
linkedit_segment_cmd_index: ?u16 = null,
/// Dyld info
dyld_info_cmd_index: ?u16 = null,
/// Symbol table
symtab_cmd_index: ?u16 = null,
/// Dynamic symbol table
dysymtab_cmd_index: ?u16 = null,
/// Path to dyld linker
dylinker_cmd_index: ?u16 = null,
/// Path to libSystem
libsystem_cmd_index: ?u16 = null,
/// Data-in-code section of __LINKEDIT segment
data_in_code_cmd_index: ?u16 = null,
/// Address to entry point function
function_starts_cmd_index: ?u16 = null,
/// Main/entry point
/// Specifies offset wrt __TEXT segment start address to the main entry point
/// of the binary.
main_cmd_index: ?u16 = null,
/// Minimum OS version
version_min_cmd_index: ?u16 = null,
/// Source version
source_version_cmd_index: ?u16 = null,
/// UUID load command
uuid_cmd_index: ?u16 = null,
/// Code signature
code_signature_cmd_index: ?u16 = null,
/// Index into __TEXT,__text section.
text_section_index: ?u16 = null,
/// Index into __TEXT,__ziggot section.
got_section_index: ?u16 = null,
/// Index into __TEXT,__stubs section.
stubs_section_index: ?u16 = null,
/// Index into __TEXT,__stub_helper section.
stub_helper_section_index: ?u16 = null,
/// Index into __DATA_CONST,__got section.
data_got_section_index: ?u16 = null,
/// Index into __DATA,__la_symbol_ptr section.
la_symbol_ptr_section_index: ?u16 = null,
/// Index into __DATA,__data section.
data_section_index: ?u16 = null,
/// The absolute address of the entry point.
entry_addr: ?u64 = null,
/// Table of all local symbols
/// Internally references string table for names (which are optional).
local_symbols: std.ArrayListUnmanaged(macho.nlist_64) = .{},
/// Table of all global symbols
global_symbols: std.ArrayListUnmanaged(macho.nlist_64) = .{},
/// Table of all extern nonlazy symbols, indexed by name.
extern_nonlazy_symbols: std.StringArrayHashMapUnmanaged(ExternSymbol) = .{},
/// Table of all extern lazy symbols, indexed by name.
extern_lazy_symbols: std.StringArrayHashMapUnmanaged(ExternSymbol) = .{},
local_symbol_free_list: std.ArrayListUnmanaged(u32) = .{},
global_symbol_free_list: std.ArrayListUnmanaged(u32) = .{},
offset_table_free_list: std.ArrayListUnmanaged(u32) = .{},
stub_helper_stubs_start_off: ?u64 = null,
/// Table of symbol names aka the string table.
string_table: std.ArrayListUnmanaged(u8) = .{},
string_table_directory: std.StringHashMapUnmanaged(u32) = .{},
/// Table of trampolines to the actual symbols in __text section.
offset_table: std.ArrayListUnmanaged(u64) = .{},
error_flags: File.ErrorFlags = File.ErrorFlags{},
offset_table_count_dirty: bool = false,
header_dirty: bool = false,
load_commands_dirty: bool = false,
rebase_info_dirty: bool = false,
binding_info_dirty: bool = false,
lazy_binding_info_dirty: bool = false,
export_info_dirty: bool = false,
string_table_dirty: bool = false,
string_table_needs_relocation: bool = false,
/// A list of text blocks that have surplus capacity. This list can have false
/// positives, as functions grow and shrink over time, only sometimes being added
/// or removed from the freelist.
///
/// A text block has surplus capacity when its overcapacity value is greater than
/// padToIdeal(minimum_text_block_size). That is, when it has so
/// much extra capacity, that we could fit a small new symbol in it, itself with
/// ideal_capacity or more.
///
/// Ideal capacity is defined by size + (size / ideal_factor).
///
/// Overcapacity is measured by actual_capacity - ideal_capacity. Note that
/// overcapacity can be negative. A simple way to have negative overcapacity is to
/// allocate a fresh text block, which will have ideal capacity, and then grow it
/// by 1 byte. It will then have -1 overcapacity.
text_block_free_list: std.ArrayListUnmanaged(*TextBlock) = .{},
/// Pointer to the last allocated text block
last_text_block: ?*TextBlock = null,
/// A list of all PIE fixups required for this run of the linker.
/// Warning, this is currently NOT thread-safe. See the TODO below.
/// TODO Move this list inside `updateDecl` where it should be allocated
/// prior to calling `generateSymbol`, and then immediately deallocated
/// rather than sitting in the global scope.
pie_fixups: std.ArrayListUnmanaged(PieFixup) = .{},
/// A list of all stub (extern decls) fixups required for this run of the linker.
/// Warning, this is currently NOT thread-safe. See the TODO below.
/// TODO Move this list inside `updateDecl` where it should be allocated
/// prior to calling `generateSymbol`, and then immediately deallocated
/// rather than sitting in the global scope.
stub_fixups: std.ArrayListUnmanaged(StubFixup) = .{},
pub const PieFixup = struct {
/// Target address we wanted to address in absolute terms.
address: u64,
/// Where in the byte stream we should perform the fixup.
start: usize,
/// The length of the byte stream. For x86_64, this will be
/// variable. For aarch64, it will be fixed at 4 bytes.
len: usize,
};
pub const StubFixup = struct {
/// Id of extern (lazy) symbol.
symbol: u32,
/// Signals whether the symbol has already been declared before. If so,
/// then there is no need to rewrite the stub entry and related.
already_defined: bool,
/// Where in the byte stream we should perform the fixup.
start: usize,
/// The length of the byte stream. For x86_64, this will be
/// variable. For aarch64, it will be fixed at 4 bytes.
len: usize,
};
/// When allocating, the ideal_capacity is calculated by
/// actual_capacity + (actual_capacity / ideal_factor)
const ideal_factor = 2;
/// Default path to dyld
/// TODO instead of hardcoding it, we should probably look through some env vars and search paths
/// instead but this will do for now.
const DEFAULT_DYLD_PATH: [*:0]const u8 = "/usr/lib/dyld";
/// Default lib search path
/// TODO instead of hardcoding it, we should probably look through some env vars and search paths
/// instead but this will do for now.
const DEFAULT_LIB_SEARCH_PATH: []const u8 = "/usr/lib";
const LIB_SYSTEM_NAME: [*:0]const u8 = "System";
/// TODO we should search for libSystem and fail if it doesn't exist, instead of hardcoding it
const LIB_SYSTEM_PATH: [*:0]const u8 = DEFAULT_LIB_SEARCH_PATH ++ "/libSystem.B.dylib";
/// In order for a slice of bytes to be considered eligible to keep metadata pointing at
/// it as a possible place to put new symbols, it must have enough room for this many bytes
/// (plus extra for reserved capacity).
const minimum_text_block_size = 64;
const min_text_capacity = padToIdeal(minimum_text_block_size);
pub const TextBlock = struct {
/// Each decl always gets a local symbol with the fully qualified name.
/// The vaddr and size are found here directly.
/// The file offset is found by computing the vaddr offset from the section vaddr
/// the symbol references, and adding that to the file offset of the section.
/// If this field is 0, it means the codegen size = 0 and there is no symbol or
/// offset table entry.
local_sym_index: u32,
/// Index into offset table
/// This field is undefined for symbols with size = 0.
offset_table_index: u32,
/// Size of this text block
/// Unlike in Elf, we need to store the size of this symbol as part of
/// the TextBlock since macho.nlist_64 lacks this information.
size: u64,
/// Points to the previous and next neighbours
prev: ?*TextBlock,
next: ?*TextBlock,
/// Previous/next linked list pointers.
/// This is the linked list node for this Decl's corresponding .debug_info tag.
dbg_info_prev: ?*TextBlock,
dbg_info_next: ?*TextBlock,
/// Offset into .debug_info pointing to the tag for this Decl.
dbg_info_off: u32,
/// Size of the .debug_info tag for this Decl, not including padding.
dbg_info_len: u32,
pub const empty = TextBlock{
.local_sym_index = 0,
.offset_table_index = undefined,
.size = 0,
.prev = null,
.next = null,
.dbg_info_prev = null,
.dbg_info_next = null,
.dbg_info_off = undefined,
.dbg_info_len = undefined,
};
/// Returns how much room there is to grow in virtual address space.
/// File offset relocation happens transparently, so it is not included in
/// this calculation.
fn capacity(self: TextBlock, macho_file: MachO) u64 {
const self_sym = macho_file.local_symbols.items[self.local_sym_index];
if (self.next) |next| {
const next_sym = macho_file.local_symbols.items[next.local_sym_index];
return next_sym.n_value - self_sym.n_value;
} else {
// We are the last block.
// The capacity is limited only by virtual address space.
return std.math.maxInt(u64) - self_sym.n_value;
}
}
fn freeListEligible(self: TextBlock, macho_file: MachO) bool {
// No need to keep a free list node for the last block.
const next = self.next orelse return false;
const self_sym = macho_file.local_symbols.items[self.local_sym_index];
const next_sym = macho_file.local_symbols.items[next.local_sym_index];
const cap = next_sym.n_value - self_sym.n_value;
const ideal_cap = padToIdeal(self.size);
if (cap <= ideal_cap) return false;
const surplus = cap - ideal_cap;
return surplus >= min_text_capacity;
}
};
pub const Export = struct {
sym_index: ?u32 = null,
};
pub const SrcFn = struct {
/// Offset from the beginning of the Debug Line Program header that contains this function.
off: u32,
/// Size of the line number program component belonging to this function, not
/// including padding.
len: u32,
/// Points to the previous and next neighbors, based on the offset from .debug_line.
/// This can be used to find, for example, the capacity of this `SrcFn`.
prev: ?*SrcFn,
next: ?*SrcFn,
pub const empty: SrcFn = .{
.off = 0,
.len = 0,
.prev = null,
.next = null,
};
};
pub fn openPath(allocator: *Allocator, sub_path: []const u8, options: link.Options) !*MachO {
assert(options.object_format == .macho);
if (options.use_llvm) return error.LLVM_BackendIsTODO_ForMachO; // TODO
if (options.use_lld) return error.LLD_LinkingIsTODO_ForMachO; // TODO
const file = try options.emit.?.directory.handle.createFile(sub_path, .{
.truncate = false,
.read = true,
.mode = link.determineMode(options),
});
errdefer file.close();
const self = try createEmpty(allocator, options);
errdefer {
self.base.file = null;
self.base.destroy();
}
self.base.file = file;
// Create dSYM bundle.
const d_sym_path = try fmt.allocPrint(allocator, "{s}.dSYM/Contents/Resources/DWARF/", .{sub_path});
defer allocator.free(d_sym_path);
var d_sym_bundle = try options.emit.?.directory.handle.makeOpenPath(d_sym_path, .{});
defer d_sym_bundle.close();
const d_sym_file = try d_sym_bundle.createFile(sub_path, .{
.truncate = false,
.read = true,
});
self.d_sym = .{
.base = self,
.file = d_sym_file,
};
// Index 0 is always a null symbol.
try self.local_symbols.append(allocator, .{
.n_strx = 0,
.n_type = 0,
.n_sect = 0,
.n_desc = 0,
.n_value = 0,
});
switch (options.output_mode) {
.Exe => {},
.Obj => {},
.Lib => return error.TODOImplementWritingLibFiles,
}
try self.populateMissingMetadata();
try self.writeLocalSymbol(0);
if (self.d_sym) |*ds| {
try ds.populateMissingMetadata(allocator);
try ds.writeLocalSymbol(0);
}
return self;
}
pub fn createEmpty(gpa: *Allocator, options: link.Options) !*MachO {
const self = try gpa.create(MachO);
self.* = .{
.base = .{
.tag = .macho,
.options = options,
.allocator = gpa,
.file = null,
},
.page_size = if (options.target.cpu.arch == .aarch64) 0x4000 else 0x1000,
};
return self;
}
pub fn flush(self: *MachO, comp: *Compilation) !void {
if (build_options.have_llvm and self.base.options.use_lld) {
return self.linkWithLLD(comp);
} else {
switch (self.base.options.effectiveOutputMode()) {
.Exe, .Obj => {},
.Lib => return error.TODOImplementWritingLibFiles,
}
return self.flushModule(comp);
}
}
pub fn flushModule(self: *MachO, comp: *Compilation) !void {
const tracy = trace(@src());
defer tracy.end();
const output_mode = self.base.options.output_mode;
const target = self.base.options.target;
switch (output_mode) {
.Exe => {
if (self.entry_addr) |addr| {
// Update LC_MAIN with entry offset.
const text_segment = self.load_commands.items[self.text_segment_cmd_index.?].Segment;
const main_cmd = &self.load_commands.items[self.main_cmd_index.?].Main;
main_cmd.entryoff = addr - text_segment.inner.vmaddr;
self.load_commands_dirty = true;
}
try self.writeRebaseInfoTable();
try self.writeBindingInfoTable();
try self.writeLazyBindingInfoTable();
try self.writeExportTrie();
try self.writeAllGlobalAndUndefSymbols();
try self.writeIndirectSymbolTable();
try self.writeStringTable();
try self.updateLinkeditSegmentSizes();
if (self.d_sym) |*ds| {
// Flush debug symbols bundle.
try ds.flushModule(self.base.allocator, self.base.options);
}
if (target.cpu.arch == .aarch64) {
// Preallocate space for the code signature.
// We need to do this at this stage so that we have the load commands with proper values
// written out to the file.
// The most important here is to have the correct vm and filesize of the __LINKEDIT segment
// where the code signature goes into.
try self.writeCodeSignaturePadding();
}
},
.Obj => {},
.Lib => return error.TODOImplementWritingLibFiles,
}
try self.writeLoadCommands();
try self.writeHeader();
if (self.entry_addr == null and self.base.options.output_mode == .Exe) {
log.debug("flushing. no_entry_point_found = true", .{});
self.error_flags.no_entry_point_found = true;
} else {
log.debug("flushing. no_entry_point_found = false", .{});
self.error_flags.no_entry_point_found = false;
}
assert(!self.offset_table_count_dirty);
assert(!self.header_dirty);
assert(!self.load_commands_dirty);
assert(!self.rebase_info_dirty);
assert(!self.binding_info_dirty);
assert(!self.lazy_binding_info_dirty);
assert(!self.export_info_dirty);
assert(!self.string_table_dirty);
assert(!self.string_table_needs_relocation);
if (target.cpu.arch == .aarch64) {
switch (output_mode) {
.Exe, .Lib => try self.writeCodeSignature(), // code signing always comes last
else => {},
}
}
}
fn linkWithLLD(self: *MachO, comp: *Compilation) !void {
const tracy = trace(@src());
defer tracy.end();
var arena_allocator = std.heap.ArenaAllocator.init(self.base.allocator);
defer arena_allocator.deinit();
const arena = &arena_allocator.allocator;
const directory = self.base.options.emit.?.directory; // Just an alias to make it shorter to type.
// If there is no Zig code to compile, then we should skip flushing the output file because it
// will not be part of the linker line anyway.
const module_obj_path: ?[]const u8 = if (self.base.options.module) |module| blk: {
const use_stage1 = build_options.is_stage1 and self.base.options.use_llvm;
if (use_stage1) {
const obj_basename = try std.zig.binNameAlloc(arena, .{
.root_name = self.base.options.root_name,
.target = self.base.options.target,
.output_mode = .Obj,
});
const o_directory = self.base.options.module.?.zig_cache_artifact_directory;
const full_obj_path = try o_directory.join(arena, &[_][]const u8{obj_basename});
break :blk full_obj_path;
}
try self.flushModule(comp);
const obj_basename = self.base.intermediary_basename.?;
const full_obj_path = try directory.join(arena, &[_][]const u8{obj_basename});
break :blk full_obj_path;
} else null;
const is_lib = self.base.options.output_mode == .Lib;
const is_dyn_lib = self.base.options.link_mode == .Dynamic and is_lib;
const is_exe_or_dyn_lib = is_dyn_lib or self.base.options.output_mode == .Exe;
const target = self.base.options.target;
const stack_size = self.base.options.stack_size_override orelse 16777216;
const allow_shlib_undefined = self.base.options.allow_shlib_undefined orelse !self.base.options.is_native_os;
const id_symlink_basename = "lld.id";
var man: Cache.Manifest = undefined;
defer if (!self.base.options.disable_lld_caching) man.deinit();
var digest: [Cache.hex_digest_len]u8 = undefined;
if (!self.base.options.disable_lld_caching) {
man = comp.cache_parent.obtain();
// We are about to obtain this lock, so here we give other processes a chance first.
self.base.releaseLock();
try man.addOptionalFile(self.base.options.linker_script);
try man.addOptionalFile(self.base.options.version_script);
try man.addListOfFiles(self.base.options.objects);
for (comp.c_object_table.items()) |entry| {
_ = try man.addFile(entry.key.status.success.object_path, null);
}
try man.addOptionalFile(module_obj_path);
// We can skip hashing libc and libc++ components that we are in charge of building from Zig
// installation sources because they are always a product of the compiler version + target information.
man.hash.add(stack_size);
man.hash.add(self.base.options.rdynamic);
man.hash.addListOfBytes(self.base.options.extra_lld_args);
man.hash.addListOfBytes(self.base.options.lib_dirs);
man.hash.addListOfBytes(self.base.options.framework_dirs);
man.hash.addListOfBytes(self.base.options.frameworks);
man.hash.addListOfBytes(self.base.options.rpath_list);
man.hash.add(self.base.options.skip_linker_dependencies);
man.hash.add(self.base.options.z_nodelete);
man.hash.add(self.base.options.z_defs);
if (is_dyn_lib) {
man.hash.addOptional(self.base.options.version);
}
man.hash.addStringSet(self.base.options.system_libs);
man.hash.add(allow_shlib_undefined);
man.hash.add(self.base.options.bind_global_refs_locally);
man.hash.add(self.base.options.system_linker_hack);
man.hash.addOptionalBytes(self.base.options.syslibroot);
// We don't actually care whether it's a cache hit or miss; we just need the digest and the lock.
_ = try man.hit();
digest = man.final();
var prev_digest_buf: [digest.len]u8 = undefined;
const prev_digest: []u8 = Cache.readSmallFile(
directory.handle,
id_symlink_basename,
&prev_digest_buf,
) catch |err| blk: {
log.debug("MachO LLD new_digest={} error: {s}", .{ digest, @errorName(err) });
// Handle this as a cache miss.
break :blk prev_digest_buf[0..0];
};
if (mem.eql(u8, prev_digest, &digest)) {
log.debug("MachO LLD digest={} match - skipping invocation", .{digest});
// Hot diggity dog! The output binary is already there.
self.base.lock = man.toOwnedLock();
return;
}
log.debug("MachO LLD prev_digest={} new_digest={}", .{ prev_digest, digest });
// We are about to change the output file to be different, so we invalidate the build hash now.
directory.handle.deleteFile(id_symlink_basename) catch |err| switch (err) {
error.FileNotFound => {},
else => |e| return e,
};
}
const full_out_path = try directory.join(arena, &[_][]const u8{self.base.options.emit.?.sub_path});
if (self.base.options.output_mode == .Obj) {
// LLD's MachO driver does not support the equvialent of `-r` so we do a simple file copy
// here. TODO: think carefully about how we can avoid this redundant operation when doing
// build-obj. See also the corresponding TODO in linkAsArchive.
const the_object_path = blk: {
if (self.base.options.objects.len != 0)
break :blk self.base.options.objects[0];
if (comp.c_object_table.count() != 0)
break :blk comp.c_object_table.items()[0].key.status.success.object_path;
if (module_obj_path) |p|
break :blk p;
// TODO I think this is unreachable. Audit this situation when solving the above TODO
// regarding eliding redundant object -> object transformations.
return error.NoObjectsToLink;
};
// This can happen when using --enable-cache and using the stage1 backend. In this case
// we can skip the file copy.
if (!mem.eql(u8, the_object_path, full_out_path)) {
try fs.cwd().copyFile(the_object_path, fs.cwd(), full_out_path, .{});
}
} else {
// Create an LLD command line and invoke it.
var argv = std.ArrayList([]const u8).init(self.base.allocator);
defer argv.deinit();
// TODO https://github.com/ziglang/zig/issues/6971
// Note that there is no need to check if running natively since we do that already
// when setting `system_linker_hack` in Compilation struct.
if (self.base.options.system_linker_hack) {
try argv.append("ld");
} else {
// We will invoke ourselves as a child process to gain access to LLD.
// This is necessary because LLD does not behave properly as a library -
// it calls exit() and does not reset all global data between invocations.
try argv.appendSlice(&[_][]const u8{ comp.self_exe_path.?, "ld64.lld" });
try argv.append("-error-limit");
try argv.append("0");
}
try argv.append("-demangle");
if (self.base.options.rdynamic and !self.base.options.system_linker_hack) {
try argv.append("--export-dynamic");
}
try argv.appendSlice(self.base.options.extra_lld_args);
if (self.base.options.z_nodelete) {
try argv.append("-z");
try argv.append("nodelete");
}
if (self.base.options.z_defs) {
try argv.append("-z");
try argv.append("defs");
}
if (is_dyn_lib) {
try argv.append("-static");
} else {
try argv.append("-dynamic");
}
if (is_dyn_lib) {
try argv.append("-dylib");
if (self.base.options.version) |ver| {
const compat_vers = try std.fmt.allocPrint(arena, "{d}.0.0", .{ver.major});
try argv.append("-compatibility_version");
try argv.append(compat_vers);
const cur_vers = try std.fmt.allocPrint(arena, "{d}.{d}.{d}", .{ ver.major, ver.minor, ver.patch });
try argv.append("-current_version");
try argv.append(cur_vers);
}
const dylib_install_name = try std.fmt.allocPrint(arena, "@rpath/{s}", .{self.base.options.emit.?.sub_path});
try argv.append("-install_name");
try argv.append(dylib_install_name);
}
try argv.append("-arch");
try argv.append(darwinArchString(target.cpu.arch));
switch (target.os.tag) {
.macos => {
try argv.append("-macosx_version_min");
},
.ios, .tvos, .watchos => switch (target.cpu.arch) {
.i386, .x86_64 => {
try argv.append("-ios_simulator_version_min");
},
else => {
try argv.append("-iphoneos_version_min");
},
},
else => unreachable,
}
const ver = target.os.version_range.semver.min;
const version_string = try std.fmt.allocPrint(arena, "{d}.{d}.{d}", .{ ver.major, ver.minor, ver.patch });
try argv.append(version_string);
try argv.append("-sdk_version");
try argv.append(version_string);
if (target_util.requiresPIE(target) and self.base.options.output_mode == .Exe) {
try argv.append("-pie");
}
try argv.append("-o");
try argv.append(full_out_path);
// rpaths
var rpath_table = std.StringHashMap(void).init(self.base.allocator);
defer rpath_table.deinit();
for (self.base.options.rpath_list) |rpath| {
if ((try rpath_table.fetchPut(rpath, {})) == null) {
try argv.append("-rpath");
try argv.append(rpath);
}
}
if (is_dyn_lib) {
if ((try rpath_table.fetchPut(full_out_path, {})) == null) {
try argv.append("-rpath");
try argv.append(full_out_path);
}
}
if (self.base.options.syslibroot) |dir| {
try argv.append("-syslibroot");
try argv.append(dir);
}
for (self.base.options.lib_dirs) |lib_dir| {
try argv.append("-L");
try argv.append(lib_dir);
}
// Positional arguments to the linker such as object files.
try argv.appendSlice(self.base.options.objects);
for (comp.c_object_table.items()) |entry| {
try argv.append(entry.key.status.success.object_path);
}
if (module_obj_path) |p| {
try argv.append(p);
}
// compiler_rt on darwin is missing some stuff, so we still build it and rely on LinkOnce
if (is_exe_or_dyn_lib and !self.base.options.skip_linker_dependencies) {
try argv.append(comp.compiler_rt_static_lib.?.full_object_path);
}
// Shared libraries.
const system_libs = self.base.options.system_libs.items();
try argv.ensureCapacity(argv.items.len + system_libs.len);
for (system_libs) |entry| {
const link_lib = entry.key;
// By this time, we depend on these libs being dynamically linked libraries and not static libraries
// (the check for that needs to be earlier), but they could be full paths to .dylib files, in which
// case we want to avoid prepending "-l".
const ext = Compilation.classifyFileExt(link_lib);
const arg = if (ext == .shared_library) link_lib else try std.fmt.allocPrint(arena, "-l{s}", .{link_lib});
argv.appendAssumeCapacity(arg);
}
// libc++ dep
if (self.base.options.link_libcpp) {
try argv.append(comp.libcxxabi_static_lib.?.full_object_path);
try argv.append(comp.libcxx_static_lib.?.full_object_path);
}
// On Darwin, libSystem has libc in it, but also you have to use it
// to make syscalls because the syscall numbers are not documented
// and change between versions. So we always link against libSystem.
// LLD craps out if you do -lSystem cross compiling, so until that
// codebase gets some love from the new maintainers we're left with
// this dirty hack.
if (self.base.options.is_native_os) {
try argv.append("-lSystem");
}
for (self.base.options.framework_dirs) |framework_dir| {
try argv.append("-F");
try argv.append(framework_dir);
}
for (self.base.options.frameworks) |framework| {
try argv.append("-framework");
try argv.append(framework);
}
if (allow_shlib_undefined) {
try argv.append("-undefined");
try argv.append("dynamic_lookup");
}
if (self.base.options.bind_global_refs_locally) {
try argv.append("-Bsymbolic");
}
if (self.base.options.verbose_link) {
// Potentially skip over our own name so that the LLD linker name is the first argv item.
const adjusted_argv = if (self.base.options.system_linker_hack) argv.items else argv.items[1..];
Compilation.dump_argv(adjusted_argv);
}
// TODO https://github.com/ziglang/zig/issues/6971
// Note that there is no need to check if running natively since we do that already
// when setting `system_linker_hack` in Compilation struct.
if (self.base.options.system_linker_hack) {
const result = try std.ChildProcess.exec(.{ .allocator = self.base.allocator, .argv = argv.items });
defer {
self.base.allocator.free(result.stdout);
self.base.allocator.free(result.stderr);
}
if (result.stdout.len != 0) {
log.warn("unexpected LD stdout: {s}", .{result.stdout});
}
if (result.stderr.len != 0) {
log.warn("unexpected LD stderr: {s}", .{result.stderr});
}
if (result.term != .Exited or result.term.Exited != 0) {
// TODO parse this output and surface with the Compilation API rather than
// directly outputting to stderr here.
log.err("{s}", .{result.stderr});
return error.LDReportedFailure;
}
} else {
// Sadly, we must run LLD as a child process because it does not behave
// properly as a library.
const child = try std.ChildProcess.init(argv.items, arena);
defer child.deinit();
if (comp.clang_passthrough_mode) {
child.stdin_behavior = .Inherit;
child.stdout_behavior = .Inherit;
child.stderr_behavior = .Inherit;
const term = child.spawnAndWait() catch |err| {
log.err("unable to spawn {s}: {s}", .{ argv.items[0], @errorName(err) });
return error.UnableToSpawnSelf;
};
switch (term) {
.Exited => |code| {
if (code != 0) {
// TODO https://github.com/ziglang/zig/issues/6342
std.process.exit(1);
}
},
else => std.process.abort(),
}
} else {
child.stdin_behavior = .Ignore;
child.stdout_behavior = .Ignore;
child.stderr_behavior = .Pipe;
try child.spawn();
const stderr = try child.stderr.?.reader().readAllAlloc(arena, 10 * 1024 * 1024);
const term = child.wait() catch |err| {
log.err("unable to spawn {s}: {s}", .{ argv.items[0], @errorName(err) });
return error.UnableToSpawnSelf;
};
switch (term) {
.Exited => |code| {
if (code != 0) {
// TODO parse this output and surface with the Compilation API rather than
// directly outputting to stderr here.
std.debug.print("{s}", .{stderr});
return error.LLDReportedFailure;
}
},
else => {
log.err("{s} terminated with stderr:\n{s}", .{ argv.items[0], stderr });
return error.LLDCrashed;
},
}
if (stderr.len != 0) {
log.warn("unexpected LLD stderr:\n{s}", .{stderr});
}
}
// At this stage, LLD has done its job. It is time to patch the resultant
// binaries up!
const out_file = try directory.handle.openFile(self.base.options.emit.?.sub_path, .{ .write = true });
try self.parseFromFile(out_file);
if (self.libsystem_cmd_index == null and self.header.?.filetype == macho.MH_EXECUTE) {
const text_segment = self.load_commands.items[self.text_segment_cmd_index.?].Segment;
const text_section = text_segment.sections.items[self.text_section_index.?];
const after_last_cmd_offset = self.header.?.sizeofcmds + @sizeOf(macho.mach_header_64);
const needed_size = padToIdeal(@sizeOf(macho.linkedit_data_command));
if (needed_size + after_last_cmd_offset > text_section.offset) {
log.err("Unable to extend padding between the end of load commands and start of __text section.", .{});
log.err("Re-run the linker with '-headerpad 0x{x}' option if available, or", .{needed_size});
log.err("fall back to the system linker by exporting 'ZIG_SYSTEM_LINKER_HACK=1'.", .{});
return error.NotEnoughPadding;
}
// Calculate next available dylib ordinal.
const next_ordinal = blk: {
var ordinal: u32 = 1;
for (self.load_commands.items) |cmd| {
switch (cmd) {
.Dylib => ordinal += 1,
else => {},
}
}
break :blk ordinal;
};
// Add load dylib load command
self.libsystem_cmd_index = @intCast(u16, self.load_commands.items.len);
const cmdsize = @intCast(u32, mem.alignForwardGeneric(
u64,
@sizeOf(macho.dylib_command) + mem.lenZ(LIB_SYSTEM_PATH),
@sizeOf(u64),
));
// TODO Find a way to work out runtime version from the OS version triple stored in std.Target.
// In the meantime, we're gonna hardcode to the minimum compatibility version of 0.0.0.
const min_version = 0x0;
var dylib_cmd = emptyGenericCommandWithData(macho.dylib_command{
.cmd = macho.LC_LOAD_DYLIB,
.cmdsize = cmdsize,
.dylib = .{
.name = @sizeOf(macho.dylib_command),
.timestamp = 2, // not sure why not simply 0; this is reverse engineered from Mach-O files
.current_version = min_version,
.compatibility_version = min_version,
},
});
dylib_cmd.data = try self.base.allocator.alloc(u8, cmdsize - dylib_cmd.inner.dylib.name);
mem.set(u8, dylib_cmd.data, 0);
mem.copy(u8, dylib_cmd.data, mem.spanZ(LIB_SYSTEM_PATH));
try self.load_commands.append(self.base.allocator, .{ .Dylib = dylib_cmd });
self.header_dirty = true;
self.load_commands_dirty = true;
if (self.symtab_cmd_index == null or self.dysymtab_cmd_index == null) {
log.err("Incomplete Mach-O binary: no LC_SYMTAB or LC_DYSYMTAB load command found!", .{});
log.err("Without the symbol table, it is not possible to patch up the binary for cross-compilation.", .{});
return error.NoSymbolTableFound;
}
// Patch dyld info
try self.fixupBindInfo(next_ordinal);
try self.fixupLazyBindInfo(next_ordinal);
// Write updated load commands and the header
try self.writeLoadCommands();
try self.writeHeader();
assert(!self.header_dirty);
assert(!self.load_commands_dirty);
}
if (self.code_signature_cmd_index == null) outer: {
if (target.cpu.arch != .aarch64) break :outer; // This is currently needed only for aarch64 targets.
const text_segment = self.load_commands.items[self.text_segment_cmd_index.?].Segment;
const text_section = text_segment.sections.items[self.text_section_index.?];
const after_last_cmd_offset = self.header.?.sizeofcmds + @sizeOf(macho.mach_header_64);
const needed_size = padToIdeal(@sizeOf(macho.linkedit_data_command));
if (needed_size + after_last_cmd_offset > text_section.offset) {
log.err("Unable to extend padding between the end of load commands and start of __text section.", .{});
log.err("Re-run the linker with '-headerpad 0x{x}' option if available, or", .{needed_size});
log.err("fall back to the system linker by exporting 'ZIG_SYSTEM_LINKER_HACK=1'.", .{});
return error.NotEnoughPadding;
}
// Add code signature load command
self.code_signature_cmd_index = @intCast(u16, self.load_commands.items.len);
try self.load_commands.append(self.base.allocator, .{
.LinkeditData = .{
.cmd = macho.LC_CODE_SIGNATURE,
.cmdsize = @sizeOf(macho.linkedit_data_command),
.dataoff = 0,
.datasize = 0,
},
});
self.header_dirty = true;
self.load_commands_dirty = true;
// Pad out space for code signature
try self.writeCodeSignaturePadding();
// Write updated load commands and the header
try self.writeLoadCommands();
try self.writeHeader();
// Generate adhoc code signature
try self.writeCodeSignature();
assert(!self.header_dirty);
assert(!self.load_commands_dirty);
}
}
}
if (!self.base.options.disable_lld_caching) {
// Update the file with the digest. If it fails we can continue; it only
// means that the next invocation will have an unnecessary cache miss.
Cache.writeSmallFile(directory.handle, id_symlink_basename, &digest) catch |err| {
log.warn("failed to save linking hash digest file: {s}", .{@errorName(err)});
};
// Again failure here only means an unnecessary cache miss.
man.writeManifest() catch |err| {
log.warn("failed to write cache manifest when linking: {s}", .{@errorName(err)});
};
// We hang on to this lock so that the output file path can be used without
// other processes clobbering it.
self.base.lock = man.toOwnedLock();
}
}
fn darwinArchString(arch: std.Target.Cpu.Arch) []const u8 {
return switch (arch) {
.aarch64, .aarch64_be, .aarch64_32 => "arm64",
.thumb, .arm => "arm",
.thumbeb, .armeb => "armeb",
.powerpc => "ppc",
.powerpc64 => "ppc64",
.powerpc64le => "ppc64le",
else => @tagName(arch),
};
}
pub fn deinit(self: *MachO) void {
if (self.d_sym) |*ds| {
ds.deinit(self.base.allocator);
}
for (self.extern_lazy_symbols.items()) |*entry| {
self.base.allocator.free(entry.key);
}
self.extern_lazy_symbols.deinit(self.base.allocator);
for (self.extern_nonlazy_symbols.items()) |*entry| {
self.base.allocator.free(entry.key);
}
self.extern_nonlazy_symbols.deinit(self.base.allocator);
self.pie_fixups.deinit(self.base.allocator);
self.stub_fixups.deinit(self.base.allocator);
self.text_block_free_list.deinit(self.base.allocator);
self.offset_table.deinit(self.base.allocator);
self.offset_table_free_list.deinit(self.base.allocator);
{
var it = self.string_table_directory.iterator();
while (it.next()) |entry| {
self.base.allocator.free(entry.key);
}
}
self.string_table_directory.deinit(self.base.allocator);
self.string_table.deinit(self.base.allocator);
self.global_symbols.deinit(self.base.allocator);
self.global_symbol_free_list.deinit(self.base.allocator);
self.local_symbols.deinit(self.base.allocator);
self.local_symbol_free_list.deinit(self.base.allocator);
for (self.load_commands.items) |*lc| {
lc.deinit(self.base.allocator);
}
self.load_commands.deinit(self.base.allocator);
}
fn freeTextBlock(self: *MachO, text_block: *TextBlock) void {
var already_have_free_list_node = false;
{
var i: usize = 0;
// TODO turn text_block_free_list into a hash map
while (i < self.text_block_free_list.items.len) {
if (self.text_block_free_list.items[i] == text_block) {
_ = self.text_block_free_list.swapRemove(i);
continue;
}
if (self.text_block_free_list.items[i] == text_block.prev) {
already_have_free_list_node = true;
}
i += 1;
}
}
// TODO process free list for dbg info just like we do above for vaddrs
if (self.last_text_block == text_block) {
// TODO shrink the __text section size here
self.last_text_block = text_block.prev;
}
if (text_block.prev) |prev| {
prev.next = text_block.next;
if (!already_have_free_list_node and prev.freeListEligible(self.*)) {
// The free list is heuristics, it doesn't have to be perfect, so we can ignore
// the OOM here.
self.text_block_free_list.append(self.base.allocator, prev) catch {};
}
} else {
text_block.prev = null;
}
if (text_block.next) |next| {
next.prev = text_block.prev;
} else {
text_block.next = null;
}
}
fn shrinkTextBlock(self: *MachO, text_block: *TextBlock, new_block_size: u64) void {
// TODO check the new capacity, and if it crosses the size threshold into a big enough
// capacity, insert a free list node for it.
}
fn growTextBlock(self: *MachO, text_block: *TextBlock, new_block_size: u64, alignment: u64) !u64 {
const sym = self.local_symbols.items[text_block.local_sym_index];
const align_ok = mem.alignBackwardGeneric(u64, sym.n_value, alignment) == sym.n_value;
const need_realloc = !align_ok or new_block_size > text_block.capacity(self.*);
if (!need_realloc) return sym.n_value;
return self.allocateTextBlock(text_block, new_block_size, alignment);
}
pub fn allocateDeclIndexes(self: *MachO, decl: *Module.Decl) !void {
if (decl.link.macho.local_sym_index != 0) return;
try self.local_symbols.ensureCapacity(self.base.allocator, self.local_symbols.items.len + 1);
try self.offset_table.ensureCapacity(self.base.allocator, self.offset_table.items.len + 1);
if (self.local_symbol_free_list.popOrNull()) |i| {
log.debug("reusing symbol index {d} for {s}", .{ i, decl.name });
decl.link.macho.local_sym_index = i;
} else {
log.debug("allocating symbol index {d} for {s}", .{ self.local_symbols.items.len, decl.name });
decl.link.macho.local_sym_index = @intCast(u32, self.local_symbols.items.len);
_ = self.local_symbols.addOneAssumeCapacity();
}
if (self.offset_table_free_list.popOrNull()) |i| {
decl.link.macho.offset_table_index = i;
} else {
decl.link.macho.offset_table_index = @intCast(u32, self.offset_table.items.len);
_ = self.offset_table.addOneAssumeCapacity();
self.offset_table_count_dirty = true;
}
self.local_symbols.items[decl.link.macho.local_sym_index] = .{
.n_strx = 0,
.n_type = 0,
.n_sect = 0,
.n_desc = 0,
.n_value = 0,
};
self.offset_table.items[decl.link.macho.offset_table_index] = 0;
}
pub fn updateDecl(self: *MachO, module: *Module, decl: *Module.Decl) !void {
const tracy = trace(@src());
defer tracy.end();
const typed_value = decl.typed_value.most_recent.typed_value;
if (typed_value.val.tag() == .extern_fn) {
return; // TODO Should we do more when front-end analyzed extern decl?
}
var code_buffer = std.ArrayList(u8).init(self.base.allocator);
defer code_buffer.deinit();
var debug_buffers = if (self.d_sym) |*ds| try ds.initDeclDebugBuffers(self.base.allocator, module, decl) else null;
defer {
if (debug_buffers) |*dbg| {
dbg.dbg_line_buffer.deinit();
dbg.dbg_info_buffer.deinit();
var it = dbg.dbg_info_type_relocs.iterator();
while (it.next()) |entry| {
entry.value.relocs.deinit(self.base.allocator);
}
dbg.dbg_info_type_relocs.deinit(self.base.allocator);
}
}
const res = if (debug_buffers) |*dbg|
try codegen.generateSymbol(&self.base, decl.srcLoc(), typed_value, &code_buffer, .{
.dwarf = .{
.dbg_line = &dbg.dbg_line_buffer,
.dbg_info = &dbg.dbg_info_buffer,
.dbg_info_type_relocs = &dbg.dbg_info_type_relocs,
},
})
else
try codegen.generateSymbol(&self.base, decl.srcLoc(), typed_value, &code_buffer, .none);
const code = switch (res) {
.externally_managed => |x| x,
.appended => code_buffer.items,
.fail => |em| {
// Clear any PIE fixups and stub fixups for this decl.
self.pie_fixups.shrinkRetainingCapacity(0);
self.stub_fixups.shrinkRetainingCapacity(0);
decl.analysis = .codegen_failure;
try module.failed_decls.put(module.gpa, decl, em);
return;
},
};
const required_alignment = typed_value.ty.abiAlignment(self.base.options.target);
assert(decl.link.macho.local_sym_index != 0); // Caller forgot to call allocateDeclIndexes()
const symbol = &self.local_symbols.items[decl.link.macho.local_sym_index];
if (decl.link.macho.size != 0) {
const capacity = decl.link.macho.capacity(self.*);
const need_realloc = code.len > capacity or !mem.isAlignedGeneric(u64, symbol.n_value, required_alignment);
if (need_realloc) {
const vaddr = try self.growTextBlock(&decl.link.macho, code.len, required_alignment);
log.debug("growing {s} from 0x{x} to 0x{x}", .{ decl.name, symbol.n_value, vaddr });
if (vaddr != symbol.n_value) {
symbol.n_value = vaddr;
log.debug(" (writing new offset table entry)", .{});
self.offset_table.items[decl.link.macho.offset_table_index] = vaddr;
try self.writeOffsetTableEntry(decl.link.macho.offset_table_index);
}
} else if (code.len < decl.link.macho.size) {
self.shrinkTextBlock(&decl.link.macho, code.len);
}
decl.link.macho.size = code.len;
symbol.n_strx = try self.updateString(symbol.n_strx, mem.spanZ(decl.name));
symbol.n_type = macho.N_SECT;
symbol.n_sect = @intCast(u8, self.text_section_index.?) + 1;
symbol.n_desc = 0;
try self.writeLocalSymbol(decl.link.macho.local_sym_index);
if (self.d_sym) |*ds|
try ds.writeLocalSymbol(decl.link.macho.local_sym_index);
} else {
const decl_name = mem.spanZ(decl.name);
const name_str_index = try self.makeString(decl_name);
const addr = try self.allocateTextBlock(&decl.link.macho, code.len, required_alignment);
log.debug("allocated text block for {s} at 0x{x}", .{ decl_name, addr });
errdefer self.freeTextBlock(&decl.link.macho);
symbol.* = .{
.n_strx = name_str_index,
.n_type = macho.N_SECT,
.n_sect = @intCast(u8, self.text_section_index.?) + 1,
.n_desc = 0,
.n_value = addr,
};
self.offset_table.items[decl.link.macho.offset_table_index] = addr;
try self.writeLocalSymbol(decl.link.macho.local_sym_index);
if (self.d_sym) |*ds|
try ds.writeLocalSymbol(decl.link.macho.local_sym_index);
try self.writeOffsetTableEntry(decl.link.macho.offset_table_index);
}
// Perform PIE fixups (if any)
const text_segment = &self.load_commands.items[self.text_segment_cmd_index.?].Segment;
const got_section = text_segment.sections.items[self.got_section_index.?];
while (self.pie_fixups.popOrNull()) |fixup| {
const target_addr = fixup.address;
const this_addr = symbol.n_value + fixup.start;
switch (self.base.options.target.cpu.arch) {
.x86_64 => {
assert(target_addr >= this_addr + fixup.len);
const displacement = try math.cast(u32, target_addr - this_addr - fixup.len);
var placeholder = code_buffer.items[fixup.start + fixup.len - @sizeOf(u32) ..][0..@sizeOf(u32)];
mem.writeIntSliceLittle(u32, placeholder, displacement);
},
.aarch64 => {
assert(target_addr >= this_addr);
const displacement = try math.cast(u27, target_addr - this_addr);
var placeholder = code_buffer.items[fixup.start..][0..fixup.len];
mem.writeIntSliceLittle(u32, placeholder, aarch64.Instruction.b(@as(i28, displacement)).toU32());
},
else => unreachable, // unsupported target architecture
}
}
// Resolve stubs (if any)
const stubs = text_segment.sections.items[self.stubs_section_index.?];
for (self.stub_fixups.items) |fixup| {
const stub_addr = stubs.addr + fixup.symbol * stubs.reserved2;
const text_addr = symbol.n_value + fixup.start;
switch (self.base.options.target.cpu.arch) {
.x86_64 => {
assert(stub_addr >= text_addr + fixup.len);
const displacement = try math.cast(u32, stub_addr - text_addr - fixup.len);
var placeholder = code_buffer.items[fixup.start + fixup.len - @sizeOf(u32) ..][0..@sizeOf(u32)];
mem.writeIntSliceLittle(u32, placeholder, displacement);
},
.aarch64 => {
assert(stub_addr >= text_addr);
const displacement = try math.cast(i28, stub_addr - text_addr);
var placeholder = code_buffer.items[fixup.start..][0..fixup.len];
mem.writeIntSliceLittle(u32, placeholder, aarch64.Instruction.bl(displacement).toU32());
},
else => unreachable, // unsupported target architecture
}
if (!fixup.already_defined) {
try self.writeStub(fixup.symbol);
try self.writeStubInStubHelper(fixup.symbol);
try self.writeLazySymbolPointer(fixup.symbol);
const extern_sym = &self.extern_lazy_symbols.items()[fixup.symbol].value;
extern_sym.segment = self.data_segment_cmd_index.?;
extern_sym.offset = fixup.symbol * @sizeOf(u64);
self.rebase_info_dirty = true;
self.lazy_binding_info_dirty = true;
}
}
self.stub_fixups.shrinkRetainingCapacity(0);
const text_section = text_segment.sections.items[self.text_section_index.?];
const section_offset = symbol.n_value - text_section.addr;
const file_offset = text_section.offset + section_offset;
try self.base.file.?.pwriteAll(code, file_offset);
if (debug_buffers) |*db| {
try self.d_sym.?.commitDeclDebugInfo(
self.base.allocator,
module,
decl,
db,
self.base.options.target,
);
}
// Since we updated the vaddr and the size, each corresponding export symbol also needs to be updated.
const decl_exports = module.decl_exports.get(decl) orelse &[0]*Module.Export{};
try self.updateDeclExports(module, decl, decl_exports);
}
pub fn updateDeclLineNumber(self: *MachO, module: *Module, decl: *const Module.Decl) !void {
if (self.d_sym) |*ds| {
try ds.updateDeclLineNumber(module, decl);
}
}
pub fn updateDeclExports(
self: *MachO,
module: *Module,
decl: *const Module.Decl,
exports: []const *Module.Export,
) !void {
const tracy = trace(@src());
defer tracy.end();
try self.global_symbols.ensureCapacity(self.base.allocator, self.global_symbols.items.len + exports.len);
if (decl.link.macho.local_sym_index == 0) return;
const decl_sym = &self.local_symbols.items[decl.link.macho.local_sym_index];
for (exports) |exp| {
if (exp.options.section) |section_name| {
if (!mem.eql(u8, section_name, "__text")) {
try module.failed_exports.ensureCapacity(module.gpa, module.failed_exports.items().len + 1);
module.failed_exports.putAssumeCapacityNoClobber(
exp,
try Module.ErrorMsg.create(self.base.allocator, decl.srcLoc(), "Unimplemented: ExportOptions.section", .{}),
);
continue;
}
}
const n_desc = switch (exp.options.linkage) {
.Internal => macho.REFERENCE_FLAG_PRIVATE_DEFINED,
.Strong => blk: {
if (mem.eql(u8, exp.options.name, "_start")) {
self.entry_addr = decl_sym.n_value;
}
break :blk macho.REFERENCE_FLAG_DEFINED;
},
.Weak => macho.N_WEAK_REF,
.LinkOnce => {
try module.failed_exports.ensureCapacity(module.gpa, module.failed_exports.items().len + 1);
module.failed_exports.putAssumeCapacityNoClobber(
exp,
try Module.ErrorMsg.create(self.base.allocator, decl.srcLoc(), "Unimplemented: GlobalLinkage.LinkOnce", .{}),
);
continue;
},
};
const n_type = decl_sym.n_type | macho.N_EXT;
if (exp.link.macho.sym_index) |i| {
const sym = &self.global_symbols.items[i];
sym.* = .{
.n_strx = try self.updateString(sym.n_strx, exp.options.name),
.n_type = n_type,
.n_sect = @intCast(u8, self.text_section_index.?) + 1,
.n_desc = n_desc,
.n_value = decl_sym.n_value,
};
} else {
const name_str_index = try self.makeString(exp.options.name);
const i = if (self.global_symbol_free_list.popOrNull()) |i| i else blk: {
_ = self.global_symbols.addOneAssumeCapacity();
self.export_info_dirty = true;
break :blk self.global_symbols.items.len - 1;
};
self.global_symbols.items[i] = .{
.n_strx = name_str_index,
.n_type = n_type,
.n_sect = @intCast(u8, self.text_section_index.?) + 1,
.n_desc = n_desc,
.n_value = decl_sym.n_value,
};
exp.link.macho.sym_index = @intCast(u32, i);
}
}
}
pub fn deleteExport(self: *MachO, exp: Export) void {
const sym_index = exp.sym_index orelse return;
self.global_symbol_free_list.append(self.base.allocator, sym_index) catch {};
self.global_symbols.items[sym_index].n_type = 0;
}
pub fn freeDecl(self: *MachO, decl: *Module.Decl) void {
// Appending to free lists is allowed to fail because the free lists are heuristics based anyway.
self.freeTextBlock(&decl.link.macho);
if (decl.link.macho.local_sym_index != 0) {
self.local_symbol_free_list.append(self.base.allocator, decl.link.macho.local_sym_index) catch {};
self.offset_table_free_list.append(self.base.allocator, decl.link.macho.offset_table_index) catch {};
self.local_symbols.items[decl.link.macho.local_sym_index].n_type = 0;
decl.link.macho.local_sym_index = 0;
}
}
pub fn getDeclVAddr(self: *MachO, decl: *const Module.Decl) u64 {
assert(decl.link.macho.local_sym_index != 0);
return self.local_symbols.items[decl.link.macho.local_sym_index].n_value;
}
pub fn populateMissingMetadata(self: *MachO) !void {
switch (self.base.options.output_mode) {
.Exe => {},
.Obj => return error.TODOImplementWritingObjFiles,
.Lib => return error.TODOImplementWritingLibFiles,
}
if (self.header == null) {
var header: macho.mach_header_64 = undefined;
header.magic = macho.MH_MAGIC_64;
const CpuInfo = struct {
cpu_type: macho.cpu_type_t,
cpu_subtype: macho.cpu_subtype_t,
};
const cpu_info: CpuInfo = switch (self.base.options.target.cpu.arch) {
.aarch64 => .{
.cpu_type = macho.CPU_TYPE_ARM64,
.cpu_subtype = macho.CPU_SUBTYPE_ARM_ALL,
},
.x86_64 => .{
.cpu_type = macho.CPU_TYPE_X86_64,
.cpu_subtype = macho.CPU_SUBTYPE_X86_64_ALL,
},
else => return error.UnsupportedMachOArchitecture,
};
header.cputype = cpu_info.cpu_type;
header.cpusubtype = cpu_info.cpu_subtype;
const filetype: u32 = switch (self.base.options.output_mode) {
.Exe => macho.MH_EXECUTE,
.Obj => macho.MH_OBJECT,
.Lib => switch (self.base.options.link_mode) {
.Static => return error.TODOStaticLibMachOType,
.Dynamic => macho.MH_DYLIB,
},
};
header.filetype = filetype;
// These will get populated at the end of flushing the results to file.
header.ncmds = 0;
header.sizeofcmds = 0;
switch (self.base.options.output_mode) {
.Exe => {
header.flags = macho.MH_NOUNDEFS | macho.MH_DYLDLINK | macho.MH_PIE;
},
else => {
header.flags = 0;
},
}
header.reserved = 0;
self.header = header;
self.header_dirty = true;
}
if (self.pagezero_segment_cmd_index == null) {
self.pagezero_segment_cmd_index = @intCast(u16, self.load_commands.items.len);
try self.load_commands.append(self.base.allocator, .{
.Segment = SegmentCommand.empty(.{
.cmd = macho.LC_SEGMENT_64,
.cmdsize = @sizeOf(macho.segment_command_64),
.segname = makeStaticString("__PAGEZERO"),
.vmaddr = 0,
.vmsize = 0x100000000, // size always set to 4GB
.fileoff = 0,
.filesize = 0,
.maxprot = 0,
.initprot = 0,
.nsects = 0,
.flags = 0,
}),
});
self.header_dirty = true;
self.load_commands_dirty = true;
}
if (self.text_segment_cmd_index == null) {
self.text_segment_cmd_index = @intCast(u16, self.load_commands.items.len);
const maxprot = macho.VM_PROT_READ | macho.VM_PROT_WRITE | macho.VM_PROT_EXECUTE;
const initprot = macho.VM_PROT_READ | macho.VM_PROT_EXECUTE;
const program_code_size_hint = self.base.options.program_code_size_hint;
const offset_table_size_hint = @sizeOf(u64) * self.base.options.symbol_count_hint;
const ideal_size = self.header_pad + program_code_size_hint + 3 * offset_table_size_hint;
const needed_size = mem.alignForwardGeneric(u64, padToIdeal(ideal_size), self.page_size);
log.debug("found __TEXT segment free space 0x{x} to 0x{x}", .{ 0, needed_size });
try self.load_commands.append(self.base.allocator, .{
.Segment = SegmentCommand.empty(.{
.cmd = macho.LC_SEGMENT_64,
.cmdsize = @sizeOf(macho.segment_command_64),
.segname = makeStaticString("__TEXT"),
.vmaddr = 0x100000000, // always starts at 4GB
.vmsize = needed_size,
.fileoff = 0,
.filesize = needed_size,
.maxprot = maxprot,
.initprot = initprot,
.nsects = 0,
.flags = 0,
}),
});
self.header_dirty = true;
self.load_commands_dirty = true;
}
if (self.text_section_index == null) {
const text_segment = &self.load_commands.items[self.text_segment_cmd_index.?].Segment;
self.text_section_index = @intCast(u16, text_segment.sections.items.len);
const alignment: u2 = switch (self.base.options.target.cpu.arch) {
.x86_64 => 0,
.aarch64 => 2,
else => unreachable, // unhandled architecture type
};
const flags = macho.S_REGULAR | macho.S_ATTR_PURE_INSTRUCTIONS | macho.S_ATTR_SOME_INSTRUCTIONS;
const needed_size = self.base.options.program_code_size_hint;
const off = text_segment.findFreeSpace(needed_size, @as(u16, 1) << alignment, self.header_pad);
log.debug("found __text section free space 0x{x} to 0x{x}", .{ off, off + needed_size });
try text_segment.addSection(self.base.allocator, .{
.sectname = makeStaticString("__text"),
.segname = makeStaticString("__TEXT"),
.addr = text_segment.inner.vmaddr + off,
.size = @intCast(u32, needed_size),
.offset = @intCast(u32, off),
.@"align" = alignment,
.reloff = 0,
.nreloc = 0,
.flags = flags,
.reserved1 = 0,
.reserved2 = 0,
.reserved3 = 0,
});
self.header_dirty = true;
self.load_commands_dirty = true;
}
if (self.got_section_index == null) {
const text_segment = &self.load_commands.items[self.text_segment_cmd_index.?].Segment;
self.got_section_index = @intCast(u16, text_segment.sections.items.len);
const alignment: u2 = switch (self.base.options.target.cpu.arch) {
.x86_64 => 0,
.aarch64 => 2,
else => unreachable, // unhandled architecture type
};
const flags = macho.S_REGULAR | macho.S_ATTR_PURE_INSTRUCTIONS | macho.S_ATTR_SOME_INSTRUCTIONS;
const needed_size = @sizeOf(u64) * self.base.options.symbol_count_hint;
const off = text_segment.findFreeSpace(needed_size, @alignOf(u64), self.header_pad);
assert(off + needed_size <= text_segment.inner.fileoff + text_segment.inner.filesize); // TODO Must expand __TEXT segment.
log.debug("found __ziggot section free space 0x{x} to 0x{x}", .{ off, off + needed_size });
try text_segment.addSection(self.base.allocator, .{
.sectname = makeStaticString("__ziggot"),
.segname = makeStaticString("__TEXT"),
.addr = text_segment.inner.vmaddr + off,
.size = needed_size,
.offset = @intCast(u32, off),
.@"align" = alignment,
.reloff = 0,
.nreloc = 0,
.flags = flags,
.reserved1 = 0,
.reserved2 = 0,
.reserved3 = 0,
});
self.header_dirty = true;
self.load_commands_dirty = true;
}
if (self.stubs_section_index == null) {
const text_segment = &self.load_commands.items[self.text_segment_cmd_index.?].Segment;
self.stubs_section_index = @intCast(u16, text_segment.sections.items.len);
const alignment: u2 = switch (self.base.options.target.cpu.arch) {
.x86_64 => 0,
.aarch64 => 2,
else => unreachable, // unhandled architecture type
};
const stub_size: u4 = switch (self.base.options.target.cpu.arch) {
.x86_64 => 6,
.aarch64 => 2 * @sizeOf(u32),
else => unreachable, // unhandled architecture type
};
const flags = macho.S_SYMBOL_STUBS | macho.S_ATTR_PURE_INSTRUCTIONS | macho.S_ATTR_SOME_INSTRUCTIONS;
const needed_size = @sizeOf(u64) * self.base.options.symbol_count_hint;
const off = text_segment.findFreeSpace(needed_size, @alignOf(u64), self.header_pad);
assert(off + needed_size <= text_segment.inner.fileoff + text_segment.inner.filesize); // TODO Must expand __TEXT segment.
log.debug("found __stubs section free space 0x{x} to 0x{x}", .{ off, off + needed_size });
try text_segment.addSection(self.base.allocator, .{
.sectname = makeStaticString("__stubs"),
.segname = makeStaticString("__TEXT"),
.addr = text_segment.inner.vmaddr + off,
.size = needed_size,
.offset = @intCast(u32, off),
.@"align" = alignment,
.reloff = 0,
.nreloc = 0,
.flags = flags,
.reserved1 = 0,
.reserved2 = stub_size,
.reserved3 = 0,
});
self.header_dirty = true;
self.load_commands_dirty = true;
}
if (self.stub_helper_section_index == null) {
const text_segment = &self.load_commands.items[self.text_segment_cmd_index.?].Segment;
self.stub_helper_section_index = @intCast(u16, text_segment.sections.items.len);
const alignment: u2 = switch (self.base.options.target.cpu.arch) {
.x86_64 => 0,
.aarch64 => 2,
else => unreachable, // unhandled architecture type
};
const flags = macho.S_REGULAR | macho.S_ATTR_PURE_INSTRUCTIONS | macho.S_ATTR_SOME_INSTRUCTIONS;
const needed_size = @sizeOf(u64) * self.base.options.symbol_count_hint;
const off = text_segment.findFreeSpace(needed_size, @alignOf(u64), self.header_pad);
assert(off + needed_size <= text_segment.inner.fileoff + text_segment.inner.filesize); // TODO Must expand __TEXT segment.
log.debug("found __stub_helper section free space 0x{x} to 0x{x}", .{ off, off + needed_size });
try text_segment.addSection(self.base.allocator, .{
.sectname = makeStaticString("__stub_helper"),
.segname = makeStaticString("__TEXT"),
.addr = text_segment.inner.vmaddr + off,
.size = needed_size,
.offset = @intCast(u32, off),
.@"align" = alignment,
.reloff = 0,
.nreloc = 0,
.flags = flags,
.reserved1 = 0,
.reserved2 = 0,
.reserved3 = 0,
});
self.header_dirty = true;
self.load_commands_dirty = true;
}
if (self.data_const_segment_cmd_index == null) {
self.data_const_segment_cmd_index = @intCast(u16, self.load_commands.items.len);
const maxprot = macho.VM_PROT_READ | macho.VM_PROT_WRITE | macho.VM_PROT_EXECUTE;
const initprot = macho.VM_PROT_READ | macho.VM_PROT_WRITE;
const address_and_offset = self.nextSegmentAddressAndOffset();
const ideal_size = @sizeOf(u64) * self.base.options.symbol_count_hint;
const needed_size = mem.alignForwardGeneric(u64, padToIdeal(ideal_size), self.page_size);
log.debug("found __DATA_CONST segment free space 0x{x} to 0x{x}", .{ address_and_offset.offset, address_and_offset.offset + needed_size });
try self.load_commands.append(self.base.allocator, .{
.Segment = SegmentCommand.empty(.{
.cmd = macho.LC_SEGMENT_64,
.cmdsize = @sizeOf(macho.segment_command_64),
.segname = makeStaticString("__DATA_CONST"),
.vmaddr = address_and_offset.address,
.vmsize = needed_size,
.fileoff = address_and_offset.offset,
.filesize = needed_size,
.maxprot = maxprot,
.initprot = initprot,
.nsects = 0,
.flags = 0,
}),
});
self.header_dirty = true;
self.load_commands_dirty = true;
}
if (self.data_got_section_index == null) {
const dc_segment = &self.load_commands.items[self.data_const_segment_cmd_index.?].Segment;
self.data_got_section_index = @intCast(u16, dc_segment.sections.items.len);
const flags = macho.S_NON_LAZY_SYMBOL_POINTERS;
const needed_size = @sizeOf(u64) * self.base.options.symbol_count_hint;
const off = dc_segment.findFreeSpace(needed_size, @alignOf(u64), null);
assert(off + needed_size <= dc_segment.inner.fileoff + dc_segment.inner.filesize); // TODO Must expand __DATA_CONST segment.
log.debug("found __got section free space 0x{x} to 0x{x}", .{ off, off + needed_size });
try dc_segment.addSection(self.base.allocator, .{
.sectname = makeStaticString("__got"),
.segname = makeStaticString("__DATA_CONST"),
.addr = dc_segment.inner.vmaddr + off - dc_segment.inner.fileoff,
.size = needed_size,
.offset = @intCast(u32, off),
.@"align" = 3, // 2^3 = @sizeOf(u64)
.reloff = 0,
.nreloc = 0,
.flags = flags,
.reserved1 = 0,
.reserved2 = 0,
.reserved3 = 0,
});
self.header_dirty = true;
self.load_commands_dirty = true;
}
if (self.data_segment_cmd_index == null) {
self.data_segment_cmd_index = @intCast(u16, self.load_commands.items.len);
const maxprot = macho.VM_PROT_READ | macho.VM_PROT_WRITE | macho.VM_PROT_EXECUTE;
const initprot = macho.VM_PROT_READ | macho.VM_PROT_WRITE;
const address_and_offset = self.nextSegmentAddressAndOffset();
const ideal_size = 2 * @sizeOf(u64) * self.base.options.symbol_count_hint;
const needed_size = mem.alignForwardGeneric(u64, padToIdeal(ideal_size), self.page_size);
log.debug("found __DATA segment free space 0x{x} to 0x{x}", .{ address_and_offset.offset, address_and_offset.offset + needed_size });
try self.load_commands.append(self.base.allocator, .{
.Segment = SegmentCommand.empty(.{
.cmd = macho.LC_SEGMENT_64,
.cmdsize = @sizeOf(macho.segment_command_64),
.segname = makeStaticString("__DATA"),
.vmaddr = address_and_offset.address,
.vmsize = needed_size,
.fileoff = address_and_offset.offset,
.filesize = needed_size,
.maxprot = maxprot,
.initprot = initprot,
.nsects = 0,
.flags = 0,
}),
});
self.header_dirty = true;
self.load_commands_dirty = true;
}
if (self.la_symbol_ptr_section_index == null) {
const data_segment = &self.load_commands.items[self.data_segment_cmd_index.?].Segment;
self.la_symbol_ptr_section_index = @intCast(u16, data_segment.sections.items.len);
const flags = macho.S_LAZY_SYMBOL_POINTERS;
const needed_size = @sizeOf(u64) * self.base.options.symbol_count_hint;
const off = data_segment.findFreeSpace(needed_size, @alignOf(u64), null);
assert(off + needed_size <= data_segment.inner.fileoff + data_segment.inner.filesize); // TODO Must expand __DATA segment.
log.debug("found __la_symbol_ptr section free space 0x{x} to 0x{x}", .{ off, off + needed_size });
try data_segment.addSection(self.base.allocator, .{
.sectname = makeStaticString("__la_symbol_ptr"),
.segname = makeStaticString("__DATA"),
.addr = data_segment.inner.vmaddr + off - data_segment.inner.fileoff,
.size = needed_size,
.offset = @intCast(u32, off),
.@"align" = 3, // 2^3 = @sizeOf(u64)
.reloff = 0,
.nreloc = 0,
.flags = flags,
.reserved1 = 0,
.reserved2 = 0,
.reserved3 = 0,
});
self.header_dirty = true;
self.load_commands_dirty = true;
}
if (self.data_section_index == null) {
const data_segment = &self.load_commands.items[self.data_segment_cmd_index.?].Segment;
self.data_section_index = @intCast(u16, data_segment.sections.items.len);
const flags = macho.S_REGULAR;
const needed_size = @sizeOf(u64) * self.base.options.symbol_count_hint;
const off = data_segment.findFreeSpace(needed_size, @alignOf(u64), null);
assert(off + needed_size <= data_segment.inner.fileoff + data_segment.inner.filesize); // TODO Must expand __DATA segment.
log.debug("found __data section free space 0x{x} to 0x{x}", .{ off, off + needed_size });
try data_segment.addSection(self.base.allocator, .{
.sectname = makeStaticString("__data"),
.segname = makeStaticString("__DATA"),
.addr = data_segment.inner.vmaddr + off - data_segment.inner.fileoff,
.size = needed_size,
.offset = @intCast(u32, off),
.@"align" = 3, // 2^3 = @sizeOf(u64)
.reloff = 0,
.nreloc = 0,
.flags = flags,
.reserved1 = 0,
.reserved2 = 0,
.reserved3 = 0,
});
self.header_dirty = true;
self.load_commands_dirty = true;
}
if (self.linkedit_segment_cmd_index == null) {
self.linkedit_segment_cmd_index = @intCast(u16, self.load_commands.items.len);
const maxprot = macho.VM_PROT_READ | macho.VM_PROT_WRITE | macho.VM_PROT_EXECUTE;
const initprot = macho.VM_PROT_READ;
const address_and_offset = self.nextSegmentAddressAndOffset();
log.debug("found __LINKEDIT segment free space at 0x{x}", .{address_and_offset.offset});
try self.load_commands.append(self.base.allocator, .{
.Segment = SegmentCommand.empty(.{
.cmd = macho.LC_SEGMENT_64,
.cmdsize = @sizeOf(macho.segment_command_64),
.segname = makeStaticString("__LINKEDIT"),
.vmaddr = address_and_offset.address,
.vmsize = 0,
.fileoff = address_and_offset.offset,
.filesize = 0,
.maxprot = maxprot,
.initprot = initprot,
.nsects = 0,
.flags = 0,
}),
});
self.header_dirty = true;
self.load_commands_dirty = true;
}
if (self.dyld_info_cmd_index == null) {
self.dyld_info_cmd_index = @intCast(u16, self.load_commands.items.len);
try self.load_commands.append(self.base.allocator, .{
.DyldInfoOnly = .{
.cmd = macho.LC_DYLD_INFO_ONLY,
.cmdsize = @sizeOf(macho.dyld_info_command),
.rebase_off = 0,
.rebase_size = 0,
.bind_off = 0,
.bind_size = 0,
.weak_bind_off = 0,
.weak_bind_size = 0,
.lazy_bind_off = 0,
.lazy_bind_size = 0,
.export_off = 0,
.export_size = 0,
},
});
const dyld = &self.load_commands.items[self.dyld_info_cmd_index.?].DyldInfoOnly;
// Preallocate rebase, binding, lazy binding info, and export info.
const expected_size = 48; // TODO This is totally random.
const rebase_off = self.findFreeSpaceLinkedit(expected_size, 1, null);
log.debug("found rebase info free space 0x{x} to 0x{x}", .{ rebase_off, rebase_off + expected_size });
dyld.rebase_off = @intCast(u32, rebase_off);
dyld.rebase_size = expected_size;
const bind_off = self.findFreeSpaceLinkedit(expected_size, 1, null);
log.debug("found binding info free space 0x{x} to 0x{x}", .{ bind_off, bind_off + expected_size });
dyld.bind_off = @intCast(u32, bind_off);
dyld.bind_size = expected_size;
const lazy_bind_off = self.findFreeSpaceLinkedit(expected_size, 1, null);
log.debug("found lazy binding info free space 0x{x} to 0x{x}", .{ lazy_bind_off, lazy_bind_off + expected_size });
dyld.lazy_bind_off = @intCast(u32, lazy_bind_off);
dyld.lazy_bind_size = expected_size;
const export_off = self.findFreeSpaceLinkedit(expected_size, 1, null);
log.debug("found export info free space 0x{x} to 0x{x}", .{ export_off, export_off + expected_size });
dyld.export_off = @intCast(u32, export_off);
dyld.export_size = expected_size;
self.header_dirty = true;
self.load_commands_dirty = true;
}
if (self.symtab_cmd_index == null) {
self.symtab_cmd_index = @intCast(u16, self.load_commands.items.len);
try self.load_commands.append(self.base.allocator, .{
.Symtab = .{
.cmd = macho.LC_SYMTAB,
.cmdsize = @sizeOf(macho.symtab_command),
.symoff = 0,
.nsyms = 0,
.stroff = 0,
.strsize = 0,
},
});
const symtab = &self.load_commands.items[self.symtab_cmd_index.?].Symtab;
const symtab_size = self.base.options.symbol_count_hint * @sizeOf(macho.nlist_64);
const symtab_off = self.findFreeSpaceLinkedit(symtab_size, @sizeOf(macho.nlist_64), null);
log.debug("found symbol table free space 0x{x} to 0x{x}", .{ symtab_off, symtab_off + symtab_size });
symtab.symoff = @intCast(u32, symtab_off);
symtab.nsyms = @intCast(u32, self.base.options.symbol_count_hint);
try self.string_table.append(self.base.allocator, 0); // Need a null at position 0.
const strtab_size = self.string_table.items.len;
const strtab_off = self.findFreeSpaceLinkedit(strtab_size, 1, symtab_off);
log.debug("found string table free space 0x{x} to 0x{x}", .{ strtab_off, strtab_off + strtab_size });
symtab.stroff = @intCast(u32, strtab_off);
symtab.strsize = @intCast(u32, strtab_size);
self.header_dirty = true;
self.load_commands_dirty = true;
self.string_table_dirty = true;
}
if (self.dysymtab_cmd_index == null) {
self.dysymtab_cmd_index = @intCast(u16, self.load_commands.items.len);
// Preallocate space for indirect symbol table.
const indsymtab_size = self.base.options.symbol_count_hint * @sizeOf(u64); // Each entry is just a u64.
const indsymtab_off = self.findFreeSpaceLinkedit(indsymtab_size, @sizeOf(u64), null);
log.debug("found indirect symbol table free space 0x{x} to 0x{x}", .{ indsymtab_off, indsymtab_off + indsymtab_size });
try self.load_commands.append(self.base.allocator, .{
.Dysymtab = .{
.cmd = macho.LC_DYSYMTAB,
.cmdsize = @sizeOf(macho.dysymtab_command),
.ilocalsym = 0,
.nlocalsym = 0,
.iextdefsym = 0,
.nextdefsym = 0,
.iundefsym = 0,
.nundefsym = 0,
.tocoff = 0,
.ntoc = 0,
.modtaboff = 0,
.nmodtab = 0,
.extrefsymoff = 0,
.nextrefsyms = 0,
.indirectsymoff = @intCast(u32, indsymtab_off),
.nindirectsyms = @intCast(u32, self.base.options.symbol_count_hint),
.extreloff = 0,
.nextrel = 0,
.locreloff = 0,
.nlocrel = 0,
},
});
self.header_dirty = true;
self.load_commands_dirty = true;
}
if (self.dylinker_cmd_index == null) {
self.dylinker_cmd_index = @intCast(u16, self.load_commands.items.len);
const cmdsize = @intCast(u32, mem.alignForwardGeneric(
u64,
@sizeOf(macho.dylinker_command) + mem.lenZ(DEFAULT_DYLD_PATH),
@sizeOf(u64),
));
var dylinker_cmd = emptyGenericCommandWithData(macho.dylinker_command{
.cmd = macho.LC_LOAD_DYLINKER,
.cmdsize = cmdsize,
.name = @sizeOf(macho.dylinker_command),
});
dylinker_cmd.data = try self.base.allocator.alloc(u8, cmdsize - dylinker_cmd.inner.name);
mem.set(u8, dylinker_cmd.data, 0);
mem.copy(u8, dylinker_cmd.data, mem.spanZ(DEFAULT_DYLD_PATH));
try self.load_commands.append(self.base.allocator, .{ .Dylinker = dylinker_cmd });
self.header_dirty = true;
self.load_commands_dirty = true;
}
if (self.libsystem_cmd_index == null) {
self.libsystem_cmd_index = @intCast(u16, self.load_commands.items.len);
const cmdsize = @intCast(u32, mem.alignForwardGeneric(
u64,
@sizeOf(macho.dylib_command) + mem.lenZ(LIB_SYSTEM_PATH),
@sizeOf(u64),
));
// TODO Find a way to work out runtime version from the OS version triple stored in std.Target.
// In the meantime, we're gonna hardcode to the minimum compatibility version of 0.0.0.
const min_version = 0x0;
var dylib_cmd = emptyGenericCommandWithData(macho.dylib_command{
.cmd = macho.LC_LOAD_DYLIB,
.cmdsize = cmdsize,
.dylib = .{
.name = @sizeOf(macho.dylib_command),
.timestamp = 2, // not sure why not simply 0; this is reverse engineered from Mach-O files
.current_version = min_version,
.compatibility_version = min_version,
},
});
dylib_cmd.data = try self.base.allocator.alloc(u8, cmdsize - dylib_cmd.inner.dylib.name);
mem.set(u8, dylib_cmd.data, 0);
mem.copy(u8, dylib_cmd.data, mem.spanZ(LIB_SYSTEM_PATH));
try self.load_commands.append(self.base.allocator, .{ .Dylib = dylib_cmd });
self.header_dirty = true;
self.load_commands_dirty = true;
}
if (self.main_cmd_index == null) {
self.main_cmd_index = @intCast(u16, self.load_commands.items.len);
try self.load_commands.append(self.base.allocator, .{
.Main = .{
.cmd = macho.LC_MAIN,
.cmdsize = @sizeOf(macho.entry_point_command),
.entryoff = 0x0,
.stacksize = 0,
},
});
self.header_dirty = true;
self.load_commands_dirty = true;
}
if (self.version_min_cmd_index == null) {
self.version_min_cmd_index = @intCast(u16, self.load_commands.items.len);
const cmd: u32 = switch (self.base.options.target.os.tag) {
.macos => macho.LC_VERSION_MIN_MACOSX,
.ios => macho.LC_VERSION_MIN_IPHONEOS,
.tvos => macho.LC_VERSION_MIN_TVOS,
.watchos => macho.LC_VERSION_MIN_WATCHOS,
else => unreachable, // wrong OS
};
const ver = self.base.options.target.os.version_range.semver.min;
const version = ver.major << 16 | ver.minor << 8 | ver.patch;
try self.load_commands.append(self.base.allocator, .{
.VersionMin = .{
.cmd = cmd,
.cmdsize = @sizeOf(macho.version_min_command),
.version = version,
.sdk = version,
},
});
self.header_dirty = true;
self.load_commands_dirty = true;
}
if (self.source_version_cmd_index == null) {
self.source_version_cmd_index = @intCast(u16, self.load_commands.items.len);
try self.load_commands.append(self.base.allocator, .{
.SourceVersion = .{
.cmd = macho.LC_SOURCE_VERSION,
.cmdsize = @sizeOf(macho.source_version_command),
.version = 0x0,
},
});
self.header_dirty = true;
self.load_commands_dirty = true;
}
if (self.uuid_cmd_index == null) {
self.uuid_cmd_index = @intCast(u16, self.load_commands.items.len);
var uuid_cmd: macho.uuid_command = .{
.cmd = macho.LC_UUID,
.cmdsize = @sizeOf(macho.uuid_command),
.uuid = undefined,
};
std.crypto.random.bytes(&uuid_cmd.uuid);
try self.load_commands.append(self.base.allocator, .{ .Uuid = uuid_cmd });
self.header_dirty = true;
self.load_commands_dirty = true;
}
if (self.code_signature_cmd_index == null) {
self.code_signature_cmd_index = @intCast(u16, self.load_commands.items.len);
try self.load_commands.append(self.base.allocator, .{
.LinkeditData = .{
.cmd = macho.LC_CODE_SIGNATURE,
.cmdsize = @sizeOf(macho.linkedit_data_command),
.dataoff = 0,
.datasize = 0,
},
});
self.header_dirty = true;
self.load_commands_dirty = true;
}
if (!self.extern_nonlazy_symbols.contains("dyld_stub_binder")) {
const index = @intCast(u32, self.extern_nonlazy_symbols.items().len);
const name = try self.base.allocator.dupe(u8, "dyld_stub_binder");
const offset = try self.makeString("dyld_stub_binder");
try self.extern_nonlazy_symbols.putNoClobber(self.base.allocator, name, .{
.inner = .{
.n_strx = offset,
.n_type = std.macho.N_UNDF | std.macho.N_EXT,
.n_sect = 0,
.n_desc = std.macho.REFERENCE_FLAG_UNDEFINED_NON_LAZY | std.macho.N_SYMBOL_RESOLVER,
.n_value = 0,
},
.dylib_ordinal = 1, // TODO this is currently hardcoded.
.segment = self.data_const_segment_cmd_index.?,
.offset = index * @sizeOf(u64),
});
self.binding_info_dirty = true;
}
if (self.stub_helper_stubs_start_off == null) {
const text_segment = &self.load_commands.items[self.text_segment_cmd_index.?].Segment;
const stub_helper = &text_segment.sections.items[self.stub_helper_section_index.?];
const data_segment = &self.load_commands.items[self.data_segment_cmd_index.?].Segment;
const data = &data_segment.sections.items[self.data_section_index.?];
const data_const_segment = &self.load_commands.items[self.data_const_segment_cmd_index.?].Segment;
const got = &data_const_segment.sections.items[self.data_got_section_index.?];
switch (self.base.options.target.cpu.arch) {
.x86_64 => {
const code_size = 15;
var code: [code_size]u8 = undefined;
// lea %r11, [rip + disp]
code[0] = 0x4c;
code[1] = 0x8d;
code[2] = 0x1d;
{
const displacement = try math.cast(u32, data.addr - stub_helper.addr - 7);
mem.writeIntLittle(u32, code[3..7], displacement);
}
// push %r11
code[7] = 0x41;
code[8] = 0x53;
// jmp [rip + disp]
code[9] = 0xff;
code[10] = 0x25;
{
const displacement = try math.cast(u32, got.addr - stub_helper.addr - code_size);
mem.writeIntLittle(u32, code[11..], displacement);
}
self.stub_helper_stubs_start_off = stub_helper.offset + code_size;
try self.base.file.?.pwriteAll(&code, stub_helper.offset);
},
.aarch64 => {
var code: [4 * @sizeOf(u32)]u8 = undefined;
{
const displacement = try math.cast(i21, data.addr - stub_helper.addr);
mem.writeIntLittle(u32, code[0..4], aarch64.Instruction.adr(.x17, displacement).toU32());
}
mem.writeIntLittle(u32, code[4..8], aarch64.Instruction.stp(
.x16,
.x17,
aarch64.Register.sp,
aarch64.Instruction.LoadStorePairOffset.pre_index(-16),
).toU32());
{
const displacement = try math.divExact(u64, got.addr - stub_helper.addr - 2 * @sizeOf(u32), 4);
const literal = try math.cast(u19, displacement);
mem.writeIntLittle(u32, code[8..12], aarch64.Instruction.ldr(.x16, .{
.literal = literal,
}).toU32());
}
mem.writeIntLittle(u32, code[12..16], aarch64.Instruction.br(.x16).toU32());
self.stub_helper_stubs_start_off = stub_helper.offset + 4 * @sizeOf(u32);
try self.base.file.?.pwriteAll(&code, stub_helper.offset);
},
else => unreachable,
}
}
}
fn allocateTextBlock(self: *MachO, text_block: *TextBlock, new_block_size: u64, alignment: u64) !u64 {
const text_segment = &self.load_commands.items[self.text_segment_cmd_index.?].Segment;
const text_section = &text_segment.sections.items[self.text_section_index.?];
const new_block_ideal_capacity = padToIdeal(new_block_size);
// We use these to indicate our intention to update metadata, placing the new block,
// and possibly removing a free list node.
// It would be simpler to do it inside the for loop below, but that would cause a
// problem if an error was returned later in the function. So this action
// is actually carried out at the end of the function, when errors are no longer possible.
var block_placement: ?*TextBlock = null;
var free_list_removal: ?usize = null;
// First we look for an appropriately sized free list node.
// The list is unordered. We'll just take the first thing that works.
const vaddr = blk: {
var i: usize = 0;
while (i < self.text_block_free_list.items.len) {
const big_block = self.text_block_free_list.items[i];
// We now have a pointer to a live text block that has too much capacity.
// Is it enough that we could fit this new text block?
const sym = self.local_symbols.items[big_block.local_sym_index];
const capacity = big_block.capacity(self.*);
const ideal_capacity = padToIdeal(capacity);
const ideal_capacity_end_vaddr = sym.n_value + ideal_capacity;
const capacity_end_vaddr = sym.n_value + capacity;
const new_start_vaddr_unaligned = capacity_end_vaddr - new_block_ideal_capacity;
const new_start_vaddr = mem.alignBackwardGeneric(u64, new_start_vaddr_unaligned, alignment);
if (new_start_vaddr < ideal_capacity_end_vaddr) {
// Additional bookkeeping here to notice if this free list node
// should be deleted because the block that it points to has grown to take up
// more of the extra capacity.
if (!big_block.freeListEligible(self.*)) {
_ = self.text_block_free_list.swapRemove(i);
} else {
i += 1;
}
continue;
}
// At this point we know that we will place the new block here. But the
// remaining question is whether there is still yet enough capacity left
// over for there to still be a free list node.
const remaining_capacity = new_start_vaddr - ideal_capacity_end_vaddr;
const keep_free_list_node = remaining_capacity >= min_text_capacity;
// Set up the metadata to be updated, after errors are no longer possible.
block_placement = big_block;
if (!keep_free_list_node) {
free_list_removal = i;
}
break :blk new_start_vaddr;
} else if (self.last_text_block) |last| {
const last_symbol = self.local_symbols.items[last.local_sym_index];
// TODO We should pad out the excess capacity with NOPs. For executables,
// no padding seems to be OK, but it will probably not be for objects.
const ideal_capacity = padToIdeal(last.size);
const ideal_capacity_end_vaddr = last_symbol.n_value + ideal_capacity;
const new_start_vaddr = mem.alignForwardGeneric(u64, ideal_capacity_end_vaddr, alignment);
block_placement = last;
break :blk new_start_vaddr;
} else {
break :blk text_section.addr;
}
};
const expand_text_section = block_placement == null or block_placement.?.next == null;
if (expand_text_section) {
const needed_size = (vaddr + new_block_size) - text_section.addr;
assert(needed_size <= text_segment.inner.filesize); // TODO must move the entire text section.
self.last_text_block = text_block;
text_section.size = needed_size;
self.load_commands_dirty = true; // TODO Make more granular.
if (self.d_sym) |*ds| {
const debug_text_seg = &ds.load_commands.items[ds.text_segment_cmd_index.?].Segment;
const debug_text_sect = &debug_text_seg.sections.items[ds.text_section_index.?];
debug_text_sect.size = needed_size;
ds.load_commands_dirty = true;
}
}
text_block.size = new_block_size;
if (text_block.prev) |prev| {
prev.next = text_block.next;
}
if (text_block.next) |next| {
next.prev = text_block.prev;
}
if (block_placement) |big_block| {
text_block.prev = big_block;
text_block.next = big_block.next;
big_block.next = text_block;
} else {
text_block.prev = null;
text_block.next = null;
}
if (free_list_removal) |i| {
_ = self.text_block_free_list.swapRemove(i);
}
return vaddr;
}
pub fn makeStaticString(comptime bytes: []const u8) [16]u8 {
var buf = [_]u8{0} ** 16;
if (bytes.len > buf.len) @compileError("string too long; max 16 bytes");
mem.copy(u8, &buf, bytes);
return buf;
}
fn makeString(self: *MachO, bytes: []const u8) !u32 {
if (self.string_table_directory.get(bytes)) |offset| {
log.debug("reusing '{s}' from string table at offset 0x{x}", .{ bytes, offset });
return offset;
}
try self.string_table.ensureCapacity(self.base.allocator, self.string_table.items.len + bytes.len + 1);
const offset = @intCast(u32, self.string_table.items.len);
log.debug("writing new string '{s}' into string table at offset 0x{x}", .{ bytes, offset });
self.string_table.appendSliceAssumeCapacity(bytes);
self.string_table.appendAssumeCapacity(0);
try self.string_table_directory.putNoClobber(
self.base.allocator,
try self.base.allocator.dupe(u8, bytes),
offset,
);
self.string_table_dirty = true;
if (self.d_sym) |*ds|
ds.string_table_dirty = true;
return offset;
}
fn getString(self: *MachO, str_off: u32) []const u8 {
assert(str_off < self.string_table.items.len);
return mem.spanZ(@ptrCast([*:0]const u8, self.string_table.items.ptr + str_off));
}
fn updateString(self: *MachO, old_str_off: u32, new_name: []const u8) !u32 {
const existing_name = self.getString(old_str_off);
if (mem.eql(u8, existing_name, new_name)) {
return old_str_off;
}
return self.makeString(new_name);
}
pub fn addExternSymbol(self: *MachO, name: []const u8) !u32 {
const index = @intCast(u32, self.extern_lazy_symbols.items().len);
const offset = try self.makeString(name);
const sym_name = try self.base.allocator.dupe(u8, name);
const dylib_ordinal = 1; // TODO this is now hardcoded, since we only support libSystem.
try self.extern_lazy_symbols.putNoClobber(self.base.allocator, sym_name, .{
.inner = .{
.n_strx = offset,
.n_type = macho.N_UNDF | macho.N_EXT,
.n_sect = 0,
.n_desc = macho.REFERENCE_FLAG_UNDEFINED_NON_LAZY | macho.N_SYMBOL_RESOLVER,
.n_value = 0,
},
.dylib_ordinal = dylib_ordinal,
});
log.debug("adding new extern symbol '{s}' with dylib ordinal '{}'", .{ name, dylib_ordinal });
return index;
}
const NextSegmentAddressAndOffset = struct {
address: u64,
offset: u64,
};
fn nextSegmentAddressAndOffset(self: *MachO) NextSegmentAddressAndOffset {
var prev_segment_idx: ?usize = null; // We use optional here for safety.
for (self.load_commands.items) |cmd, i| {
if (cmd == .Segment) {
prev_segment_idx = i;
}
}
const prev_segment = self.load_commands.items[prev_segment_idx.?].Segment;
const address = prev_segment.inner.vmaddr + prev_segment.inner.vmsize;
const offset = prev_segment.inner.fileoff + prev_segment.inner.filesize;
return .{
.address = address,
.offset = offset,
};
}
fn allocatedSizeLinkedit(self: *MachO, start: u64) u64 {
assert(start > 0);
var min_pos: u64 = std.math.maxInt(u64);
// __LINKEDIT is a weird segment where sections get their own load commands so we
// special-case it.
if (self.dyld_info_cmd_index) |idx| {
const dyld_info = self.load_commands.items[idx].DyldInfoOnly;
if (dyld_info.rebase_off > start and dyld_info.rebase_off < min_pos) min_pos = dyld_info.rebase_off;
if (dyld_info.bind_off > start and dyld_info.bind_off < min_pos) min_pos = dyld_info.bind_off;
if (dyld_info.weak_bind_off > start and dyld_info.weak_bind_off < min_pos) min_pos = dyld_info.weak_bind_off;
if (dyld_info.lazy_bind_off > start and dyld_info.lazy_bind_off < min_pos) min_pos = dyld_info.lazy_bind_off;
if (dyld_info.export_off > start and dyld_info.export_off < min_pos) min_pos = dyld_info.export_off;
}
if (self.function_starts_cmd_index) |idx| {
const fstart = self.load_commands.items[idx].LinkeditData;
if (fstart.dataoff > start and fstart.dataoff < min_pos) min_pos = fstart.dataoff;
}
if (self.data_in_code_cmd_index) |idx| {
const dic = self.load_commands.items[idx].LinkeditData;
if (dic.dataoff > start and dic.dataoff < min_pos) min_pos = dic.dataoff;
}
if (self.dysymtab_cmd_index) |idx| {
const dysymtab = self.load_commands.items[idx].Dysymtab;
if (dysymtab.indirectsymoff > start and dysymtab.indirectsymoff < min_pos) min_pos = dysymtab.indirectsymoff;
// TODO Handle more dynamic symbol table sections.
}
if (self.symtab_cmd_index) |idx| {
const symtab = self.load_commands.items[idx].Symtab;
if (symtab.symoff > start and symtab.symoff < min_pos) min_pos = symtab.symoff;
if (symtab.stroff > start and symtab.stroff < min_pos) min_pos = symtab.stroff;
}
return min_pos - start;
}
inline fn checkForCollision(start: u64, end: u64, off: u64, size: u64) ?u64 {
const increased_size = padToIdeal(size);
const test_end = off + increased_size;
if (end > off and start < test_end) {
return test_end;
}
return null;
}
fn detectAllocCollisionLinkedit(self: *MachO, start: u64, size: u64) ?u64 {
const end = start + padToIdeal(size);
// __LINKEDIT is a weird segment where sections get their own load commands so we
// special-case it.
if (self.dyld_info_cmd_index) |idx| outer: {
if (self.load_commands.items.len == idx) break :outer;
const dyld_info = self.load_commands.items[idx].DyldInfoOnly;
if (checkForCollision(start, end, dyld_info.rebase_off, dyld_info.rebase_size)) |pos| {
return pos;
}
// Binding info
if (checkForCollision(start, end, dyld_info.bind_off, dyld_info.bind_size)) |pos| {
return pos;
}
// Weak binding info
if (checkForCollision(start, end, dyld_info.weak_bind_off, dyld_info.weak_bind_size)) |pos| {
return pos;
}
// Lazy binding info
if (checkForCollision(start, end, dyld_info.lazy_bind_off, dyld_info.lazy_bind_size)) |pos| {
return pos;
}
// Export info
if (checkForCollision(start, end, dyld_info.export_off, dyld_info.export_size)) |pos| {
return pos;
}
}
if (self.function_starts_cmd_index) |idx| outer: {
if (self.load_commands.items.len == idx) break :outer;
const fstart = self.load_commands.items[idx].LinkeditData;
if (checkForCollision(start, end, fstart.dataoff, fstart.datasize)) |pos| {
return pos;
}
}
if (self.data_in_code_cmd_index) |idx| outer: {
if (self.load_commands.items.len == idx) break :outer;
const dic = self.load_commands.items[idx].LinkeditData;
if (checkForCollision(start, end, dic.dataoff, dic.datasize)) |pos| {
return pos;
}
}
if (self.dysymtab_cmd_index) |idx| outer: {
if (self.load_commands.items.len == idx) break :outer;
const dysymtab = self.load_commands.items[idx].Dysymtab;
// Indirect symbol table
const nindirectsize = dysymtab.nindirectsyms * @sizeOf(u32);
if (checkForCollision(start, end, dysymtab.indirectsymoff, nindirectsize)) |pos| {
return pos;
}
// TODO Handle more dynamic symbol table sections.
}
if (self.symtab_cmd_index) |idx| outer: {
if (self.load_commands.items.len == idx) break :outer;
const symtab = self.load_commands.items[idx].Symtab;
// Symbol table
const symsize = symtab.nsyms * @sizeOf(macho.nlist_64);
if (checkForCollision(start, end, symtab.symoff, symsize)) |pos| {
return pos;
}
// String table
if (checkForCollision(start, end, symtab.stroff, symtab.strsize)) |pos| {
return pos;
}
}
return null;
}
fn findFreeSpaceLinkedit(self: *MachO, object_size: u64, min_alignment: u16, start: ?u64) u64 {
const linkedit = self.load_commands.items[self.linkedit_segment_cmd_index.?].Segment;
var st: u64 = start orelse linkedit.inner.fileoff;
while (self.detectAllocCollisionLinkedit(st, object_size)) |item_end| {
st = mem.alignForwardGeneric(u64, item_end, min_alignment);
}
return st;
}
fn writeOffsetTableEntry(self: *MachO, index: usize) !void {
const text_segment = &self.load_commands.items[self.text_segment_cmd_index.?].Segment;
const sect = &text_segment.sections.items[self.got_section_index.?];
const off = sect.offset + @sizeOf(u64) * index;
const vmaddr = sect.addr + @sizeOf(u64) * index;
if (self.offset_table_count_dirty) {
// TODO relocate.
self.offset_table_count_dirty = false;
}
var code: [8]u8 = undefined;
switch (self.base.options.target.cpu.arch) {
.x86_64 => {
const pos_symbol_off = try math.cast(u31, vmaddr - self.offset_table.items[index] + 7);
const symbol_off = @bitCast(u32, @as(i32, pos_symbol_off) * -1);
// lea %rax, [rip - disp]
code[0] = 0x48;
code[1] = 0x8D;
code[2] = 0x5;
mem.writeIntLittle(u32, code[3..7], symbol_off);
// ret
code[7] = 0xC3;
},
.aarch64 => {
const pos_symbol_off = try math.cast(u20, vmaddr - self.offset_table.items[index]);
const symbol_off = @as(i21, pos_symbol_off) * -1;
// adr x0, #-disp
mem.writeIntLittle(u32, code[0..4], aarch64.Instruction.adr(.x0, symbol_off).toU32());
// ret x28
mem.writeIntLittle(u32, code[4..8], aarch64.Instruction.ret(.x28).toU32());
},
else => unreachable, // unsupported target architecture
}
log.debug("writing offset table entry 0x{x} at 0x{x}", .{ self.offset_table.items[index], off });
try self.base.file.?.pwriteAll(&code, off);
}
fn writeLazySymbolPointer(self: *MachO, index: u32) !void {
const text_segment = self.load_commands.items[self.text_segment_cmd_index.?].Segment;
const stub_helper = text_segment.sections.items[self.stub_helper_section_index.?];
const data_segment = self.load_commands.items[self.data_segment_cmd_index.?].Segment;
const la_symbol_ptr = data_segment.sections.items[self.la_symbol_ptr_section_index.?];
const stub_size: u4 = switch (self.base.options.target.cpu.arch) {
.x86_64 => 10,
.aarch64 => 3 * @sizeOf(u32),
else => unreachable,
};
const stub_off = self.stub_helper_stubs_start_off.? + index * stub_size;
const end = stub_helper.addr + stub_off - stub_helper.offset;
var buf: [@sizeOf(u64)]u8 = undefined;
mem.writeIntLittle(u64, &buf, end);
const off = la_symbol_ptr.offset + index * @sizeOf(u64);
log.debug("writing lazy symbol pointer entry 0x{x} at 0x{x}", .{ end, off });
try self.base.file.?.pwriteAll(&buf, off);
}
fn writeStub(self: *MachO, index: u32) !void {
const text_segment = self.load_commands.items[self.text_segment_cmd_index.?].Segment;
const stubs = text_segment.sections.items[self.stubs_section_index.?];
const data_segment = self.load_commands.items[self.data_segment_cmd_index.?].Segment;
const la_symbol_ptr = data_segment.sections.items[self.la_symbol_ptr_section_index.?];
const stub_off = stubs.offset + index * stubs.reserved2;
const stub_addr = stubs.addr + index * stubs.reserved2;
const la_ptr_addr = la_symbol_ptr.addr + index * @sizeOf(u64);
log.debug("writing stub at 0x{x}", .{stub_off});
var code = try self.base.allocator.alloc(u8, stubs.reserved2);
defer self.base.allocator.free(code);
switch (self.base.options.target.cpu.arch) {
.x86_64 => {
assert(la_ptr_addr >= stub_addr + stubs.reserved2);
const displacement = try math.cast(u32, la_ptr_addr - stub_addr - stubs.reserved2);
// jmp
code[0] = 0xff;
code[1] = 0x25;
mem.writeIntLittle(u32, code[2..][0..4], displacement);
},
.aarch64 => {
assert(la_ptr_addr >= stub_addr);
const displacement = try math.divExact(u64, la_ptr_addr - stub_addr, 4);
const literal = try math.cast(u19, displacement);
mem.writeIntLittle(u32, code[0..4], aarch64.Instruction.ldr(.x16, .{
.literal = literal,
}).toU32());
mem.writeIntLittle(u32, code[4..8], aarch64.Instruction.br(.x16).toU32());
},
else => unreachable,
}
try self.base.file.?.pwriteAll(code, stub_off);
}
fn writeStubInStubHelper(self: *MachO, index: u32) !void {
const text_segment = self.load_commands.items[self.text_segment_cmd_index.?].Segment;
const stub_helper = text_segment.sections.items[self.stub_helper_section_index.?];
const stub_size: u4 = switch (self.base.options.target.cpu.arch) {
.x86_64 => 10,
.aarch64 => 3 * @sizeOf(u32),
else => unreachable,
};
const stub_off = self.stub_helper_stubs_start_off.? + index * stub_size;
var code = try self.base.allocator.alloc(u8, stub_size);
defer self.base.allocator.free(code);
switch (self.base.options.target.cpu.arch) {
.x86_64 => {
const displacement = try math.cast(
i32,
@intCast(i64, stub_helper.offset) - @intCast(i64, stub_off) - stub_size,
);
// pushq
code[0] = 0x68;
mem.writeIntLittle(u32, code[1..][0..4], 0x0); // Just a placeholder populated in `populateLazyBindOffsetsInStubHelper`.
// jmpq
code[5] = 0xe9;
mem.writeIntLittle(u32, code[6..][0..4], @bitCast(u32, displacement));
},
.aarch64 => {
const displacement = try math.cast(i28, @intCast(i64, stub_helper.offset) - @intCast(i64, stub_off) - 4);
mem.writeIntLittle(u32, code[0..4], aarch64.Instruction.ldr(.w16, .{
.literal = @divExact(stub_size - @sizeOf(u32), 4),
}).toU32());
mem.writeIntLittle(u32, code[4..8], aarch64.Instruction.b(displacement).toU32());
mem.writeIntLittle(u32, code[8..12], 0x0); // Just a placeholder populated in `populateLazyBindOffsetsInStubHelper`.
},
else => unreachable,
}
try self.base.file.?.pwriteAll(code, stub_off);
}
fn relocateSymbolTable(self: *MachO) !void {
const symtab = &self.load_commands.items[self.symtab_cmd_index.?].Symtab;
const nlocals = self.local_symbols.items.len;
const nglobals = self.global_symbols.items.len;
const nundefs = self.extern_lazy_symbols.items().len + self.extern_nonlazy_symbols.items().len;
const nsyms = nlocals + nglobals + nundefs;
if (symtab.nsyms < nsyms) {
const linkedit_segment = self.load_commands.items[self.linkedit_segment_cmd_index.?].Segment;
const needed_size = nsyms * @sizeOf(macho.nlist_64);
if (needed_size > self.allocatedSizeLinkedit(symtab.symoff)) {
// Move the entire symbol table to a new location
const new_symoff = self.findFreeSpaceLinkedit(needed_size, @alignOf(macho.nlist_64), null);
const existing_size = symtab.nsyms * @sizeOf(macho.nlist_64);
log.debug("relocating symbol table from 0x{x}-0x{x} to 0x{x}-0x{x}", .{
symtab.symoff,
symtab.symoff + existing_size,
new_symoff,
new_symoff + existing_size,
});
const amt = try self.base.file.?.copyRangeAll(symtab.symoff, self.base.file.?, new_symoff, existing_size);
if (amt != existing_size) return error.InputOutput;
symtab.symoff = @intCast(u32, new_symoff);
self.string_table_needs_relocation = true;
}
symtab.nsyms = @intCast(u32, nsyms);
self.load_commands_dirty = true;
}
}
fn writeLocalSymbol(self: *MachO, index: usize) !void {
const tracy = trace(@src());
defer tracy.end();
try self.relocateSymbolTable();
const symtab = &self.load_commands.items[self.symtab_cmd_index.?].Symtab;
const off = symtab.symoff + @sizeOf(macho.nlist_64) * index;
log.debug("writing local symbol {} at 0x{x}", .{ index, off });
try self.base.file.?.pwriteAll(mem.asBytes(&self.local_symbols.items[index]), off);
}
fn writeAllGlobalAndUndefSymbols(self: *MachO) !void {
const tracy = trace(@src());
defer tracy.end();
try self.relocateSymbolTable();
const symtab = &self.load_commands.items[self.symtab_cmd_index.?].Symtab;
const nlocals = self.local_symbols.items.len;
const nglobals = self.global_symbols.items.len;
const nundefs = self.extern_lazy_symbols.items().len + self.extern_nonlazy_symbols.items().len;
var undefs = std.ArrayList(macho.nlist_64).init(self.base.allocator);
defer undefs.deinit();
try undefs.ensureCapacity(nundefs);
for (self.extern_lazy_symbols.items()) |entry| {
undefs.appendAssumeCapacity(entry.value.inner);
}
for (self.extern_nonlazy_symbols.items()) |entry| {
undefs.appendAssumeCapacity(entry.value.inner);
}
const locals_off = symtab.symoff;
const locals_size = nlocals * @sizeOf(macho.nlist_64);
const globals_off = locals_off + locals_size;
const globals_size = nglobals * @sizeOf(macho.nlist_64);
log.debug("writing global symbols from 0x{x} to 0x{x}", .{ globals_off, globals_size + globals_off });
try self.base.file.?.pwriteAll(mem.sliceAsBytes(self.global_symbols.items), globals_off);
const undefs_off = globals_off + globals_size;
const undefs_size = nundefs * @sizeOf(macho.nlist_64);
log.debug("writing extern symbols from 0x{x} to 0x{x}", .{ undefs_off, undefs_size + undefs_off });
try self.base.file.?.pwriteAll(mem.sliceAsBytes(undefs.items), undefs_off);
// Update dynamic symbol table.
const dysymtab = &self.load_commands.items[self.dysymtab_cmd_index.?].Dysymtab;
dysymtab.nlocalsym = @intCast(u32, nlocals);
dysymtab.iextdefsym = @intCast(u32, nlocals);
dysymtab.nextdefsym = @intCast(u32, nglobals);
dysymtab.iundefsym = @intCast(u32, nlocals + nglobals);
dysymtab.nundefsym = @intCast(u32, nundefs);
self.load_commands_dirty = true;
}
fn writeIndirectSymbolTable(self: *MachO) !void {
// TODO figure out a way not to rewrite the table every time if
// no new undefs are not added.
const tracy = trace(@src());
defer tracy.end();
const text_segment = &self.load_commands.items[self.text_segment_cmd_index.?].Segment;
const stubs = &text_segment.sections.items[self.stubs_section_index.?];
const data_const_seg = &self.load_commands.items[self.data_const_segment_cmd_index.?].Segment;
const got = &data_const_seg.sections.items[self.data_got_section_index.?];
const data_segment = &self.load_commands.items[self.data_segment_cmd_index.?].Segment;
const la_symbol_ptr = &data_segment.sections.items[self.la_symbol_ptr_section_index.?];
const dysymtab = &self.load_commands.items[self.dysymtab_cmd_index.?].Dysymtab;
const lazy = self.extern_lazy_symbols.items();
const nonlazy = self.extern_nonlazy_symbols.items();
const allocated_size = self.allocatedSizeLinkedit(dysymtab.indirectsymoff);
const nindirectsyms = @intCast(u32, lazy.len * 2 + nonlazy.len);
const needed_size = @intCast(u32, nindirectsyms * @sizeOf(u32));
if (needed_size > allocated_size) {
dysymtab.nindirectsyms = 0;
dysymtab.indirectsymoff = @intCast(u32, self.findFreeSpaceLinkedit(needed_size, @sizeOf(u32), null));
}
dysymtab.nindirectsyms = nindirectsyms;
log.debug("writing indirect symbol table from 0x{x} to 0x{x}", .{
dysymtab.indirectsymoff,
dysymtab.indirectsymoff + needed_size,
});
var buf = try self.base.allocator.alloc(u8, needed_size);
defer self.base.allocator.free(buf);
var stream = std.io.fixedBufferStream(buf);
var writer = stream.writer();
stubs.reserved1 = 0;
for (self.extern_lazy_symbols.items()) |_, i| {
const symtab_idx = @intCast(u32, dysymtab.iundefsym + i);
try writer.writeIntLittle(u32, symtab_idx);
}
const base_id = @intCast(u32, lazy.len);
got.reserved1 = base_id;
for (self.extern_nonlazy_symbols.items()) |_, i| {
const symtab_idx = @intCast(u32, dysymtab.iundefsym + i + base_id);
try writer.writeIntLittle(u32, symtab_idx);
}
la_symbol_ptr.reserved1 = got.reserved1 + @intCast(u32, nonlazy.len);
for (self.extern_lazy_symbols.items()) |_, i| {
const symtab_idx = @intCast(u32, dysymtab.iundefsym + i);
try writer.writeIntLittle(u32, symtab_idx);
}
try self.base.file.?.pwriteAll(buf, dysymtab.indirectsymoff);
self.load_commands_dirty = true;
}
fn writeCodeSignaturePadding(self: *MachO) !void {
// TODO figure out how not to rewrite padding every single time.
const tracy = trace(@src());
defer tracy.end();
const linkedit_segment = &self.load_commands.items[self.linkedit_segment_cmd_index.?].Segment;
const code_sig_cmd = &self.load_commands.items[self.code_signature_cmd_index.?].LinkeditData;
const fileoff = linkedit_segment.inner.fileoff + linkedit_segment.inner.filesize;
const needed_size = CodeSignature.calcCodeSignaturePaddingSize(
self.base.options.emit.?.sub_path,
fileoff,
self.page_size,
);
code_sig_cmd.dataoff = @intCast(u32, fileoff);
code_sig_cmd.datasize = needed_size;
// Advance size of __LINKEDIT segment
linkedit_segment.inner.filesize += needed_size;
if (linkedit_segment.inner.vmsize < linkedit_segment.inner.filesize) {
linkedit_segment.inner.vmsize = mem.alignForwardGeneric(u64, linkedit_segment.inner.filesize, self.page_size);
}
log.debug("writing code signature padding from 0x{x} to 0x{x}", .{ fileoff, fileoff + needed_size });
// Pad out the space. We need to do this to calculate valid hashes for everything in the file
// except for code signature data.
try self.base.file.?.pwriteAll(&[_]u8{0}, fileoff + needed_size - 1);
self.load_commands_dirty = true;
}
fn writeCodeSignature(self: *MachO) !void {
const tracy = trace(@src());
defer tracy.end();
const text_segment = self.load_commands.items[self.text_segment_cmd_index.?].Segment;
const code_sig_cmd = self.load_commands.items[self.code_signature_cmd_index.?].LinkeditData;
var code_sig = CodeSignature.init(self.base.allocator, self.page_size);
defer code_sig.deinit();
try code_sig.calcAdhocSignature(
self.base.file.?,
self.base.options.emit.?.sub_path,
text_segment.inner,
code_sig_cmd,
self.base.options.output_mode,
);
var buffer = try self.base.allocator.alloc(u8, code_sig.size());
defer self.base.allocator.free(buffer);
var stream = std.io.fixedBufferStream(buffer);
try code_sig.write(stream.writer());
log.debug("writing code signature from 0x{x} to 0x{x}", .{ code_sig_cmd.dataoff, code_sig_cmd.dataoff + buffer.len });
try self.base.file.?.pwriteAll(buffer, code_sig_cmd.dataoff);
}
fn writeExportTrie(self: *MachO) !void {
if (!self.export_info_dirty) return;
if (self.global_symbols.items.len == 0) return;
const tracy = trace(@src());
defer tracy.end();
var trie = Trie.init(self.base.allocator);
defer trie.deinit();
const text_segment = self.load_commands.items[self.text_segment_cmd_index.?].Segment;
for (self.global_symbols.items) |symbol| {
// TODO figure out if we should put all global symbols into the export trie
const name = self.getString(symbol.n_strx);
assert(symbol.n_value >= text_segment.inner.vmaddr);
try trie.put(.{
.name = name,
.vmaddr_offset = symbol.n_value - text_segment.inner.vmaddr,
.export_flags = macho.EXPORT_SYMBOL_FLAGS_KIND_REGULAR,
});
}
try trie.finalize();
var buffer = try self.base.allocator.alloc(u8, @intCast(usize, trie.size));
defer self.base.allocator.free(buffer);
var stream = std.io.fixedBufferStream(buffer);
const nwritten = try trie.write(stream.writer());
assert(nwritten == trie.size);
const linkedit_segment = self.load_commands.items[self.linkedit_segment_cmd_index.?].Segment;
const dyld_info = &self.load_commands.items[self.dyld_info_cmd_index.?].DyldInfoOnly;
const allocated_size = self.allocatedSizeLinkedit(dyld_info.export_off);
const needed_size = mem.alignForwardGeneric(u64, buffer.len, @alignOf(u64));
if (needed_size > allocated_size) {
dyld_info.export_off = 0;
dyld_info.export_off = @intCast(u32, self.findFreeSpaceLinkedit(needed_size, 1, null));
// TODO this might require relocating all following LC_DYLD_INFO_ONLY sections too.
}
dyld_info.export_size = @intCast(u32, needed_size);
log.debug("writing export info from 0x{x} to 0x{x}", .{ dyld_info.export_off, dyld_info.export_off + dyld_info.export_size });
try self.base.file.?.pwriteAll(buffer, dyld_info.export_off);
self.load_commands_dirty = true;
self.export_info_dirty = false;
}
fn writeRebaseInfoTable(self: *MachO) !void {
if (!self.rebase_info_dirty) return;
const tracy = trace(@src());
defer tracy.end();
const size = try rebaseInfoSize(self.extern_lazy_symbols.items());
var buffer = try self.base.allocator.alloc(u8, @intCast(usize, size));
defer self.base.allocator.free(buffer);
var stream = std.io.fixedBufferStream(buffer);
try writeRebaseInfo(self.extern_lazy_symbols.items(), stream.writer());
const linkedit_segment = &self.load_commands.items[self.linkedit_segment_cmd_index.?].Segment;
const dyld_info = &self.load_commands.items[self.dyld_info_cmd_index.?].DyldInfoOnly;
const allocated_size = self.allocatedSizeLinkedit(dyld_info.rebase_off);
const needed_size = mem.alignForwardGeneric(u64, buffer.len, @alignOf(u64));
if (needed_size > allocated_size) {
dyld_info.rebase_off = 0;
dyld_info.rebase_off = @intCast(u32, self.findFreeSpaceLinkedit(needed_size, 1, null));
// TODO this might require relocating all following LC_DYLD_INFO_ONLY sections too.
}
dyld_info.rebase_size = @intCast(u32, needed_size);
log.debug("writing rebase info from 0x{x} to 0x{x}", .{ dyld_info.rebase_off, dyld_info.rebase_off + dyld_info.rebase_size });
try self.base.file.?.pwriteAll(buffer, dyld_info.rebase_off);
self.load_commands_dirty = true;
self.rebase_info_dirty = false;
}
fn writeBindingInfoTable(self: *MachO) !void {
if (!self.binding_info_dirty) return;
const tracy = trace(@src());
defer tracy.end();
const size = try bindInfoSize(self.extern_nonlazy_symbols.items());
var buffer = try self.base.allocator.alloc(u8, @intCast(usize, size));
defer self.base.allocator.free(buffer);
var stream = std.io.fixedBufferStream(buffer);
try writeBindInfo(self.extern_nonlazy_symbols.items(), stream.writer());
const linkedit_segment = self.load_commands.items[self.linkedit_segment_cmd_index.?].Segment;
const dyld_info = &self.load_commands.items[self.dyld_info_cmd_index.?].DyldInfoOnly;
const allocated_size = self.allocatedSizeLinkedit(dyld_info.bind_off);
const needed_size = mem.alignForwardGeneric(u64, buffer.len, @alignOf(u64));
if (needed_size > allocated_size) {
dyld_info.bind_off = 0;
dyld_info.bind_off = @intCast(u32, self.findFreeSpaceLinkedit(needed_size, 1, null));
// TODO this might require relocating all following LC_DYLD_INFO_ONLY sections too.
}
dyld_info.bind_size = @intCast(u32, needed_size);
log.debug("writing binding info from 0x{x} to 0x{x}", .{ dyld_info.bind_off, dyld_info.bind_off + dyld_info.bind_size });
try self.base.file.?.pwriteAll(buffer, dyld_info.bind_off);
self.load_commands_dirty = true;
self.binding_info_dirty = false;
}
fn writeLazyBindingInfoTable(self: *MachO) !void {
if (!self.lazy_binding_info_dirty) return;
const size = try lazyBindInfoSize(self.extern_lazy_symbols.items());
var buffer = try self.base.allocator.alloc(u8, @intCast(usize, size));
defer self.base.allocator.free(buffer);
var stream = std.io.fixedBufferStream(buffer);
try writeLazyBindInfo(self.extern_lazy_symbols.items(), stream.writer());
const linkedit_segment = self.load_commands.items[self.linkedit_segment_cmd_index.?].Segment;
const dyld_info = &self.load_commands.items[self.dyld_info_cmd_index.?].DyldInfoOnly;
const allocated_size = self.allocatedSizeLinkedit(dyld_info.lazy_bind_off);
const needed_size = mem.alignForwardGeneric(u64, buffer.len, @alignOf(u64));
if (needed_size > allocated_size) {
dyld_info.lazy_bind_off = 0;
dyld_info.lazy_bind_off = @intCast(u32, self.findFreeSpaceLinkedit(needed_size, 1, null));
// TODO this might require relocating all following LC_DYLD_INFO_ONLY sections too.
}
dyld_info.lazy_bind_size = @intCast(u32, needed_size);
log.debug("writing lazy binding info from 0x{x} to 0x{x}", .{ dyld_info.lazy_bind_off, dyld_info.lazy_bind_off + dyld_info.lazy_bind_size });
try self.base.file.?.pwriteAll(buffer, dyld_info.lazy_bind_off);
try self.populateLazyBindOffsetsInStubHelper(buffer);
self.load_commands_dirty = true;
self.lazy_binding_info_dirty = false;
}
fn populateLazyBindOffsetsInStubHelper(self: *MachO, buffer: []const u8) !void {
if (self.extern_lazy_symbols.items().len == 0) return;
var stream = std.io.fixedBufferStream(buffer);
var reader = stream.reader();
var offsets = std.ArrayList(u32).init(self.base.allocator);
try offsets.append(0);
defer offsets.deinit();
var valid_block = false;
while (true) {
const inst = reader.readByte() catch |err| switch (err) {
error.EndOfStream => break,
else => return err,
};
const imm: u8 = inst & macho.BIND_IMMEDIATE_MASK;
const opcode: u8 = inst & macho.BIND_OPCODE_MASK;
switch (opcode) {
macho.BIND_OPCODE_DO_BIND => {
valid_block = true;
},
macho.BIND_OPCODE_DONE => {
if (valid_block) {
const offset = try stream.getPos();
try offsets.append(@intCast(u32, offset));
}
valid_block = false;
},
macho.BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM => {
var next = try reader.readByte();
while (next != @as(u8, 0)) {
next = try reader.readByte();
}
},
macho.BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB => {
_ = try std.leb.readULEB128(u64, reader);
},
macho.BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB => {
_ = try std.leb.readULEB128(u64, reader);
},
macho.BIND_OPCODE_SET_ADDEND_SLEB => {
_ = try std.leb.readILEB128(i64, reader);
},
else => {},
}
}
assert(self.extern_lazy_symbols.items().len <= offsets.items.len);
const stub_size: u4 = switch (self.base.options.target.cpu.arch) {
.x86_64 => 10,
.aarch64 => 3 * @sizeOf(u32),
else => unreachable,
};
const off: u4 = switch (self.base.options.target.cpu.arch) {
.x86_64 => 1,
.aarch64 => 2 * @sizeOf(u32),
else => unreachable,
};
var buf: [@sizeOf(u32)]u8 = undefined;
for (self.extern_lazy_symbols.items()) |_, i| {
const placeholder_off = self.stub_helper_stubs_start_off.? + i * stub_size + off;
mem.writeIntLittle(u32, &buf, offsets.items[i]);
try self.base.file.?.pwriteAll(&buf, placeholder_off);
}
}
fn writeStringTable(self: *MachO) !void {
if (!self.string_table_dirty) return;
const tracy = trace(@src());
defer tracy.end();
const symtab = &self.load_commands.items[self.symtab_cmd_index.?].Symtab;
const allocated_size = self.allocatedSizeLinkedit(symtab.stroff);
const needed_size = mem.alignForwardGeneric(u64, self.string_table.items.len, @alignOf(u64));
if (needed_size > allocated_size or self.string_table_needs_relocation) {
symtab.strsize = 0;
symtab.stroff = @intCast(u32, self.findFreeSpaceLinkedit(needed_size, 1, symtab.symoff));
self.string_table_needs_relocation = false;
}
symtab.strsize = @intCast(u32, needed_size);
log.debug("writing string table from 0x{x} to 0x{x}", .{ symtab.stroff, symtab.stroff + symtab.strsize });
try self.base.file.?.pwriteAll(self.string_table.items, symtab.stroff);
self.load_commands_dirty = true;
self.string_table_dirty = false;
}
fn updateLinkeditSegmentSizes(self: *MachO) !void {
if (!self.load_commands_dirty) return;
const tracy = trace(@src());
defer tracy.end();
// Now, we are in position to update __LINKEDIT segment sizes.
// TODO Add checkpointing so that we don't have to do this every single time.
const linkedit_segment = &self.load_commands.items[self.linkedit_segment_cmd_index.?].Segment;
var final_offset = linkedit_segment.inner.fileoff;
if (self.dyld_info_cmd_index) |idx| {
const dyld_info = self.load_commands.items[idx].DyldInfoOnly;
final_offset = std.math.max(final_offset, dyld_info.rebase_off + dyld_info.rebase_size);
final_offset = std.math.max(final_offset, dyld_info.bind_off + dyld_info.bind_size);
final_offset = std.math.max(final_offset, dyld_info.weak_bind_off + dyld_info.weak_bind_size);
final_offset = std.math.max(final_offset, dyld_info.lazy_bind_off + dyld_info.lazy_bind_size);
final_offset = std.math.max(final_offset, dyld_info.export_off + dyld_info.export_size);
}
if (self.function_starts_cmd_index) |idx| {
const fstart = self.load_commands.items[idx].LinkeditData;
final_offset = std.math.max(final_offset, fstart.dataoff + fstart.datasize);
}
if (self.data_in_code_cmd_index) |idx| {
const dic = self.load_commands.items[idx].LinkeditData;
final_offset = std.math.max(final_offset, dic.dataoff + dic.datasize);
}
if (self.dysymtab_cmd_index) |idx| {
const dysymtab = self.load_commands.items[idx].Dysymtab;
const nindirectsize = dysymtab.nindirectsyms * @sizeOf(u32);
final_offset = std.math.max(final_offset, dysymtab.indirectsymoff + nindirectsize);
// TODO Handle more dynamic symbol table sections.
}
if (self.symtab_cmd_index) |idx| {
const symtab = self.load_commands.items[idx].Symtab;
const symsize = symtab.nsyms * @sizeOf(macho.nlist_64);
final_offset = std.math.max(final_offset, symtab.symoff + symsize);
final_offset = std.math.max(final_offset, symtab.stroff + symtab.strsize);
}
const filesize = final_offset - linkedit_segment.inner.fileoff;
linkedit_segment.inner.filesize = filesize;
linkedit_segment.inner.vmsize = mem.alignForwardGeneric(u64, filesize, self.page_size);
try self.base.file.?.pwriteAll(&[_]u8{0}, final_offset);
self.load_commands_dirty = true;
}
/// Writes all load commands and section headers.
fn writeLoadCommands(self: *MachO) !void {
if (!self.load_commands_dirty) return;
var sizeofcmds: u32 = 0;
for (self.load_commands.items) |lc| {
sizeofcmds += lc.cmdsize();
}
var buffer = try self.base.allocator.alloc(u8, sizeofcmds);
defer self.base.allocator.free(buffer);
var writer = std.io.fixedBufferStream(buffer).writer();
for (self.load_commands.items) |lc| {
try lc.write(writer);
}
const off = @sizeOf(macho.mach_header_64);
log.debug("writing {} load commands from 0x{x} to 0x{x}", .{ self.load_commands.items.len, off, off + sizeofcmds });
try self.base.file.?.pwriteAll(buffer, off);
self.load_commands_dirty = false;
}
/// Writes Mach-O file header.
fn writeHeader(self: *MachO) !void {
if (!self.header_dirty) return;
self.header.?.ncmds = @intCast(u32, self.load_commands.items.len);
var sizeofcmds: u32 = 0;
for (self.load_commands.items) |cmd| {
sizeofcmds += cmd.cmdsize();
}
self.header.?.sizeofcmds = sizeofcmds;
log.debug("writing Mach-O header {}", .{self.header.?});
try self.base.file.?.pwriteAll(mem.asBytes(&self.header.?), 0);
self.header_dirty = false;
}
/// Parse MachO contents from existing binary file.
fn parseFromFile(self: *MachO, file: fs.File) !void {
self.base.file = file;
var reader = file.reader();
const header = try reader.readStruct(macho.mach_header_64);
try self.load_commands.ensureCapacity(self.base.allocator, header.ncmds);
var i: u16 = 0;
while (i < header.ncmds) : (i += 1) {
const cmd = try LoadCommand.read(self.base.allocator, reader);
switch (cmd.cmd()) {
macho.LC_SEGMENT_64 => {
const x = cmd.Segment;
if (parseAndCmpName(&x.inner.segname, "__PAGEZERO")) {
self.pagezero_segment_cmd_index = i;
} else if (parseAndCmpName(&x.inner.segname, "__LINKEDIT")) {
self.linkedit_segment_cmd_index = i;
} else if (parseAndCmpName(&x.inner.segname, "__TEXT")) {
self.text_segment_cmd_index = i;
for (x.sections.items) |sect, j| {
if (parseAndCmpName(§.sectname, "__text")) {
self.text_section_index = @intCast(u16, j);
}
}
} else if (parseAndCmpName(&x.inner.segname, "__DATA")) {
self.data_segment_cmd_index = i;
} else if (parseAndCmpName(&x.inner.segname, "__DATA_CONST")) {
self.data_const_segment_cmd_index = i;
}
},
macho.LC_DYLD_INFO_ONLY => {
self.dyld_info_cmd_index = i;
},
macho.LC_SYMTAB => {
self.symtab_cmd_index = i;
},
macho.LC_DYSYMTAB => {
self.dysymtab_cmd_index = i;
},
macho.LC_LOAD_DYLINKER => {
self.dylinker_cmd_index = i;
},
macho.LC_VERSION_MIN_MACOSX, macho.LC_VERSION_MIN_IPHONEOS, macho.LC_VERSION_MIN_WATCHOS, macho.LC_VERSION_MIN_TVOS => {
self.version_min_cmd_index = i;
},
macho.LC_SOURCE_VERSION => {
self.source_version_cmd_index = i;
},
macho.LC_UUID => {
self.uuid_cmd_index = i;
},
macho.LC_MAIN => {
self.main_cmd_index = i;
},
macho.LC_LOAD_DYLIB => {
const x = cmd.Dylib;
if (parseAndCmpName(x.data, mem.spanZ(LIB_SYSTEM_PATH))) {
self.libsystem_cmd_index = i;
}
},
macho.LC_FUNCTION_STARTS => {
self.function_starts_cmd_index = i;
},
macho.LC_DATA_IN_CODE => {
self.data_in_code_cmd_index = i;
},
macho.LC_CODE_SIGNATURE => {
self.code_signature_cmd_index = i;
},
else => {
log.warn("Unknown load command detected: 0x{x}.", .{cmd.cmd()});
},
}
self.load_commands.appendAssumeCapacity(cmd);
}
self.header = header;
}
fn parseAndCmpName(name: []const u8, needle: []const u8) bool {
const len = mem.indexOfScalar(u8, name, @as(u8, 0)) orelse name.len;
return mem.eql(u8, name[0..len], needle);
}
fn parseSymbolTable(self: *MachO) !void {
const symtab = self.load_commands.items[self.symtab_cmd_index.?].Symtab;
const dysymtab = self.load_commands.items[self.dysymtab_cmd_index.?].Dysymtab;
var buffer = try self.base.allocator.alloc(macho.nlist_64, symtab.nsyms);
defer self.base.allocator.free(buffer);
const nread = try self.base.file.?.preadAll(@ptrCast([*]u8, buffer)[0 .. symtab.nsyms * @sizeOf(macho.nlist_64)], symtab.symoff);
assert(@divExact(nread, @sizeOf(macho.nlist_64)) == buffer.len);
try self.local_symbols.ensureCapacity(self.base.allocator, dysymtab.nlocalsym);
try self.global_symbols.ensureCapacity(self.base.allocator, dysymtab.nextdefsym);
try self.undef_symbols.ensureCapacity(self.base.allocator, dysymtab.nundefsym);
self.local_symbols.appendSliceAssumeCapacity(buffer[dysymtab.ilocalsym .. dysymtab.ilocalsym + dysymtab.nlocalsym]);
self.global_symbols.appendSliceAssumeCapacity(buffer[dysymtab.iextdefsym .. dysymtab.iextdefsym + dysymtab.nextdefsym]);
self.undef_symbols.appendSliceAssumeCapacity(buffer[dysymtab.iundefsym .. dysymtab.iundefsym + dysymtab.nundefsym]);
}
fn parseStringTable(self: *MachO) !void {
const symtab = self.load_commands.items[self.symtab_cmd_index.?].Symtab;
var buffer = try self.base.allocator.alloc(u8, symtab.strsize);
defer self.base.allocator.free(buffer);
const nread = try self.base.file.?.preadAll(buffer, symtab.stroff);
assert(nread == buffer.len);
try self.string_table.ensureCapacity(self.base.allocator, symtab.strsize);
self.string_table.appendSliceAssumeCapacity(buffer);
}
fn fixupBindInfo(self: *MachO, dylib_ordinal: u32) !void {
const dyld_info = self.load_commands.items[self.dyld_info_cmd_index.?].DyldInfoOnly;
var buffer = try self.base.allocator.alloc(u8, dyld_info.bind_size);
defer self.base.allocator.free(buffer);
const nread = try self.base.file.?.preadAll(buffer, dyld_info.bind_off);
assert(nread == buffer.len);
try self.fixupInfoCommon(buffer, dylib_ordinal);
try self.base.file.?.pwriteAll(buffer, dyld_info.bind_off);
}
fn fixupLazyBindInfo(self: *MachO, dylib_ordinal: u32) !void {
const dyld_info = self.load_commands.items[self.dyld_info_cmd_index.?].DyldInfoOnly;
var buffer = try self.base.allocator.alloc(u8, dyld_info.lazy_bind_size);
defer self.base.allocator.free(buffer);
const nread = try self.base.file.?.preadAll(buffer, dyld_info.lazy_bind_off);
assert(nread == buffer.len);
try self.fixupInfoCommon(buffer, dylib_ordinal);
try self.base.file.?.pwriteAll(buffer, dyld_info.lazy_bind_off);
}
fn fixupInfoCommon(self: *MachO, buffer: []u8, dylib_ordinal: u32) !void {
var stream = std.io.fixedBufferStream(buffer);
var reader = stream.reader();
while (true) {
const inst = reader.readByte() catch |err| switch (err) {
error.EndOfStream => break,
else => return err,
};
const imm: u8 = inst & macho.BIND_IMMEDIATE_MASK;
const opcode: u8 = inst & macho.BIND_OPCODE_MASK;
switch (opcode) {
macho.BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM => {
var next = try reader.readByte();
while (next != @as(u8, 0)) {
next = try reader.readByte();
}
},
macho.BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB => {
_ = try std.leb.readULEB128(u64, reader);
},
macho.BIND_OPCODE_SET_DYLIB_SPECIAL_IMM, macho.BIND_OPCODE_SET_DYLIB_ORDINAL_IMM => {
// Perform the fixup.
try stream.seekBy(-1);
var writer = stream.writer();
try writer.writeByte(macho.BIND_OPCODE_SET_DYLIB_ORDINAL_IMM | @truncate(u4, dylib_ordinal));
},
macho.BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB => {
_ = try std.leb.readULEB128(u64, reader);
},
macho.BIND_OPCODE_SET_ADDEND_SLEB => {
_ = try std.leb.readILEB128(i64, reader);
},
else => {},
}
}
}
pub fn padToIdeal(actual_size: anytype) @TypeOf(actual_size) {
// TODO https://github.com/ziglang/zig/issues/1284
return std.math.add(@TypeOf(actual_size), actual_size, actual_size / ideal_factor) catch
std.math.maxInt(@TypeOf(actual_size));
} | src/link/MachO.zig |
const std = @import("std");
const mem = std.mem;
const Allocator = mem.Allocator;
const Source = @import("Source.zig");
const Compilation = @import("Compilation.zig");
const Tree = @import("Tree.zig");
const util = @import("util.zig");
const is_windows = @import("builtin").os.tag == .windows;
const Diagnostics = @This();
pub const Message = struct {
tag: Tag,
kind: Kind = undefined,
loc: Source.Location = .{},
extra: Extra = .{ .none = {} },
pub const Extra = union {
str: []const u8,
tok_id: struct {
expected: Tree.Token.Id,
actual: Tree.Token.Id,
},
tok_id_expected: Tree.Token.Id,
arguments: struct {
expected: u32,
actual: u32,
},
codepoints: struct {
actual: u21,
resembles: u21,
},
actual_codepoint: u21,
unsigned: u64,
signed: i64,
none: void,
};
};
pub const Tag = blk: {
const decls = @typeInfo(messages).Struct.decls;
var enum_fields: [decls.len]std.builtin.TypeInfo.EnumField = undefined;
inline for (decls) |decl, i| {
enum_fields[i] = .{
.name = decl.name,
.value = i,
};
}
break :blk @Type(.{
.Enum = .{
.layout = .Auto,
.tag_type = std.math.IntFittingRange(0, decls.len - 1),
.fields = &enum_fields,
.decls = &.{},
.is_exhaustive = true,
},
});
};
// u4 to avoid any possible packed struct issues
pub const Kind = enum(u4) { @"fatal error", @"error", note, warning, off, default };
pub const Options = packed struct {
// do not directly use these, instead add `const NAME = true;`
all: Kind = .default,
extra: Kind = .default,
pedantic: Kind = .default,
@"unsupported-pragma": Kind = .default,
@"c99-extensions": Kind = .default,
@"implicit-int": Kind = .default,
@"duplicate-decl-specifier": Kind = .default,
@"missing-declaration": Kind = .default,
@"extern-initializer": Kind = .default,
@"implicit-function-declaration": Kind = .default,
@"unused-value": Kind = .default,
@"unreachable-code": Kind = .default,
@"unknown-warning-option": Kind = .default,
@"gnu-empty-struct": Kind = .default,
@"gnu-alignof-expression": Kind = .default,
@"macro-redefined": Kind = .default,
@"generic-qual-type": Kind = .default,
multichar: Kind = .default,
@"pointer-integer-compare": Kind = .default,
@"compare-distinct-pointer-types": Kind = .default,
@"literal-conversion": Kind = .default,
@"cast-qualifiers": Kind = .default,
@"array-bounds": Kind = .default,
@"int-conversion": Kind = .default,
@"pointer-type-mismatch": Kind = .default,
@"c2x-extensions": Kind = .default,
@"incompatible-pointer-types": Kind = .default,
@"excess-initializers": Kind = .default,
@"division-by-zero": Kind = .default,
@"initializer-overrides": Kind = .default,
@"incompatible-pointer-types-discards-qualifiers": Kind = .default,
@"unknown-attributes": Kind = .default,
@"ignored-attributes": Kind = .default,
@"builtin-macro-redefined": Kind = .default,
@"gnu-label-as-value": Kind = .default,
@"malformed-warning-check": Kind = .default,
@"#pragma-messages": Kind = .default,
@"newline-eof": Kind = .default,
@"empty-translation-unit": Kind = .default,
@"implicitly-unsigned-literal": Kind = .default,
@"c99-compat": Kind = .default,
@"unicode-zero-width": Kind = .default,
@"unicode-homoglyph": Kind = .default,
@"return-type": Kind = .default,
@"dollar-in-identifier-extension": Kind = .default,
@"unknown-pragmas": Kind = .default,
@"predefined-identifier-outside-function": Kind = .default,
@"many-braces-around-scalar-init": Kind = .default,
uninitialized: Kind = .default,
@"gnu-statement-expression": Kind = .default,
@"gnu-imaginary-constant": Kind = .default,
@"ignored-qualifiers": Kind = .default,
@"integer-overflow": Kind = .default,
@"extra-semi": Kind = .default,
@"gnu-binary-literal": Kind = .default,
@"variadic-macros": Kind = .default,
varargs: Kind = .default,
@"#warnings": Kind = .default,
};
const messages = struct {
const todo = struct { // Maybe someday this will no longer be needed.
const msg = "TODO: {s}";
const extra = .str;
const kind = .@"error";
};
const error_directive = struct {
const msg = "{s}";
const extra = .str;
const kind = .@"error";
};
const warning_directive = struct {
const msg = "{s}";
const opt = "#warnings";
const extra = .str;
const kind = .@"warning";
};
const elif_without_if = struct {
const msg = "#elif without #if";
const kind = .@"error";
};
const elif_after_else = struct {
const msg = "#elif after #else";
const kind = .@"error";
};
const else_without_if = struct {
const msg = "#else without #if";
const kind = .@"error";
};
const else_after_else = struct {
const msg = "#else after #else";
const kind = .@"error";
};
const endif_without_if = struct {
const msg = "#endif without #if";
const kind = .@"error";
};
const unknown_pragma = struct {
const msg = "unknown pragma ignored";
const opt = "unknown-pragmas";
const kind = .off;
const all = true;
};
const line_simple_digit = struct {
const msg = "#line directive requires a simple digit sequence";
const kind = .@"error";
};
const line_invalid_filename = struct {
const msg = "invalid filename for #line directive";
const kind = .@"error";
};
const unterminated_conditional_directive = struct {
const msg = "unterminated conditional directive";
const kind = .@"error";
};
const invalid_preprocessing_directive = struct {
const msg = "invalid preprocessing directive";
const kind = .@"error";
};
const macro_name_missing = struct {
const msg = "macro name missing";
const kind = .@"error";
};
const extra_tokens_directive_end = struct {
const msg = "extra tokens at end of macro directive";
const kind = .@"error";
};
const expected_value_in_expr = struct {
const msg = "expected value in expression";
const kind = .@"error";
};
const closing_paren = struct {
const msg = "expected closing ')'";
const kind = .@"error";
};
const to_match_paren = struct {
const msg = "to match this '('";
const kind = .note;
};
const to_match_brace = struct {
const msg = "to match this '{'";
const kind = .note;
};
const to_match_bracket = struct {
const msg = "to match this '['";
const kind = .note;
};
const header_str_closing = struct {
const msg = "expected closing '>'";
const kind = .@"error";
};
const header_str_match = struct {
const msg = "to match this '<'";
const kind = .note;
};
const string_literal_in_pp_expr = struct {
const msg = "string literal in preprocessor expression";
const kind = .@"error";
};
const float_literal_in_pp_expr = struct {
const msg = "floating point literal in preprocessor expression";
const kind = .@"error";
};
const defined_as_macro_name = struct {
const msg = "'defined' cannot be used as a macro name";
const kind = .@"error";
};
const macro_name_must_be_identifier = struct {
const msg = "macro name must be an identifier";
const kind = .@"error";
};
const whitespace_after_macro_name = struct {
const msg = "ISO C99 requires whitespace after the macro name";
const opt = "c99-extensions";
const kind = .warning;
};
const hash_hash_at_start = struct {
const msg = "'##' cannot appear at the start of a macro expansion";
const kind = .@"error";
};
const hash_hash_at_end = struct {
const msg = "'##' cannot appear at the end of a macro expansion";
const kind = .@"error";
};
const pasting_formed_invalid = struct {
const msg = "pasting formed '{s}', an invalid preprocessing token";
const extra = .str;
const kind = .@"error";
};
const missing_paren_param_list = struct {
const msg = "missing ')' in macro parameter list";
const kind = .@"error";
};
const unterminated_macro_param_list = struct {
const msg = "unterminated macro param list";
const kind = .@"error";
};
const invalid_token_param_list = struct {
const msg = "invalid token in macro parameter list";
const kind = .@"error";
};
const expected_comma_param_list = struct {
const msg = "expected comma in macro parameter list";
const kind = .@"error";
};
const hash_not_followed_param = struct {
const msg = "'#' is not followed by a macro parameter";
const kind = .@"error";
};
const expected_filename = struct {
const msg = "expected \"FILENAME\" or <FILENAME>";
const kind = .@"error";
};
const empty_filename = struct {
const msg = "empty filename";
const kind = .@"error";
};
const expected_invalid = struct {
const msg = "expected '{s}', found invalid bytes";
const extra = .tok_id_expected;
const kind = .@"error";
};
const expected_eof = struct {
const msg = "expected '{s}' before end of file";
const extra = .tok_id_expected;
const kind = .@"error";
};
const expected_token = struct {
const msg = "expected '{s}', found '{s}'";
const extra = .tok_id;
const kind = .@"error";
};
const expected_expr = struct {
const msg = "expected expression";
const kind = .@"error";
};
const expected_integer_constant_expr = struct {
const msg = "expression is not an integer constant expression";
const kind = .@"error";
};
const missing_type_specifier = struct {
const msg = "type specifier missing, defaults to 'int'";
const opt = "implicit-int";
const kind = .warning;
const all = true;
};
const multiple_storage_class = struct {
const msg = "cannot combine with previous '{s}' declaration specifier";
const extra = .str;
const kind = .@"error";
};
const static_assert_failure = struct {
const msg = "static assertion failed";
const kind = .@"error";
};
const static_assert_failure_message = struct {
const msg = "static assertion failed {s}";
const extra = .str;
const kind = .@"error";
};
const expected_type = struct {
const msg = "expected a type";
const kind = .@"error";
};
const cannot_combine_spec = struct {
const msg = "cannot combine with previous '{s}' specifier";
const extra = .str;
const kind = .@"error";
};
const duplicate_decl_spec = struct {
const msg = "duplicate '{s}' declaration specifier";
const extra = .str;
const opt = "duplicate-decl-specifier";
const kind = .warning;
const all = true;
};
const restrict_non_pointer = struct {
const msg = "restrict requires a pointer or reference ('{s}' is invalid)";
const extra = .str;
const kind = .@"error";
};
const expected_external_decl = struct {
const msg = "expected external declaration";
const kind = .@"error";
};
const expected_ident_or_l_paren = struct {
const msg = "expected identifier or '('";
const kind = .@"error";
};
const missing_declaration = struct {
const msg = "declaration does not declare anything";
const opt = "missing-declaration";
const kind = .warning;
};
const func_not_in_root = struct {
const msg = "function definition is not allowed here";
const kind = .@"error";
};
const illegal_initializer = struct {
const msg = "illegal initializer (only variables can be initialized)";
const kind = .@"error";
};
const extern_initializer = struct {
const msg = "extern variable has initializer";
const opt = "extern-initializer";
const kind = .warning;
};
const spec_from_typedef = struct {
const msg = "'{s}' came from typedef";
const extra = .str;
const kind = .note;
};
const type_is_invalid = struct {
const msg = "'{s}' is invalid";
const extra = .str;
const kind = .@"error";
};
const param_before_var_args = struct {
const msg = "ISO C requires a named parameter before '...'";
const kind = .@"error";
};
const void_only_param = struct {
const msg = "'void' must be the only parameter if specified";
const kind = .@"error";
};
const void_param_qualified = struct {
const msg = "'void' parameter cannot be qualified";
const kind = .@"error";
};
const void_must_be_first_param = struct {
const msg = "'void' must be the first parameter if specified";
const kind = .@"error";
};
const invalid_storage_on_param = struct {
const msg = "invalid storage class on function parameter";
const kind = .@"error";
};
const threadlocal_non_var = struct {
const msg = "_Thread_local only allowed on variables";
const kind = .@"error";
};
const func_spec_non_func = struct {
const msg = "'{s}' can only appear on functions";
const extra = .str;
const kind = .@"error";
};
const illegal_storage_on_func = struct {
const msg = "illegal storage class on function";
const kind = .@"error";
};
const illegal_storage_on_global = struct {
const msg = "illegal storage class on global variable";
const kind = .@"error";
};
const expected_stmt = struct {
const msg = "expected statement";
const kind = .@"error";
};
const func_cannot_return_func = struct {
const msg = "function cannot return a function";
const kind = .@"error";
};
const func_cannot_return_array = struct {
const msg = "function cannot return an array";
const kind = .@"error";
};
const undeclared_identifier = struct {
const msg = "use of undeclared identifier '{s}'";
const extra = .str;
const kind = .@"error";
};
const not_callable = struct {
const msg = "cannot call non function type '{s}'";
const extra = .str;
const kind = .@"error";
};
const unsupported_str_cat = struct {
const msg = "unsupported string literal concatenation";
const kind = .@"error";
};
const static_func_not_global = struct {
const msg = "static functions must be global";
const kind = .@"error";
};
const implicit_func_decl = struct {
const msg = "implicit declaration of function '{s}' is invalid in C99";
const extra = .str;
const opt = "implicit-function-declaration";
const kind = .warning;
const all = true;
};
const unknown_builtin = struct {
const msg = "use of unknown builtin '{s}'";
const extra = .str;
const opt = "implicit-function-declaration";
const kind = .@"error";
const all = true;
};
const expected_param_decl = struct {
const msg = "expected parameter declaration";
const kind = .@"error";
};
const invalid_old_style_params = struct {
const msg = "identifier parameter lists are only allowed in function definitions";
const kind = .@"error";
};
const expected_fn_body = struct {
const msg = "expected function body after function declaration";
const kind = .@"error";
};
const invalid_void_param = struct {
const msg = "parameter cannot have void type";
const kind = .@"error";
};
const unused_value = struct {
const msg = "expression result unused";
const opt = "unused-value";
const kind = .warning;
const all = true;
};
const continue_not_in_loop = struct {
const msg = "'continue' statement not in a loop";
const kind = .@"error";
};
const break_not_in_loop_or_switch = struct {
const msg = "'break' statement not in a loop or a switch";
const kind = .@"error";
};
const unreachable_code = struct {
const msg = "unreachable code";
const opt = "unreachable-code";
const kind = .warning;
const all = true;
};
const duplicate_label = struct {
const msg = "duplicate label '{s}'";
const extra = .str;
const kind = .@"error";
};
const previous_label = struct {
const msg = "previous definition of label '{s}' was here";
const extra = .str;
const kind = .note;
};
const undeclared_label = struct {
const msg = "use of undeclared label '{s}'";
const extra = .str;
const kind = .@"error";
};
const case_not_in_switch = struct {
const msg = "'{s}' statement not in a switch statement";
const extra = .str;
const kind = .@"error";
};
const duplicate_switch_case_signed = struct {
const msg = "duplicate case value '{d}'";
const extra = .signed;
const kind = .@"error";
};
const duplicate_switch_case_unsigned = struct {
const msg = "duplicate case value '{d}'";
const extra = .unsigned;
const kind = .@"error";
};
const multiple_default = struct {
const msg = "multiple default cases in the same switch";
const kind = .@"error";
};
const previous_case = struct {
const msg = "previous case defined here";
const kind = .note;
};
const expected_arguments = struct {
const msg = "expected {d} argument(s) got {d}";
const extra = .arguments;
const kind = .@"error";
};
const expected_arguments_old = struct {
const msg = expected_arguments.msg;
const extra = .arguments;
const kind = .warning;
};
const expected_at_least_arguments = struct {
const msg = "expected at least {d} argument(s) got {d}";
const extra = .arguments;
const kind = .warning;
};
const invalid_static_star = struct {
const msg = "'static' may not be used with an unspecified variable length array size";
const kind = .@"error";
};
const static_non_param = struct {
const msg = "'static' used outside of function parameters";
const kind = .@"error";
};
const array_qualifiers = struct {
const msg = "type qualifier in non parameter array type";
const kind = .@"error";
};
const star_non_param = struct {
const msg = "star modifier used outside of function parameters";
const kind = .@"error";
};
const variable_len_array_file_scope = struct {
const msg = "variable length arrays not allowed at file scope";
const kind = .@"error";
};
const useless_static = struct {
const msg = "'static' useless without a constant size";
const kind = .warning;
const w_extra = true;
};
const negative_array_size = struct {
const msg = "array size must be 0 or greater";
const kind = .@"error";
};
const array_incomplete_elem = struct {
const msg = "array has incomplete element type '{s}'";
const extra = .str;
const kind = .@"error";
};
const array_func_elem = struct {
const msg = "arrays cannot have functions as their element type";
const kind = .@"error";
};
const static_non_outermost_array = struct {
const msg = "'static' used in non-outermost array type";
const kind = .@"error";
};
const qualifier_non_outermost_array = struct {
const msg = "type qualifier used in non-outermost array type";
const kind = .@"error";
};
const unterminated_macro_arg_list = struct {
const msg = "unterminated function macro argument list";
const kind = .@"error";
};
const unknown_warning = struct {
const msg = "unknown warning '{s}'";
const extra = .str;
const opt = "unknown-warning-option";
const kind = .warning;
};
const overflow_signed = struct {
const msg = "overflow in expression; result is '{d}'";
const extra = .signed;
const opt = "integer-overflow";
const kind = .warning;
};
const overflow_unsigned = struct {
const msg = overflow_signed.msg;
const extra = .unsigned;
const opt = "integer-overflow";
const kind = .warning;
};
const int_literal_too_big = struct {
const msg = "integer literal is too large to be represented in any integer type";
const kind = .@"error";
};
const indirection_ptr = struct {
const msg = "indirection requires pointer operand";
const kind = .@"error";
};
const addr_of_rvalue = struct {
const msg = "cannot take the address of an rvalue";
const kind = .@"error";
};
const not_assignable = struct {
const msg = "expression is not assignable";
const kind = .@"error";
};
const ident_or_l_brace = struct {
const msg = "expected identifier or '{'";
const kind = .@"error";
};
const empty_enum = struct {
const msg = "empty enum is invalid";
const kind = .@"error";
};
const redefinition = struct {
const msg = "redefinition of '{s}'";
const extra = .str;
const kind = .@"error";
};
const previous_definition = struct {
const msg = "previous definition is here";
const kind = .note;
};
const expected_identifier = struct {
const msg = "expected identifier";
const kind = .@"error";
};
const expected_str_literal = struct {
const msg = "expected string literal for diagnostic message in static_assert";
const kind = .@"error";
};
const expected_str_literal_in = struct {
const msg = "expected string literal in '{s}'";
const extra = .str;
const kind = .@"error";
};
const parameter_missing = struct {
const msg = "parameter named '{s}' is missing";
const extra = .str;
const kind = .@"error";
};
const empty_record = struct {
const msg = "empty {s} is a GNU extension";
const extra = .str;
const opt = "gnu-empty-struct";
const kind = .off;
const pedantic = true;
};
const wrong_tag = struct {
const msg = "use of '{s}' with tag type that does not match previous definition";
const extra = .str;
const kind = .@"error";
};
const expected_parens_around_typename = struct {
const msg = "expected parentheses around type name";
const kind = .@"error";
};
const alignof_expr = struct {
const msg = "'_Alignof' applied to an expression is a GNU extension";
const opt = "gnu-alignof-expression";
const kind = .warning;
const suppress_gnu = true;
};
const invalid_sizeof = struct {
const msg = "invalid application of 'sizeof' to an incomplete type '{s}'";
const extra = .str;
const kind = .@"error";
};
const macro_redefined = struct {
const msg = "'{s}' macro redefined";
const extra = .str;
const opt = "macro-redefined";
const kind = .warning;
};
const generic_qual_type = struct {
const msg = "generic association with qualifiers cannot be matched with";
const opt = "generic-qual-type";
const kind = .warning;
};
const generic_duplicate = struct {
const msg = "type '{s}' in generic association compatible with previously specified type";
const extra = .str;
const kind = .@"error";
};
const generic_duplicate_default = struct {
const msg = "duplicate default generic association";
const kind = .@"error";
};
const generic_no_match = struct {
const msg = "controlling expression type '{s}' not compatible with any generic association type";
const extra = .str;
const kind = .@"error";
};
const escape_sequence_overflow = struct {
const msg = "escape sequence out of range";
const kind = .@"error";
};
const invalid_universal_character = struct {
const msg = "invalid universal character";
const kind = .@"error";
};
const multichar_literal = struct {
const msg = "multi-character character constant";
const opt = "multichar";
const kind = .warning;
const all = true;
};
const unicode_multichar_literal = struct {
const msg = "Unicode character literals may not contain multiple characters";
const kind = .@"error";
};
const wide_multichar_literal = struct {
const msg = "extraneous characters in character constant ignored";
const kind = .warning;
};
const char_lit_too_wide = struct {
const msg = "character constant too long for its type";
const kind = .warning;
const all = true;
};
const char_too_large = struct {
const msg = "character too large for enclosing character literal type";
const kind = .@"error";
};
const must_use_struct = struct {
const msg = "must use 'struct' tag to refer to type '{s}'";
const extra = .str;
const kind = .@"error";
};
const must_use_union = struct {
const msg = "must use 'union' tag to refer to type '{s}'";
const extra = .str;
const kind = .@"error";
};
const must_use_enum = struct {
const msg = "must use 'enum' tag to refer to type '{s}'";
const extra = .str;
const kind = .@"error";
};
const redefinition_different_sym = struct {
const msg = "redefinition of '{s}' as different kind of symbol";
const extra = .str;
const kind = .@"error";
};
const redefinition_incompatible = struct {
const msg = "redefinition of '{s}' with a different type";
const extra = .str;
const kind = .@"error";
};
const redefinition_of_parameter = struct {
const msg = "redefinition of parameter '{s}'";
const extra = .str;
const kind = .@"error";
};
const invalid_bin_types = struct {
const msg = "invalid operands to binary expression ({s})";
const extra = .str;
const kind = .@"error";
};
const comparison_ptr_int = struct {
const msg = "comparison between pointer and integer ({s})";
const extra = .str;
const opt = "pointer-integer-compare";
const kind = .warning;
};
const comparison_distinct_ptr = struct {
const msg = "comparison of distinct pointer types ({s})";
const extra = .str;
const opt = "compare-distinct-pointer-types";
const kind = .warning;
};
const incompatible_pointers = struct {
const msg = "incompatible pointer types ({s})";
const extra = .str;
const kind = .@"error";
};
const invalid_argument_un = struct {
const msg = "invalid argument type '{s}' to unary expression";
const extra = .str;
const kind = .@"error";
};
const incompatible_assign = struct {
const msg = "assignment to {s}";
const extra = .str;
const kind = .@"error";
};
const implicit_ptr_to_int = struct {
const msg = "implicit pointer to integer conversion from {s}";
const extra = .str;
const opt = "int-conversion";
const kind = .warning;
};
const invalid_cast_to_float = struct {
const msg = "pointer cannot be cast to type '{s}'";
const extra = .str;
const kind = .@"error";
};
const invalid_cast_to_pointer = struct {
const msg = "operand of type '{s}' cannot be cast to a pointer type";
const extra = .str;
const kind = .@"error";
};
const invalid_cast_type = struct {
const msg = "cannot cast to non arithmetic or pointer type '{s}'";
const extra = .str;
const kind = .@"error";
};
const qual_cast = struct {
const msg = "cast to type '{s}' will not preserve qualifiers";
const extra = .str;
const opt = "cast-qualifiers";
const kind = .warning;
};
const invalid_index = struct {
const msg = "array subscript is not an integer";
const kind = .@"error";
};
const invalid_subscript = struct {
const msg = "subscripted value is not an array or pointer";
const kind = .@"error";
};
const array_after = struct {
const msg = "array index {d} is past the end of the array";
const extra = .unsigned;
const opt = "array-bounds";
const kind = .warning;
};
const array_before = struct {
const msg = "array index {d} is before the beginning of the array";
const extra = .signed;
const opt = "array-bounds";
const kind = .warning;
};
const statement_int = struct {
const msg = "statement requires expression with integer type ('{s}' invalid)";
const extra = .str;
const kind = .@"error";
};
const statement_scalar = struct {
const msg = "statement requires expression with scalar type ('{s}' invalid)";
const extra = .str;
const kind = .@"error";
};
const func_should_return = struct {
const msg = "non-void function '{s}' should return a value";
const extra = .str;
const opt = "return-type";
const kind = .@"error";
const all = true;
};
const incompatible_return = struct {
const msg = "returning '{s}' from a function with incompatible result type";
const extra = .str;
const kind = .@"error";
};
const implicit_int_to_ptr = struct {
const msg = "implicit integer to pointer conversion from {s}";
const extra = .str;
const opt = "int-conversion";
const kind = .warning;
};
const func_does_not_return = struct {
const msg = "non-void function '{s}' does not return a value";
const extra = .str;
const opt = "return-type";
const kind = .warning;
const all = true;
};
const void_func_returns_value = struct {
const msg = "void function '{s}' should not return a value";
const extra = .str;
const opt = "return-type";
const kind = .@"error";
const all = true;
};
const incompatible_param = struct {
const msg = "passing '{s}' to parameter of incompatible type";
const extra = .str;
const kind = .@"error";
};
const parameter_here = struct {
const msg = "passing argument to parameter here";
const kind = .note;
};
const atomic_array = struct {
const msg = "atomic cannot be applied to array type '{s}'";
const extra = .str;
const kind = .@"error";
};
const atomic_func = struct {
const msg = "atomic cannot be applied to function type '{s}'";
const extra = .str;
const kind = .@"error";
};
const atomic_incomplete = struct {
const msg = "atomic cannot be applied to incomplete type '{s}'";
const extra = .str;
const kind = .@"error";
};
const addr_of_register = struct {
const msg = "address of register variable requested";
const kind = .@"error";
};
const variable_incomplete_ty = struct {
const msg = "variable has incomplete type '{s}'";
const extra = .str;
const kind = .@"error";
};
const parameter_incomplete_ty = struct {
const msg = "parameter has incomplete type '{s}'";
const extra = .str;
const kind = .@"error";
};
const deref_incomplete_ty_ptr = struct {
const msg = "dereferencing pointer to incomplete type '{s}'";
const extra = .str;
const kind = .@"error";
};
const alignas_on_func = struct {
const msg = "'_Alignas' attribute only applies to variables and fields";
const kind = .@"error";
};
const alignas_on_param = struct {
const msg = "'_Alignas' attribute cannot be applied to a function parameter";
const kind = .@"error";
};
const minimum_alignment = struct {
const msg = "requested alignment is less than minimum alignment of {d}";
const extra = .unsigned;
const kind = .@"error";
};
const maximum_alignment = struct {
const msg = "requested alignment of {d} is too large";
const extra = .unsigned;
const kind = .@"error";
};
const negative_alignment = struct {
const msg = "requested negative alignment of {d} is invalid";
const extra = .signed;
const kind = .@"error";
};
const align_ignored = struct {
const msg = "'_Alignas' attribute is ignored here";
const kind = .warning;
};
const zero_align_ignored = struct {
const msg = "requested alignment of zero is ignored";
const kind = .warning;
};
const non_pow2_align = struct {
const msg = "requested alignment is not a power of 2";
const kind = .@"error";
};
const pointer_mismatch = struct {
const msg = "pointer type mismatch ({s})";
const extra = .str;
const opt = "pointer-type-mismatch";
const kind = .warning;
};
const static_assert_not_constant = struct {
const msg = "static_assert expression is not an integral constant expression";
const kind = .@"error";
};
const static_assert_missing_message = struct {
const msg = "static_assert with no message is a C2X extension";
const opt = "c2x-extensions";
const kind = .warning;
const suppress_version = .c2x;
};
const unbound_vla = struct {
const msg = "variable length array must be bound in function definition";
const kind = .@"error";
};
const array_too_large = struct {
const msg = "array is too large";
const kind = .@"error";
};
const incompatible_ptr_init = struct {
const msg = "incompatible pointer types initializing {s}";
const extra = .str;
const opt = "incompatible-pointer-types";
const kind = .warning;
};
const incompatible_ptr_assign = struct {
const msg = "incompatible pointer types assigning to {s}";
const extra = .str;
const opt = "incompatible-pointer-types";
const kind = .warning;
};
const vla_init = struct {
const msg = "variable-sized object may not be initialized";
const kind = .@"error";
};
const func_init = struct {
const msg = "illegal initializer type";
const kind = .@"error";
};
const incompatible_init = struct {
const msg = "initializing {s}";
const extra = .str;
const kind = .@"error";
};
const empty_scalar_init = struct {
const msg = "scalar initializer cannot be empty";
const kind = .@"error";
};
const excess_scalar_init = struct {
const msg = "excess elements in scalar initializer";
const opt = "excess-initializers";
const kind = .warning;
};
const excess_str_init = struct {
const msg = "excess elements in string initializer";
const opt = "excess-initializers";
const kind = .warning;
};
const excess_struct_init = struct {
const msg = "excess elements in struct initializer";
const opt = "excess-initializers";
const kind = .warning;
};
const excess_array_init = struct {
const msg = "excess elements in array initializer";
const opt = "excess-initializers";
const kind = .warning;
};
const str_init_too_long = struct {
const msg = "initializer-string for char array is too long";
const opt = "excess-initializers";
const kind = .warning;
};
const arr_init_too_long = struct {
const msg = "cannot initialize type ({s})";
const extra = .str;
const kind = .@"error";
};
const invalid_typeof = struct {
const msg = "'{s} typeof' is invalid";
const extra = .str;
const kind = .@"error";
};
const division_by_zero = struct {
const msg = "{s} by zero is undefined";
const extra = .str;
const opt = "division-by-zero";
const kind = .warning;
};
const division_by_zero_macro = struct {
const msg = "{s} by zero in preprocessor expression";
const extra = .str;
const kind = .@"error";
};
const builtin_choose_cond = struct {
const msg = "'__builtin_choose_expr' requires a constant expression";
const kind = .@"error";
};
const alignas_unavailable = struct {
const msg = "'_Alignas' attribute requires integer constant expression";
const kind = .@"error";
};
const case_val_unavailable = struct {
const msg = "case value must be an integer constant expression";
const kind = .@"error";
};
const enum_val_unavailable = struct {
const msg = "enum value must be an integer constant expression";
const kind = .@"error";
};
const incompatible_array_init = struct {
const msg = "cannot initialize array of type {s}";
const extra = .str;
const kind = .@"error";
};
const array_init_str = struct {
const msg = "array initializer must be an initializer list or wide string literal";
const kind = .@"error";
};
const initializer_overrides = struct {
const msg = "initializer overrides previous initialization";
const opt = "initializer-overrides";
const kind = .warning;
const w_extra = true;
};
const previous_initializer = struct {
const msg = "previous initialization";
const kind = .note;
};
const invalid_array_designator = struct {
const msg = "array designator used for non-array type '{s}'";
const extra = .str;
const kind = .@"error";
};
const negative_array_designator = struct {
const msg = "array designator value {d} is negative";
const extra = .signed;
const kind = .@"error";
};
const oob_array_designator = struct {
const msg = "array designator index {d} exceeds array bounds";
const extra = .unsigned;
const kind = .@"error";
};
const invalid_field_designator = struct {
const msg = "field designator used for non-record type '{s}'";
const extra = .str;
const kind = .@"error";
};
const no_such_field_designator = struct {
const msg = "record type has no field named '{s}'";
const extra = .str;
const kind = .@"error";
};
const empty_aggregate_init_braces = struct {
const msg = "initializer for aggregate with no elements requires explicit braces";
const kind = .@"error";
};
const ptr_init_discards_quals = struct {
const msg = "initializing {s} discards qualifiers";
const extra = .str;
const opt = "incompatible-pointer-types-discards-qualifiers";
const kind = .warning;
};
const ptr_assign_discards_quals = struct {
const msg = "assigning to {s} discards qualifiers";
const extra = .str;
const opt = "incompatible-pointer-types-discards-qualifiers";
const kind = .warning;
};
const unknown_attribute = struct {
const msg = "unknown attribute '{s}' ignored";
const extra = .str;
const opt = "unknown-attributes";
const kind = .warning;
};
const ignored_attribute = struct {
const msg = "{s}";
const extra = .str;
const opt = "ignored-attributes";
const kind = .warning;
};
const invalid_fallthrough = struct {
const msg = "fallthrough annotation does not directly precede switch label";
const kind = .@"error";
};
const cannot_apply_attribute_to_statement = struct {
const msg = "attribute cannot be applied to a statement";
const kind = .@"error";
};
const builtin_macro_redefined = struct {
const msg = "redefining builtin macro";
const opt = "builtin-macro-redefined";
const kind = .warning;
};
const feature_check_requires_identifier = struct {
const msg = "builtin feature check macro requires a parenthesized identifier";
const kind = .@"error";
};
const missing_tok_builtin = struct {
const msg = "missing '{s}', after builtin feature-check macro";
const extra = .tok_id_expected;
const kind = .@"error";
};
const gnu_label_as_value = struct {
const msg = "use of GNU address-of-label extension";
const opt = "gnu-label-as-value";
const kind = .off;
const pedantic = true;
};
const expected_record_ty = struct {
const msg = "member reference base type '{s}' is not a structure or union";
const extra = .str;
const kind = .@"error";
};
const member_expr_not_ptr = struct {
const msg = "member reference type '{s}' is not a pointer; did you mean to use '.'?";
const extra = .str;
const kind = .@"error";
};
const member_expr_ptr = struct {
const msg = "member reference type '{s}' is a pointer; did you mean to use '->'?";
const extra = .str;
const kind = .@"error";
};
const no_such_member = struct {
const msg = "no member named {s}";
const extra = .str;
const kind = .@"error";
};
const malformed_warning_check = struct {
const msg = "{s} expected option name (e.g. \"-Wundef\")";
const extra = .str;
const opt = "malformed-warning-check";
const kind = .warning;
const all = true;
};
const invalid_computed_goto = struct {
const msg = "computed goto in function with no address-of-label expressions";
const kind = .@"error";
};
const pragma_warning_message = struct {
const msg = "{s}";
const extra = .str;
const opt = "#pragma-messages";
const kind = .warning;
};
const pragma_error_message = struct {
const msg = "{s}";
const extra = .str;
const kind = .@"error";
};
const pragma_message = struct {
const msg = "#pragma message: {s}";
const extra = .str;
const kind = .note;
};
const pragma_requires_string_literal = struct {
const msg = "pragma {s} requires string literal";
const extra = .str;
const kind = .@"error";
};
const poisoned_identifier = struct {
const msg = "attempt to use a poisoned identifier";
const kind = .@"error";
};
const pragma_poison_identifier = struct {
const msg = "can only poison identifier tokens";
const kind = .@"error";
};
const pragma_poison_macro = struct {
const msg = "poisoning existing macro";
const kind = .warning;
};
const newline_eof = struct {
const msg = "no newline at end of file";
const opt = "newline-eof";
const kind = .off;
const pedantic = true;
};
const empty_translation_unit = struct {
const msg = "ISO C requires a translation unit to contain at least one declaration";
const opt = "empty-translation-unit";
const kind = .off;
const pedantic = true;
};
const omitting_parameter_name = struct {
const msg = "omitting the parameter name in a function definition is a C2x extension";
const opt = "c2x-extensions";
const kind = .warning;
const suppress_version = .c2x;
};
const non_int_bitfield = struct {
const msg = "bit-field has non-integer type '{s}'";
const extra = .str;
const kind = .@"error";
};
const negative_bitwidth = struct {
const msg = "bit-field has negative width ({d})";
const extra = .signed;
const kind = .@"error";
};
const zero_width_named_field = struct {
const msg = "named bit-field has zero width";
const kind = .@"error";
};
const bitfield_too_big = struct {
const msg = "width of bit-field exceeds width of its type";
const kind = .@"error";
};
const invalid_utf8 = struct {
const msg = "source file is not valid UTF-8";
const kind = .@"error";
};
const implicitly_unsigned_literal = struct {
const msg = "integer literal is too large to be represented in a signed integer type, interpreting as unsigned";
const opt = "implicitly-unsigned-literal";
const kind = .warning;
};
const invalid_preproc_operator = struct {
const msg = "token is not a valid binary operator in a preprocessor subexpression";
const kind = .@"error";
};
const invalid_preproc_expr_start = struct {
const msg = "invalid token at start of a preprocessor expression";
const kind = .@"error";
};
const c99_compat = struct {
const msg = "using this character in an identifier is incompatible with C99";
const opt = "c99-compat";
const kind = .off;
};
const unicode_zero_width = struct {
const msg = "identifier contains Unicode character <U+{X:0>4}> that is invisible in some environments";
const opt = "unicode-homoglyph";
const extra = .actual_codepoint;
const kind = .warning;
};
const unicode_homoglyph = struct {
const msg = "treating Unicode character <U+{X:0>4}> as identifier character rather than as '{u}' symbol";
const extra = .codepoints;
const opt = "unicode-homoglyph";
const kind = .warning;
};
const pragma_inside_macro = struct {
const msg = "#pragma directive in macro expansion";
const kind = .@"error";
};
const meaningless_asm_qual = struct {
const msg = "meaningless '{s}' on assembly outside function";
const extra = .str;
const kind = .@"error";
};
const duplicate_asm_qual = struct {
const msg = "duplicate asm qualifier '{s}'";
const extra = .str;
const kind = .@"error";
};
const invalid_asm_str = struct {
const msg = "cannot use {s} string literal in assembly";
const extra = .str;
const kind = .@"error";
};
const dollar_in_identifier_extension = struct {
const msg = "'$' in identifier";
const opt = "dollar-in-identifier-extension";
const kind = .off;
const suppress_language_option = "dollars_in_identifiers";
const pedantic = true;
};
const dollars_in_identifiers = struct {
const msg = "illegal character '$' in identifier";
const kind = .@"error";
};
const expanded_from_here = struct {
const msg = "expanded from here";
const kind = .note;
};
const skipping_macro_backtrace = struct {
const msg = "(skipping {d} expansions in backtrace; use -fmacro-backtrace-limit=0 to see all)";
const extra = .unsigned;
const kind = .note;
};
const pragma_operator_string_literal = struct {
const msg = "_Pragma requires exactly one string literal token";
const kind = .@"error";
};
const unknown_gcc_pragma = struct {
const msg = "pragma GCC expected 'error', 'warning', 'diagnostic', 'poison'";
const opt = "unknown-pragmas";
const kind = .off;
const all = true;
};
const unknown_gcc_pragma_directive = struct {
const msg = "pragma GCC diagnostic expected 'error', 'warning', 'ignored', 'fatal', 'push', or 'pop'";
const opt = "unknown-pragmas";
const kind = .off;
const all = true;
};
const predefined_top_level = struct {
const msg = "predefined identifier is only valid inside function";
const opt = "predefined-identifier-outside-function";
const kind = .warning;
};
const incompatible_va_arg = struct {
const msg = "first argument to va_arg, is of type '{s}' and not 'va_list'";
const extra = .str;
const kind = .@"error";
};
const too_many_scalar_init_braces = struct {
const msg = "too many braces around scalar initializer";
const opt = "many-braces-around-scalar-init";
const kind = .warning;
};
const uninitialized_in_own_init = struct {
const msg = "variable '{s}' is uninitialized when used within its own initialization";
const extra = .str;
const opt = "uninitialized";
const kind = .off;
const all = true;
};
const gnu_statement_expression = struct {
const msg = "use of GNU statement expression extension";
const opt = "gnu-statement-expression";
const kind = .off;
const suppress_gnu = true;
const pedantic = true;
};
const stmt_expr_not_allowed_file_scope = struct {
const msg = "statement expression not allowed at file scope";
const kind = .@"error";
};
const gnu_imaginary_constant = struct {
const msg = "imaginary constants are a GNU extension";
const opt = "gnu-imaginary-constant";
const kind = .off;
const suppress_gnu = true;
const pedantic = true;
};
const plain_complex = struct {
const msg = "plain '_Complex' requires a type specifier; assuming '_Complex double'";
const kind = .warning;
};
const qual_on_ret_type = struct {
const msg = "'{s}' type qualifier on return type has no effect";
const opt = "ignored-qualifiers";
const extra = .str;
const kind = .off;
const all = true;
};
const cli_invalid_standard = struct {
const msg = "invalid standard '{s}'";
const extra = .str;
const kind = .@"error";
};
const cli_invalid_target = struct {
const msg = "invalid target '{s}'";
const extra = .str;
const kind = .@"error";
};
const cli_unknown_arg = struct {
const msg = "unknown argument '{s}'";
const extra = .str;
const kind = .@"error";
};
const cli_error = struct {
const msg = "{s}";
const extra = .str;
const kind = .@"error";
};
const extra_semi = struct {
const msg = "extra ';' outside of a function";
const opt = "extra-semi";
const kind = .off;
const pedantic = true;
};
const func_field = struct {
const msg = "field declared as a function";
const kind = .@"error";
};
const vla_field = struct {
const msg = "variable length array fields extension is not supported";
const kind = .@"error";
};
const field_incomplete_ty = struct {
const msg = "field has incomplete type '{s}'";
const extra = .str;
const kind = .@"error";
};
const flexible_in_union = struct {
const msg = "flexible array member in union is not allowed";
const kind = .@"error";
};
const flexible_non_final = struct {
const msg = "flexible array member is not at the end of struct";
const kind = .@"error";
};
const flexible_in_empty = struct {
const msg = "flexible array member in otherwise empty struct";
const kind = .@"error";
};
const duplicate_member = struct {
const msg = "duplicate member '{s}'";
const extra = .str;
const kind = .@"error";
};
const binary_integer_literal = struct {
const msg = "binary integer literals are a GNU extension";
const kind = .off;
const opt = "gnu-binary-literal";
const pedantic = true;
};
const gnu_va_macro = struct {
const msg = "named variadic macros are a GNU extension";
const opt = "variadic-macros";
const kind = .off;
const pedantic = true;
};
const builtin_must_be_called = struct {
const msg = "builtin function must be directly called";
const kind = .@"error";
};
const va_start_not_in_func = struct {
const msg = "'va_start' cannot be used outside a function";
const kind = .@"error";
};
const va_start_fixed_args = struct {
const msg = "'va_start' used in a function with fixed args";
const kind = .@"error";
};
const va_start_not_last_param = struct {
const msg = "second argument to 'va_start' is not the last named parameter";
const opt = "varargs";
const kind = .warning;
};
};
list: std.ArrayListUnmanaged(Message) = .{},
arena: std.heap.ArenaAllocator,
color: bool = true,
fatal_errors: bool = false,
options: Options = .{},
errors: u32 = 0,
macro_backtrace_limit: u32 = 6,
pub fn warningExists(name: []const u8) bool {
inline for (std.meta.fields(Options)) |f| {
if (mem.eql(u8, f.name, name)) return true;
}
return false;
}
pub fn set(diag: *Diagnostics, name: []const u8, to: Kind) !void {
inline for (std.meta.fields(Options)) |f| {
if (mem.eql(u8, f.name, name)) {
@field(diag.options, f.name) = to;
return;
}
}
try diag.add(.{
.tag = .unknown_warning,
.extra = .{ .str = name },
}, &.{});
}
pub fn init(gpa: Allocator) Diagnostics {
return .{
.color = std.io.getStdErr().supportsAnsiEscapeCodes() or (is_windows and std.io.getStdErr().isTty()),
.arena = std.heap.ArenaAllocator.init(gpa),
};
}
pub fn deinit(diag: *Diagnostics) void {
diag.list.deinit(diag.arena.allocator());
diag.arena.deinit();
}
pub fn add(diag: *Diagnostics, msg: Message, expansion_locs: []const Source.Location) Compilation.Error!void {
const kind = diag.tagKind(msg.tag);
if (kind == .off) return;
var copy = msg;
copy.kind = kind;
if (expansion_locs.len != 0) copy.loc = expansion_locs[expansion_locs.len - 1];
try diag.list.append(diag.arena.allocator(), copy);
if (expansion_locs.len != 0) {
// Add macro backtrace notes in reverse order omitting from the middle if needed.
var i = expansion_locs.len - 1;
const half = diag.macro_backtrace_limit / 2;
const limit = if (i < diag.macro_backtrace_limit) 0 else i - half;
try diag.list.ensureUnusedCapacity(
diag.arena.allocator(),
if (limit == 0) expansion_locs.len else diag.macro_backtrace_limit + 1,
);
while (i > limit) {
i -= 1;
diag.list.appendAssumeCapacity(.{
.tag = .expanded_from_here,
.kind = .note,
.loc = expansion_locs[i],
});
}
if (limit != 0) {
diag.list.appendAssumeCapacity(.{
.tag = .skipping_macro_backtrace,
.kind = .note,
.extra = .{ .unsigned = expansion_locs.len - diag.macro_backtrace_limit },
});
i = half - 1;
while (i > 0) {
i -= 1;
diag.list.appendAssumeCapacity(.{
.tag = .expanded_from_here,
.kind = .note,
.loc = expansion_locs[i],
});
}
}
diag.list.appendAssumeCapacity(.{
.tag = .expanded_from_here,
.kind = .note,
.loc = msg.loc,
});
}
if (kind == .@"fatal error" or (kind == .@"error" and diag.fatal_errors))
return error.FatalError;
}
pub fn fatal(
diag: *Diagnostics,
path: []const u8,
line: []const u8,
line_no: u32,
col: u32,
comptime fmt: []const u8,
args: anytype,
) Compilation.Error {
var m = MsgWriter.init(diag.color);
defer m.deinit();
m.location(path, line_no, col);
m.start(.@"fatal error");
m.print(fmt, args);
m.end(line, col);
return error.FatalError;
}
pub fn fatalNoSrc(diag: *Diagnostics, comptime fmt: []const u8, args: anytype) error{FatalError} {
if (!diag.color) {
std.debug.print("fatal error: " ++ fmt ++ "\n", args);
} else {
const std_err = std.io.getStdErr().writer();
util.setColor(.red, std_err);
std_err.writeAll("fatal error: ") catch {};
util.setColor(.white, std_err);
std_err.print(fmt ++ "\n", args) catch {};
util.setColor(.reset, std_err);
}
return error.FatalError;
}
pub fn render(comp: *Compilation) void {
if (comp.diag.list.items.len == 0) return;
var m = MsgWriter.init(comp.diag.color);
defer m.deinit();
renderExtra(comp, &m);
}
pub fn renderExtra(comp: *Compilation, m: anytype) void {
var errors: u32 = 0;
var warnings: u32 = 0;
for (comp.diag.list.items) |msg| {
switch (msg.kind) {
.@"fatal error", .@"error" => errors += 1,
.warning => warnings += 1,
.note => {},
.off => continue, // happens if an error is added before it is disabled
.default => unreachable,
}
var line: ?[]const u8 = null;
var col = switch (msg.tag) {
.escape_sequence_overflow,
.invalid_universal_character,
// use msg.extra.unsigned for index into string literal
=> @truncate(u32, msg.extra.unsigned),
else => 0,
};
var width = col;
if (msg.loc.id != .unused) {
const source = comp.getSource(msg.loc.id);
const line_col = source.lineCol(msg.loc.byte_offset);
line = line_col.line;
col += line_col.col;
width += line_col.width;
m.location(source.path, msg.loc.line, col);
}
m.start(msg.kind);
inline for (std.meta.fields(Tag)) |field| {
if (field.value == @enumToInt(msg.tag)) {
const info = @field(messages, field.name);
if (@hasDecl(info, "extra")) {
switch (info.extra) {
.str => m.print(info.msg, .{msg.extra.str}),
.tok_id => m.print(info.msg, .{
msg.extra.tok_id.expected.symbol(),
msg.extra.tok_id.actual.symbol(),
}),
.tok_id_expected => m.print(info.msg, .{msg.extra.tok_id_expected.symbol()}),
.arguments => m.print(info.msg, .{ msg.extra.arguments.expected, msg.extra.arguments.actual }),
.codepoints => m.print(info.msg, .{
msg.extra.codepoints.actual,
msg.extra.codepoints.resembles,
}),
.actual_codepoint => m.print(info.msg, .{msg.extra.actual_codepoint}),
.unsigned => m.print(info.msg, .{msg.extra.unsigned}),
.signed => m.print(info.msg, .{msg.extra.signed}),
else => unreachable,
}
} else {
m.write(info.msg);
}
if (@hasDecl(info, "opt")) {
if (msg.kind == .@"error" and info.kind != .@"error") {
m.print(" [-Werror,-W{s}]", .{info.opt});
} else {
m.print(" [-W{s}]", .{info.opt});
}
}
}
}
m.end(line, width);
}
const w_s: []const u8 = if (warnings == 1) "" else "s";
const e_s: []const u8 = if (errors == 1) "" else "s";
if (errors != 0 and warnings != 0) {
m.print("{d} warning{s} and {d} error{s} generated.\n", .{ warnings, w_s, errors, e_s });
} else if (warnings != 0) {
m.print("{d} warning{s} generated.\n", .{ warnings, w_s });
} else if (errors != 0) {
m.print("{d} error{s} generated.\n", .{ errors, e_s });
}
comp.diag.list.items.len = 0;
comp.diag.errors += errors;
}
fn tagKind(diag: *Diagnostics, tag: Tag) Kind {
// XXX: horrible hack, do not do this
const comp = @fieldParentPtr(Compilation, "diag", diag);
var kind: Kind = undefined;
inline for (std.meta.fields(Tag)) |field| {
if (field.value == @enumToInt(tag)) {
const info = @field(messages, field.name);
kind = info.kind;
// stage1 doesn't like when I combine these ifs
if (@hasDecl(info, "all")) {
if (diag.options.all != .default) kind = diag.options.all;
}
if (@hasDecl(info, "w_extra")) {
if (diag.options.extra != .default) kind = diag.options.extra;
}
if (@hasDecl(info, "pedantic")) {
if (diag.options.pedantic != .default) kind = diag.options.pedantic;
}
if (@hasDecl(info, "opt")) {
if (@field(diag.options, info.opt) != .default) kind = @field(diag.options, info.opt);
}
if (@hasDecl(info, "suppress_version")) if (comp.langopts.standard.atLeast(info.suppress_version)) return .off;
if (@hasDecl(info, "suppress_gnu")) if (comp.langopts.standard.isExplicitGNU()) return .off;
if (@hasDecl(info, "suppress_language_option")) if (!@field(comp.langopts, info.suppress_language_option)) return .off;
if (kind == .@"error" and diag.fatal_errors) kind = .@"fatal error";
return kind;
}
}
unreachable;
}
const MsgWriter = struct {
w: std.io.BufferedWriter(4096, std.fs.File.Writer),
color: bool,
fn init(color: bool) MsgWriter {
std.debug.getStderrMutex().lock();
return .{
.w = std.io.bufferedWriter(std.io.getStdErr().writer()),
.color = color,
};
}
fn deinit(m: *MsgWriter) void {
m.w.flush() catch {};
std.debug.getStderrMutex().unlock();
}
fn print(m: *MsgWriter, comptime fmt: []const u8, args: anytype) void {
m.w.writer().print(fmt, args) catch {};
}
fn write(m: *MsgWriter, msg: []const u8) void {
m.w.writer().writeAll(msg) catch {};
}
fn setColor(m: *MsgWriter, color: util.Color) void {
util.setColor(color, m.w.writer());
}
fn location(m: *MsgWriter, path: []const u8, line: u32, col: u32) void {
const prefix = if (std.fs.path.dirname(path) == null and path[0] != '<') "." ++ std.fs.path.sep_str else "";
if (!m.color) {
m.print("{s}{s}:{d}:{d}: ", .{ prefix, path, line, col });
} else {
m.setColor(.white);
m.print("{s}{s}:{d}:{d}: ", .{ prefix, path, line, col });
}
}
fn start(m: *MsgWriter, kind: Kind) void {
if (!m.color) {
m.print("{s}: ", .{@tagName(kind)});
} else {
switch (kind) {
.@"fatal error", .@"error" => m.setColor(.red),
.note => m.setColor(.cyan),
.warning => m.setColor(.purple),
.off, .default => unreachable,
}
m.write(switch (kind) {
.@"fatal error" => "fatal error: ",
.@"error" => "error: ",
.note => "note: ",
.warning => "warning: ",
.off, .default => unreachable,
});
m.setColor(.white);
}
}
fn end(m: *MsgWriter, maybe_line: ?[]const u8, col: u32) void {
const line = maybe_line orelse {
m.write("\n");
return;
};
if (!m.color) {
m.print("\n{s}\n", .{line});
m.print("{s: >[1]}^\n", .{ "", col });
} else {
m.setColor(.reset);
m.print("\n{s}\n{s: >[2]}", .{ line, "", col });
m.setColor(.green);
m.write("^\n");
m.setColor(.reset);
}
}
}; | src/Diagnostics.zig |
const std = @import("std");
usingnamespace @import("mecha");
const builtin = std.builtin;
const testing = std.testing;
const json = combine(.{ ws, element });
const value = oneOf(.{
object,
array,
jstring,
number,
jtrue,
jfalse,
jnull,
});
const members = combine(.{
member,
discard(many(combine(.{ comma, member }), .{ .collect = false })),
});
const elements = combine(.{
element,
discard(many(combine(.{ comma, element }), .{ .collect = false })),
});
const array = combine(.{ lbracket, discard(opt(elements)), rbracket });
const element = ref(valueRef);
const member = combine(.{ jstring, colon, element });
const object = combine(.{ lcurly, discard(opt(members)), rcurly });
fn valueRef() Parser(void) {
return value;
}
const colon = token(utf8.char(':'));
const comma = token(utf8.char(','));
const jfalse = token(string("false"));
const jnull = token(string("null"));
const jstring = token(combine(.{ utf8.char('"'), chars, utf8.char('"') }));
const jtrue = token(string("true"));
const lbracket = token(utf8.char('['));
const lcurly = token(utf8.char('{'));
const number = token(combine(.{ integer, fraction, exponent }));
const rbracket = token(utf8.char(']'));
const rcurly = token(utf8.char('}'));
fn token(comptime parser: anytype) Parser(void) {
return combine(.{ discard(parser), ws });
}
const chars = discard(many(char, .{ .collect = false }));
const char = oneOf(.{
discard(utf8.range(0x0020, '"' - 1)),
discard(utf8.range('"' + 1, '\\' - 1)),
discard(utf8.range('\\' + 1, 0x10FFFF)),
combine(.{ utf8.char('\\'), escape }),
});
const escape = oneOf(.{
utf8.char('"'),
utf8.char('\\'),
utf8.char('/'),
utf8.char('b'),
utf8.char('f'),
utf8.char('n'),
utf8.char('r'),
utf8.char('t'),
combine(.{ utf8.char('u'), hex, hex, hex, hex }),
});
const hex = oneOf(.{
jdigit,
discard(utf8.range('a', 'f')),
discard(utf8.range('A', 'F')),
});
const integer = oneOf(.{
combine(.{ onenine, digits }),
jdigit,
combine(.{ utf8.char('-'), onenine, digits }),
combine(.{ utf8.char('-'), jdigit }),
});
const digits = discard(many(jdigit, .{ .collect = false, .min = 1 }));
const jdigit = oneOf(.{
utf8.char('0'),
onenine,
});
const onenine = discard(utf8.range('1', '9'));
const fraction = discard(opt(
combine(.{ utf8.char('.'), digits }),
));
const exponent = discard(opt(
combine(.{ oneOf(.{ utf8.char('E'), utf8.char('e') }), sign, digits }),
));
const sign = discard(opt(oneOf(.{
utf8.char('+'),
utf8.char('-'),
})));
const ws = discard(many(oneOf(.{
utf8.char(0x0020),
utf8.char(0x000A),
utf8.char(0x000D),
utf8.char(0x0009),
}), .{ .collect = false }));
fn ok(s: []const u8) void {
const res = json(testing.allocator, s) catch @panic("test failure");
testing.expectEqualStrings("", res.rest);
}
fn err(s: []const u8) void {
testing.expectError(error.ParserFailed, json(testing.allocator, s));
}
fn errNotAllParsed(s: []const u8) void {
const res = json(testing.allocator, s) catch @panic("test failure");
testing.expect(res.rest.len != 0);
}
fn any(s: []const u8) void {
_ = json(testing.allocator, s) catch {};
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Additional tests not part of test JSONTestSuite.
test "y_trailing_comma_after_empty" {
ok(
\\{"1":[],"2":{},"3":"4"}
);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
test "y_array_arraysWithSpaces" {
ok(
\\[[] ]
);
}
test "y_array_empty" {
ok(
\\[]
);
}
test "y_array_empty-string" {
ok(
\\[""]
);
}
test "y_array_ending_with_newline" {
ok(
\\["a"]
);
}
test "y_array_false" {
ok(
\\[false]
);
}
test "y_array_heterogeneous" {
ok(
\\[null, 1, "1", {}]
);
}
test "y_array_null" {
ok(
\\[null]
);
}
test "y_array_with_1_and_newline" {
ok(
\\[1
\\]
);
}
test "y_array_with_leading_space" {
ok(
\\ [1]
);
}
test "y_array_with_several_null" {
ok(
\\[1,null,null,null,2]
);
}
test "y_array_with_trailing_space" {
ok("[2] ");
}
test "y_number_0e+1" {
ok(
\\[0e+1]
);
}
test "y_number_0e1" {
ok(
\\[0e1]
);
}
test "y_number_after_space" {
ok(
\\[ 4]
);
}
test "y_number_double_close_to_zero" {
ok(
\\[-0.000000000000000000000000000000000000000000000000000000000000000000000000000001]
);
}
test "y_number_int_with_exp" {
ok(
\\[20e1]
);
}
test "y_number" {
ok(
\\[123e65]
);
}
test "y_number_minus_zero" {
ok(
\\[-0]
);
}
test "y_number_negative_int" {
ok(
\\[-123]
);
}
test "y_number_negative_one" {
ok(
\\[-1]
);
}
test "y_number_negative_zero" {
ok(
\\[-0]
);
}
test "y_number_real_capital_e" {
ok(
\\[1E22]
);
}
test "y_number_real_capital_e_neg_exp" {
ok(
\\[1E-2]
);
}
test "y_number_real_capital_e_pos_exp" {
ok(
\\[1E+2]
);
}
test "y_number_real_exponent" {
ok(
\\[123e45]
);
}
test "y_number_real_fraction_exponent" {
ok(
\\[123.456e78]
);
}
test "y_number_real_neg_exp" {
ok(
\\[1e-2]
);
}
test "y_number_real_pos_exponent" {
ok(
\\[1e+2]
);
}
test "y_number_simple_int" {
ok(
\\[123]
);
}
test "y_number_simple_real" {
ok(
\\[123.456789]
);
}
test "y_object_basic" {
ok(
\\{"asd":"sdf"}
);
}
test "y_object_duplicated_key_and_value" {
ok(
\\{"a":"b","a":"b"}
);
}
test "y_object_duplicated_key" {
ok(
\\{"a":"b","a":"c"}
);
}
test "y_object_empty" {
ok(
\\{}
);
}
test "y_object_empty_key" {
ok(
\\{"":0}
);
}
test "y_object_escaped_null_in_key" {
ok(
\\{"foo\u0000bar": 42}
);
}
test "y_object_extreme_numbers" {
ok(
\\{ "min": -1.0e+28, "max": 1.0e+28 }
);
}
test "y_object" {
ok(
\\{"asd":"sdf", "dfg":"fgh"}
);
}
test "y_object_long_strings" {
ok(
\\{"x":[{"id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}], "id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}
);
}
test "y_object_simple" {
ok(
\\{"a":[]}
);
}
test "y_object_string_unicode" {
ok(
\\{"title":"\u041f\u043e\u043b\u0442\u043e\u0440\u0430 \u0417\u0435\u043c\u043b\u0435\u043a\u043e\u043f\u0430" }
);
}
test "y_object_with_newlines" {
ok(
\\{
\\"a": "b"
\\}
);
}
test "y_string_1_2_3_bytes_UTF-8_sequences" {
ok(
\\["\u0060\u012a\u12AB"]
);
}
test "y_string_accepted_surrogate_pair" {
ok(
\\["\uD801\udc37"]
);
}
test "y_string_accepted_surrogate_pairs" {
ok(
\\["\ud83d\ude39\ud83d\udc8d"]
);
}
test "y_string_allowed_escapes" {
ok(
\\["\"\\\/\b\f\n\r\t"]
);
}
test "y_string_backslash_and_u_escaped_zero" {
ok(
\\["\\u0000"]
);
}
test "y_string_backslash_doublequotes" {
ok(
\\["\""]
);
}
test "y_string_comments" {
ok(
\\["a/*b*/c/*d//e"]
);
}
test "y_string_double_escape_a" {
ok(
\\["\\a"]
);
}
test "y_string_double_escape_n" {
ok(
\\["\\n"]
);
}
test "y_string_escaped_control_character" {
ok(
\\["\u0012"]
);
}
test "y_string_escaped_noncharacter" {
ok(
\\["\uFFFF"]
);
}
test "y_string_in_array" {
ok(
\\["asd"]
);
}
test "y_string_in_array_with_leading_space" {
ok(
\\[ "asd"]
);
}
test "y_string_last_surrogates_1_and_2" {
ok(
\\["\uDBFF\uDFFF"]
);
}
test "y_string_nbsp_uescaped" {
ok(
\\["new\u00A0line"]
);
}
test "y_string_nonCharacterInUTF-8_U+10FFFF" {
ok(
\\[""]
);
}
test "y_string_nonCharacterInUTF-8_U+FFFF" {
ok(
\\[""]
);
}
test "y_string_null_escape" {
ok(
\\["\u0000"]
);
}
test "y_string_one-byte-utf-8" {
ok(
\\["\u002c"]
);
}
test "y_string_pi" {
ok(
\\["π"]
);
}
test "y_string_reservedCharacterInUTF-8_U+1BFFF" {
ok(
\\[""]
);
}
test "y_string_simple_ascii" {
ok(
\\["asd "]
);
}
test "y_string_space" {
ok(
\\" "
);
}
test "y_string_surrogates_U+1D11E_MUSICAL_SYMBOL_G_CLEF" {
ok(
\\["\uD834\uDd1e"]
);
}
test "y_string_three-byte-utf-8" {
ok(
\\["\u0821"]
);
}
test "y_string_two-byte-utf-8" {
ok(
\\["\u0123"]
);
}
test "y_string_u+2028_line_sep" {
ok("[\"\xe2\x80\xa8\"]");
}
test "y_string_u+2029_par_sep" {
ok("[\"\xe2\x80\xa9\"]");
}
test "y_string_uescaped_newline" {
ok(
\\["new\u000Aline"]
);
}
test "y_string_uEscape" {
ok(
\\["\u0061\u30af\u30EA\u30b9"]
);
}
test "y_string_unescaped_char_delete" {
ok("[\"\x7f\"]");
}
test "y_string_unicode_2" {
ok(
\\["⍂㈴⍂"]
);
}
test "y_string_unicodeEscapedBackslash" {
ok(
\\["\u005C"]
);
}
test "y_string_unicode_escaped_double_quote" {
ok(
\\["\u0022"]
);
}
test "y_string_unicode" {
ok(
\\["\uA66D"]
);
}
test "y_string_unicode_U+10FFFE_nonchar" {
ok(
\\["\uDBFF\uDFFE"]
);
}
test "y_string_unicode_U+1FFFE_nonchar" {
ok(
\\["\uD83F\uDFFE"]
);
}
test "y_string_unicode_U+200B_ZERO_WIDTH_SPACE" {
ok(
\\["\u200B"]
);
}
test "y_string_unicode_U+2064_invisible_plus" {
ok(
\\["\u2064"]
);
}
test "y_string_unicode_U+FDD0_nonchar" {
ok(
\\["\uFDD0"]
);
}
test "y_string_unicode_U+FFFE_nonchar" {
ok(
\\["\uFFFE"]
);
}
test "y_string_utf8" {
ok(
\\["€𝄞"]
);
}
test "y_string_with_del_character" {
ok("[\"a\x7fa\"]");
}
test "y_structure_lonely_false" {
ok(
\\false
);
}
test "y_structure_lonely_int" {
ok(
\\42
);
}
test "y_structure_lonely_negative_real" {
ok(
\\-0.1
);
}
test "y_structure_lonely_null" {
ok(
\\null
);
}
test "y_structure_lonely_string" {
ok(
\\"asd"
);
}
test "y_structure_lonely_true" {
ok(
\\true
);
}
test "y_structure_string_empty" {
ok(
\\""
);
}
test "y_structure_trailing_newline" {
ok(
\\["a"]
);
}
test "y_structure_true_in_array" {
ok(
\\[true]
);
}
test "y_structure_whitespace_array" {
ok(" [] ");
}
////////////////////////////////////////////////////////////////////////////////////////////////////
test "n_array_1_true_without_comma" {
err(
\\[1 true]
);
}
test "n_array_a_invalid_utf8" {
err(
\\[aå]
);
}
test "n_array_colon_instead_of_comma" {
err(
\\["": 1]
);
}
test "n_array_comma_after_close" {
errNotAllParsed(
\\[""],
);
}
test "n_array_comma_and_number" {
err(
\\[,1]
);
}
test "n_array_double_comma" {
err(
\\[1,,2]
);
}
test "n_array_double_extra_comma" {
err(
\\["x",,]
);
}
test "n_array_extra_close" {
errNotAllParsed(
\\["x"]]
);
}
test "n_array_extra_comma" {
err(
\\["",]
);
}
test "n_array_incomplete_invalid_value" {
err(
\\[x
);
}
test "n_array_incomplete" {
err(
\\["x"
);
}
test "n_array_inner_array_no_comma" {
err(
\\[3[4]]
);
}
test "n_array_invalid_utf8" {
err(
\\[ÿ]
);
}
test "n_array_items_separated_by_semicolon" {
err(
\\[1:2]
);
}
test "n_array_just_comma" {
err(
\\[,]
);
}
test "n_array_just_minus" {
err(
\\[-]
);
}
test "n_array_missing_value" {
err(
\\[ , ""]
);
}
test "n_array_newlines_unclosed" {
err(
\\["a",
\\4
\\,1,
);
}
test "n_array_number_and_comma" {
err(
\\[1,]
);
}
test "n_array_number_and_several_commas" {
err(
\\[1,,]
);
}
test "n_array_spaces_vertical_tab_formfeed" {
err("[\"\x0aa\"\\f]");
}
test "n_array_star_inside" {
err(
\\[*]
);
}
test "n_array_unclosed" {
err(
\\[""
);
}
test "n_array_unclosed_trailing_comma" {
err(
\\[1,
);
}
test "n_array_unclosed_with_new_lines" {
err(
\\[1,
\\1
\\,1
);
}
test "n_array_unclosed_with_object_inside" {
err(
\\[{}
);
}
test "n_incomplete_false" {
err(
\\[fals]
);
}
test "n_incomplete_null" {
err(
\\[nul]
);
}
test "n_incomplete_true" {
err(
\\[tru]
);
}
test "n_multidigit_number_then_00" {
errNotAllParsed("123\x00");
}
test "n_number_0.1.2" {
err(
\\[0.1.2]
);
}
test "n_number_-01" {
err(
\\[-01]
);
}
test "n_number_0.3e" {
err(
\\[0.3e]
);
}
test "n_number_0.3e+" {
err(
\\[0.3e+]
);
}
test "n_number_0_capital_E" {
err(
\\[0E]
);
}
test "n_number_0_capital_E+" {
err(
\\[0E+]
);
}
test "n_number_0.e1" {
err(
\\[0.e1]
);
}
test "n_number_0e" {
err(
\\[0e]
);
}
test "n_number_0e+" {
err(
\\[0e+]
);
}
test "n_number_1_000" {
err(
\\[1 000.0]
);
}
test "n_number_1.0e-" {
err(
\\[1.0e-]
);
}
test "n_number_1.0e" {
err(
\\[1.0e]
);
}
test "n_number_1.0e+" {
err(
\\[1.0e+]
);
}
test "n_number_-1.0." {
err(
\\[-1.0.]
);
}
test "n_number_1eE2" {
err(
\\[1eE2]
);
}
test "n_number_.-1" {
err(
\\[.-1]
);
}
test "n_number_+1" {
err(
\\[+1]
);
}
test "n_number_.2e-3" {
err(
\\[.2e-3]
);
}
test "n_number_2.e-3" {
err(
\\[2.e-3]
);
}
test "n_number_2.e+3" {
err(
\\[2.e+3]
);
}
test "n_number_2.e3" {
err(
\\[2.e3]
);
}
test "n_number_-2." {
err(
\\[-2.]
);
}
test "n_number_9.e+" {
err(
\\[9.e+]
);
}
test "n_number_expression" {
err(
\\[1+2]
);
}
test "n_number_hex_1_digit" {
err(
\\[0x1]
);
}
test "n_number_hex_2_digits" {
err(
\\[0x42]
);
}
test "n_number_infinity" {
err(
\\[Infinity]
);
}
test "n_number_+Inf" {
err(
\\[+Inf]
);
}
test "n_number_Inf" {
err(
\\[Inf]
);
}
test "n_number_invalid+-" {
err(
\\[0e+-1]
);
}
test "n_number_invalid-negative-real" {
err(
\\[-123.123foo]
);
}
test "n_number_invalid-utf-8-in-bigger-int" {
err(
\\[123å]
);
}
test "n_number_invalid-utf-8-in-exponent" {
err(
\\[1e1å]
);
}
test "n_number_invalid-utf-8-in-int" {
err(
\\[0å]
);
}
test "n_number_++" {
err(
\\[++1234]
);
}
test "n_number_minus_infinity" {
err(
\\[-Infinity]
);
}
test "n_number_minus_sign_with_trailing_garbage" {
err(
\\[-foo]
);
}
test "n_number_minus_space_1" {
err(
\\[- 1]
);
}
test "n_number_-NaN" {
err(
\\[-NaN]
);
}
test "n_number_NaN" {
err(
\\[NaN]
);
}
test "n_number_neg_int_starting_with_zero" {
err(
\\[-012]
);
}
test "n_number_neg_real_without_int_part" {
err(
\\[-.123]
);
}
test "n_number_neg_with_garbage_at_end" {
err(
\\[-1x]
);
}
test "n_number_real_garbage_after_e" {
err(
\\[1ea]
);
}
test "n_number_real_with_invalid_utf8_after_e" {
err(
\\[1eå]
);
}
test "n_number_real_without_fractional_part" {
err(
\\[1.]
);
}
test "n_number_starting_with_dot" {
err(
\\[.123]
);
}
test "n_number_U+FF11_fullwidth_digit_one" {
err(
\\[ï¼]
);
}
test "n_number_with_alpha_char" {
err(
\\[1.8011670033376514H-308]
);
}
test "n_number_with_alpha" {
err(
\\[1.2a-3]
);
}
test "n_number_with_leading_zero" {
err(
\\[012]
);
}
test "n_object_bad_value" {
err(
\\["x", truth]
);
}
test "n_object_bracket_key" {
err(
\\{[: "x"}
);
}
test "n_object_comma_instead_of_colon" {
err(
\\{"x", null}
);
}
test "n_object_double_colon" {
err(
\\{"x"::"b"}
);
}
test "n_object_emoji" {
err(
\\{ð¨ð}
);
}
test "n_object_garbage_at_end" {
err(
\\{"a":"a" 123}
);
}
test "n_object_key_with_single_quotes" {
err(
\\{key: 'value'}
);
}
test "n_object_lone_continuation_byte_in_key_and_trailing_comma" {
err(
\\{"¹":"0",}
);
}
test "n_object_missing_colon" {
err(
\\{"a" b}
);
}
test "n_object_missing_key" {
err(
\\{:"b"}
);
}
test "n_object_missing_semicolon" {
err(
\\{"a" "b"}
);
}
test "n_object_missing_value" {
err(
\\{"a":
);
}
test "n_object_no-colon" {
err(
\\{"a"
);
}
test "n_object_non_string_key_but_huge_number_instead" {
err(
\\{9999E9999:1}
);
}
test "n_object_non_string_key" {
err(
\\{1:1}
);
}
test "n_object_repeated_null_null" {
err(
\\{null:null,null:null}
);
}
test "n_object_several_trailing_commas" {
err(
\\{"id":0,,,,,}
);
}
test "n_object_single_quote" {
err(
\\{'a':0}
);
}
test "n_object_trailing_comma" {
err(
\\{"id":0,}
);
}
test "n_object_trailing_comment" {
errNotAllParsed(
\\{"a":"b"}/**/
);
}
test "n_object_trailing_comment_open" {
errNotAllParsed(
\\{"a":"b"}/**//
);
}
test "n_object_trailing_comment_slash_open_incomplete" {
errNotAllParsed(
\\{"a":"b"}/
);
}
test "n_object_trailing_comment_slash_open" {
errNotAllParsed(
\\{"a":"b"}//
);
}
test "n_object_two_commas_in_a_row" {
err(
\\{"a":"b",,"c":"d"}
);
}
test "n_object_unquoted_key" {
err(
\\{a: "b"}
);
}
test "n_object_unterminated-value" {
err(
\\{"a":"a
);
}
test "n_object_with_single_string" {
err(
\\{ "foo" : "bar", "a" }
);
}
test "n_object_with_trailing_garbage" {
errNotAllParsed(
\\{"a":"b"}#
);
}
test "n_single_space" {
err(" ");
}
test "n_string_1_surrogate_then_escape" {
err(
\\["\uD800\"]
);
}
test "n_string_1_surrogate_then_escape_u1" {
err(
\\["\uD800\u1"]
);
}
test "n_string_1_surrogate_then_escape_u1x" {
err(
\\["\uD800\u1x"]
);
}
test "n_string_1_surrogate_then_escape_u" {
err(
\\["\uD800\u"]
);
}
test "n_string_accentuated_char_no_quotes" {
err(
\\[é]
);
}
test "n_string_backslash_00" {
err("[\"\x00\"]");
}
test "n_string_escaped_backslash_bad" {
err(
\\["\\\"]
);
}
test "n_string_escaped_ctrl_char_tab" {
err("\x5b\x22\x5c\x09\x22\x5d");
}
test "n_string_escaped_emoji" {
err("[\"\x5c\xc3\xb0\xc2\x9f\xc2\x8c\xc2\x80\"]");
}
test "n_string_escape_x" {
err(
\\["\x00"]
);
}
test "n_string_incomplete_escaped_character" {
err(
\\["\u00A"]
);
}
test "n_string_incomplete_escape" {
err(
\\["\"]
);
}
test "n_string_incomplete_surrogate_escape_invalid" {
err(
\\["\uD800\uD800\x"]
);
}
test "n_string_incomplete_surrogate" {
err(
\\["\uD834\uDd"]
);
}
test "n_string_invalid_backslash_esc" {
err(
\\["\a"]
);
}
test "n_string_invalid_unicode_escape" {
err(
\\["\uqqqq"]
);
}
test "n_string_invalid_utf8_after_escape" {
err("[\"\\\x75\xc3\xa5\"]");
}
test "n_string_invalid-utf-8-in-escape" {
err(
\\["\uå"]
);
}
test "n_string_leading_uescaped_thinspace" {
err(
\\[\u0020"asd"]
);
}
test "n_string_no_quotes_with_bad_escape" {
err(
\\[\n]
);
}
test "n_string_single_doublequote" {
err(
\\"
);
}
test "n_string_single_quote" {
err(
\\['single quote']
);
}
test "n_string_single_string_no_double_quotes" {
err(
\\abc
);
}
test "n_string_start_escape_unclosed" {
err(
\\["\
);
}
test "n_string_unescaped_crtl_char" {
err("[\"a\x00a\"]");
}
test "n_string_unescaped_newline" {
err(
\\["new
\\line"]
);
}
test "n_string_unescaped_tab" {
err("[\"\t\"]");
}
test "n_string_unicode_CapitalU" {
err(
\\"\UA66D"
);
}
test "n_string_with_trailing_garbage" {
errNotAllParsed(
\\""x
);
}
test "n_structure_100000_opening_arrays" {
return error.SkipZigTest;
// err("[" ** 100000);
}
test "n_structure_angle_bracket_." {
err(
\\<.>
);
}
test "n_structure_angle_bracket_null" {
err(
\\[<null>]
);
}
test "n_structure_array_trailing_garbage" {
errNotAllParsed(
\\[1]x
);
}
test "n_structure_array_with_extra_array_close" {
errNotAllParsed(
\\[1]]
);
}
test "n_structure_array_with_unclosed_string" {
err(
\\["asd]
);
}
test "n_structure_ascii-unicode-identifier" {
err(
\\aå
);
}
test "n_structure_capitalized_True" {
err(
\\[True]
);
}
test "n_structure_close_unopened_array" {
errNotAllParsed(
\\1]
);
}
test "n_structure_comma_instead_of_closing_brace" {
err(
\\{"x": true,
);
}
test "n_structure_double_array" {
errNotAllParsed(
\\[][]
);
}
test "n_structure_end_array" {
err(
\\]
);
}
test "n_structure_incomplete_UTF8_BOM" {
err(
\\ï»{}
);
}
test "n_structure_lone-invalid-utf-8" {
err(
\\å
);
}
test "n_structure_lone-open-bracket" {
err(
\\[
);
}
test "n_structure_no_data" {
err(
\\
);
}
test "n_structure_null-byte-outside-string" {
err("[\x00]");
}
test "n_structure_number_with_trailing_garbage" {
errNotAllParsed(
\\2@
);
}
test "n_structure_object_followed_by_closing_object" {
errNotAllParsed(
\\{}}
);
}
test "n_structure_object_unclosed_no_value" {
err(
\\{"":
);
}
test "n_structure_object_with_comment" {
err(
\\{"a":/*comment*/"b"}
);
}
test "n_structure_object_with_trailing_garbage" {
errNotAllParsed(
\\{"a": true} "x"
);
}
test "n_structure_open_array_apostrophe" {
err(
\\['
);
}
test "n_structure_open_array_comma" {
err(
\\[,
);
}
test "n_structure_open_array_object" {
return error.SkipZigTest;
// err("[{\"\":" ** 50000);
}
test "n_structure_open_array_open_object" {
err(
\\[{
);
}
test "n_structure_open_array_open_string" {
err(
\\["a
);
}
test "n_structure_open_array_string" {
err(
\\["a"
);
}
test "n_structure_open_object_close_array" {
err(
\\{]
);
}
test "n_structure_open_object_comma" {
err(
\\{,
);
}
test "n_structure_open_object" {
err(
\\{
);
}
test "n_structure_open_object_open_array" {
err(
\\{[
);
}
test "n_structure_open_object_open_string" {
err(
\\{"a
);
}
test "n_structure_open_object_string_with_apostrophes" {
err(
\\{'a'
);
}
test "n_structure_open_open" {
err(
\\["\{["\{["\{["\{
);
}
test "n_structure_single_eacute" {
err(
\\é
);
}
test "n_structure_single_star" {
err(
\\*
);
}
test "n_structure_trailing_#" {
errNotAllParsed(
\\{"a":"b"}#{}
);
}
test "n_structure_U+2060_word_joined" {
err(
\\[â ]
);
}
test "n_structure_uescaped_LF_before_string" {
err(
\\[\u000A""]
);
}
test "n_structure_unclosed_array" {
err(
\\[1
);
}
test "n_structure_unclosed_array_partial_null" {
err(
\\[ false, nul
);
}
test "n_structure_unclosed_array_unfinished_false" {
err(
\\[ true, fals
);
}
test "n_structure_unclosed_array_unfinished_true" {
err(
\\[ false, tru
);
}
test "n_structure_unclosed_object" {
err(
\\{"asd":"asd"
);
}
test "n_structure_unicode-identifier" {
err(
\\Ã¥
);
}
test "n_structure_UTF8_BOM_no_data" {
err(
\\
);
}
test "n_structure_whitespace_formfeed" {
err("[\x0c]");
}
test "n_structure_whitespace_U+2060_word_joiner" {
err(
\\[â ]
);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
test "i_number_double_huge_neg_exp" {
any(
\\[123.456e-789]
);
}
test "i_number_huge_exp" {
any(
\\[0.4e00669999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999969999999006]
);
}
test "i_number_neg_int_huge_exp" {
any(
\\[-1e+9999]
);
}
test "i_number_pos_double_huge_exp" {
any(
\\[1.5e+9999]
);
}
test "i_number_real_neg_overflow" {
any(
\\[-123123e100000]
);
}
test "i_number_real_pos_overflow" {
any(
\\[123123e100000]
);
}
test "i_number_real_underflow" {
any(
\\[123e-10000000]
);
}
test "i_number_too_big_neg_int" {
any(
\\[-123123123123123123123123123123]
);
}
test "i_number_too_big_pos_int" {
any(
\\[100000000000000000000]
);
}
test "i_number_very_big_negative_int" {
any(
\\[-237462374673276894279832749832423479823246327846]
);
}
test "i_object_key_lone_2nd_surrogate" {
any(
\\{"\uDFAA":0}
);
}
test "i_string_1st_surrogate_but_2nd_missing" {
any(
\\["\uDADA"]
);
}
test "i_string_1st_valid_surrogate_2nd_invalid" {
any(
\\["\uD888\u1234"]
);
}
test "i_string_incomplete_surrogate_and_escape_valid" {
any(
\\["\uD800\n"]
);
}
test "i_string_incomplete_surrogate_pair" {
any(
\\["\uDd1ea"]
);
}
test "i_string_incomplete_surrogates_escape_valid" {
any(
\\["\uD800\uD800\n"]
);
}
test "i_string_invalid_lonely_surrogate" {
any(
\\["\ud800"]
);
}
test "i_string_invalid_surrogate" {
any(
\\["\ud800abc"]
);
}
test "i_string_invalid_utf-8" {
any(
\\["ÿ"]
);
}
test "i_string_inverted_surrogates_U+1D11E" {
any(
\\["\uDd1e\uD834"]
);
}
test "i_string_iso_latin_1" {
any(
\\["é"]
);
}
test "i_string_lone_second_surrogate" {
any(
\\["\uDFAA"]
);
}
test "i_string_lone_utf8_continuation_byte" {
any(
\\[""]
);
}
test "i_string_not_in_unicode_range" {
any(
\\["ô¿¿¿"]
);
}
test "i_string_overlong_sequence_2_bytes" {
any(
\\["À¯"]
);
}
test "i_string_overlong_sequence_6_bytes" {
any(
\\["ü¿¿¿¿"]
);
}
test "i_string_overlong_sequence_6_bytes_null" {
any(
\\["ü"]
);
}
test "i_string_truncated-utf-8" {
any(
\\["àÿ"]
);
}
test "i_string_utf16BE_no_BOM" {
any("\x00\x5b\x00\x22\x00\xc3\xa9\x00\x22\x00\x5d");
}
test "i_string_utf16LE_no_BOM" {
any("\x5b\x00\x22\x00\xc3\xa9\x00\x22\x00\x5d\x00");
}
test "i_string_UTF-16LE_with_BOM" {
any("\xc3\xbf\xc3\xbe\x5b\x00\x22\x00\xc3\xa9\x00\x22\x00\x5d\x00");
}
test "i_string_UTF-8_invalid_sequence" {
any(
\\["æ¥Ñú"]
);
}
test "i_string_UTF8_surrogate_U+D800" {
any(
\\["í "]
);
}
test "i_structure_500_nested_arrays" {
any(("[" ** 500) ++ ("]" ** 500));
}
test "i_structure_UTF-8_BOM_empty_object" {
any(
\\{}
);
}
test "truncated UTF-8 sequence" {
err("\"\xc2\"");
err("\"\xdf\"");
err("\"\xed\xa0\"");
err("\"\xf0\x80\"");
err("\"\xf0\x80\x80\"");
}
test "invalid continuation byte" {
err("\"\xc2\x00\"");
err("\"\xc2\x7f\"");
err("\"\xc2\xc0\"");
err("\"\xc3\xc1\"");
err("\"\xc4\xf5\"");
err("\"\xc5\xff\"");
err("\"\xe4\x80\x00\"");
err("\"\xe5\x80\x10\"");
err("\"\xe6\x80\xc0\"");
err("\"\xe7\x80\xf5\"");
err("\"\xe8\x00\x80\"");
err("\"\xf2\x00\x80\x80\"");
err("\"\xf0\x80\x00\x80\"");
err("\"\xf1\x80\xc0\x80\"");
err("\"\xf2\x80\x80\x00\"");
err("\"\xf3\x80\x80\xc0\"");
err("\"\xf4\x80\x80\xf5\"");
}
test "disallowed overlong form" {
err("\"\xc0\x80\"");
err("\"\xc0\x90\"");
err("\"\xc1\x80\"");
err("\"\xc1\x90\"");
err("\"\xe0\x80\x80\"");
err("\"\xf0\x80\x80\x80\"");
}
test "out of UTF-16 range" {
err("\"\xf4\x90\x80\x80\"");
err("\"\xf5\x80\x80\x80\"");
err("\"\xf6\x80\x80\x80\"");
err("\"\xf7\x80\x80\x80\"");
err("\"\xf8\x80\x80\x80\"");
err("\"\xf9\x80\x80\x80\"");
err("\"\xfa\x80\x80\x80\"");
err("\"\xfb\x80\x80\x80\"");
err("\"\xfc\x80\x80\x80\"");
err("\"\xfd\x80\x80\x80\"");
err("\"\xfe\x80\x80\x80\"");
err("\"\xff\x80\x80\x80\"");
} | example/json.zig |
const std = @import("std");
const builtin = @import("builtin");
const event = std.event;
const Target = @import("target.zig").Target;
const c = @import("c.zig");
/// See the render function implementation for documentation of the fields.
pub const LibCInstallation = struct {
include_dir: []const u8,
lib_dir: ?[]const u8,
static_lib_dir: ?[]const u8,
msvc_lib_dir: ?[]const u8,
kernel32_lib_dir: ?[]const u8,
dynamic_linker_path: ?[]const u8,
pub const FindError = error{
OutOfMemory,
FileSystem,
UnableToSpawnCCompiler,
CCompilerExitCode,
CCompilerCrashed,
CCompilerCannotFindHeaders,
LibCRuntimeNotFound,
LibCStdLibHeaderNotFound,
LibCKernel32LibNotFound,
UnsupportedArchitecture,
};
pub fn parse(
self: *LibCInstallation,
allocator: *std.mem.Allocator,
libc_file: []const u8,
stderr: *std.io.OutStream(std.io.FileOutStream.Error),
) !void {
self.initEmpty();
const keys = []const []const u8{
"include_dir",
"lib_dir",
"static_lib_dir",
"msvc_lib_dir",
"kernel32_lib_dir",
"dynamic_linker_path",
};
const FoundKey = struct {
found: bool,
allocated: ?[]u8,
};
var found_keys = [1]FoundKey{FoundKey{ .found = false, .allocated = null }} ** keys.len;
errdefer {
self.initEmpty();
for (found_keys) |found_key| {
if (found_key.allocated) |s| allocator.free(s);
}
}
const contents = try std.io.readFileAlloc(allocator, libc_file);
defer allocator.free(contents);
var it = std.mem.split(contents, "\n");
while (it.next()) |line| {
if (line.len == 0 or line[0] == '#') continue;
var line_it = std.mem.split(line, "=");
const name = line_it.next() orelse {
try stderr.print("missing equal sign after field name\n");
return error.ParseError;
};
const value = line_it.rest();
inline for (keys) |key, i| {
if (std.mem.eql(u8, name, key)) {
found_keys[i].found = true;
switch (@typeInfo(@typeOf(@field(self, key)))) {
builtin.TypeId.Optional => {
if (value.len == 0) {
@field(self, key) = null;
} else {
found_keys[i].allocated = try std.mem.dupe(allocator, u8, value);
@field(self, key) = found_keys[i].allocated;
}
},
else => {
if (value.len == 0) {
try stderr.print("field cannot be empty: {}\n", key);
return error.ParseError;
}
const dupe = try std.mem.dupe(allocator, u8, value);
found_keys[i].allocated = dupe;
@field(self, key) = dupe;
},
}
break;
}
}
}
for (found_keys) |found_key, i| {
if (!found_key.found) {
try stderr.print("missing field: {}\n", keys[i]);
return error.ParseError;
}
}
}
pub fn render(self: *const LibCInstallation, out: *std.io.OutStream(std.io.FileOutStream.Error)) !void {
@setEvalBranchQuota(4000);
try out.print(
\\# The directory that contains `stdlib.h`.
\\# On Linux, can be found with: `cc -E -Wp,-v -xc /dev/null`
\\include_dir={}
\\
\\# The directory that contains `crt1.o`.
\\# On Linux, can be found with `cc -print-file-name=crt1.o`.
\\# Not needed when targeting MacOS.
\\lib_dir={}
\\
\\# The directory that contains `crtbegin.o`.
\\# On Linux, can be found with `cc -print-file-name=crtbegin.o`.
\\# Not needed when targeting MacOS or Windows.
\\static_lib_dir={}
\\
\\# The directory that contains `vcruntime.lib`.
\\# Only needed when targeting Windows.
\\msvc_lib_dir={}
\\
\\# The directory that contains `kernel32.lib`.
\\# Only needed when targeting Windows.
\\kernel32_lib_dir={}
\\
\\# The full path to the dynamic linker, on the target system.
\\# Only needed when targeting Linux.
\\dynamic_linker_path={}
\\
,
self.include_dir,
self.lib_dir orelse "",
self.static_lib_dir orelse "",
self.msvc_lib_dir orelse "",
self.kernel32_lib_dir orelse "",
self.dynamic_linker_path orelse Target(Target.Native).getDynamicLinkerPath(),
);
}
/// Finds the default, native libc.
pub async fn findNative(self: *LibCInstallation, loop: *event.Loop) !void {
self.initEmpty();
var group = event.Group(FindError!void).init(loop);
errdefer group.deinit();
var windows_sdk: ?*c.ZigWindowsSDK = null;
errdefer if (windows_sdk) |sdk| c.zig_free_windows_sdk(@ptrCast(?[*]c.ZigWindowsSDK, sdk));
switch (builtin.os) {
builtin.Os.windows => {
var sdk: *c.ZigWindowsSDK = undefined;
switch (c.zig_find_windows_sdk(@ptrCast(?[*]?[*]c.ZigWindowsSDK, &sdk))) {
c.ZigFindWindowsSdkError.None => {
windows_sdk = sdk;
if (sdk.msvc_lib_dir_ptr) |ptr| {
self.msvc_lib_dir = try std.mem.dupe(loop.allocator, u8, ptr[0..sdk.msvc_lib_dir_len]);
}
try group.call(findNativeKernel32LibDir, self, loop, sdk);
try group.call(findNativeIncludeDirWindows, self, loop, sdk);
try group.call(findNativeLibDirWindows, self, loop, sdk);
},
c.ZigFindWindowsSdkError.OutOfMemory => return error.OutOfMemory,
c.ZigFindWindowsSdkError.NotFound => return error.NotFound,
c.ZigFindWindowsSdkError.PathTooLong => return error.NotFound,
}
},
builtin.Os.linux => {
try group.call(findNativeIncludeDirLinux, self, loop);
try group.call(findNativeLibDirLinux, self, loop);
try group.call(findNativeStaticLibDir, self, loop);
try group.call(findNativeDynamicLinker, self, loop);
},
builtin.Os.macosx => {
self.include_dir = try std.mem.dupe(loop.allocator, u8, "/usr/include");
},
else => @compileError("unimplemented: find libc for this OS"),
}
return await (async group.wait() catch unreachable);
}
async fn findNativeIncludeDirLinux(self: *LibCInstallation, loop: *event.Loop) !void {
const cc_exe = std.os.getEnvPosix("CC") orelse "cc";
const argv = []const []const u8{
cc_exe,
"-E",
"-Wp,-v",
"-xc",
"/dev/null",
};
// TODO make this use event loop
const errorable_result = std.os.ChildProcess.exec(loop.allocator, argv, null, null, 1024 * 1024);
const exec_result = if (std.debug.runtime_safety) blk: {
break :blk errorable_result catch unreachable;
} else blk: {
break :blk errorable_result catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
else => return error.UnableToSpawnCCompiler,
};
};
defer {
loop.allocator.free(exec_result.stdout);
loop.allocator.free(exec_result.stderr);
}
switch (exec_result.term) {
std.os.ChildProcess.Term.Exited => |code| {
if (code != 0) return error.CCompilerExitCode;
},
else => {
return error.CCompilerCrashed;
},
}
var it = std.mem.split(exec_result.stderr, "\n\r");
var search_paths = std.ArrayList([]const u8).init(loop.allocator);
defer search_paths.deinit();
while (it.next()) |line| {
if (line.len != 0 and line[0] == ' ') {
try search_paths.append(line);
}
}
if (search_paths.len == 0) {
return error.CCompilerCannotFindHeaders;
}
// search in reverse order
var path_i: usize = 0;
while (path_i < search_paths.len) : (path_i += 1) {
const search_path_untrimmed = search_paths.at(search_paths.len - path_i - 1);
const search_path = std.mem.trimLeft(u8, search_path_untrimmed, " ");
const stdlib_path = try std.os.path.join(loop.allocator, search_path, "stdlib.h");
defer loop.allocator.free(stdlib_path);
if (try fileExists(loop.allocator, stdlib_path)) {
self.include_dir = try std.mem.dupe(loop.allocator, u8, search_path);
return;
}
}
return error.LibCStdLibHeaderNotFound;
}
async fn findNativeIncludeDirWindows(self: *LibCInstallation, loop: *event.Loop, sdk: *c.ZigWindowsSDK) !void {
var search_buf: [2]Search = undefined;
const searches = fillSearch(&search_buf, sdk);
var result_buf = try std.Buffer.initSize(loop.allocator, 0);
defer result_buf.deinit();
for (searches) |search| {
result_buf.shrink(0);
const stream = &std.io.BufferOutStream.init(&result_buf).stream;
try stream.print("{}\\Include\\{}\\ucrt", search.path, search.version);
const stdlib_path = try std.os.path.join(loop.allocator, result_buf.toSliceConst(), "stdlib.h");
defer loop.allocator.free(stdlib_path);
if (try fileExists(loop.allocator, stdlib_path)) {
self.include_dir = result_buf.toOwnedSlice();
return;
}
}
return error.LibCStdLibHeaderNotFound;
}
async fn findNativeLibDirWindows(self: *LibCInstallation, loop: *event.Loop, sdk: *c.ZigWindowsSDK) FindError!void {
var search_buf: [2]Search = undefined;
const searches = fillSearch(&search_buf, sdk);
var result_buf = try std.Buffer.initSize(loop.allocator, 0);
defer result_buf.deinit();
for (searches) |search| {
result_buf.shrink(0);
const stream = &std.io.BufferOutStream.init(&result_buf).stream;
try stream.print("{}\\Lib\\{}\\ucrt\\", search.path, search.version);
switch (builtin.arch) {
builtin.Arch.i386 => try stream.write("x86"),
builtin.Arch.x86_64 => try stream.write("x64"),
builtin.Arch.aarch64 => try stream.write("arm"),
else => return error.UnsupportedArchitecture,
}
const ucrt_lib_path = try std.os.path.join(loop.allocator, result_buf.toSliceConst(), "ucrt.lib");
defer loop.allocator.free(ucrt_lib_path);
if (try fileExists(loop.allocator, ucrt_lib_path)) {
self.lib_dir = result_buf.toOwnedSlice();
return;
}
}
return error.LibCRuntimeNotFound;
}
async fn findNativeLibDirLinux(self: *LibCInstallation, loop: *event.Loop) FindError!void {
self.lib_dir = try await (async ccPrintFileName(loop, "crt1.o", true) catch unreachable);
}
async fn findNativeStaticLibDir(self: *LibCInstallation, loop: *event.Loop) FindError!void {
self.static_lib_dir = try await (async ccPrintFileName(loop, "crtbegin.o", true) catch unreachable);
}
async fn findNativeDynamicLinker(self: *LibCInstallation, loop: *event.Loop) FindError!void {
var dyn_tests = []DynTest{
DynTest{
.name = "ld-linux-x86-64.so.2",
.result = null,
},
DynTest{
.name = "ld-musl-x86_64.so.1",
.result = null,
},
};
var group = event.Group(FindError!void).init(loop);
errdefer group.deinit();
for (dyn_tests) |*dyn_test| {
try group.call(testNativeDynamicLinker, self, loop, dyn_test);
}
try await (async group.wait() catch unreachable);
for (dyn_tests) |*dyn_test| {
if (dyn_test.result) |result| {
self.dynamic_linker_path = result;
return;
}
}
}
const DynTest = struct {
name: []const u8,
result: ?[]const u8,
};
async fn testNativeDynamicLinker(self: *LibCInstallation, loop: *event.Loop, dyn_test: *DynTest) FindError!void {
if (await (async ccPrintFileName(loop, dyn_test.name, false) catch unreachable)) |result| {
dyn_test.result = result;
return;
} else |err| switch (err) {
error.LibCRuntimeNotFound => return,
else => return err,
}
}
async fn findNativeKernel32LibDir(self: *LibCInstallation, loop: *event.Loop, sdk: *c.ZigWindowsSDK) FindError!void {
var search_buf: [2]Search = undefined;
const searches = fillSearch(&search_buf, sdk);
var result_buf = try std.Buffer.initSize(loop.allocator, 0);
defer result_buf.deinit();
for (searches) |search| {
result_buf.shrink(0);
const stream = &std.io.BufferOutStream.init(&result_buf).stream;
try stream.print("{}\\Lib\\{}\\um\\", search.path, search.version);
switch (builtin.arch) {
builtin.Arch.i386 => try stream.write("x86\\"),
builtin.Arch.x86_64 => try stream.write("x64\\"),
builtin.Arch.aarch64 => try stream.write("arm\\"),
else => return error.UnsupportedArchitecture,
}
const kernel32_path = try std.os.path.join(loop.allocator, result_buf.toSliceConst(), "kernel32.lib");
defer loop.allocator.free(kernel32_path);
if (try fileExists(loop.allocator, kernel32_path)) {
self.kernel32_lib_dir = result_buf.toOwnedSlice();
return;
}
}
return error.LibCKernel32LibNotFound;
}
fn initEmpty(self: *LibCInstallation) void {
self.* = LibCInstallation{
.include_dir = ([*]const u8)(undefined)[0..0],
.lib_dir = null,
.static_lib_dir = null,
.msvc_lib_dir = null,
.kernel32_lib_dir = null,
.dynamic_linker_path = null,
};
}
};
/// caller owns returned memory
async fn ccPrintFileName(loop: *event.Loop, o_file: []const u8, want_dirname: bool) ![]u8 {
const cc_exe = std.os.getEnvPosix("CC") orelse "cc";
const arg1 = try std.fmt.allocPrint(loop.allocator, "-print-file-name={}", o_file);
defer loop.allocator.free(arg1);
const argv = []const []const u8{ cc_exe, arg1 };
// TODO This simulates evented I/O for the child process exec
await (async loop.yield() catch unreachable);
const errorable_result = std.os.ChildProcess.exec(loop.allocator, argv, null, null, 1024 * 1024);
const exec_result = if (std.debug.runtime_safety) blk: {
break :blk errorable_result catch unreachable;
} else blk: {
break :blk errorable_result catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
else => return error.UnableToSpawnCCompiler,
};
};
defer {
loop.allocator.free(exec_result.stdout);
loop.allocator.free(exec_result.stderr);
}
switch (exec_result.term) {
std.os.ChildProcess.Term.Exited => |code| {
if (code != 0) return error.CCompilerExitCode;
},
else => {
return error.CCompilerCrashed;
},
}
var it = std.mem.split(exec_result.stdout, "\n\r");
const line = it.next() orelse return error.LibCRuntimeNotFound;
const dirname = std.os.path.dirname(line) orelse return error.LibCRuntimeNotFound;
if (want_dirname) {
return std.mem.dupe(loop.allocator, u8, dirname);
} else {
return std.mem.dupe(loop.allocator, u8, line);
}
}
const Search = struct {
path: []const u8,
version: []const u8,
};
fn fillSearch(search_buf: *[2]Search, sdk: *c.ZigWindowsSDK) []Search {
var search_end: usize = 0;
if (sdk.path10_ptr) |path10_ptr| {
if (sdk.version10_ptr) |ver10_ptr| {
search_buf[search_end] = Search{
.path = path10_ptr[0..sdk.path10_len],
.version = ver10_ptr[0..sdk.version10_len],
};
search_end += 1;
}
}
if (sdk.path81_ptr) |path81_ptr| {
if (sdk.version81_ptr) |ver81_ptr| {
search_buf[search_end] = Search{
.path = path81_ptr[0..sdk.path81_len],
.version = ver81_ptr[0..sdk.version81_len],
};
search_end += 1;
}
}
return search_buf[0..search_end];
}
fn fileExists(allocator: *std.mem.Allocator, path: []const u8) !bool {
if (std.os.File.access(allocator, path)) |_| {
return true;
} else |err| switch (err) {
error.NotFound, error.PermissionDenied => return false,
error.OutOfMemory => return error.OutOfMemory,
else => return error.FileSystem,
}
} | src-self-hosted/libc_installation.zig |
const std = @import("std");
const print = std.debug.print;
usingnamespace @import("common.zig");
usingnamespace @import("value.zig");
usingnamespace @import("chunk.zig");
pub const Token = struct {
tokenType: TokenType,
literal: []const u8,
line: usize,
};
pub const TokenType = enum {
// Single-character tokens.
TOKEN_LEFT_PAREN, TOKEN_RIGHT_PAREN, TOKEN_LEFT_BRACE, TOKEN_RIGHT_BRACE, TOKEN_COMMA, TOKEN_DOT, TOKEN_MINUS, TOKEN_PLUS, TOKEN_SEMICOLON, TOKEN_SLASH, TOKEN_STAR,
// One or two character tokens.
TOKEN_BANG, TOKEN_BANG_EQUAL, TOKEN_EQUAL, TOKEN_EQUAL_EQUAL, TOKEN_GREATER, TOKEN_GREATER_EQUAL, TOKEN_LESS, TOKEN_LESS_EQUAL,
// Literals.
TOKEN_IDENTIFIER, TOKEN_STRING, TOKEN_NUMBER,
// Keywords.
TOKEN_AND, TOKEN_CLASS, TOKEN_ELSE, TOKEN_FALSE, TOKEN_FOR, TOKEN_FUN, TOKEN_IF, TOKEN_NIL, TOKEN_OR, TOKEN_PRINT, TOKEN_RETURN, TOKEN_SUPER, TOKEN_THIS, TOKEN_TRUE, TOKEN_VAR, TOKEN_WHILE, TOKEN_ERROR, TOKEN_EOF
};
pub const Scanner = struct {
start: [*]const u8,
current: [*]const u8,
line: usize,
pub fn init(source: []const u8) Scanner {
return Scanner{
.start = source.ptr,
.current = source.ptr,
.line = 1,
};
}
pub fn scanToken(self: *Scanner) Token {
self.skipWhitespace();
self.start = self.current;
if (self.isAtEnd()) return self.makeToken(.TOKEN_EOF);
const char = self.advance();
if (isAlpha(char)) return self.identifier();
if (isDigit(char)) return self.number();
return switch (char) {
'(' => self.makeToken(.TOKEN_LEFT_PAREN),
')' => self.makeToken(.TOKEN_RIGHT_PAREN),
'{' => self.makeToken(.TOKEN_LEFT_BRACE),
'}' => self.makeToken(.TOKEN_RIGHT_BRACE),
';' => self.makeToken(.TOKEN_SEMICOLON),
',' => self.makeToken(.TOKEN_COMMA),
'.' => self.makeToken(.TOKEN_DOT),
'-' => self.makeToken(.TOKEN_MINUS),
'+' => self.makeToken(.TOKEN_PLUS),
'/' => self.makeToken(.TOKEN_SLASH),
'*' => self.makeToken(.TOKEN_STAR),
'!' => self.makeToken(if (self.match('=')) .TOKEN_BANG_EQUAL else .TOKEN_BANG),
'=' => self.makeToken(if (self.match('=')) .TOKEN_EQUAL_EQUAL else .TOKEN_EQUAL),
'<' => self.makeToken(if (self.match('=')) .TOKEN_LESS_EQUAL else .TOKEN_LESS),
'>' => self.makeToken(if (self.match('=')) .TOKEN_GREATER_EQUAL else .TOKEN_GREATER),
'"' => self.string(),
else => self.errorToken("Unexpected character."),
};
}
fn number(self: *Scanner) Token {
while (isDigit(self.peek())) _ = self.advance();
if (self.peek() == '.' and isDigit(self.peekNext())) {
_ = self.advance();
while (isDigit(self.peek())) _ = self.advance();
}
return self.makeToken(.TOKEN_NUMBER);
}
fn isDigit(char: u8) bool {
return char >= '0' and char <= '9';
}
fn isAlpha(char: u8) bool {
return (char >= 'a' and char <= 'z') or (char >= 'A' and char <= 'Z') or (char == '_');
}
fn string(self: *Scanner) Token {
while (self.peek() != '"' and !self.isAtEnd()) {
if (self.peek() == '\n') self.line += 1;
_ = self.advance();
}
if (self.isAtEnd()) return self.errorToken("Unterminated string.");
_ = self.advance();
return self.makeToken(.TOKEN_STRING);
}
fn identifier(self: *Scanner) Token {
while (isAlpha(self.peek()) or isDigit(self.peek())) _ = self.advance();
return self.makeToken(self.identifierType());
}
fn identifierType(self: *Scanner) TokenType {
return switch (self.start[0]) {
'a' => self.checkKeyword(1, 2, "nd", .TOKEN_AND),
'c' => self.checkKeyword(1, 4, "lass", .TOKEN_CLASS),
'e' => self.checkKeyword(1, 3, "lse", .TOKEN_ELSE),
'f' => if (@ptrToInt(self.current) - @ptrToInt(self.start) > 1) blk: {
switch (self.start[1]) {
'a' => break :blk self.checkKeyword(2, 3, "lse", .TOKEN_FALSE),
'o' => break :blk self.checkKeyword(2, 1, "r", .TOKEN_FOR),
'u' => break :blk self.checkKeyword(2, 1, "n", .TOKEN_FUN),
else => break :blk .TOKEN_IDENTIFIER,
}
} else .TOKEN_IDENTIFIER,
'i' => self.checkKeyword(1, 1, "f", .TOKEN_IF),
'n' => self.checkKeyword(1, 2, "il", .TOKEN_NIL),
'o' => self.checkKeyword(1, 1, "r", .TOKEN_OR),
'p' => self.checkKeyword(1, 4, "rint", .TOKEN_PRINT),
'r' => self.checkKeyword(1, 5, "eturn", .TOKEN_AND),
's' => self.checkKeyword(1, 4, "uper", .TOKEN_AND),
't' => if (@ptrToInt(self.current) - @ptrToInt(self.start) > 1) blk: {
switch (self.start[1]) {
'h' => break :blk self.checkKeyword(2, 2, "is", .TOKEN_THIS),
'r' => break :blk self.checkKeyword(2, 2, "ue", .TOKEN_TRUE),
else => break :blk .TOKEN_IDENTIFIER,
}
} else .TOKEN_IDENTIFIER,
'v' => self.checkKeyword(1, 2, "ar", .TOKEN_VAR),
'w' => self.checkKeyword(1, 4, "hile", .TOKEN_WHILE),
else => .TOKEN_IDENTIFIER,
};
}
fn checkKeyword(self: *Scanner, start: usize, length: usize, rest: []const u8, tokenType: TokenType) TokenType {
return if ((@ptrToInt(self.current) - @ptrToInt(self.start) == start + length) and std.mem.eql(u8, self.start[start .. start + length], rest))
tokenType
else
.TOKEN_IDENTIFIER;
}
fn match(self: *Scanner, char: u8) bool {
if (self.isAtEnd() or self.current[0] != char) {
return false;
}
self.current += 1;
return true;
}
fn advance(self: *Scanner) u8 {
const res = self.current[0];
self.current += 1;
return res;
}
fn isAtEnd(self: *Scanner) bool {
return self.current[0] == 0;
}
fn makeToken(self: *Scanner, tokenType: TokenType) Token {
return Token{
.tokenType = tokenType,
.literal = self.start[0 .. @ptrToInt(self.current) - @ptrToInt(self.start)],
.line = self.line,
};
}
fn errorToken(self: *Scanner, message: []const u8) Token {
return Token{
.tokenType = .TOKEN_ERROR,
.literal = message,
.line = self.line,
};
}
fn skipWhitespace(self: *Scanner) void {
while (true) {
const char = self.peek();
switch (char) {
' ', '\r', '\t' => _ = self.advance(),
'\n' => {
self.line += 1;
_ = self.advance();
},
'/' => {
if (self.peekNext() == '/') {
// A comment goes until the end of the line.
while (self.peek() != '\n' and !self.isAtEnd())
_ = self.advance();
} else {
return;
}
},
else => return,
}
}
}
fn peek(self: *Scanner) u8 {
return self.current[0];
}
fn peekNext(self: *Scanner) u8 {
if (self.isAtEnd()) return 0;
return self.current[1];
}
}; | vm/src/scanner.zig |
const std = @import("std");
const builtin = @import("builtin");
const kernel = @This();
pub const arch = @import("arch.zig");
pub const log = std.log;
pub const build_mode = builtin.mode;
pub const Physical = @import("physical.zig");
pub const Virtual = @import("virtual.zig");
pub usingnamespace @import("assertion.zig");
pub usingnamespace @import("data_manipulation.zig");
const panic_file = @import("panic.zig");
pub const panic = panic_file.panic;
pub const TODO = panic_file.TODO;
pub const SourceLocation = panic_file.SourceLocation;
pub const bounds = arch.Bounds;
pub const Spinlock = arch.Spinlock;
pub const AVL = @import("avl.zig");
pub const Heap = @import("heap.zig");
pub const CoreHeap = @import("core_heap.zig");
pub const PSF1 = @import("psf1.zig");
pub const graphics = @import("graphics.zig");
pub const scheduler = @import("scheduler.zig");
pub const Filesystem = @import("filesystem.zig");
pub const Disk = @import("disk.zig");
// TODO: move this to drivers
pub const RNUFS = @import("rnu_fs.zig");
pub const driver = @import("driver.zig");
pub const Driver = driver.Driver;
pub const ELF = @import("elf.zig");
pub const Syscall = @import("syscall.zig");
comptime {
kernel.reference_all_declarations(Syscall);
}
pub var address_space = Virtual.AddressSpace.from_context(undefined);
pub var memory_region = Virtual.Memory.Region.new(Virtual.Address.new(0xFFFF900000000000), 0xFFFFF00000000000 - 0xFFFF900000000000);
pub const core_memory_region = Virtual.Memory.Region.new(Virtual.Address.new(0xFFFF800100000000), 0xFFFF800200000000 - 0xFFFF800100000000);
pub var heap: Heap = undefined;
pub var core_heap: CoreHeap = undefined;
pub var font: PSF1.Font = undefined;
pub const Writer = std.io.Writer;
pub var higher_half_direct_map: Virtual.Address = undefined;
pub var file: File = undefined;
pub var sections_in_memory: []Virtual.Memory.RegionWithPermissions = undefined;
pub const File = struct {
address: Virtual.Address,
size: u64,
};
pub var cpus: []arch.CPU = undefined;
pub const PrivilegeLevel = enum(u1) {
kernel = 0,
user = 1,
}; | src/kernel/kernel.zig |
const std = @import("std");
const unit = @import("unit.zig");
const CompileInfo = unit.CompileInfo;
pub fn usage() void {
std.debug.print("usage text\n", .{});
}
pub fn help() void {
std.debug.print("help text\n", .{});
}
const ArgType = enum {
file_name,
show_help,
show_usage,
opt_level,
build_mode,
link_library,
};
const long_args = std.ComptimeStringMap(ArgType, .{
.{ "help", .show_help },
.{ "usage", .show_usage },
.{ "opt-level", .opt_level },
.{ "build-mode", .build_mode },
.{ "link-library", .link_library },
});
const short_args = std.ComptimeStringMap(ArgType, .{
.{ "h", .show_help },
.{ "O", .opt_level },
.{ "l", .link_library },
.{ "b", .build_mode },
});
const JobType = enum {
none,
build,
run,
compile,
};
const JobData = union(JobType) {
none: void,
build: void,
run: void,
compile: CompileInfo,
};
pub fn parse_command(allocator: std.mem.Allocator, args: []const []u8) !JobData {
const cmd = args[1];
if (std.mem.eql(u8, cmd, "help")) {
help();
return error.Canceled;
} else if (std.mem.eql(u8, cmd, "build")) {
return error.NotImplemented;
} else if (std.mem.eql(u8, cmd, "run")) {
return error.NotImplemented;
} else if (std.mem.eql(u8, cmd, "compile")) {
const build_info = try parse_compile_args(allocator, args);
return JobData{ .compile = build_info };
} else {
std.debug.print("error: invalid command \"{s}\"\n", .{cmd});
return error.InvalidCommand;
}
}
pub fn parse_compile_args(allocator: std.mem.Allocator, args: []const []u8) !CompileInfo {
var info = CompileInfo{
.files = undefined,
.link_libraries = undefined,
.opt_level = .no_opt,
.build_mode = .debug,
};
var i: usize = 2;
var files = std.ArrayList([]u8).init(allocator);
errdefer files.deinit();
while (i < args.len) : (i += 1) {
var arg: ?ArgType = null;
if (std.mem.startsWith(u8, args[i], "--")) {
arg = long_args.get(args[i][2..]);
} else if (std.mem.startsWith(u8, args[i], "-")) {
arg = short_args.get(args[i][1..2]);
} else {
arg = ArgType.file_name;
}
if (arg == null) {
std.debug.print("error: unrecognized argument \"{s}\"\n", .{args[i]});
return error.UnrecognizedArgument;
}
switch (arg.?) {
// TODO(mia): make printing help/usage cancel
.show_help => {
help();
return error.Canceled;
},
.show_usage => {
usage();
return error.Canceled;
},
.file_name => try files.append(args[i]),
else => return error.NotImplemented,
}
}
info.files = files.toOwnedSlice();
return info;
} | src/args.zig |
const std = @import("std");
const PrintHelper = @import("print_helper.zig").PrintHelper;
const CodegenState = @import("codegen.zig").CodegenState;
const CodegenModuleState = @import("codegen.zig").CodegenModuleState;
const ExpressionResult = @import("codegen.zig").ExpressionResult;
const BufferDest = @import("codegen.zig").BufferDest;
const FloatDest = @import("codegen.zig").FloatDest;
const Instruction = @import("codegen.zig").Instruction;
const State = struct {
cs: *const CodegenState,
cms: *const CodegenModuleState,
helper: PrintHelper,
pub fn print(self: *State, comptime fmt: []const u8, args: var) !void {
try self.helper.print(self, fmt, args);
}
pub fn printArgValue(self: *State, comptime arg_format: []const u8, arg: var) !void {
if (comptime std.mem.eql(u8, arg_format, "buffer_dest")) {
try self.printBufferDest(arg);
} else if (comptime std.mem.eql(u8, arg_format, "float_dest")) {
try self.printFloatDest(arg);
} else if (comptime std.mem.eql(u8, arg_format, "expression_result")) {
try self.printExpressionResult(arg);
} else {
@compileError("unknown arg_format: \"" ++ arg_format ++ "\"");
}
}
fn printExpressionResult(self: *State, result: ExpressionResult) std.os.WriteError!void {
switch (result) {
.nothing => unreachable,
.temp_buffer => |temp_ref| try self.print("temp{usize}", .{temp_ref.index}),
.temp_float => |temp_ref| try self.print("temp_float{usize}", .{temp_ref.index}),
.literal_boolean => |value| try self.print("{bool}", .{value}),
.literal_number => |value| try self.print("{number_literal}", .{value}),
.literal_enum_value => |v| {
try self.print("'{str}'", .{v.label});
if (v.payload) |payload| {
try self.print("({expression_result})", .{payload.*});
}
},
.literal_curve => |curve_index| try self.print("(curve_{usize})", .{curve_index}),
.literal_track => |track_index| try self.print("(track_{usize})", .{track_index}),
.literal_module => |module_index| try self.print("(module_{usize})", .{module_index}),
.self_param => |i| {
const module = self.cs.modules[self.cms.module_index];
try self.print("params.{str}", .{module.params[i].name});
},
.track_param => |x| {
try self.print("@{str}", .{self.cs.tracks[x.track_index].params[x.param_index].name});
},
}
}
fn printFloatDest(self: *State, dest: FloatDest) !void {
try self.print("temp_float{usize}", .{dest.temp_float_index});
}
fn printBufferDest(self: *State, dest: BufferDest) !void {
switch (dest) {
.temp_buffer_index => |i| try self.print("temp{usize}", .{i}),
.output_index => |i| try self.print("output{usize}", .{i}),
}
}
fn indent(self: *State, indentation: usize) !void {
var i: usize = 0;
while (i < indentation) : (i += 1) {
try self.print(" ", .{});
}
}
};
pub fn printBytecode(out: std.io.StreamSource.OutStream, cs: *const CodegenState, cms: *const CodegenModuleState) !void {
var self: State = .{
.cs = cs,
.cms = cms,
.helper = PrintHelper.init(out),
};
const self_module = cs.modules[cms.module_index];
try self.print("module {usize}\n", .{cms.module_index});
try self.print(" num_temp_buffers: {usize}\n", .{cms.temp_buffers.finalCount()});
try self.print(" num_temp_floats: {usize}\n", .{cms.temp_floats.finalCount()});
try self.print("bytecode:\n", .{});
for (cms.instructions.items) |instr| {
try printInstruction(&self, instr, 1);
}
try self.print("\n", .{});
self.helper.finish();
}
fn printInstruction(self: *State, instr: Instruction, indentation: usize) std.os.WriteError!void {
try self.indent(indentation);
switch (instr) {
.copy_buffer => |x| {
try self.print("{buffer_dest} = {expression_result}\n", .{ x.out, x.in });
},
.float_to_buffer => |x| {
try self.print("{buffer_dest} = {expression_result}\n", .{ x.out, x.in });
},
.cob_to_buffer => |x| {
const module = self.cs.modules[self.cms.module_index];
try self.print("{buffer_dest} = COB_TO_BUFFER params.{str}\n", .{ x.out, module.params[x.in_self_param].name });
},
.arith_float => |x| {
try self.print("{float_dest} = ARITH_FLOAT({auto}) {expression_result}\n", .{ x.out, x.op, x.a });
},
.arith_buffer => |x| {
try self.print("{buffer_dest} = ARITH_BUFFER({auto}) {expression_result}\n", .{ x.out, x.op, x.a });
},
.arith_float_float => |x| {
try self.print("{float_dest} = ARITH_FLOAT_FLOAT({auto}) {expression_result} {expression_result}\n", .{ x.out, x.op, x.a, x.b });
},
.arith_float_buffer => |x| {
try self.print("{buffer_dest} = ARITH_FLOAT_BUFFER({auto}) {expression_result} {expression_result}\n", .{ x.out, x.op, x.a, x.b });
},
.arith_buffer_float => |x| {
try self.print("{buffer_dest} = ARITH_BUFFER_FLOAT({auto}) {expression_result} {expression_result}\n", .{ x.out, x.op, x.a, x.b });
},
.arith_buffer_buffer => |x| {
try self.print("{buffer_dest} = ARITH_BUFFER_BUFFER({auto}) {expression_result} {expression_result}\n", .{ x.out, x.op, x.a, x.b });
},
.call => |call| {
const field_module_index = self.cms.fields.items[call.field_index].module_index;
const callee_module = self.cs.modules[field_module_index];
try self.print("{buffer_dest} = CALL #{usize}(module{usize})\n", .{ call.out, call.field_index, field_module_index });
try self.indent(indentation + 1);
try self.print("temps: [", .{});
for (call.temps) |temp, i| {
if (i > 0) try self.print(", ", .{});
try self.print("temp{usize}", .{temp});
}
try self.print("]\n", .{});
for (call.args) |arg, i| {
try self.indent(indentation + 1);
try self.print("{str} = {expression_result}\n", .{ callee_module.params[i].name, arg });
}
},
.track_call => |track_call| {
try self.print("{buffer_dest} = TRACK_CALL track_{usize} ({expression_result}):\n", .{
track_call.out,
track_call.track_index,
track_call.speed,
});
for (track_call.instructions) |sub_instr| {
try printInstruction(self, sub_instr, indentation + 1);
}
},
.delay => |delay| {
try self.print("{buffer_dest} = DELAY (feedback provided at temps[{usize}]):\n", .{ delay.out, delay.feedback_temp_buffer_index });
for (delay.instructions) |sub_instr| {
try printInstruction(self, sub_instr, indentation + 1);
}
//try self.print("{buffer_dest} = DELAY_END {expression_result}\n", .{delay_end.out,delay_end.inner_value}); // FIXME
},
}
} | src/zangscript/codegen_print.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
//;
/// SPSC, lock-free push and pop
/// allocation free, data is fixed size
pub fn Queue(comptime T: type) type {
return struct {
const Self = @This();
pub const Error = error{
OutOfSpace,
Empty,
};
allocator: *Allocator,
data: []T,
write_pt: usize,
read_pt: usize,
fn next_idx(self: Self, idx: usize) usize {
return (idx + 1) % self.data.len;
}
pub fn init(allocator: *Allocator, count: usize) !Self {
return Self{
.allocator = allocator,
.data = try allocator.alloc(T, count),
.write_pt = 0,
.read_pt = 0,
};
}
pub fn deinit(self: *Self) void {
self.allocator.free(self.data);
}
pub fn push(self: *Self, val: T) Error!void {
const read_pt = @atomicLoad(@TypeOf(self.read_pt), &self.read_pt, .Monotonic);
if (read_pt == self.next_idx(self.write_pt)) {
return Error.OutOfSpace;
}
self.data[self.write_pt] = val;
@fence(.SeqCst);
self.write_pt = self.next_idx(self.write_pt);
}
pub fn pop(self: *Self) Error!T {
const write_pt = @atomicLoad(@TypeOf(self.write_pt), &self.write_pt, .Monotonic);
if (write_pt == self.read_pt) {
return Error.Empty;
}
const ret = self.data[self.read_pt];
@fence(.SeqCst);
self.read_pt = self.next_idx(self.read_pt);
return ret;
}
};
}
/// MPSC, lock-free pop, uses spin lock to protect pushes
/// allocation free, doesnt own data
pub fn Channel(comptime T: type) type {
return struct {
const Self = @This();
pub const Error = Queue(T).Error;
pub const Receiver = struct {
channel: *Self,
pub fn tryRecv(self: *Receiver) ?T {
return self.channel.pop() catch null;
}
};
pub const Sender = struct {
channel: *Self,
pub fn send(self: *Sender, val: T) Error!void {
return self.channel.push(val);
}
};
queue: Queue(T),
write_lock: bool,
pub fn init(allocator: *Allocator, count: usize) Allocator.Error!Self {
return Self{
.write_lock = false,
.queue = try Queue(T).init(allocator, count),
};
}
pub fn deinit(self: *Self) void {
self.queue.deinit();
}
pub fn push(self: *Self, val: T) Error!void {
while (@atomicRmw(@TypeOf(self.write_lock), &self.write_lock, .Xchg, true, .SeqCst)) {}
defer assert(@atomicRmw(@TypeOf(self.write_lock), &self.write_lock, .Xchg, false, .SeqCst));
return self.queue.push(val);
}
pub fn pop(self: *Self) !T {
return self.queue.pop();
}
pub fn makeSender(self: *Self) Sender {
return .{ .channel = self };
}
pub fn makeReceiver(self: *Self) Receiver {
return .{ .channel = self };
}
};
}
/// MPSC, lock-free pop, uses spin lock to protect pushes
/// allocation free, doesnt own data
/// timed-stamped messages
pub fn EventChannel(comptime T: type) type {
return struct {
const Self = @This();
pub const Error = Channel(T).Error;
pub const Event = struct {
timestamp: u64,
data: T,
};
// TODO use channel.receiver and sender
pub const Receiver = struct {
event_channel: *EventChannel(T),
last_event: ?Event,
pub fn tryRecv(self: *Receiver, now: u64) ?Event {
if (self.last_event) |ev| {
if (ev.timestamp <= now) {
self.last_event = null;
return ev;
} else {
return null;
}
} else {
const get = self.event_channel.channel.pop() catch {
return null;
};
if (get.timestamp <= now) {
return get;
} else {
self.last_event = get;
return null;
}
}
}
};
pub const Sender = struct {
event_channel: *EventChannel(T),
pub fn send(self: *Sender, timestamp: u64, data: T) Error!void {
// TODO make sure this timestamp isnt before the last one pushed
// invalid timestamp error
return self.event_channel.channel.push(.{
.timestamp = timestamp,
.data = data,
});
}
};
channel: Channel(Event),
pub fn init(allocator: *Allocator, count: usize) Allocator.Error!Self {
return Self{
.channel = try Channel(Event).init(allocator, count),
};
}
pub fn deinit(self: *Self) void {
self.channel.deinit();
}
pub fn makeSender(self: *Self) Sender {
return .{ .event_channel = self };
}
pub fn makeReceiver(self: *Self) Receiver {
return .{
.event_channel = self,
.last_event = null,
};
}
};
}
// tests ===
const testing = std.testing;
const expect = testing.expect;
test "Queue: push pop" {
var q = try Queue(u8).init(testing.allocator, 15);
defer q.deinit();
try q.push(1);
try q.push(2);
try q.push(3);
expect((try q.pop()) == 1);
expect((try q.pop()) == 2);
expect((try q.pop()) == 3);
}
test "EventChannel: send recv" {
const EnvChan = EventChannel(u8);
var chan = try EnvChan.init(testing.allocator, 50);
defer chan.deinit();
var send = chan.makeSender();
var recv = chan.makeReceiver();
var tm = try @import("timer.zig").Timer.start();
try send.send(tm.now(), 0);
try send.send(tm.now(), 1);
try send.send(tm.now(), 2);
expect(recv.tryRecv(tm.now()).?.data == 0);
expect(recv.tryRecv(tm.now()).?.data == 1);
expect(recv.tryRecv(tm.now()).?.data == 2);
const time = tm.now();
try send.send(time, 0);
try send.send(time + 10, 1);
try send.send(time + 20, 2);
expect(recv.tryRecv(time).?.data == 0);
expect(recv.tryRecv(time) == null);
expect(recv.tryRecv(time + 9) == null);
expect(recv.tryRecv(time + 10).?.data == 1);
expect(recv.tryRecv(time + 15) == null);
expect(recv.tryRecv(time + 25).?.data == 2);
} | src/communication.zig |
const fmath = @import("index.zig");
pub fn asinh(x: var) -> @typeOf(x) {
const T = @typeOf(x);
switch (T) {
f32 => @inlineCall(asinhf, x),
f64 => @inlineCall(asinhd, x),
else => @compileError("asinh not implemented for " ++ @typeName(T)),
}
}
// asinh(x) = sign(x) * log(|x| + sqrt(x * x + 1)) ~= x - x^3/6 + o(x^5)
fn asinhf(x: f32) -> f32 {
const u = @bitCast(u32, x);
const i = u & 0x7FFFFFFF;
const s = i >> 31;
var rx = @bitCast(f32, i); // |x|
// |x| >= 0x1p12 or inf or nan
if (i >= 0x3F800000 + (12 << 23)) {
rx = fmath.log(rx) + 0.69314718055994530941723212145817656;
}
// |x| >= 2
else if (i >= 0x3F800000 + (1 << 23)) {
rx = fmath.log(2 * x + 1 / (fmath.sqrt(x * x + 1) + x));
}
// |x| >= 0x1p-12, up to 1.6ulp error
else if (i >= 0x3F800000 - (12 << 23)) {
rx = fmath.log1p(x + x * x / (fmath.sqrt(x * x + 1) + 1));
}
// |x| < 0x1p-12, inexact if x != 0
else {
fmath.forceEval(x + 0x1.0p120);
}
if (s != 0) -rx else rx
}
fn asinhd(x: f64) -> f64 {
const u = @bitCast(u64, x);
const e = (u >> 52) & 0x7FF;
const s = u >> 63;
var rx = @bitCast(f64, u & (@maxValue(u64) >> 1)); // |x|
// |x| >= 0x1p26 or inf or nan
if (e >= 0x3FF + 26) {
rx = fmath.log(rx) + 0.693147180559945309417232121458176568;
}
// |x| >= 2
else if (e >= 0x3FF + 1) {
rx = fmath.log(2 * x + 1 / (fmath.sqrt(x * x + 1) + x));
}
// |x| >= 0x1p-12, up to 1.6ulp error
else if (e >= 0x3FF - 26) {
rx = fmath.log1p(x + x * x / (fmath.sqrt(x * x + 1) + 1));
}
// |x| < 0x1p-12, inexact if x != 0
else {
fmath.forceEval(x + 0x1.0p120);
}
if (s != 0) -rx else rx
}
test "asinh" {
fmath.assert(asinh(f32(0.0)) == asinhf(0.0));
fmath.assert(asinh(f64(0.0)) == asinhd(0.0));
}
test "asinhf" {
const epsilon = 0.000001;
fmath.assert(fmath.approxEq(f32, asinhf(0.0), 0.0, epsilon));
fmath.assert(fmath.approxEq(f32, asinhf(0.2), 0.198690, epsilon));
fmath.assert(fmath.approxEq(f32, asinhf(0.8923), 0.803133, epsilon));
fmath.assert(fmath.approxEq(f32, asinhf(1.5), 1.194763, epsilon));
fmath.assert(fmath.approxEq(f32, asinhf(37.45), 4.316332, epsilon));
fmath.assert(fmath.approxEq(f32, asinhf(89.123), 5.183196, epsilon));
fmath.assert(fmath.approxEq(f32, asinhf(123123.234375), 12.414088, epsilon));
}
test "asinhd" {
const epsilon = 0.000001;
fmath.assert(fmath.approxEq(f64, asinhd(0.0), 0.0, epsilon));
fmath.assert(fmath.approxEq(f64, asinhd(0.2), 0.198690, epsilon));
fmath.assert(fmath.approxEq(f64, asinhd(0.8923), 0.803133, epsilon));
fmath.assert(fmath.approxEq(f64, asinhd(1.5), 1.194763, epsilon));
fmath.assert(fmath.approxEq(f64, asinhd(37.45), 4.316332, epsilon));
fmath.assert(fmath.approxEq(f64, asinhd(89.123), 5.183196, epsilon));
fmath.assert(fmath.approxEq(f64, asinhd(123123.234375), 12.414088, epsilon));
} | src/asinh.zig |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.